Merge mrbatch-0904: 17 Community-MRs plus Tester-Fixes fuer v1.3.2

This commit is contained in:
Duarte Santos committed 2026-09-05 14:17:21 +02:00
commit 9eccb5a5c3
56 files changed
+2494 -235

No files matched your search

+15 -3
View File
@@ -59,6 +59,11 @@ const EX_SCHEMA = {
required: ['id', 'sets']
};
// `week` and `routines[].id` are required, not optional: the week is the only thing that says
// which day trains which routine, and it points at a routine by id. A schema that leaves either
// out lets a small local model answer with routines that have no id and a week naming "r1" —
// grammar-valid, and something validate.js can only ever reject ("the week schedules 0 days but
// 3 were asked for"), through the repair round and out as a failed job.
export const CREATE_SCHEMA = {
type: 'object',
properties: {
@@ -67,15 +72,22 @@ export const CREATE_SCHEMA = {
summary: STR,
basedOn: STR,
week: { type: 'object' },
// The caps are the validator's own (MAX_ROUTINES, MAX_EX_PER_ROUTINE), stated here as well
// because "1-7 routines, each 3-12 exercises" in create.md is only a request. A small model
// that starts repeating itself does not stop at a request: qwen2.5:3b walks the library id by
// id, three sets of eight apiece, until it hits the output limit — twelve minutes for an
// answer that arrives cut in half and cannot be parsed. maxItems ends that run at seven
// routines instead.
routines: {
type: 'array',
maxItems: 7,
items: {
type: 'object',
properties: {
id: STR, name: STR, emoji: STR, prog: STR, why: STR,
ex: { type: 'array', items: EX_SCHEMA }
ex: { type: 'array', maxItems: 20, items: EX_SCHEMA }
},
required: ['name', 'ex']
required: ['id', 'name', 'ex']
}
},
customEx: {
@@ -83,7 +95,7 @@ export const CREATE_SCHEMA = {
items: { type: 'object', properties: { id: STR, n: STR, bp: STR, desc: STR }, required: ['id', 'n'] }
}
},
required: ['coach_contract', 'routines']
required: ['coach_contract', 'week', 'routines']
};
export const DEBRIEF_SCHEMA = {
+27
View File
@@ -4,6 +4,7 @@ import { buildPrompt, buildPromptParts, taskOf } from '../coach/core/prompt.js';
import { SCHEMAS } from '../coach/core/schemas.js';
import { build, FULL_DETAIL_SESSIONS } from '../coach/core/payload.js';
import { chatCompletionsSpec } from '../coach/core/adapters/openai.js';
import { validatePlan } from '../coach/core/validate.js';
const S = (workouts = []) => ({
lang: 'en', unit: 'kg', routines: [{ id: 'r1', name: 'A', ex: [{ id: '0001', sets: 3, reps: 8 }] }],
@@ -48,6 +49,32 @@ test('every task has a flat schema — no $ref, no anyOf/oneOf (llama.cpp gramma
assert.equal(taskOf('create', { refine: 'x' }), 'refine');
});
test('the create schema requires what the week resolves through: a routine id, and a week', () => {
// A schema handed to a grammar-constrained decoder is the only thing standing between a small
// local model and an answer the validator can only reject. These two fields are where that
// showed: llama3.2:3b and qwen2.5:3b both answer with routines that carry no `id` and a week
// naming what they put in `name`, which costs a job and a repair round to find out.
assert.ok(SCHEMAS.create.properties.routines.items.required.includes('id'));
assert.ok(SCHEMAS.create.required.includes('week'));
assert.equal(SCHEMAS.refine, SCHEMAS.create); // refine reuses it, same guarantee
const noId = {
coach_contract: 1,
routines: [{ name: 'r1', ex: [{ id: '0001', sets: 3, reps: 8 }] }],
week: { 1: 'r1' }
};
const checked = validatePlan(noId, { daysPerWeek: 1 });
assert.ok(!checked.ok);
assert.ok(checked.errors.some(e => e.includes('week[1] points at "r1"')));
});
test('the create schema caps the two arrays the validator caps, so a repeating model stops', () => {
// validate.js slices at MAX_ROUTINES / MAX_EX_PER_ROUTINE; a model that never stops emitting
// otherwise runs to the output limit first and the answer arrives truncated and unparseable.
assert.equal(SCHEMAS.create.properties.routines.maxItems, 7);
assert.equal(SCHEMAS.create.properties.routines.items.properties.ex.maxItems, 20);
});
test('older sessions in a review window are compacted, the recent ones keep full sets', () => {
const many = Array.from({ length: FULL_DETAIL_SESSIONS + 4 }, (_, i) => workout('2026-08-' + String(i + 1).padStart(2, '0')));
const p = build(S(many), { handle: 'h1', kind: 'review' });
+2
View File
@@ -26,6 +26,7 @@ import Workout from './views/Workout.jsx'
import Stats from './views/Stats.jsx'
import History from './views/History.jsx'
import Library from './views/Library.jsx'
import Muscles from './views/Muscles.jsx'
import Settings from './views/Settings.jsx'
import Admin from './views/Admin.jsx'
import CoachChat from './views/CoachChat.jsx'
@@ -123,6 +124,7 @@ function Shell() {
<Route path="/stats" element={<Stats />} />
<Route path="/history" element={<History />} />
<Route path="/library" element={<Library />} />
<Route path="/muscles" element={<Muscles />} />
<Route path="/settings" element={<Settings />} />
{/* The Coach screens gate themselves on the instance config; the routes exist
unconditionally so a deep link from a notification lands somewhere sane
+9 -1
View File
@@ -1,7 +1,7 @@
// @vitest-environment happy-dom
import React, { act } from 'react'
import { createRoot } from 'react-dom/client'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
import BodyMap, { BodyMapLegend } from './BodyMap.jsx'
globalThis.IS_REACT_ACT_ENVIRONMENT = true
@@ -9,6 +9,14 @@ globalThis.IS_REACT_ACT_ENVIRONMENT = true
let container
let root
// BodyMap fetches its ~90 KB of geometry with a dynamic import on first render, and the
// waitFor below allows one second for it. That is ample once the module is in the ESM
// registry and not always ample when it is not: on a loaded CI runner the first map render
// in this file paid the cold import and timed out, while every later test passed on the
// component's warm CACHE. Import it here so the wait covers rendering, not module loading,
// and the file stops depending on how fast the machine is.
beforeAll(() => import('../lib/body-paths.js'))
beforeEach(() => {
container = document.createElement('div')
document.body.appendChild(container)
@@ -0,0 +1,97 @@
import { useMemo, useState } from 'react'
import { useStore } from '../store/useStore.js'
import { BODYPARTS, allExercises, equipmentOf, matchExercise } from '../lib/exercises.js'
import { activeProfile, exAvailable } from '../lib/equipment.js'
import { bestWeightFor } from '../lib/history.js'
import { fmtNum } from '../lib/format.js'
import { MUSCLES, MUSCLE_NAME, musclesOf } from '../lib/muscles.js'
import { t, exerciseNameFor } from '../lib/i18n.js'
import BodyMap from './BodyMap.jsx'
import { Thumb } from './Media.jsx'
import Icon from './Icon.jsx'
import { Button } from './ui.jsx'
import { tappable } from '../lib/use-sheet-keyboard.js'
// One explorer for the Library and every catalogue picker. Supplying `onPick` turns
// a result into a selection; without it the explorer behaves like the normal Library.
export default function MuscleExplorer({ onPick, onDetail, onPlan }) {
const S = useStore(s => s.S)
const [selected, setSelected] = useState(null)
const [q, setQ] = useState('')
const [bp, setBp] = useState('')
const [eq, setEq] = useState('')
const [shown, setShown] = useState(40)
const [showAll, setShowAll] = useState(false) // ignore the active equipment profile for this session
// Same rule as the Library and the picker: the active equipment profile narrows the catalogue
// (and the per-muscle counts) unless the user asks for everything.
const profile = activeProfile(S)
const catalog = useMemo(() => {
const all = allExercises(S)
return (profile && !showAll) ? all.filter(e => exAvailable(S, e)) : all
}, [S.customEx, S.equipFilterOn, S.activeEquipId, S.equipProfiles, showAll])
const counts = useMemo(() => Object.fromEntries(MUSCLES.map(m => [m,
catalog.filter(e => musclesOf(e)[m]).length
])), [catalog])
const pick = muscle => { setSelected(muscle === selected ? null : muscle); setEq(''); setShown(40) }
const targeted = selected ? catalog.filter(e => musclesOf(e)[selected]) : []
const base = targeted.filter(e => (!bp || e.bp === bp) && matchExercise(e, q))
const eqOpts = equipmentOf(base)
const eqOn = eqOpts.includes(eq) ? eq : ''
const exercises = eqOn ? base.filter(e => e.eq === eqOn) : base
const choose = ex => onPick ? onPick(ex) : onDetail(ex)
return <>
{profile && <div className="small dim row" style={{ margin: '-4px 2px 10px', 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); setEq(''); setShown(40) }}>
{showAll ? t('Filter by "{0}"', profile.name) : t('Show all equipment')}
</button>
</div>}
<div className="card">
<BodyMap className="tappable" body={S.body} selected={selected} onMuscle={pick} />
<div className="chips" style={{ marginTop: 10 }}>
{MUSCLES.map(m => <button key={m} className={'chip' + (selected === m ? ' on' : '')}
aria-pressed={selected === m} onClick={() => pick(m)}>
{t(MUSCLE_NAME[m])} <span className="dim">{counts[m]}</span>
</button>)}
</div>
</div>
{!selected && onPick && <div className="empty"><div className="ico"><Icon name="target" /></div>{t('Choose a muscle to see exercises that train it.')}</div>}
{selected && <>
<div className="row between" style={{ margin: '2px 0 10px' }}>
<h4 className="sec" style={{ margin: 0 }}>{t('Exercises for {0}', t(MUSCLE_NAME[selected]))}</h4>
<Button size="sm" variant="ghost" onClick={() => pick(selected)}>{t('Clear selection')}</Button>
</div>
<div className="search" style={{ marginBottom: 10 }}><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…')} value={q} onChange={e => { setQ(e.target.value); setShown(40) }} />
</div>
<div className="chips" style={{ marginBottom: eqOpts.length > 1 ? 8 : 12 }}>
<button className={'chip nocap' + (!bp ? ' on' : '')} onClick={() => { setBp(''); setEq(''); setShown(40) }}>{t('All')}</button>
{BODYPARTS.map(b => <button key={b} className={'chip' + (bp === b ? ' on' : '')} onClick={() => { setBp(b); setEq(''); setShown(40) }}>{t(b)}</button>)}
</div>
{eqOpts.length > 1 && <div className="chips" style={{ marginBottom: 12 }}>
<button className={'chip nocap' + (!eqOn ? ' on' : '')} onClick={() => { setEq(''); setShown(40) }}>{t('Any equipment')}</button>
{eqOpts.map(x => <button key={x} className={'chip' + (eqOn === x ? ' on' : '')} onClick={() => { setEq(x); setShown(40) }}>{t(x)}</button>)}
</div>}
<div className="list">
{exercises.slice(0, shown).map(e => {
const best = bestWeightFor(S, e.id)
const primary = musclesOf(e)[selected] === 1
return <div key={e.id} className="item" {...tappable(() => choose(e))}>
<Thumb ex={e} />
<div className="grow"><div className="tt capitalize">{exerciseNameFor(e)}</div><div className="ss">{t(primary ? 'Primary target' : 'Also trains')} · <span className="capitalize">{t(e.tg || e.bp)} · {t(e.eq)}</span></div></div>
{onPick ? <Icon name="plus" className="chev" /> : <>
{best > 0 && <span className="tag acc">{fmtNum(best)}</span>}
<Button size="sm" variant="tinted" icon="plus" onClick={ev => { ev.stopPropagation(); onPlan(e) }}>{t('Plan')}</Button>
</>}
</div>
})}
{exercises.length === 0 && <div className="empty"><div className="ico"><Icon name="magnifier" /></div>{t('No match')}</div>}
</div>
{exercises.length > shown && <><div style={{ height: 10 }} /><Button onClick={() => setShown(s => s + 40)}>{t('Show more')}</Button></>}
</>}
</>
}
+1 -1
View File
@@ -13,7 +13,7 @@ export default function TabBar({ onStart }) {
const isGuest = useStore(s => s.isGuest())
if (!user && !isGuest) return null
const cur = loc.pathname.split('/')[1] || 'home'
const on = k => cur === k || (cur === 'history' && k === 'stats') || (cur === 'settings' && k === 'home')
const on = k => cur === k || (cur === 'history' && k === 'stats') || (cur === 'settings' && k === 'home') || (cur === 'muscles' && k === 'library')
const startWorkout = () => {
if (!S.active) {
+17 -3
View File
@@ -1,8 +1,22 @@
import { useEffect } from 'react'
import { useUI } from '../store/useUI.js'
// A new key restarts the CSS sequence even when two timers finish close together.
// The layer never catches taps and ends transparent, so it can safely stay mounted.
// Flips the app's real light/dark theme on and off twice (~2.4s) instead of laying an
// opaque black/white rectangle over the screen — the alert reads as the app itself
// blinking, and it always settles back on whatever theme the user actually had.
export default function TimerFlash() {
const id = useUI(s => s.timerFlashId)
return id ? <div key={id} className="timer-flash" aria-hidden="true" /> : null
useEffect(() => {
if (!id) return
const de = document.documentElement
const original = de.dataset.theme
const opposite = original === 'light' ? 'dark' : 'light'
const steps = [opposite, original, opposite, original]
const timers = steps.map((theme, i) => setTimeout(() => { de.dataset.theme = theme }, i * 600))
return () => {
timers.forEach(clearTimeout)
de.dataset.theme = original
}
}, [id])
return null
}
+14 -14
View File
@@ -262,7 +262,7 @@ h4.sec{
display:grid;grid-template-columns:minmax(0,1fr) auto;grid-template-rows:auto auto;
}
.lrow.lrow-stack-value .lrow-m{grid-column:1;grid-row:1}
.lrow.lrow-stack-value .lrow-v{grid-column:1;grid-row:2;text-align:left}
.lrow.lrow-stack-value .lrow-v{grid-column:1;grid-row:2;width:100%;max-width:none;text-align:left}
.lrow.lrow-stack-value .lrow-c{grid-column:2;grid-row:1 / span 2;align-self:center}
/* an (i) before a row's control: painted small and dim so the control stays the loud thing,
but with a finger-sized target like everything else — the padding is the hit area and the
@@ -438,6 +438,7 @@ h4.sec{
}
.chip:active{background:var(--surface-2)}
.chip.on{background:var(--acc);color:var(--on-acc);font-weight:500}
.chip.on .dim{color:color-mix(in srgb,var(--on-acc) 62%,transparent)}
/* =========================== CONTROLS ==================================== */
@@ -802,19 +803,6 @@ h4.sec{
.glyph-cell:active{transform:scale(.92)}
.glyph-cell.on{background:var(--acc);color:var(--on-acc)}
/* --- opt-in timer completion flash ---
Four deliberate pulses over 2.4s stay below three flashes per second. Transparent
gaps keep the black and white pulses visually distinct. */
.timer-flash{
position:fixed;inset:0;z-index:1000;pointer-events:none;opacity:0;
animation:timer-flash-four 2.4s linear both;
}
@keyframes timer-flash-four{
0%,20%,28%,48%,56%,76%,84%,100%{opacity:0}
4%,16%,60%,72%{background:#000;opacity:1}
32%,44%,88%,96%{background:#fff;opacity:1}
}
/* --- big weight readout --- */
.bwstep{display:flex;align-items:center;justify-content:center;gap:18px;margin:14px 0 6px}
.bw-pm{
@@ -1010,6 +998,18 @@ h4.sec{
.ss-ex{position:relative}
.ss-amp{text-align:center;font-size:15px;font-weight:600;color:var(--acc);margin:14px 0 8px}
/* --- workout list view: every unit stacked, the current one outlined --- */
.workout-list{display:grid;gap:14px}
.wl-unit{
border-radius:var(--r-lg);padding:14px 14px 4px;
background:var(--surface-2);
}
.wl-unit.cur{box-shadow:inset 0 0 0 1.5px var(--acc-line)}
.wl-hd{display:flex;align-items:center;justify-content:space-between;gap:8px;margin-bottom:10px}
@media (max-width:400px){
.wl-unit{padding:10px 8px 2px}
}
/* --- home: today's session row --- */
.today-row{
display:flex;align-items:center;justify-content:space-between;gap:10px;
+3 -1
View File
@@ -1,11 +1,13 @@
// The persisted boundary for a finished session. Keep this pure so compatibility tests can
// exercise the exact shape the UI writes without mounting React or mutating store state.
import { bestWeightForEntry } from './history.js'
export function buildCompletedWorkout(active, { end = Date.now(), prs = [], snapshotFor } = {}) {
const entries = (active?.entries || []).map(entry => {
const completed = {
id: entry.id,
sets: entry.sets,
topW: entry.topW || null,
topW: bestWeightForEntry(entry) || null,
target: entry.target || null,
}
const snapshot = typeof snapshotFor === 'function' ? snapshotFor(entry) : null
+30
View File
@@ -15,6 +15,36 @@ describe('completed workout boundary', () => {
})
})
it('derives topW from the highest completed non-warm-up work set, not stale entry data', () => {
const active = {
id: 'active-1', d: '2026-08-08', start: 1000,
entries: [{
id: '0025', topW: 80, target: { mode: 'reps', sets: 2, reps: 8 },
sets: [
{ phase: 'warmup', done: true, w: 120, r: 8 },
{ done: true, w: 75, r: 8 },
{ done: true, w: 85, r: 7 },
{ done: false, w: 100, r: 8 },
],
}],
}
expect(buildCompletedWorkout(active).entries[0].topW).toBe(85)
expect(buildCompletedWorkout({
...active,
entries: [{ ...active.entries[0], topW: 120 }],
}).entries[0].topW).toBe(85)
})
it('keeps a legacy topW when old completed rows have no usable weight', () => {
const active = {
id: 'active-1', d: '2026-08-08', start: 1000,
entries: [{ id: '0025', topW: 60, sets: [{ done: true, r: 8 }] }],
}
expect(buildCompletedWorkout(active).entries[0].topW).toBe(60)
})
it('persists progression exclusion only for a marked session', () => {
const active = {
id: 'active-1', d: '2026-08-08', start: 1000, routineId: 'routine-1', name: 'Deload', bw: 80,
+14 -10
View File
@@ -626,20 +626,24 @@ export function bestWeightForEntry(entry = {}) {
? entry.sets.filter(s => phaseForSet(s) === 'work')
: []
const repsRows = metricRowsForEntry(entry, 'reps')
if (!repsRows.length) {
return workRows.reduce((best, set) => {
if (set?.done !== true || isWarmupRow(set)) return best
const weight = Number(set.w)
return Number.isFinite(weight) && weight > best ? weight : best
}, 0)
}
// Reps rows are the authoritative load metric for a mixed entry. Otherwise use every
// completed work row (timed holds can carry an added load too).
const completedRows = repsRows.length
? repsRows
: workRows.filter(set => set?.done === true && !isWarmupRow(set))
let best = 0
repsRows.forEach(set => {
let hasUsableWeight = false
completedRows.forEach(set => {
const weight = Number(set?.w)
if (Number.isFinite(weight) && weight > best) best = weight
if (!Number.isFinite(weight)) return
hasUsableWeight = true
if (weight > best) best = weight
})
// A real completed row, including an explicit zero for an unloaded bodyweight set, always
// wins. A manual topW is only useful for old records whose rows did not carry a usable load.
if (hasUsableWeight) return best
const parentMode = modeForSet({}, target)
const hasNonRepsWorkRow = workRows.some(set => modeForSet(set, target) !== 'reps')
const hasWarmupRow = Array.isArray(entry.sets) && entry.sets.some(isWarmupRow)
+66
View File
@@ -501,6 +501,72 @@ describe('buildSets', () => {
.toEqual([{ w: 40, r: 12, done: false }, { w: 40, r: 12, done: false }])
})
it('uses the current routine target instead of another routine\'s bodyweight history', () => {
const S = {
exWeights: {},
workouts: [{
d: '2026-01-01',
routineId: 'routine-a',
entries: [{
id: BW,
target: { sets: 2, reps: 15, weight: 0, bodyweight: true },
sets: [{ w: 0, r: 15, done: true }, { w: 0, r: 15, done: true }]
}]
}]
}
const cfg = { id: BW, sets: 4, reps: 8, weight: 0, bodyweight: true, prog: 'off' }
expect(buildSets(S, cfg, { useTarget: true })).toEqual([
{ w: 0, r: 8, done: false },
{ w: 0, r: 8, done: false },
{ w: 0, r: 8, done: false },
{ w: 0, r: 8, done: false }
])
const reverseS = {
exWeights: {},
workouts: [{
d: '2026-01-02',
routineId: 'routine-b',
entries: [{
id: BW,
target: { sets: 4, reps: 8, weight: 0, bodyweight: true },
sets: [
{ w: 0, r: 8, done: true }, { w: 0, r: 8, done: true },
{ w: 0, r: 8, done: true }, { w: 0, r: 8, done: true }
]
}]
}]
}
expect(buildSets(reverseS, { ...cfg, sets: 2, reps: 15 }, { useTarget: true })).toEqual([
{ w: 0, r: 15, done: false },
{ w: 0, r: 15, done: false }
])
})
it('preserves configured load, reps, duration and cardio targets when history is present', () => {
const repsS = {
exWeights: { [LIFT]: { w: 75 } },
workouts: [{ d: '2026-01-01', entries: [{ id: LIFT, sets: [{ w: 75, r: 15, done: true }] }] }]
}
expect(buildSets(repsS, { id: LIFT, sets: 2, reps: 8, weight: 40 }, { useTarget: true }))
.toEqual([{ w: 40, r: 8, done: false }, { w: 40, r: 8, done: false }])
const timedS = {
exWeights: {},
workouts: [{ d: '2026-01-02', entries: [{ id: LIFT, target: { mode: 'time' }, sets: [{ sec: 90, w: 20, done: true }] }] }]
}
expect(buildSets(timedS, { id: LIFT, mode: 'time', sets: 2, sec: 30, weight: 5 }, { useTarget: true }))
.toEqual([{ sec: 30, w: 5, done: false }, { sec: 30, w: 5, done: false }])
const cardioS = {
exWeights: {},
workouts: [{ d: '2026-01-03', entries: [{ id: CARDIO, sets: [{ min: 45, speed: 10, done: true }] }] }]
}
expect(buildSets(cardioS, { id: CARDIO, sets: 2, min: 20, speed: 8 }, { useTarget: true }))
.toEqual([{ min: 20, speed: 8, done: false }, { min: 20, speed: 8, done: false }])
})
})
describe('applyIntensifierPlan', () => {
+29 -8
View File
@@ -61,6 +61,11 @@ export function defaultIncrement(exId, unit) {
if (unit === 'lb') return heavy ? 10 : 5
return heavy ? 5 : 2.5
}
// Resolve the load step for reps-mode weight controls and progression. Timed exercises use
// `inc` for seconds, so their optional weight column must not call this helper.
export function weightIncrement(cfg, unit) {
return cfg && cfg.inc > 0 ? cfg.inc : defaultIncrement(cfg?.id, unit)
}
export const DEFAULT_SEC_INCREMENT = 5
// Where adding another set of push-ups stops being progress and starts being a way to spend
// an evening. Past this the honest advice is load or a harder variation (issue #33).
@@ -76,18 +81,28 @@ export function policyFor(cfg, routine, mode) {
}
const round1 = v => Math.round(v * 10) / 10
// Snap to a loadable multiple of the step.
function snap(v, step) {
// Snap to a loadable multiple of the step. Manual weight controls use this same normalization
// so fractional increments produce the same number as automatic progression.
export function snapWeight(v, step) {
if (!(step > 0)) return round1(v)
return round1(Math.round(v / step) * step)
}
// A tap moves by one step. Snapping to the grid keeps the number identical to what progression
// would prescribe (61.3 → 62.5 with a 1.25 step, not 62.55) — but only when the current value
// already sits on that grid; from 62.5 with a 5 kg step a tap gives 67.5, not 70.
export function stepWeight(value, step, direction) {
const v = Number(value) || 0
const onGrid = step > 0 && Math.abs(v - Math.round(v / step) * step) <= 0.1
const next = v + direction * step
return Math.max(0, onGrid ? snapWeight(next, step) : round1(next))
}
// Back off by DELOAD_FACTOR, landing on something you can actually load. Rounding to the
// nearest step keeps the cut close to the intended 10 %, but on small weights the nearest
// step can be the weight you started from — so a deload that did not actually reduce
// anything takes one step down instead. Never goes below a single step.
function deloadTo(cur, step) {
let next = snap(cur * DELOAD_FACTOR, step)
if (next >= cur) next = snap(cur - step, step)
let next = snapWeight(cur * DELOAD_FACTOR, step)
if (next >= cur) next = snapWeight(cur - step, step)
return Math.max(step, next)
}
@@ -145,11 +160,15 @@ export function sessionsFor(S, exId, fallback) {
return out
}
// How many sessions in a row ended in a miss, counting back from the most recent.
// How many sessions in a row ended in a miss, counting back from the most recent. A change of
// weight starts a new streak, so there won't be a perpetual stall.
// Rationale: deload should reflect the failures in sessions with weight that earned it.
// Not the lighter weight that follows.
export function stallCount(sessions) {
let n = 0
for (let i = sessions.length - 1; i >= 0; i--) {
if (sessions[i].ok) break
if (i < sessions.length -1 && sessions[i].weight !== sessions[i+1].weight) break
n++
}
return n
@@ -167,7 +186,9 @@ export function nextPrescription(S, cfg, routine) {
const mode = modeOf(cfg)
const policy = policyFor(cfg, routine, mode)
const unit = S.unit || 'kg'
const inc = cfg.inc > 0 ? cfg.inc : (mode === 'time' ? DEFAULT_SEC_INCREMENT : defaultIncrement(cfg.id, unit))
const inc = mode === 'time'
? (cfg.inc > 0 ? cfg.inc : DEFAULT_SEC_INCREMENT)
: weightIncrement(cfg, unit)
if (policy === 'off') return { policy, kind: 'off' }
const sessions = sessionsFor(S, cfg.id, cfg).filter(s => s.mode === mode)
@@ -218,7 +239,7 @@ export function nextPrescription(S, cfg, routine) {
const range = normalizeRepRange(cfg.reps || last.goal || 10, cfg.repsMin, repStep(cfg))
const top = range.reps
const bottom = range.repsMin
if (last.ok) return { policy, kind: 'up', weight: snap(w + inc, inc), reps: bottom, why: ['Top of the rep range in every set — {0} {1} more, back to {2} reps.', inc, unit, bottom] }
if (last.ok) return { policy, kind: 'up', weight: snapWeight(w + inc, inc), reps: bottom, why: ['Top of the rep range in every set — {0} {1} more, back to {2} reps.', inc, unit, bottom] }
if (stalls >= deloadAt) {
const dw = deloadTo(w, inc)
return { policy, kind: 'deload', weight: dw, reps: bottom, why: ['Stalled {0} sessions — deload to {1} {2}.', stalls, dw, unit] }
@@ -234,7 +255,7 @@ export function nextPrescription(S, cfg, routine) {
const dbl = policy === 'greyskull' && last.goal > 0 && last.amrap >= last.goal * 2
const step = dbl ? inc * 2 : inc
return {
policy, kind: 'up', weight: snap(w + step, inc),
policy, kind: 'up', weight: snapWeight(w + step, inc),
why: dbl
? ['Last set hit {0} reps — twice the target, so take a double jump of {1} {2}.', last.amrap, step, unit]
: ['Every rep last time — {0} {1} more.', step, unit]
+38 -1
View File
@@ -1,7 +1,7 @@
import { describe, it, expect } from 'vitest'
import {
readSession, sessionsFor, stallCount, nextPrescription, applyPrescription,
policyFor, defaultIncrement, POLICIES_FOR, DELOAD_AFTER, MAX_BW_SETS
policyFor, defaultIncrement, weightIncrement, POLICIES_FOR, DELOAD_AFTER, MAX_BW_SETS
} from './progression.js'
import { EXDB } from './exercises.js'
@@ -103,6 +103,14 @@ describe('defaultIncrement', () => {
})
})
describe('weightIncrement', () => {
it('uses a positive exercise override and otherwise the exercise/unit default', () => {
expect(weightIncrement({ id: LIFT, inc: 1 }, 'kg')).toBe(1)
expect(weightIncrement({ id: LIFT }, 'kg')).toBe(2.5)
expect(weightIncrement({ id: HEAVY, inc: 0 }, 'kg')).toBe(5)
})
})
describe('linear progression', () => {
const cfg = { id: LIFT, sets: 3, reps: 5, weight: 60, prog: 'linear' }
@@ -142,6 +150,19 @@ describe('linear progression', () => {
expect(p.kind).toBe('hold')
})
it('a deload starts a new streak, so one miss at the new weight does not deload again', () => {
// Three misses at 60 kg earn a deload.
const stalled = [[60, 4, 4, 4], [60, 4, 4, 4], [60, 4, 4, 4]]
const deload = nextPrescription(hist(LIFT, stalled), cfg)
expect(deload.kind).toBe('deload')
// A bad day at the lighter weight is the first miss of a new run, not the fourth of the old
// one. A deload is owed a fresh set of attempts, not an immediate second cut.
const next = nextPrescription(hist(LIFT, [...stalled, [deload.weight, 4, 4, 4]]), cfg)
expect(next.kind).toBe('hold')
expect(next.weight).toBe(deload.weight)
})
it('never deloads below one increment, however light the lift already is', () => {
const p = nextPrescription(hist(LIFT, [[2.5, 1, 1, 1], [2.5, 1, 1, 1], [2.5, 1, 1, 1]]), cfg)
expect(p.kind).toBe('deload')
@@ -292,6 +313,22 @@ describe('double progression', () => {
expect(p.reps).toBe(8)
})
it('does not deload again when the deload was performed exactly as prescribed', () => {
const target = { sets: 3, reps: 12 }
// Three sessions stuck mid-range where every set misses the top, so a deload falls due (see DELOAD_POLICY)
const stalled = [[40, 9, 9, 9], [40, 9, 9, 9], [40, 9, 9, 9]]
const deload = nextPrescription(hist(LIFT, stalled, target), cfg)
expect(deload.kind).toBe('deload')
// Training exactly what it asked for: its weight, its reps, every set checked off.
const asPrescribed = [deload.weight, ...Array(target.sets).fill(deload.reps)]
const next = nextPrescription(hist(LIFT, [...stalled, asPrescribed], target), cfg)
// Complying with the app's own prescription must not be scored as another failure.
expect(next.kind).not.toBe('deload')
expect(next.weight).toBeGreaterThanOrEqual(deload.weight)
})
it('keeps the weight and asks for one more rep while inside the range', () => {
const p = nextPrescription(hist(LIFT, [[40, 10, 9, 9]], { sets: 3, reps: 12 }), cfg)
expect(p.kind).toBe('hold')
+4 -4
View File
@@ -27,11 +27,11 @@ describe('Brazilian Portuguese locale', () => {
.sort(byCodeUnit)
const fingerprint = createHash('sha256').update(JSON.stringify(inherited)).digest('hex')
expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(603)
expect(inherited).toHaveLength(565)
expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(612)
expect(inherited).toHaveLength(583)
// If this fails, review the changed keys and wording before accepting a new hash. From
// frontend/: node scripts/pt-br-inheritance-fingerprint.mjs --list
expect(fingerprint, 'pt-PT inheritance changed; review the inherited pt-BR wording').toBe('e6addc025574b25e392121fe543012a189116d8cb9c91fe5e96caeb3c3e450f2')
expect(fingerprint, 'pt-PT inheritance changed; review the inherited pt-BR wording').toBe('c7ddbc412a3e758704289b4414372f2cbc0e26be4c0a0d95676cb3316ecae85a')
})
test('does not leak European Portuguese UI terms', () => {
@@ -49,6 +49,6 @@ describe('Brazilian Portuguese locale', () => {
expect(ptBR['resistance band']).toBe('faixa elástica')
expect(ptBR.soleus).toBe('sóleo')
expect(ptBR.Unpair).toBe('Desvincular')
expect(ptBR['Starter plan loaded — Mon Push · Wed Pull · Fri Legs']).toContain('Seg Push · Qua Pull')
expect(ptBR['Choose starter plan']).toBe('Escolha um plano inicial')
})
})
+12
View File
@@ -0,0 +1,12 @@
import { uid } from './format.js'
/**
* Create a deep copy of a routine with a new id and a "(Copy)" suffix.
* All exercises and their configuration are preserved independently.
*/
export function copyRoutine(routine, suffix = 'Copy') {
const copy = structuredClone(routine)
copy.id = uid()
copy.name = routine.name + ' (' + suffix + ')'
return copy
}
+79
View File
@@ -0,0 +1,79 @@
import { describe, it, expect } from 'vitest'
import { copyRoutine } from './routines.js'
const routine = {
id: 'r1',
name: 'Push Day',
emoji: 'arm',
prog: 'linear',
ex: [
{ id: 'ex1', sets: 3, reps: 10, weight: 60, sg: 'sg1' },
{ id: 'ex2', sets: 4, reps: 8, weight: 80, sg: 'sg1' },
{ id: 'ex3', sets: 3, reps: 12, weight: 20 }
]
}
describe('copyRoutine', () => {
it('returns a new routine with a different id', () => {
const copy = copyRoutine(routine)
expect(copy.id).not.toBe(routine.id)
expect(copy.id).toBeTruthy()
})
it('appends "(Copy)" to the name by default', () => {
const copy = copyRoutine(routine)
expect(copy.name).toBe('Push Day (Copy)')
})
it('uses a custom suffix when provided', () => {
const copy = copyRoutine(routine, 'Kopie')
expect(copy.name).toBe('Push Day (Kopie)')
})
it('deep-copies all exercises with their configuration', () => {
const copy = copyRoutine(routine)
expect(copy.ex).toHaveLength(3)
expect(copy.ex[0]).toEqual(routine.ex[0])
expect(copy.ex[1]).toEqual(routine.ex[1])
expect(copy.ex[2]).toEqual(routine.ex[2])
})
it('preserves exercise ids (references to the global library)', () => {
const copy = copyRoutine(routine)
expect(copy.ex[0].id).toBe('ex1')
expect(copy.ex[1].id).toBe('ex2')
expect(copy.ex[2].id).toBe('ex3')
})
it('preserves superset groupings', () => {
const copy = copyRoutine(routine)
expect(copy.ex[0].sg).toBe('sg1')
expect(copy.ex[1].sg).toBe('sg1')
expect(copy.ex[2].sg).toBeUndefined()
})
it('preserves the emoji and progression settings', () => {
const copy = copyRoutine(routine)
expect(copy.emoji).toBe('arm')
expect(copy.prog).toBe('linear')
})
it('produces an independent copy — mutating it does not affect the original', () => {
const copy = copyRoutine(routine)
copy.name = 'Modified'
copy.ex[0].weight = 999
copy.ex.push({ id: 'ex4', sets: 5, reps: 5 })
expect(routine.name).toBe('Push Day')
expect(routine.ex[0].weight).toBe(60)
expect(routine.ex).toHaveLength(3)
})
it('handles a routine with no exercises', () => {
const empty = { id: 'r2', name: 'Empty', emoji: 'dumbbell', ex: [] }
const copy = copyRoutine(empty)
expect(copy.ex).toEqual([])
expect(copy.name).toBe('Empty (Copy)')
expect(copy.id).not.toBe('r2')
})
})
+1 -1
View File
@@ -14,7 +14,7 @@ export function buildSessionEntries(st, r) {
const entries = (r ? r.ex : []).map(cfg => {
const plan = excluded ? { policy: 'off', kind: 'off' } : nextPrescription(st, cfg, r)
const step = defaultIncrement(cfg.id, st.unit)
const sets = applyIntensifierPlan(applyPrescription(buildSets(st, cfg, { step, useTarget: excluded }), plan, step), cfg)
const sets = applyIntensifierPlan(applyPrescription(buildSets(st, cfg, { step, useTarget: plan.kind === 'off' }), plan, step), cfg)
return { id: cfg.id, sg: cfg.sg, target: { ...cfg }, plan, sets }
})
return { entries, excluded }
+64 -9
View File
@@ -1,13 +1,68 @@
// The Push/Pull/Legs starter plan. Shared by the "Load starter plan" action in Settings
// and by the demo build, which seeds a history on top of exactly these routines.
// The starter-plan catalog. Training data only: the chooser's plan names and descriptions are
// written as string literals inside t() calls in sheets.jsx, because check-source-strings.mjs
// only finds them there — copy parked in here would silently ship English in every language.
//
// A routine is [key, name, emoji, [[exerciseId, sets, reps], …]]. The key is what a plan's
// schedule points at, so a weekday never depends on the position of a routine in the array.
// Names stay canonical English — they become ordinary user routines, which are not translated.
import { uid } from './format.js'
const SPEC = [
['Push Day', 'barbell', [['0025', 4, 8], ['0047', 3, 10], ['0426', 3, 10], ['0334', 3, 12], ['0241', 3, 12], ['0251', 3, 10]]],
['Pull Day', 'pullup', [['2330', 4, 10], ['0027', 4, 8], ['1323', 3, 10], ['0031', 3, 10], ['0313', 3, 12]]],
['Leg Day', 'legs', [['0043', 4, 8], ['0085', 3, 10], ['0739', 3, 12], ['0585', 3, 12], ['0586', 3, 12], ['0605', 4, 15]]]
const PPL = [
['push', 'Push Day', 'barbell', [['0025', 4, 8], ['0047', 3, 10], ['0426', 3, 10], ['0334', 3, 12], ['0241', 3, 12], ['0251', 3, 10]]],
['pull', 'Pull Day', 'pullup', [['2330', 4, 10], ['0027', 4, 8], ['1323', 3, 10], ['0031', 3, 10], ['0313', 3, 12]]],
['legs', 'Leg Day', 'legs', [['0043', 4, 8], ['0085', 3, 10], ['0739', 3, 12], ['0585', 3, 12], ['0586', 3, 12], ['0605', 4, 15]]]
]
// Fresh routine objects (new ids) — [push, pull, legs].
export const starterRoutines = () =>
SPEC.map(([name, emoji, list]) => ({ id: uid(), name, emoji, ex: list.map(([id, sets, reps]) => ({ id, sets, reps, weight: 0 })) }))
const UPPER_LOWER = [
['upper-a', 'Upper A', 'barbell', [['0025', 3, 8], ['2330', 3, 10], ['0047', 2, 10], ['1323', 2, 10], ['0334', 2, 12], ['0241', 2, 12], ['0031', 2, 12]]],
['lower-a', 'Lower A', 'legs', [['0043', 3, 8], ['0085', 3, 8], ['0739', 2, 10], ['0586', 2, 12], ['0605', 3, 15]]],
['upper-b', 'Upper B', 'barbell', [['0047', 3, 8], ['0027', 3, 8], ['0426', 2, 10], ['2330', 2, 10], ['0334', 2, 12], ['0241', 2, 12], ['0313', 2, 12]]],
['lower-b', 'Lower B', 'legs', [['0739', 3, 10], ['0085', 2, 10], ['0585', 2, 12], ['0586', 3, 12], ['0605', 3, 15]]]
]
const FULL_BODY = [
['fb-a', 'Full Body A', 'figureStrength', [['0043', 3, 8], ['0025', 3, 8], ['2330', 3, 10], ['0586', 3, 12], ['0334', 2, 12], ['0031', 2, 12]]],
['fb-b', 'Full Body B', 'figureStrength', [['0085', 3, 8], ['0047', 3, 10], ['1323', 3, 10], ['0585', 3, 12], ['0334', 2, 12], ['0241', 2, 12]]],
['fb-c', 'Full Body C', 'figureStrength', [['0739', 3, 10], ['0025', 2, 10], ['0027', 3, 10], ['0426', 2, 10], ['0586', 3, 12], ['0605', 3, 15]]]
]
const FIVE_BY_FIVE = [
['5x5-a', '5×5 A', 'barbell', [['0043', 5, 5], ['0025', 5, 5], ['0027', 5, 5]]],
['5x5-b', '5×5 B', 'barbell', [['0085', 5, 5], ['0426', 5, 5], ['2330', 5, 5]]],
['5x5-c', '5×5 C', 'barbell', [['0739', 5, 5], ['0047', 5, 5], ['1323', 5, 5]]]
]
// [weekday, routineKey] — weekday is a DAYN index, so 1 is Monday. Fixed weeks only: every
// plan repeats the same seven days, which is all the weekly plan model can represent.
const PLANS = {
ppl: { routines: PPL, schedule: [[1, 'push'], [3, 'pull'], [5, 'legs']] },
'upper-lower': { routines: UPPER_LOWER, schedule: [[1, 'upper-a'], [2, 'lower-a'], [4, 'upper-b'], [5, 'lower-b']] },
'full-body': { routines: FULL_BODY, schedule: [[1, 'fb-a'], [3, 'fb-b'], [5, 'fb-c']] },
'5x5': { routines: FIVE_BY_FIVE, schedule: [[1, '5x5-a'], [3, '5x5-b'], [5, '5x5-c']] }
}
const build = routines =>
routines.map(([, name, emoji, list]) => ({ id: uid(), name, emoji, ex: list.map(([id, sets, reps]) => ({ id, sets, reps, weight: 0 })) }))
// Fresh routine objects (new ids) — [push, pull, legs]. The demo build seeds a history on
// top of exactly these three, so this entry point keeps its shape.
export const starterRoutines = () => build(PPL)
// [{ id, days }] for the chooser. The day count is read off the schedule rather than stored
// beside it, so the two can never disagree.
export const starterPlanOptions = () =>
Object.entries(PLANS).map(([id, { schedule }]) => ({ id, days: schedule.length }))
// The weekdays a plan would claim, or null for an unknown id.
export const starterPlanDays = id => PLANS[id]?.schedule.map(([day]) => day) ?? null
// Fresh routines plus the weekdays to put them on, or null for an unknown id — a caller that
// treats null as "change nothing" can never half-apply a plan.
export const buildStarterPlan = id => {
const plan = PLANS[id]
if (!plan) return null
const routines = build(plan.routines)
// key → the id just minted for it, so the schedule below names its routine
const byKey = Object.fromEntries(plan.routines.map(([key], i) => [key, routines[i].id]))
return { routines, schedule: plan.schedule.map(([day, key]) => ({ day, routineId: byKey[key] })) }
}
+104
View File
@@ -0,0 +1,104 @@
import { describe, expect, it } from 'vitest'
import { EXIDX } from './exercises.js'
import { buildStarterPlan, starterPlanDays, starterPlanOptions, starterRoutines } from './starter.js'
// The approved prescription, written out again rather than imported: a test that reads the
// same table as the code would pass no matter what that table said. [weekday, name, sets].
const APPROVED = {
ppl: [
[1, 'Push Day', [['0025', 4, 8], ['0047', 3, 10], ['0426', 3, 10], ['0334', 3, 12], ['0241', 3, 12], ['0251', 3, 10]]],
[3, 'Pull Day', [['2330', 4, 10], ['0027', 4, 8], ['1323', 3, 10], ['0031', 3, 10], ['0313', 3, 12]]],
[5, 'Leg Day', [['0043', 4, 8], ['0085', 3, 10], ['0739', 3, 12], ['0585', 3, 12], ['0586', 3, 12], ['0605', 4, 15]]],
],
'upper-lower': [
[1, 'Upper A', [['0025', 3, 8], ['2330', 3, 10], ['0047', 2, 10], ['1323', 2, 10], ['0334', 2, 12], ['0241', 2, 12], ['0031', 2, 12]]],
[2, 'Lower A', [['0043', 3, 8], ['0085', 3, 8], ['0739', 2, 10], ['0586', 2, 12], ['0605', 3, 15]]],
[4, 'Upper B', [['0047', 3, 8], ['0027', 3, 8], ['0426', 2, 10], ['2330', 2, 10], ['0334', 2, 12], ['0241', 2, 12], ['0313', 2, 12]]],
[5, 'Lower B', [['0739', 3, 10], ['0085', 2, 10], ['0585', 2, 12], ['0586', 3, 12], ['0605', 3, 15]]],
],
'full-body': [
[1, 'Full Body A', [['0043', 3, 8], ['0025', 3, 8], ['2330', 3, 10], ['0586', 3, 12], ['0334', 2, 12], ['0031', 2, 12]]],
[3, 'Full Body B', [['0085', 3, 8], ['0047', 3, 10], ['1323', 3, 10], ['0585', 3, 12], ['0334', 2, 12], ['0241', 2, 12]]],
[5, 'Full Body C', [['0739', 3, 10], ['0025', 2, 10], ['0027', 3, 10], ['0426', 2, 10], ['0586', 3, 12], ['0605', 3, 15]]],
],
'5x5': [
[1, '5×5 A', [['0043', 5, 5], ['0025', 5, 5], ['0027', 5, 5]]],
[3, '5×5 B', [['0085', 5, 5], ['0426', 5, 5], ['2330', 5, 5]]],
[5, '5×5 C', [['0739', 5, 5], ['0047', 5, 5], ['1323', 5, 5]]],
],
}
const shape = r => r.ex.map(e => [e.id, e.sets, e.reps])
describe('starter plan catalog', () => {
it('offers exactly the four plans, with the day count read off the schedule', () => {
expect(starterPlanOptions()).toEqual([
{ id: 'ppl', days: 3 }, { id: 'upper-lower', days: 4 },
{ id: 'full-body', days: 3 }, { id: '5x5', days: 3 },
])
for (const { id, days } of starterPlanOptions()) expect(starterPlanDays(id)).toHaveLength(days)
})
it('changes nothing for an unknown plan id', () => {
expect(buildStarterPlan('nope')).toBeNull()
expect(buildStarterPlan(undefined)).toBeNull()
// A click handler wired straight to a loader would hand the event in as the plan.
expect(buildStarterPlan({ type: 'click' })).toBeNull()
expect(starterPlanDays('nope')).toBeNull()
})
})
describe.each(Object.keys(APPROVED))('%s', planId => {
const approved = APPROVED[planId]
it('builds the approved exercises, sets and reps in order', () => {
const { routines } = buildStarterPlan(planId)
expect(routines.map(r => r.name)).toEqual(approved.map(([, name]) => name))
routines.forEach((r, i) => expect(shape(r)).toEqual(approved[i][2]))
})
it('puts each routine on its approved weekday, by identity not position', () => {
const { routines, schedule } = buildStarterPlan(planId)
const nameOf = Object.fromEntries(routines.map(r => [r.id, r.name]))
expect(schedule.map(({ day, routineId }) => [day, nameOf[routineId]]))
.toEqual(approved.map(([day, name]) => [day, name]))
})
it('references only real exercises and starts every one at weight 0', () => {
for (const r of buildStarterPlan(planId).routines) {
for (const e of r.ex) {
expect(EXIDX[e.id], e.id).toBeTruthy()
expect(e.sets).toBeGreaterThan(0)
expect(e.reps).toBeGreaterThan(0)
expect(e.weight).toBe(0)
}
}
})
it('mints fresh ids and independent objects on every build', () => {
const first = buildStarterPlan(planId)
const second = buildStarterPlan(planId)
const ids = first.routines.map(r => r.id)
expect(new Set(ids).size).toBe(ids.length)
expect(second.routines.some(r => ids.includes(r.id))).toBe(false)
expect(first.routines[0].ex[0]).not.toBe(second.routines[0].ex[0])
// and the static definition survives a caller mutating what it got back
first.routines[0].ex[0].sets = 99
expect(buildStarterPlan(planId).routines[0].ex[0].sets).toBe(approved[0][2][0][1])
})
})
describe('starterRoutines (the demo build entry point)', () => {
it('still returns push, pull and legs unchanged', () => {
const routines = starterRoutines()
expect(routines.map(r => r.name)).toEqual(['Push Day', 'Pull Day', 'Leg Day'])
routines.forEach((r, i) => expect(shape(r)).toEqual(APPROVED.ppl[i][2]))
expect(routines.map(r => r.emoji)).toEqual(['barbell', 'pullup', 'legs'])
})
it('mints fresh ids on every invocation', () => {
const first = starterRoutines().map(r => r.id)
const second = starterRoutines().map(r => r.id)
expect(new Set([...first, ...second]).size).toBe(6)
})
})
+31 -4
View File
@@ -24,6 +24,13 @@ export default {
'Resume': 'Weiter',
'Stats': 'Statistik',
'Exercises': 'Übungen',
'By muscle': 'Nach Muskel',
'Explore muscles': 'Muskeln entdecken',
'Choose a muscle to see exercises that train it.': 'Wähle einen Muskel, um Übungen zu sehen, die ihn trainieren.',
'Exercises for {0}': 'Übungen für {0}',
'Clear selection': 'Auswahl aufheben',
'Primary target': 'Hauptmuskel',
'Also trains': 'Trainiert auch',
'History': 'Verlauf',
'Settings': 'Einstellungen',
'Freestyle': 'Freies Training',
@@ -210,8 +217,22 @@ export default {
'{0} — in progress': '{0} — läuft',
'Resume ▶': 'Weiter ▶',
'Welcome!': 'Willkommen!',
'Set up your weekly routine to get going — or load a ready-made Push / Pull / Legs plan.': 'Richte deinen Wochenplan ein — oder lade einen fertigen Push-/Pull-/Beine-Plan.',
'Load starter plan (PPL)': 'Starterplan laden (PPL)',
'Set up your weekly routine to get going — or load a ready-made starter plan.': 'Richte deinen Wochenplan ein — oder lade einen fertigen Starterplan.',
'Load starter plan': 'Starterplan laden',
'Choose starter plan': 'Starterplan wählen',
'{0} days per week': '{0} Tage pro Woche',
'{0} loaded': '{0} geladen',
'Load {0}?': '{0} laden?',
'Load plan': 'Plan laden',
'The new plan will be scheduled on {0}. Existing routines are kept — only those days of the weekly plan change.': 'Der neue Plan kommt auf {0}. Deine Routinen bleiben alle erhalten — nur diese Tage im Wochenplan ändern sich.',
'Push / Pull / Legs': 'Push / Pull / Beine',
'Push, pull and legs each get their own day.': 'Drücken, Ziehen und Beine an je eigenen Tagen.',
'Upper / Lower': 'Oberkörper / Unterkörper',
'Upper body twice, lower body twice.': 'Oberkörper zweimal, Unterkörper zweimal.',
'Full Body': 'Ganzkörper',
'Three sessions, the whole body each time.': 'Drei Einheiten, jedes Mal der ganze Körper.',
'5×5': '5×5',
'Five sets of five on the main barbell lifts.': 'Fünf Sätze à fünf bei den großen Langhantelübungen.',
'Build my own plan': 'Eigenen Plan erstellen',
'{0} week streak': '{0} Wochen in Folge',
'this week': 'diese Woche',
@@ -238,7 +259,6 @@ export default {
'Week schedule': 'Wochenplan',
'No routines yet.': 'Noch keine Routinen.',
'Create one or load the starter plan.': 'Erstelle eine oder lade den Starterplan.',
'Load starter plan (Push / Pull / Legs)': 'Starterplan laden (Push / Pull / Beine)',
// --- routine edit ---
'Superset with exercise above': 'Supersatz mit der Übung darüber',
'Note (optional) — loading cues, "bar only then +1 plate/side each set", anything worth remembering here': 'Notiz (optional) — Hinweise zur Belastung, z. B. „nur die Stange, dann pro Satz +1 Scheibe pro Seite“, was immer du dir merken willst',
@@ -247,11 +267,12 @@ export default {
'Delete routine?': 'Routine löschen?',
'“{0}” and its exercises will be removed.': '„{0}“ und ihre Übungen werden entfernt.',
'Delete routine': 'Routine löschen',
'Copy routine': 'Routine kopieren',
'Copy': 'Kopie',
// --- library / history ---
'{0} exercises with animations': '{0} Übungen mit Animationen',
'Search…': 'Suchen…',
'No workouts yet.': 'Noch keine Trainings.',
'Starter plan loaded — Mon Push · Wed Pull · Fri Legs': 'Starterplan geladen — Mo Push · Mi Pull · Fr Beine',
// --- login / account ---
'Enter a name': 'Gib einen Namen ein',
'Profile created — data from this device moved into it': 'Profil erstellt — Daten von diesem Gerät wurden übernommen',
@@ -412,6 +433,12 @@ export default {
'Minimize': 'Verkleinern',
'Expand': 'Vergrössern',
'Exercise animations': 'Übungs-Animationen',
'Workout view': 'Trainingsansicht',
'Cards': 'Karten',
'List': 'Liste',
'Current': 'Aktuell',
'Set current': 'Als aktuell markieren',
'Move, swap and remove below act on the exercise marked {0}.': 'Verschieben, Tauschen und Entfernen unten wirken auf die als {0} markierte Übung.',
'Full': 'Gross',
'Small': 'Klein',
'Hidden': 'Versteckt',
+31 -4
View File
@@ -23,6 +23,13 @@ export default {
'Resume': 'Seguir',
'Stats': 'Progreso',
'Exercises': 'Ejercicios',
'By muscle': 'Por músculo',
'Explore muscles': 'Explorar músculos',
'Choose a muscle to see exercises that train it.': 'Elige un músculo para ver los ejercicios que lo entrenan.',
'Exercises for {0}': 'Ejercicios para {0}',
'Clear selection': 'Borrar selección',
'Primary target': 'Músculo principal',
'Also trains': 'También trabaja',
'History': 'Historial',
'Settings': 'Ajustes',
'Freestyle': 'Libre',
@@ -202,8 +209,22 @@ export default {
'{0} — in progress': '{0} — en curso',
'Resume ▶': 'Seguir ▶',
'Welcome!': '¡Bienvenido!',
'Set up your weekly routine to get going — or load a ready-made Push / Pull / Legs plan.': 'Configura tu rutina semanal para empezar — o carga un plan Push / Pull / Piernas ya hecho.',
'Load starter plan (PPL)': 'Cargar plan inicial (PPL)',
'Set up your weekly routine to get going — or load a ready-made starter plan.': 'Configura tu rutina semanal para empezar — o carga un plan inicial ya hecho.',
'Load starter plan': 'Cargar plan inicial',
'Choose starter plan': 'Elige un plan inicial',
'{0} days per week': '{0} días por semana',
'{0} loaded': '{0} cargado',
'Load {0}?': '¿Cargar {0}?',
'Load plan': 'Cargar plan',
'The new plan will be scheduled on {0}. Existing routines are kept — only those days of the weekly plan change.': 'El nuevo plan se programará en {0}. Tus rutinas se conservan — solo cambian esos días del plan semanal.',
'Push / Pull / Legs': 'Push / Pull / Piernas',
'Push, pull and legs each get their own day.': 'Empuje, tirón y piernas, cada uno en su día.',
'Upper / Lower': 'Superior / Inferior',
'Upper body twice, lower body twice.': 'Tren superior dos veces, tren inferior dos veces.',
'Full Body': 'Cuerpo completo',
'Three sessions, the whole body each time.': 'Tres sesiones, todo el cuerpo en cada una.',
'5×5': '5×5',
'Five sets of five on the main barbell lifts.': 'Cinco series de cinco en los básicos con barra.',
'Build my own plan': 'Crear mi propio plan',
'{0} week streak': 'racha de {0} semanas',
'this week': 'esta semana',
@@ -228,7 +249,6 @@ export default {
'Week schedule': 'Horario semanal',
'No routines yet.': 'Aún no hay rutinas.',
'Create one or load the starter plan.': 'Crea una o carga el plan inicial.',
'Load starter plan (Push / Pull / Legs)': 'Cargar plan inicial (Push / Pull / Piernas)',
'Superset with exercise above': 'Superserie con el ejercicio de arriba',
'Note (optional) — loading cues, "bar only then +1 plate/side each set", anything worth remembering here': 'Nota (opcional) — indicaciones de carga, ej. «solo barra y +1 disco por lado en cada serie», lo que quieras recordar',
'No exercises yet — add your first one.': 'Aún no hay ejercicios — añade el primero.',
@@ -236,10 +256,11 @@ export default {
'Delete routine?': '¿Eliminar rutina?',
'“{0}” and its exercises will be removed.': '«{0}» y sus ejercicios se eliminarán.',
'Delete routine': 'Eliminar rutina',
'Copy routine': 'Copiar rutina',
'Copy': 'Copia',
'{0} exercises with animations': '{0} ejercicios con animaciones',
'Search…': 'Buscar…',
'No workouts yet.': 'Aún no hay entrenamientos.',
'Starter plan loaded — Mon Push · Wed Pull · Fri Legs': 'Plan inicial cargado — Lun Push · Mié Pull · Vie Piernas',
'Enter a name': 'Introduce un nombre',
'Profile created — data from this device moved into it': 'Perfil creado — los datos de este dispositivo se han movido a él',
'Profile created — data moved into it': 'Perfil creado — datos movidos a él',
@@ -394,6 +415,12 @@ export default {
'Minimize': 'Minimizar',
'Expand': 'Ampliar',
'Exercise animations': 'Animaciones de los ejercicios',
'Workout view': 'Vista del entrenamiento',
'Cards': 'Tarjetas',
'List': 'Lista',
'Current': 'Actual',
'Set current': 'Marcar actual',
'Move, swap and remove below act on the exercise marked {0}.': 'Mover, cambiar y eliminar actúan sobre el ejercicio marcado como {0}.',
'Full': 'Completa',
'Small': 'Pequeña',
'Hidden': 'Oculta',
+31 -4
View File
@@ -23,6 +23,13 @@ export default {
'Resume': 'Reprendre',
'Stats': 'Stats',
'Exercises': 'Exercices',
'By muscle': 'Par muscle',
'Explore muscles': 'Explorer les muscles',
'Choose a muscle to see exercises that train it.': 'Choisissez un muscle pour voir les exercices qui le sollicitent.',
'Exercises for {0}': 'Exercices pour {0}',
'Clear selection': 'Effacer la sélection',
'Primary target': 'Cible principale',
'Also trains': 'Sollicite aussi',
'History': 'Historique',
'Settings': 'Réglages',
'Freestyle': 'Libre',
@@ -202,8 +209,22 @@ export default {
'{0} — in progress': '{0} — en cours',
'Resume ▶': 'Reprendre ▶',
'Welcome!': 'Bienvenue !',
'Set up your weekly routine to get going — or load a ready-made Push / Pull / Legs plan.': 'Configure ta routine hebdo pour commencer — ou charge un plan Push / Pull / Jambes tout prêt.',
'Load starter plan (PPL)': 'Charger le plan de départ (PPL)',
'Set up your weekly routine to get going — or load a ready-made starter plan.': 'Configure ta routine hebdo pour commencer — ou charge un plan de départ tout prêt.',
'Load starter plan': 'Charger un plan de départ',
'Choose starter plan': 'Choisis un plan de départ',
'{0} days per week': '{0} jours par semaine',
'{0} loaded': '{0} chargé',
'Load {0}?': 'Charger {0} ?',
'Load plan': 'Charger le plan',
'The new plan will be scheduled on {0}. Existing routines are kept — only those days of the weekly plan change.': 'Le nouveau plan sera placé sur {0}. Tes routines sont toutes conservées — seuls ces jours du plan hebdo changent.',
'Push / Pull / Legs': 'Push / Pull / Jambes',
'Push, pull and legs each get their own day.': 'Poussée, tirage et jambes, chacun son jour.',
'Upper / Lower': 'Haut / Bas',
'Upper body twice, lower body twice.': 'Haut du corps deux fois, bas du corps deux fois.',
'Full Body': 'Corps entier',
'Three sessions, the whole body each time.': 'Trois séances, tout le corps à chaque fois.',
'5×5': '5×5',
'Five sets of five on the main barbell lifts.': 'Cinq séries de cinq sur les gros mouvements à la barre.',
'Build my own plan': 'Créer mon propre plan',
'{0} week streak': 'série de {0} semaines',
'this week': 'cette semaine',
@@ -228,7 +249,6 @@ export default {
'Week schedule': 'Planning de la semaine',
'No routines yet.': 'Aucune routine pour l’instant.',
'Create one or load the starter plan.': 'Crées-en une ou charge le plan de départ.',
'Load starter plan (Push / Pull / Legs)': 'Charger le plan de départ (Push / Pull / Jambes)',
'Superset with exercise above': "Superset avec l'exercice au-dessus",
'Note (optional) — loading cues, "bar only then +1 plate/side each set", anything worth remembering here': 'Note (optionnelle) — indications de charge, ex. « barre seule puis +1 disque par côté à chaque série », tout ce que tu veux te rappeler',
'No exercises yet — add your first one.': 'Aucun exercice — ajoute le premier.',
@@ -236,10 +256,11 @@ export default {
'Delete routine?': 'Supprimer la routine ?',
'“{0}” and its exercises will be removed.': '« {0} » et ses exercices seront supprimés.',
'Delete routine': 'Supprimer la routine',
'Copy routine': 'Copier la routine',
'Copy': 'Copie',
'{0} exercises with animations': '{0} exercices avec animations',
'Search…': 'Rechercher…',
'No workouts yet.': 'Aucune séance pour l’instant.',
'Starter plan loaded — Mon Push · Wed Pull · Fri Legs': 'Plan de départ chargé — Lun Push · Mer Pull · Ven Jambes',
'Enter a name': 'Entre un nom',
'Profile created — data from this device moved into it': 'Profil créé — les données de cet appareil y ont été transférées',
'Profile created — data moved into it': 'Profil créé — données transférées',
@@ -394,6 +415,12 @@ export default {
'Minimize': 'Réduire',
'Expand': 'Agrandir',
'Exercise animations': 'Animations des exercices',
'Workout view': 'Vue de l’entraînement',
'Cards': 'Cartes',
'List': 'Liste',
'Current': 'En cours',
'Set current': 'Marquer comme en cours',
'Move, swap and remove below act on the exercise marked {0}.': 'Déplacer, échanger et supprimer ci-dessous s’appliquent à l’exercice marqué {0}.',
'Full': 'Grande',
'Small': 'Petite',
'Hidden': 'Masquée',
+31 -4
View File
@@ -23,6 +23,13 @@ export default {
'Resume': 'जारी रखें',
'Stats': 'आँकड़े',
'Exercises': 'व्यायाम',
'By muscle': 'मांसपेशी से',
'Explore muscles': 'मांसपेशियाँ खोजें',
'Choose a muscle to see exercises that train it.': 'उस मांसपेशी को प्रशिक्षित करने वाले व्यायाम देखने के लिए एक मांसपेशी चुनें।',
'Exercises for {0}': '{0} के लिए व्यायाम',
'Clear selection': 'चयन साफ़ करें',
'Primary target': 'मुख्य लक्ष्य',
'Also trains': 'यह भी प्रशिक्षित करता है',
'History': 'इतिहास',
'Settings': 'सेटिंग्स',
'Freestyle': 'फ्रीस्टाइल',
@@ -202,8 +209,22 @@ export default {
'{0} — in progress': '{0} — चल रहा है',
'Resume ▶': 'जारी रखें ▶',
'Welcome!': 'स्वागत है!',
'Set up your weekly routine to get going — or load a ready-made Push / Pull / Legs plan.': 'शुरू करने के लिए अपना साप्ताहिक रूटीन बनाएँ — या बना-बनाया पुश / पुल / लेग्स प्लान लोड करें।',
'Load starter plan (PPL)': 'स्टार्टर प्लान लोड करें (PPL)',
'Set up your weekly routine to get going — or load a ready-made starter plan.': 'शुरू करने के लिए अपना साप्ताहिक रूटीन बनाएँ — या बना-बनाया स्टार्टर प्लान लोड करें।',
'Load starter plan': 'स्टार्टर प्लान लोड करें',
'Choose starter plan': 'स्टार्टर प्लान चुनें',
'{0} days per week': 'हफ़्ते में {0} दिन',
'{0} loaded': '{0} लोड हुआ',
'Load {0}?': '{0} लोड करें?',
'Load plan': 'प्लान लोड करें',
'The new plan will be scheduled on {0}. Existing routines are kept — only those days of the weekly plan change.': 'नया प्लान {0} पर लगेगा। आपकी सभी रूटीन बनी रहेंगी — साप्ताहिक प्लान में सिर्फ़ ये दिन बदलेंगे।',
'Push / Pull / Legs': 'पुश / पुल / लेग्स',
'Push, pull and legs each get their own day.': 'पुश, पुल और लेग्स, हर एक का अपना दिन।',
'Upper / Lower': 'ऊपरी / निचला',
'Upper body twice, lower body twice.': 'ऊपरी शरीर दो बार, निचला शरीर दो बार।',
'Full Body': 'फ़ुल बॉडी',
'Three sessions, the whole body each time.': 'तीन सेशन, हर बार पूरा शरीर।',
'5×5': '5×5',
'Five sets of five on the main barbell lifts.': 'मुख्य बारबेल लिफ़्ट पर पाँच सेट, पाँच रेप।',
'Build my own plan': 'अपनी योजना बनाएँ',
'{0} week streak': '{0} हफ़्तों की स्ट्रीक',
'this week': 'इस हफ़्ते',
@@ -228,7 +249,6 @@ export default {
'Week schedule': 'हफ़्ते का कार्यक्रम',
'No routines yet.': 'अभी कोई रूटीन नहीं।',
'Create one or load the starter plan.': 'एक बनाएँ या स्टार्टर प्लान लोड करें।',
'Load starter plan (Push / Pull / Legs)': 'स्टार्टर प्लान लोड करें (पुश / पुल / लेग्स)',
'Superset with exercise above': 'ऊपर वाले व्यायाम के साथ सुपरसेट',
'Note (optional) — loading cues, "bar only then +1 plate/side each set", anything worth remembering here': 'नोट (वैकल्पिक) — लोडिंग संकेत, जैसे "सिर्फ़ खाली बार, फिर हर सेट में हर तरफ़ +1 प्लेट", जो भी याद रखना चाहें',
'No exercises yet — add your first one.': 'अभी कोई व्यायाम नहीं — पहला जोड़ें।',
@@ -236,10 +256,11 @@ export default {
'Delete routine?': 'रूटीन हटाएँ?',
'“{0}” and its exercises will be removed.': '"{0}" और उसके व्यायाम हटा दिए जाएँगे।',
'Delete routine': 'रूटीन हटाएँ',
'Copy routine': 'रूटीन कॉपी करें',
'Copy': 'कॉपी',
'{0} exercises with animations': 'एनिमेशन के साथ {0} व्यायाम',
'Search…': 'खोजें…',
'No workouts yet.': 'अभी कोई वर्कआउट नहीं।',
'Starter plan loaded — Mon Push · Wed Pull · Fri Legs': 'स्टार्टर प्लान लोड हुआ — सोम पुश · बुध पुल · शुक्र लेग्स',
'Enter a name': 'नाम दर्ज करें',
'Profile created — data from this device moved into it': 'प्रोफ़ाइल बनी — इस डिवाइस का डेटा उसमें चला गया',
'Profile created — data moved into it': 'प्रोफ़ाइल बनी — डेटा स्थानांतरित',
@@ -394,6 +415,12 @@ export default {
'Minimize': 'छोटा करें',
'Expand': 'बड़ा करें',
'Exercise animations': 'व्यायाम एनिमेशन',
'Workout view': 'वर्कआउट दृश्य',
'Cards': 'कार्ड',
'List': 'सूची',
'Current': 'वर्तमान',
'Set current': 'वर्तमान के रूप में चिह्नित करें',
'Move, swap and remove below act on the exercise marked {0}.': 'नीचे दिए गए मूव, स्वैप और रिमूव {0} के रूप में चिह्नित व्यायाम पर लागू होते हैं।',
'Full': 'पूर्ण',
'Small': 'छोटा',
'Hidden': 'छिपा',
+31 -4
View File
@@ -25,6 +25,13 @@ export default {
'Resume': 'Folytatás',
'Stats': 'Statisztika',
'Exercises': 'Gyakorlatok',
'By muscle': 'Izom szerint',
'Explore muscles': 'Izmok felfedezése',
'Choose a muscle to see exercises that train it.': 'Válassz izmot, hogy lásd a gyakorlatokat, amelyek edzik.',
'Exercises for {0}': '{0} gyakorlatai',
'Clear selection': 'Kijelölés törlése',
'Primary target': 'Elsődleges célizom',
'Also trains': 'Emellett edzi',
'History': 'Előzmények',
'Settings': 'Beállítások',
'Freestyle': 'Szabad edzés',
@@ -202,8 +209,22 @@ export default {
'{0} — in progress': '{0} — folyamatban',
'Resume ▶': 'Folytatás ▶',
'Welcome!': 'Üdvözlünk!',
'Set up your weekly routine to get going — or load a ready-made Push / Pull / Legs plan.': 'Állítsd be a heti rutinod, hogy elindulhass — vagy tölts be egy kész Push / Pull / Legs tervet.',
'Load starter plan (PPL)': 'Kezdő terv betöltése (PPL)',
'Set up your weekly routine to get going — or load a ready-made starter plan.': 'Állítsd be a heti rutinod, hogy elindulhass — vagy tölts be egy kész kezdő tervet.',
'Load starter plan': 'Kezdő terv betöltése',
'Choose starter plan': 'Válassz kezdő tervet',
'{0} days per week': 'Heti {0} nap',
'{0} loaded': '{0} betöltve',
'Load {0}?': 'Betöltöd: {0}?',
'Load plan': 'Terv betöltése',
'The new plan will be scheduled on {0}. Existing routines are kept — only those days of the weekly plan change.': 'Az új terv ide kerül: {0}. A meglévő rutinjaid megmaradnak — a heti tervben csak ezek a napok változnak.',
'Push / Pull / Legs': 'Push / Pull / Legs',
'Push, pull and legs each get their own day.': 'Tolás, húzás és láb, mind a maga napján.',
'Upper / Lower': 'Felső / Alsó',
'Upper body twice, lower body twice.': 'Felsőtest kétszer, alsótest kétszer.',
'Full Body': 'Teljes test',
'Three sessions, the whole body each time.': 'Három edzés, mindegyiken az egész test.',
'5×5': '5×5',
'Five sets of five on the main barbell lifts.': 'Öt ötös sorozat a fő rúdgyakorlatokon.',
'Build my own plan': 'Saját terv készítése',
'{0} week streak': '{0} hetes sorozat',
'this week': 'ezen a héten',
@@ -231,7 +252,6 @@ export default {
'Routines': 'Rutinok',
'No routines yet.': 'Még nincs rutin.',
'Create one or load the starter plan.': 'Hozz létre egyet, vagy töltsd be a kezdő tervet.',
'Load starter plan (Push / Pull / Legs)': 'Kezdő terv betöltése (Push / Pull / Legs)',
// --- routine edit ---
'Superset with exercise above': 'Szuperszett a fenti gyakorlattal',
'Note (optional) — loading cues, "bar only then +1 plate/side each set", anything worth remembering here': 'Megjegyzés (opcionális) — súlyozási tippek, pl. „csak a rúd, majd sorozatonként +1 tárcsa oldalanként”, bármi, amit érdemes megjegyezni',
@@ -240,11 +260,12 @@ export default {
'Delete routine?': 'Törlöd a rutint?',
'“{0}” and its exercises will be removed.': '„{0}” és a gyakorlatai el lesznek távolítva.',
'Delete routine': 'Rutin törlése',
'Copy routine': 'Rutin másolása',
'Copy': 'Másolat',
// --- library / history ---
'{0} exercises with animations': '{0} gyakorlat animációval',
'Search…': 'Keresés…',
'No workouts yet.': 'Még nincs edzés.',
'Starter plan loaded — Mon Push · Wed Pull · Fri Legs': 'Kezdő terv betöltve — H Push · Sze Pull · P Legs',
// --- login / account ---
'Enter a name': 'Adj meg egy nevet',
'Profile created — data from this device moved into it': 'Profil létrehozva — az eszközön lévő adatok átkerültek bele',
@@ -404,6 +425,12 @@ export default {
'Minimize': 'Kicsinyítés',
'Expand': 'Kibontás',
'Exercise animations': 'Gyakorlat-animációk',
'Workout view': 'Edzésnézet',
'Cards': 'Kártyák',
'List': 'Lista',
'Current': 'Aktuális',
'Set current': 'Megjelölés aktuálisként',
'Move, swap and remove below act on the exercise marked {0}.': 'Az alábbi áthelyezés, csere és törlés a {0} jelölésű gyakorlatra vonatkozik.',
'Full': 'Teljes',
'Small': 'Kicsi',
'Hidden': 'Rejtett',
+31 -4
View File
@@ -23,6 +23,13 @@ export default {
'Resume': 'Riprendi',
'Stats': 'Statistiche',
'Exercises': 'Esercizi',
'By muscle': 'Per muscolo',
'Explore muscles': 'Esplora i muscoli',
'Choose a muscle to see exercises that train it.': 'Scegli un muscolo per vedere gli esercizi che lo allenano.',
'Exercises for {0}': 'Esercizi per {0}',
'Clear selection': 'Cancella selezione',
'Primary target': 'Muscolo principale',
'Also trains': 'Allena anche',
'History': 'Cronologia',
'Settings': 'Impostazioni',
'Freestyle': 'Libero',
@@ -202,8 +209,22 @@ export default {
'{0} — in progress': '{0} — in corso',
'Resume ▶': 'Riprendi ▶',
'Welcome!': 'Benvenuto!',
'Set up your weekly routine to get going — or load a ready-made Push / Pull / Legs plan.': 'Imposta la tua routine settimanale — o carica un piano Push / Pull / Gambe già pronto.',
'Load starter plan (PPL)': 'Carica piano iniziale (PPL)',
'Set up your weekly routine to get going — or load a ready-made starter plan.': 'Imposta la tua routine settimanale — o carica un piano iniziale già pronto.',
'Load starter plan': 'Carica piano iniziale',
'Choose starter plan': 'Scegli un piano iniziale',
'{0} days per week': '{0} giorni a settimana',
'{0} loaded': '{0} caricato',
'Load {0}?': 'Caricare {0}?',
'Load plan': 'Carica piano',
'The new plan will be scheduled on {0}. Existing routines are kept — only those days of the weekly plan change.': 'Il nuovo piano andrà su {0}. Le tue routine restano tutte — cambiano solo quei giorni del piano settimanale.',
'Push / Pull / Legs': 'Push / Pull / Gambe',
'Push, pull and legs each get their own day.': 'Spinta, trazione e gambe, ognuna nel suo giorno.',
'Upper / Lower': 'Superiore / Inferiore',
'Upper body twice, lower body twice.': 'Parte superiore due volte, parte inferiore due volte.',
'Full Body': 'Total body',
'Three sessions, the whole body each time.': 'Tre sedute, ogni volta tutto il corpo.',
'5×5': '5×5',
'Five sets of five on the main barbell lifts.': 'Cinque serie da cinque sui fondamentali con bilanciere.',
'Build my own plan': 'Crea il mio piano',
'{0} week streak': 'serie di {0} settimane',
'this week': 'questa settimana',
@@ -228,7 +249,6 @@ export default {
'Week schedule': 'Programma settimanale',
'No routines yet.': 'Ancora nessuna routine.',
'Create one or load the starter plan.': 'Creane una o carica il piano iniziale.',
'Load starter plan (Push / Pull / Legs)': 'Carica piano iniziale (Push / Pull / Gambe)',
'Superset with exercise above': "Superset con l'esercizio sopra",
'Note (optional) — loading cues, "bar only then +1 plate/side each set", anything worth remembering here': 'Nota (facoltativa) — indicazioni di carico, es. "solo bilanciere poi +1 disco per lato a ogni serie", qualsiasi cosa tu voglia ricordare',
'No exercises yet — add your first one.': 'Ancora nessun esercizio — aggiungi il primo.',
@@ -236,10 +256,11 @@ export default {
'Delete routine?': 'Eliminare routine?',
'“{0}” and its exercises will be removed.': '«{0}» e i suoi esercizi verranno rimossi.',
'Delete routine': 'Elimina routine',
'Copy routine': 'Copia routine',
'Copy': 'Copia',
'{0} exercises with animations': '{0} esercizi con animazioni',
'Search…': 'Cerca…',
'No workouts yet.': 'Ancora nessun allenamento.',
'Starter plan loaded — Mon Push · Wed Pull · Fri Legs': 'Piano iniziale caricato — Lun Push · Mer Pull · Ven Gambe',
'Enter a name': 'Inserisci un nome',
'Profile created — data from this device moved into it': 'Profilo creato — i dati di questo dispositivo sono stati trasferiti',
'Profile created — data moved into it': 'Profilo creato — dati trasferiti',
@@ -394,6 +415,12 @@ export default {
'Minimize': 'Riduci',
'Expand': 'Ingrandisci',
'Exercise animations': 'Animazioni degli esercizi',
'Workout view': 'Vista allenamento',
'Cards': 'Schede',
'List': 'Elenco',
'Current': 'Corrente',
'Set current': 'Imposta come corrente',
'Move, swap and remove below act on the exercise marked {0}.': 'Spostamento, scambio e rimozione qui sotto agiscono sull’esercizio contrassegnato come {0}.',
'Full': 'Grande',
'Small': 'Piccola',
'Hidden': 'Nascosta',
+31 -4
View File
@@ -23,6 +23,13 @@ export default {
'Resume': '이어하기',
'Stats': '통계',
'Exercises': '운동',
'By muscle': '근육별',
'Explore muscles': '근육 탐색',
'Choose a muscle to see exercises that train it.': '운동하는 부위를 선택해 해당 근육을 훈련하는 운동을 확인하세요.',
'Exercises for {0}': '{0} 운동',
'Clear selection': '선택 지우기',
'Primary target': '주요 목표',
'Also trains': '함께 훈련',
'History': '기록',
'Settings': '설정',
'Freestyle': '자유 운동',
@@ -202,8 +209,22 @@ export default {
'{0} — in progress': '{0} — 진행 중',
'Resume ▶': '이어하기 ▶',
'Welcome!': '환영합니다!',
'Set up your weekly routine to get going — or load a ready-made Push / Pull / Legs plan.': '주간 루틴을 설정해 시작하세요 — 또는 미리 만들어진 푸시 / 풀 / 레그 계획을 불러오세요.',
'Load starter plan (PPL)': '스타터 계획 불러오기 (PPL)',
'Set up your weekly routine to get going — or load a ready-made starter plan.': '주간 루틴을 설정해 시작하세요 — 또는 미리 만들어진 스타터 계획을 불러오세요.',
'Load starter plan': '스타터 계획 불러오기',
'Choose starter plan': '스타터 계획 선택',
'{0} days per week': '주 {0}일',
'{0} loaded': '{0} 불러옴',
'Load {0}?': '{0} 불러올까요?',
'Load plan': '계획 불러오기',
'The new plan will be scheduled on {0}. Existing routines are kept — only those days of the weekly plan change.': '새 계획은 {0}에 배치됩니다. 기존 루틴은 모두 유지되고 주간 계획에서 해당 요일만 바뀝니다.',
'Push / Pull / Legs': '푸시 / 풀 / 레그',
'Push, pull and legs each get their own day.': '푸시, 풀, 레그를 각각 다른 날에.',
'Upper / Lower': '상체 / 하체',
'Upper body twice, lower body twice.': '상체 두 번, 하체 두 번.',
'Full Body': '전신',
'Three sessions, the whole body each time.': '세 번의 세션, 매번 전신.',
'5×5': '5×5',
'Five sets of five on the main barbell lifts.': '주요 바벨 종목을 5세트 5회로.',
'Build my own plan': '내 계획 만들기',
'{0} week streak': '{0}주 연속',
'this week': '이번 주',
@@ -228,7 +249,6 @@ export default {
'Week schedule': '주간 일정',
'No routines yet.': '아직 루틴이 없어요.',
'Create one or load the starter plan.': '루틴을 만들거나 스타터 계획을 불러오세요.',
'Load starter plan (Push / Pull / Legs)': '스타터 계획 불러오기 (푸시 / 풀 / 레그)',
'Superset with exercise above': '위 운동과 슈퍼세트',
'Note (optional) — loading cues, "bar only then +1 plate/side each set", anything worth remembering here': '메모(선택 사항) — 중량 안내, 예: "빈 바로 시작 후 세트마다 양쪽 +1플레이트", 기억하고 싶은 모든 것',
'No exercises yet — add your first one.': '아직 운동이 없어요 — 첫 운동을 추가하세요.',
@@ -236,10 +256,11 @@ export default {
'Delete routine?': '루틴을 삭제할까요?',
'“{0}” and its exercises will be removed.': '"{0}"과(와) 그 운동들이 삭제됩니다.',
'Delete routine': '루틴 삭제',
'Copy routine': '루틴 복사',
'Copy': '복사본',
'{0} exercises with animations': '애니메이션이 있는 운동 {0}개',
'Search…': '검색…',
'No workouts yet.': '아직 운동 기록이 없어요.',
'Starter plan loaded — Mon Push · Wed Pull · Fri Legs': '스타터 계획 불러옴 — 월 푸시 · 수 풀 · 금 레그',
'Enter a name': '이름을 입력하세요',
'Profile created — data from this device moved into it': '프로필 생성됨 — 이 기기의 데이터가 이동됨',
'Profile created — data moved into it': '프로필 생성됨 — 데이터 이동됨',
@@ -394,6 +415,12 @@ export default {
'Minimize': '축소',
'Expand': '확대',
'Exercise animations': '운동 애니메이션',
'Workout view': '운동 보기',
'Cards': '카드',
'List': '목록',
'Current': '현재',
'Set current': '현재 운동으로 설정',
'Move, swap and remove below act on the exercise marked {0}.': '아래의 이동, 교체, 삭제는 {0} 표시된 운동에 적용됩니다.',
'Full': '전체',
'Small': '작게',
'Hidden': '숨김',
+31 -4
View File
@@ -23,6 +23,13 @@ export default {
'Resume': 'Wznów',
'Stats': 'Statystyki',
'Exercises': 'Ćwiczenia',
'By muscle': 'Według mięśnia',
'Explore muscles': 'Poznaj mięśnie',
'Choose a muscle to see exercises that train it.': 'Wybierz mięsień, aby zobaczyć ćwiczenia, które go angażują.',
'Exercises for {0}': 'Ćwiczenia na {0}',
'Clear selection': 'Wyczyść wybór',
'Primary target': 'Główny cel',
'Also trains': 'Angażuje również',
'History': 'Historia',
'Settings': 'Ustawienia',
'Freestyle': 'Dowolny',
@@ -202,8 +209,22 @@ export default {
'{0} — in progress': '{0} — w trakcie',
'Resume ▶': 'Wznów ▶',
'Welcome!': 'Witaj!',
'Set up your weekly routine to get going — or load a ready-made Push / Pull / Legs plan.': 'Ustaw swój tygodniowy plan — albo wczytaj gotowy plan Push / Pull / Nogi.',
'Load starter plan (PPL)': 'Wczytaj plan startowy (PPL)',
'Set up your weekly routine to get going — or load a ready-made starter plan.': 'Ustaw swój tygodniowy plan — albo wczytaj gotowy plan startowy.',
'Load starter plan': 'Wczytaj plan startowy',
'Choose starter plan': 'Wybierz plan startowy',
'{0} days per week': '{0} dni w tygodniu',
'{0} loaded': 'Wczytano: {0}',
'Load {0}?': 'Wczytać {0}?',
'Load plan': 'Wczytaj plan',
'The new plan will be scheduled on {0}. Existing routines are kept — only those days of the weekly plan change.': 'Nowy plan trafi na {0}. Twoje plany treningowe zostają — zmienią się tylko te dni w planie tygodnia.',
'Push / Pull / Legs': 'Push / Pull / Nogi',
'Push, pull and legs each get their own day.': 'Pchanie, ciągnięcie i nogi — każde w swoim dniu.',
'Upper / Lower': 'Góra / Dół',
'Upper body twice, lower body twice.': 'Góra dwa razy, dół dwa razy.',
'Full Body': 'Całe ciało',
'Three sessions, the whole body each time.': 'Trzy treningi, za każdym razem całe ciało.',
'5×5': '5×5',
'Five sets of five on the main barbell lifts.': 'Pięć serii po pięć na głównych bojach ze sztangą.',
'Build my own plan': 'Utwórz własny plan',
'{0} week streak': 'seria {0} tyg.',
'this week': 'w tym tygodniu',
@@ -228,7 +249,6 @@ export default {
'Week schedule': 'Harmonogram tygodnia',
'No routines yet.': 'Brak planów.',
'Create one or load the starter plan.': 'Utwórz plan albo wczytaj startowy.',
'Load starter plan (Push / Pull / Legs)': 'Wczytaj plan startowy (Push / Pull / Nogi)',
'Superset with exercise above': 'Superseria z ćwiczeniem powyżej',
'Note (optional) — loading cues, "bar only then +1 plate/side each set", anything worth remembering here': 'Notatka (opcjonalnie) — wskazówki dot. obciążenia, np. "sama sztanga, potem +1 talerz na stronę w każdej serii", cokolwiek chcesz zapamiętać',
'No exercises yet — add your first one.': 'Brak ćwiczeń — dodaj pierwsze.',
@@ -236,10 +256,11 @@ export default {
'Delete routine?': 'Usunąć plan?',
'“{0}” and its exercises will be removed.': '„{0}” i jego ćwiczenia zostaną usunięte.',
'Delete routine': 'Usuń plan',
'Copy routine': 'Kopiuj plan',
'Copy': 'Kopia',
'{0} exercises with animations': '{0} ćwiczeń z animacjami',
'Search…': 'Szukaj…',
'No workouts yet.': 'Brak treningów.',
'Starter plan loaded — Mon Push · Wed Pull · Fri Legs': 'Plan startowy wczytany — Pn Push · Śr Pull · Pt Nogi',
'Enter a name': 'Podaj imię',
'Profile created — data from this device moved into it': 'Profil utworzony — dane z tego urządzenia zostały przeniesione',
'Profile created — data moved into it': 'Profil utworzony — dane przeniesione',
@@ -394,6 +415,12 @@ export default {
'Minimize': 'Zmniejsz',
'Expand': 'Powiększ',
'Exercise animations': 'Animacje ćwiczeń',
'Workout view': 'Widok treningu',
'Cards': 'Karty',
'List': 'Lista',
'Current': 'Bieżące',
'Set current': 'Ustaw jako bieżące',
'Move, swap and remove below act on the exercise marked {0}.': 'Przenoszenie, zamiana i usuwanie poniżej dotyczą ćwiczenia oznaczonego {0}.',
'Full': 'Pełna',
'Small': 'Mała',
'Hidden': 'Ukryta',
+15 -4
View File
@@ -62,13 +62,14 @@ export const PT_BR_OVERRIDES = {
'The sets you logged in this session will be lost.': 'As séries registradas nesta sessão serão perdidas.',
'Superset · do these back-to-back, rest when done': 'Superset · faça estes exercícios em sequência e descanse ao terminar',
'Freestyle workout — add your first exercise.': 'Treino livre — adicione seu primeiro exercício.',
'Set up your weekly routine to get going — or load a ready-made Push / Pull / Legs plan.': 'Configure sua rotina semanal para começar ou carregue um plano pronto de Push / Pull / Legs.',
'Load starter plan (PPL)': 'Carregar plano inicial (PPL)',
'Set up your weekly routine to get going — or load a ready-made starter plan.': 'Configure sua rotina semanal para começar — ou carregue um plano inicial já pronto.',
'Choose starter plan': 'Escolha um plano inicial',
'The new plan will be scheduled on {0}. Existing routines are kept — only those days of the weekly plan change.': 'O novo plano fica em {0}. Suas rotinas são todas mantidas — só esses dias do plano semanal mudam.',
'Push / Pull / Legs': 'Push / Pull / Legs',
'Build my own plan': 'Criar meu próprio plano',
'Finish your first workout to see progress curves here.': 'Finalize seu primeiro treino para ver os gráficos de progresso aqui.',
'Your weekly routine': 'Sua rotina semanal',
'Create one or load the starter plan.': 'Crie uma ou carregue o plano inicial.',
'Load starter plan (Push / Pull / Legs)': 'Carregar plano inicial (Push / Pull / Legs)',
'No exercises yet — add your first one.': 'Ainda não há exercícios — adicione o primeiro.',
'Exclude from automatic progression': 'Excluir da progressão automática',
'Use for planned deloads. Workouts stay in history and statistics.': 'Use para deloads planejados. Os treinos permanecem no histórico e nas estatísticas.',
@@ -76,8 +77,9 @@ export const PT_BR_OVERRIDES = {
'Tap the link button on an exercise to superset it with the one above — you’ll do them back-to-back.': 'Toque no botão de vínculo de um exercício para combiná-lo em um superset com o exercício acima — eles serão feitos em sequência.',
'Delete routine?': 'Excluir rotina?',
'Delete routine': 'Excluir rotina',
'Copy routine': 'Copiar rotina',
'Copy': 'Cópia',
'Search…': 'Buscar…',
'Starter plan loaded — Mon Push · Wed Pull · Fri Legs': 'Plano inicial carregado — Seg Push · Qua Pull · Sex Pernas',
'{0} planned for {1}': '{0} planejado para {1}',
'Planned': 'Planejado',
'Enter a name': 'Informe um nome',
@@ -627,6 +629,15 @@ export const PT_BR_OVERRIDES = {
'Point the camera at the QR code': 'Aponte a câmera para o código QR',
'Camera is not available here — import a photo or type the code instead.': 'A câmera não está disponível aqui — importe uma foto ou digite o código.',
'Camera access was denied — allow it in your browser and try again.': 'O acesso à câmera foi negado — permita-o no navegador e tente de novo.',
// --- muscle explorer ---
'By muscle': 'Por músculo',
'Explore muscles': 'Explorar músculos',
'Choose a muscle to see exercises that train it.': 'Escolha um músculo para ver os exercícios que o treinam.',
'Exercises for {0}': 'Exercícios para {0}',
'Clear selection': 'Limpar seleção',
'Primary target': 'Músculo principal',
'Also trains': 'Também trabalha',
}
export default { ...pt, ...PT_BR_OVERRIDES }
+31 -4
View File
@@ -23,6 +23,13 @@ export default {
'Resume': 'Retomar',
'Stats': 'Estatísticas',
'Exercises': 'Exercícios',
'By muscle': 'Por músculo',
'Explore muscles': 'Explorar músculos',
'Choose a muscle to see exercises that train it.': 'Escolha um músculo para ver os exercícios que o treinam.',
'Exercises for {0}': 'Exercícios para {0}',
'Clear selection': 'Limpar seleção',
'Primary target': 'Alvo principal',
'Also trains': 'Também trabalha',
'History': 'Histórico',
'Settings': 'Definições',
'Freestyle': 'Livre',
@@ -202,8 +209,22 @@ export default {
'{0} — in progress': '{0} — em curso',
'Resume ▶': 'Retomar ▶',
'Welcome!': 'Bem-vindo!',
'Set up your weekly routine to get going — or load a ready-made Push / Pull / Legs plan.': 'Configura a tua rotina semanal — ou carrega um plano Push / Pull / Pernas já feito.',
'Load starter plan (PPL)': 'Carregar plano inicial (PPL)',
'Set up your weekly routine to get going — or load a ready-made starter plan.': 'Configura a tua rotina semanal — ou carrega um plano inicial já feito.',
'Load starter plan': 'Carregar plano inicial',
'Choose starter plan': 'Escolhe um plano inicial',
'{0} days per week': '{0} dias por semana',
'{0} loaded': '{0} carregado',
'Load {0}?': 'Carregar {0}?',
'Load plan': 'Carregar plano',
'The new plan will be scheduled on {0}. Existing routines are kept — only those days of the weekly plan change.': 'O novo plano fica em {0}. As tuas rotinas mantêm-se todas — só esses dias do plano semanal mudam.',
'Push / Pull / Legs': 'Push / Pull / Pernas',
'Push, pull and legs each get their own day.': 'Empurrar, puxar e pernas, cada um no seu dia.',
'Upper / Lower': 'Superior / Inferior',
'Upper body twice, lower body twice.': 'Tronco superior duas vezes, inferior duas vezes.',
'Full Body': 'Corpo inteiro',
'Three sessions, the whole body each time.': 'Três sessões, o corpo todo de cada vez.',
'5×5': '5×5',
'Five sets of five on the main barbell lifts.': 'Cinco séries de cinco nos básicos com barra.',
'Build my own plan': 'Criar o meu próprio plano',
'{0} week streak': 'sequência de {0} semanas',
'this week': 'esta semana',
@@ -228,7 +249,6 @@ export default {
'Week schedule': 'Horário semanal',
'No routines yet.': 'Ainda sem rotinas.',
'Create one or load the starter plan.': 'Cria uma ou carrega o plano inicial.',
'Load starter plan (Push / Pull / Legs)': 'Carregar plano inicial (Push / Pull / Pernas)',
'Superset with exercise above': 'Supersérie com o exercício acima',
'Note (optional) — loading cues, "bar only then +1 plate/side each set", anything worth remembering here': 'Nota (opcional) — dicas de carga, ex. "só a barra, depois +1 anilha por lado a cada série", o que quiser lembrar',
'No exercises yet — add your first one.': 'Ainda sem exercícios — adiciona o primeiro.',
@@ -236,10 +256,11 @@ export default {
'Delete routine?': 'Eliminar rotina?',
'“{0}” and its exercises will be removed.': '«{0}» e os seus exercícios serão removidos.',
'Delete routine': 'Eliminar rotina',
'Copy routine': 'Copiar rotina',
'Copy': 'Cópia',
'{0} exercises with animations': '{0} exercícios com animações',
'Search…': 'Pesquisar…',
'No workouts yet.': 'Ainda sem treinos.',
'Starter plan loaded — Mon Push · Wed Pull · Fri Legs': 'Plano inicial carregado — Seg Push · Qua Pull · Sex Pernas',
'Enter a name': 'Introduz um nome',
'Profile created — data from this device moved into it': 'Perfil criado — os dados deste dispositivo foram movidos para ele',
'Profile created — data moved into it': 'Perfil criado — dados movidos',
@@ -394,6 +415,12 @@ export default {
'Minimize': 'Minimizar',
'Expand': 'Ampliar',
'Exercise animations': 'Animações dos exercícios',
'Workout view': 'Vista do treino',
'Cards': 'Cartões',
'List': 'Lista',
'Current': 'Atual',
'Set current': 'Marcar como atual',
'Move, swap and remove below act on the exercise marked {0}.': 'Mover, trocar e remover abaixo atuam sobre o exercício marcado como {0}.',
'Full': 'Grande',
'Small': 'Pequena',
'Hidden': 'Oculta',
+31 -4
View File
@@ -23,6 +23,13 @@ export default {
'Resume': 'Продолжить',
'Stats': 'Статистика',
'Exercises': 'Упражнения',
'By muscle': 'По мышцам',
'Explore muscles': 'Изучить мышцы',
'Choose a muscle to see exercises that train it.': 'Выберите мышцу, чтобы увидеть упражнения, которые её тренируют.',
'Exercises for {0}': 'Упражнения для {0}',
'Clear selection': 'Очистить выбор',
'Primary target': 'Основная мышца',
'Also trains': 'Также тренирует',
'History': 'История',
'Settings': 'Настройки',
'Freestyle': 'Свободная',
@@ -202,8 +209,22 @@ export default {
'{0} — in progress': '{0} — идёт',
'Resume ▶': 'Продолжить ▶',
'Welcome!': 'Добро пожаловать!',
'Set up your weekly routine to get going — or load a ready-made Push / Pull / Legs plan.': 'Настрой свой недельный план — или загрузи готовый план Push / Pull / Ноги.',
'Load starter plan (PPL)': 'Загрузить стартовый план (PPL)',
'Set up your weekly routine to get going — or load a ready-made starter plan.': 'Настрой свой недельный план — или загрузи готовый стартовый план.',
'Load starter plan': 'Загрузить стартовый план',
'Choose starter plan': 'Выбери стартовый план',
'{0} days per week': 'Дней в неделю: {0}',
'{0} loaded': '{0} загружен',
'Load {0}?': 'Загрузить {0}?',
'Load plan': 'Загрузить план',
'The new plan will be scheduled on {0}. Existing routines are kept — only those days of the weekly plan change.': 'Новый план встанет на {0}. Все твои программы сохранятся — в плане недели изменятся только эти дни.',
'Push / Pull / Legs': 'Push / Pull / Ноги',
'Push, pull and legs each get their own day.': 'Жимы, тяги и ноги — каждому свой день.',
'Upper / Lower': 'Верх / Низ',
'Upper body twice, lower body twice.': 'Верх тела дважды, низ дважды.',
'Full Body': 'Всё тело',
'Three sessions, the whole body each time.': 'Три тренировки, каждый раз всё тело.',
'5×5': '5×5',
'Five sets of five on the main barbell lifts.': 'Пять подходов по пять в основных движениях со штангой.',
'Build my own plan': 'Создать свой план',
'{0} week streak': 'серия: {0} нед.',
'this week': 'на этой неделе',
@@ -228,7 +249,6 @@ export default {
'Week schedule': 'Расписание недели',
'No routines yet.': 'Программ пока нет.',
'Create one or load the starter plan.': 'Создай программу или загрузи стартовый план.',
'Load starter plan (Push / Pull / Legs)': 'Загрузить стартовый план (Push / Pull / Ноги)',
'Superset with exercise above': 'Суперсет с упражнением выше',
'Note (optional) — loading cues, "bar only then +1 plate/side each set", anything worth remembering here': 'Заметка (необязательно) — подсказки по нагрузке, напр. «только гриф, затем +1 блин на сторону каждый подход», всё, что стоит запомнить',
'No exercises yet — add your first one.': 'Упражнений пока нет — добавь первое.',
@@ -236,10 +256,11 @@ export default {
'Delete routine?': 'Удалить программу?',
'“{0}” and its exercises will be removed.': '«{0}» и её упражнения будут удалены.',
'Delete routine': 'Удалить программу',
'Copy routine': 'Копировать программу',
'Copy': 'Копия',
'{0} exercises with animations': '{0} упражнений с анимациями',
'Search…': 'Поиск…',
'No workouts yet.': 'Тренировок пока нет.',
'Starter plan loaded — Mon Push · Wed Pull · Fri Legs': 'Стартовый план загружен — Пн Push · Ср Pull · Пт Ноги',
'Enter a name': 'Введите имя',
'Profile created — data from this device moved into it': 'Профиль создан — данные с этого устройства перенесены в него',
'Profile created — data moved into it': 'Профиль создан — данные перенесены',
@@ -394,6 +415,12 @@ export default {
'Minimize': 'Свернуть',
'Expand': 'Развернуть',
'Exercise animations': 'Анимации упражнений',
'Workout view': 'Вид тренировки',
'Cards': 'Карточки',
'List': 'Список',
'Current': 'Текущее',
'Set current': 'Сделать текущим',
'Move, swap and remove below act on the exercise marked {0}.': 'Кнопки перемещения, замены и удаления ниже действуют на упражнение с пометкой {0}.',
'Full': 'Полная',
'Small': 'Малая',
'Hidden': 'Скрыта',
+31 -4
View File
@@ -25,6 +25,13 @@ export default {
'Resume': 'เล่นต่อ',
'Stats': 'สถิติ',
'Exercises': 'ท่าออกกำลังกาย',
'By muscle': 'ตามกล้ามเนื้อ',
'Explore muscles': 'สำรวจกล้ามเนื้อ',
'Choose a muscle to see exercises that train it.': 'เลือกกล้ามเนื้อเพื่อดูท่าออกกำลังกายที่ฝึกกล้ามเนื้อนั้น',
'Exercises for {0}': 'ท่าออกกำลังกายสำหรับ {0}',
'Clear selection': 'ล้างการเลือก',
'Primary target': 'กล้ามเนื้อหลัก',
'Also trains': 'ฝึกกล้ามเนื้อนี้ด้วย',
'History': 'ประวัติ',
'Settings': 'ตั้งค่า',
'Freestyle': 'ฟรีสไตล์',
@@ -202,8 +209,22 @@ export default {
'{0} — in progress': '{0} — กำลังดำเนินการ',
'Resume ▶': 'เล่นต่อ ▶',
'Welcome!': 'ยินดีต้อนรับ!',
'Set up your weekly routine to get going — or load a ready-made Push / Pull / Legs plan.': 'ตั้งค่ารูทีนรายสัปดาห์เพื่อเริ่มต้น — หรือโหลดแผนสำเร็จรูป Push / Pull / Legs',
'Load starter plan (PPL)': 'โหลดแผนเริ่มต้น (PPL)',
'Set up your weekly routine to get going — or load a ready-made starter plan.': 'ตั้งค่ารูทีนรายสัปดาห์เพื่อเริ่มต้น — หรือโหลดแผนเริ่มต้นสำเร็จรูป',
'Load starter plan': 'โหลดแผนเริ่มต้น',
'Choose starter plan': 'เลือกแผนเริ่มต้น',
'{0} days per week': 'สัปดาห์ละ {0} วัน',
'{0} loaded': 'โหลด {0} แล้ว',
'Load {0}?': 'โหลด {0} ไหม',
'Load plan': 'โหลดแผน',
'The new plan will be scheduled on {0}. Existing routines are kept — only those days of the weekly plan change.': 'แผนใหม่จะลงใน {0} รูทีนเดิมของคุณยังอยู่ครบ — เปลี่ยนเฉพาะวันเหล่านี้ในแผนรายสัปดาห์',
'Push / Pull / Legs': 'Push / Pull / Legs',
'Push, pull and legs each get their own day.': 'ดัน ดึง และขา แยกกันคนละวัน',
'Upper / Lower': 'บน / ล่าง',
'Upper body twice, lower body twice.': 'ลำตัวบนสองครั้ง ลำตัวล่างสองครั้ง',
'Full Body': 'เต็มตัว',
'Three sessions, the whole body each time.': 'สามครั้ง ครบทั้งตัวทุกครั้ง',
'5×5': '5×5',
'Five sets of five on the main barbell lifts.': 'ห้าเซ็ต เซ็ตละห้าครั้ง ในท่าบาร์เบลหลัก',
'Build my own plan': 'สร้างแผนของตัวเอง',
'{0} week streak': 'ต่อเนื่อง {0} สัปดาห์',
'this week': 'สัปดาห์นี้',
@@ -231,7 +252,6 @@ export default {
'Routines': 'รูทีน',
'No routines yet.': 'ยังไม่มีรูทีน',
'Create one or load the starter plan.': 'สร้างใหม่หรือโหลดแผนเริ่มต้น',
'Load starter plan (Push / Pull / Legs)': 'โหลดแผนเริ่มต้น (Push / Pull / Legs)',
// --- routine edit ---
'Superset with exercise above': 'ซูเปอร์เซ็ตกับท่าด้านบน',
'Note (optional) — loading cues, "bar only then +1 plate/side each set", anything worth remembering here': 'บันทึก (ไม่บังคับ) — เคล็ดลับการตั้งน้ำหนัก เช่น "เอาแค่บาร์เปล่าก่อน แล้วค่อยเพิ่มแผ่นละ 1 แผ่นต่อข้างทุกเซ็ต" หรืออะไรก็ตามที่อยากจดจำไว้',
@@ -240,11 +260,12 @@ export default {
'Delete routine?': 'ลบรูทีนนี้?',
'“{0}” and its exercises will be removed.': '“{0}” และท่าทั้งหมดในนั้นจะถูกลบ',
'Delete routine': 'ลบรูทีน',
'Copy routine': 'คัดลอกรูทีน',
'Copy': 'สำเนา',
// --- library / history ---
'{0} exercises with animations': '{0} ท่าพร้อมภาพเคลื่อนไหว',
'Search…': 'ค้นหา…',
'No workouts yet.': 'ยังไม่มีการออกกำลังกาย',
'Starter plan loaded — Mon Push · Wed Pull · Fri Legs': 'โหลดแผนเริ่มต้นแล้ว — จ. Push · พ. Pull · ศ. Legs',
// --- login / account ---
'Enter a name': 'กรอกชื่อ',
'Profile created — data from this device moved into it': 'สร้างโปรไฟล์แล้ว — ย้ายข้อมูลจากเครื่องนี้เข้าไปแล้ว',
@@ -404,6 +425,12 @@ export default {
'Minimize': 'ย่อ',
'Expand': 'ขยาย',
'Exercise animations': 'ภาพเคลื่อนไหวท่าออกกำลังกาย',
'Workout view': 'มุมมองการฝึก',
'Cards': 'การ์ด',
'List': 'รายการ',
'Current': 'ปัจจุบัน',
'Set current': 'ตั้งเป็นปัจจุบัน',
'Move, swap and remove below act on the exercise marked {0}.': 'การย้าย สลับ และลบด้านล่างจะมีผลกับท่าที่ทำเครื่องหมาย {0} ไว้',
'Full': 'เต็ม',
'Small': 'เล็ก',
'Hidden': 'ซ่อน',
+31 -4
View File
@@ -23,6 +23,13 @@ export default {
'Resume': 'Devam et',
'Stats': 'İstatistik',
'Exercises': 'Egzersizler',
'By muscle': 'Kasa göre',
'Explore muscles': 'Kasları keşfet',
'Choose a muscle to see exercises that train it.': 'Çalıştıran egzersizleri görmek için bir kas seçin.',
'Exercises for {0}': '{0} için egzersizler',
'Clear selection': 'Seçimi temizle',
'Primary target': 'Ana hedef',
'Also trains': 'Ayrıca çalıştırır',
'History': 'Geçmiş',
'Settings': 'Ayarlar',
'Freestyle': 'Serbest',
@@ -202,8 +209,22 @@ export default {
'{0} — in progress': '{0} — devam ediyor',
'Resume ▶': 'Devam et ▶',
'Welcome!': 'Hoş geldin!',
'Set up your weekly routine to get going — or load a ready-made Push / Pull / Legs plan.': 'Başlamak için haftalık rutinini kur — ya da hazır bir Push / Pull / Bacak planı yükle.',
'Load starter plan (PPL)': 'Başlangıç planını yükle (PPL)',
'Set up your weekly routine to get going — or load a ready-made starter plan.': 'Başlamak için haftalık rutinini kur — ya da hazır bir başlangıç planı yükle.',
'Load starter plan': 'Başlangıç planı yükle',
'Choose starter plan': 'Başlangıç planı seç',
'{0} days per week': 'Haftada {0} gün',
'{0} loaded': '{0} yüklendi',
'Load {0}?': '{0} yüklensin mi?',
'Load plan': 'Planı yükle',
'The new plan will be scheduled on {0}. Existing routines are kept — only those days of the weekly plan change.': 'Yeni plan {0} günlerine yerleşecek. Mevcut rutinlerin duruyor — haftalık planda yalnızca bu günler değişiyor.',
'Push / Pull / Legs': 'Push / Pull / Bacak',
'Push, pull and legs each get their own day.': 'İtiş, çekiş ve bacak; her biri kendi gününde.',
'Upper / Lower': 'Üst / Alt',
'Upper body twice, lower body twice.': 'Üst vücut iki kez, alt vücut iki kez.',
'Full Body': 'Tüm vücut',
'Three sessions, the whole body each time.': 'Üç antrenman, her seferinde tüm vücut.',
'5×5': '5×5',
'Five sets of five on the main barbell lifts.': 'Ana halter hareketlerinde beşer tekrarlı beş set.',
'Build my own plan': 'Kendi planımı oluştur',
'{0} week streak': '{0} haftalık seri',
'this week': 'bu hafta',
@@ -228,7 +249,6 @@ export default {
'Week schedule': 'Hafta programı',
'No routines yet.': 'Henüz rutin yok.',
'Create one or load the starter plan.': 'Bir tane oluştur ya da başlangıç planını yükle.',
'Load starter plan (Push / Pull / Legs)': 'Başlangıç planını yükle (Push / Pull / Bacak)',
'Superset with exercise above': 'Üstteki egzersizle süperset',
'Note (optional) — loading cues, "bar only then +1 plate/side each set", anything worth remembering here': 'Not (isteğe bağlı) — yükleme ipuçları, örn. "sadece bar, sonra her sette +1 disk/taraf", aklında tutmak istediğin her şey',
'No exercises yet — add your first one.': 'Henüz egzersiz yok — ilkini ekle.',
@@ -236,10 +256,11 @@ export default {
'Delete routine?': 'Rutin silinsin mi?',
'“{0}” and its exercises will be removed.': '“{0}” ve egzersizleri kaldırılacak.',
'Delete routine': 'Rutini sil',
'Copy routine': 'Rutini kopyala',
'Copy': 'Kopya',
'{0} exercises with animations': 'animasyonlu {0} egzersiz',
'Search…': 'Ara…',
'No workouts yet.': 'Henüz antrenman yok.',
'Starter plan loaded — Mon Push · Wed Pull · Fri Legs': 'Başlangıç planı yüklendi — Pzt Push · Çar Pull · Cum Bacak',
'Enter a name': 'Bir isim gir',
'Profile created — data from this device moved into it': 'Profil oluşturuldu — bu cihazdaki veriler profile taşındı',
'Profile created — data moved into it': 'Profil oluşturuldu — veriler taşındı',
@@ -394,6 +415,12 @@ export default {
'Minimize': 'Küçült',
'Expand': 'Büyüt',
'Exercise animations': 'Egzersiz animasyonları',
'Workout view': 'Antrenman görünümü',
'Cards': 'Kartlar',
'List': 'Liste',
'Current': 'Aktif',
'Set current': 'Aktif olarak işaretle',
'Move, swap and remove below act on the exercise marked {0}.': 'Aşağıdaki taşıma, değiştirme ve kaldırma işlemleri {0} olarak işaretli egzersiz için geçerlidir.',
'Full': 'Tam',
'Small': 'Küçük',
'Hidden': 'Gizli',
+31 -4
View File
@@ -23,6 +23,13 @@ export default {
'Resume': '继续',
'Stats': '统计',
'Exercises': '动作库',
'By muscle': '按肌肉',
'Explore muscles': '探索肌肉',
'Choose a muscle to see exercises that train it.': '选择一块肌肉以查看训练它的动作。',
'Exercises for {0}': '{0} 训练动作',
'Clear selection': '清除选择',
'Primary target': '主要目标',
'Also trains': '同时训练',
'History': '历史',
'Settings': '设置',
'Freestyle': '自由训练',
@@ -202,8 +209,22 @@ export default {
'{0} — in progress': '{0}——进行中',
'Resume ▶': '继续 ▶',
'Welcome!': '欢迎!',
'Set up your weekly routine to get going — or load a ready-made Push / Pull / Legs plan.': '设置每周计划开始训练——或加载现成的推 / 拉 / 腿计划。',
'Load starter plan (PPL)': '加载入门计划(PPL)',
'Set up your weekly routine to get going — or load a ready-made starter plan.': '设置每周计划开始训练——或加载现成的入门计划。',
'Load starter plan': '加载入门计划',
'Choose starter plan': '选择入门计划',
'{0} days per week': '每周 {0} 天',
'{0} loaded': '已加载{0}',
'Load {0}?': '加载{0}?',
'Load plan': '加载计划',
'The new plan will be scheduled on {0}. Existing routines are kept — only those days of the weekly plan change.': '新计划将安排在{0}。你现有的训练日都会保留——每周计划中只有这几天会改变。',
'Push / Pull / Legs': '推 / 拉 / 腿',
'Push, pull and legs each get their own day.': '推、拉、腿各占一天。',
'Upper / Lower': '上肢 / 下肢',
'Upper body twice, lower body twice.': '上肢两次,下肢两次。',
'Full Body': '全身',
'Three sessions, the whole body each time.': '三次训练,每次练全身。',
'5×5': '5×5',
'Five sets of five on the main barbell lifts.': '主要杠铃动作五组五次。',
'Build my own plan': '创建自己的计划',
'{0} week streak': '连续 {0} 周',
'this week': '本周',
@@ -228,7 +249,6 @@ export default {
'Week schedule': '每周日程',
'No routines yet.': '还没有训练日。',
'Create one or load the starter plan.': '创建一个或加载入门计划。',
'Load starter plan (Push / Pull / Legs)': '加载入门计划(推 / 拉 / 腿)',
'Superset with exercise above': '与上面的动作组成超级组',
'Note (optional) — loading cues, "bar only then +1 plate/side each set", anything worth remembering here': '备注(可选)— 加重提示,例如"空杠开始,之后每组每侧+1片",任何你想记住的内容',
'No exercises yet — add your first one.': '还没有动作——添加第一个吧。',
@@ -236,10 +256,11 @@ export default {
'Delete routine?': '删除训练日?',
'“{0}” and its exercises will be removed.': '“{0}”及其动作将被移除。',
'Delete routine': '删除训练日',
'Copy routine': '复制训练日',
'Copy': '副本',
'{0} exercises with animations': '{0} 个带动画的动作',
'Search…': '搜索…',
'No workouts yet.': '还没有训练。',
'Starter plan loaded — Mon Push · Wed Pull · Fri Legs': '入门计划已加载——周一推 · 周三拉 · 周五腿',
'Enter a name': '请输入名字',
'Profile created — data from this device moved into it': '档案已创建——本设备数据已转入',
'Profile created — data moved into it': '档案已创建——数据已转入',
@@ -394,6 +415,12 @@ export default {
'Minimize': '缩小',
'Expand': '放大',
'Exercise animations': '动作动画',
'Workout view': '训练视图',
'Cards': '卡片',
'List': '列表',
'Current': '当前',
'Set current': '设为当前',
'Move, swap and remove below act on the exercise marked {0}.': '下方的移动、替换和删除将作用于标记为{0}的动作。',
'Full': '完整',
'Small': '小',
'Hidden': '隐藏',
+82 -14
View File
@@ -4,18 +4,19 @@ 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, isoOf, uid, exCount, DAYN, DAYS, weekOrder, weekStartOf, weekDayOffset, 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 { lastEntryFor, bestWeightFor, bestWeightForEntry, 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 { usesBar, barWeightFor, defaultBarWeight, hasBarOverride } from './lib/bar.js'
import { beep, vibrate } from './lib/sound.js'
import { t, instrFor, exerciseNameFor, getLang, INSTR_LANGS } from './lib/i18n.js'
import { t, dateLocale, instrFor, exerciseNameFor, getLang, INSTR_LANGS } from './lib/i18n.js'
import { nav } from './lib/nav.js'
import { starterRoutines } from './lib/starter.js'
import { buildStarterPlan, starterPlanDays, starterPlanOptions } 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 MuscleExplorer from './components/MuscleExplorer.jsx'
import { exerciseMuscleSnapshot, loadOfWorkouts, MUSCLES, MUSCLE_NAME, normalizeMuscleGroups, hasExplicitMuscleMetadata } from './lib/muscles.js'
import { parseImport, mergeImport } from './lib/import-csv.js'
import { importHevyData, HevyApiError, HEVY_DEV_SETTINGS, mergeHevyRoutines } from './lib/import-hevy.js'
@@ -54,15 +55,65 @@ export function confirmSheet(opts) {
}
/* ============================ 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'))
// 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 choose = (id, name) => {
const days = starterPlanDays(id)
close()
// A confirmation is only worth showing when one of those days is actually occupied.
if (!days.some(day => week[day])) { 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 <>
<h3>{t('Choose starter plan')}</h3>
<div className="list">
{starterPlanOptions().map(({ id, days }) => {
const { name, about } = PLAN_COPY[id]()
return <div key={id} className="item" {...tappable(() => choose(id, name))}>
<span className="lrow-i" style={{ background: 'var(--surface-3)' }}><Icon name="sparkles" /></span>
<div className="grow"><div className="tt">{name}</div><div className="ss">{t('{0} days per week', days)} · {about}</div></div>
<Icon name="chevronRight" className="chev" />
</div>
})}
</div>
</>
}
export const starterPlanSheet = () => ui().openSheet(close => <StarterPlanChooser close={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
@@ -712,6 +763,7 @@ function ExercisePicker({ onPick, close }) {
const [eq, setEq] = useState('') // '' = any equipment
const [showAll, setShowAll] = useState(false)
const [shown, setShown] = useState(50)
const [byMuscle, setByMuscle] = useState(false)
const searchRef = useRef(null)
const bpStrip = useRef(null), eqStrip = useRef(null)
const onSearchFocus = useSheetKeyboard(searchRef)
@@ -729,8 +781,17 @@ function ExercisePicker({ onPick, close }) {
const chosenCount = Object.keys(usage).length
useRevealActiveChip(bpStrip, bp)
useRevealActiveChip(eqStrip, eqOn)
if (byMuscle) return <>
<div className="row between" style={{ marginBottom: 10 }}><h3>{t('Add exercise')}</h3>
<Button size="sm" variant="ghost" onClick={() => setByMuscle(false)}>{t('All')}</Button>
</div>
<MuscleExplorer onPick={onPick} />
</>
return <>
<h3>{t('Add exercise')}</h3>
<div className="row between" style={{ marginBottom: 10 }}><h3>{t('Add exercise')}</h3>
<Button size="sm" variant="tinted" icon="target" onClick={() => setByMuscle(true)}>{t('By muscle')}</Button>
</div>
{/* .picker-search is what index.css keys the keyboard-aware sheet layout on: the sheet
lifts above the keys and the search stays put while the list scrolls under it. */}
<div className="picker-search"><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>
@@ -758,7 +819,14 @@ function ExercisePicker({ onPick, close }) {
</div>}
{f.slice(0, shown).map(e => <div key={e.id} className="item" {...tappable(() => 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" />
{usage[e.id] && <span className="tag acc"><Icon name="starFill" /></span>}
{/* A "+" glyph reads as "add this now" — it used to just open the same detail sheet as
tapping the row, so it added nothing until you'd scrolled past the sets/reps config
and found the real button. Now it does what it looks like: adds with the default
config right away. Tapping the row itself still opens the detail/config sheet, for
when you want to set sets/reps before adding. */}
<button className="iconbtn chev" aria-label={t('Add “{0}”', exerciseNameFor(e))} style={{ padding: 8, margin: -8 }}
onClick={ev => { ev.stopPropagation(); onPick(e, true) }}><Icon name="plus" /></button>
</div>)}
{f.length === 0 && bp === '★' && <div className="empty">{t('Nothing chosen yet — add exercises and they’ll show up here.')}</div>}
</div>
@@ -783,7 +851,7 @@ export function swapActiveWorkoutExercise(index) {
const freestyle = !st.active?.routineId
const step = defaultIncrement(ex.id, st.unit)
const plan = freestyle ? null : nextPrescription(st, full, st.routines.find(r => r.id === st.active.routineId))
const built = buildSets(st, full, { step, ...(freestyle ? { preferLast: true } : {}) })
const built = buildSets(st, full, { step, ...(freestyle ? { preferLast: true } : {}), ...(plan?.kind === 'off' ? { useTarget: true } : {}) })
const replacement = {
id: ex.id,
target: { ...cfg },
@@ -1740,7 +1808,7 @@ function doFinishWorkout() {
s.workouts = completeBackfill(s.workouts, A, w)
} else {
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)
const mx = bestWeightForEntry(e)
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)
+127
View File
@@ -0,0 +1,127 @@
// @vitest-environment happy-dom
// The chooser is where a starter plan can quietly do the wrong thing: overwrite a weekday
// without asking, ask when there was nothing to overwrite, or apply a plan the user cancelled.
import React, { act } from 'react'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { createRoot } from 'react-dom/client'
import { useStore } from './store/useStore.js'
import { useUI } from './store/useUI.js'
import { loadStarterPlan, starterPlanSheet } from './sheets.jsx'
const mounted = []
const S = () => useStore.getState().S
const nameOn = day => S().routines.find(r => r.id === S().week[day])?.name
// Renders whatever sheet is on top and returns its host element.
function renderTop() {
const sheet = useUI.getState().sheets.at(-1)
const host = document.createElement('div')
document.body.appendChild(host)
const root = createRoot(host)
mounted.push(root)
act(() => root.render(sheet.render(() => useUI.getState().closeSheet(sheet.id))))
return host
}
const rowFor = (host, name) => [...host.querySelectorAll('.item')].find(el => el.querySelector('.tt')?.textContent === name)
const buttonFor = (host, label) => [...host.querySelectorAll('button')].find(b => b.textContent === label)
// Opens the chooser and taps one of its rows.
function choose(name) {
starterPlanSheet()
const host = renderTop()
act(() => { rowFor(host, name).click() })
}
beforeEach(() => {
globalThis.IS_REACT_ACT_ENVIRONMENT = true
useUI.setState({ sheets: [], toastMsg: '' })
useStore.setState(s => ({
S: { ...s.S, routines: [{ id: 'mine', name: 'My routine', emoji: 'star', ex: [] }], week: {}, active: null },
}))
document.body.innerHTML = ''
})
afterEach(() => {
act(() => { mounted.splice(0).forEach(root => root.unmount()) })
})
describe('starter plan chooser', () => {
it('lists every plan with its day count', () => {
starterPlanSheet()
const host = renderTop()
expect([...host.querySelectorAll('.item .tt')].map(el => el.textContent))
.toEqual(['Push / Pull / Legs', 'Upper / Lower', 'Full Body', '5×5'])
expect(rowFor(host, 'Upper / Lower').querySelector('.ss').textContent).toContain('4 days per week')
})
it('loads straight away when the plan’s weekdays are free, without asking', () => {
useStore.setState(s => ({ S: { ...s.S, week: { 0: 'mine', 6: 'mine' } } }))
choose('Upper / Lower')
expect(useUI.getState().sheets).toHaveLength(0) // no confirmation was raised
expect(nameOn(1)).toBe('Upper A')
expect(nameOn(2)).toBe('Lower A')
expect(nameOn(4)).toBe('Upper B')
expect(nameOn(5)).toBe('Lower B')
expect(S().week[0]).toBe('mine') // untouched weekdays stay put
expect(S().week[6]).toBe('mine')
expect(S().routines[0].name).toBe('My routine') // and nothing is deleted
expect(useUI.getState().toastMsg).toBe('Upper / Lower loaded')
})
it('asks first when a weekday the plan wants is already taken', () => {
useStore.setState(s => ({ S: { ...s.S, week: { 3: 'mine' } } }))
choose('Full Body')
const confirm = renderTop()
expect(confirm.querySelector('h3').textContent).toBe('Load Full Body?')
expect(confirm.textContent).toContain('Monday, Wednesday and Friday')
expect(S().week[3]).toBe('mine') // nothing applied yet
expect(S().routines).toHaveLength(1)
act(() => { buttonFor(confirm, 'Load plan').click() })
expect(nameOn(1)).toBe('Full Body A')
expect(nameOn(3)).toBe('Full Body B')
expect(nameOn(5)).toBe('Full Body C')
})
it('leaves everything alone when the confirmation is cancelled', () => {
useStore.setState(s => ({ S: { ...s.S, week: { 1: 'mine' } } }))
const before = structuredClone(S())
choose('5×5')
const confirm = renderTop()
act(() => { buttonFor(confirm, 'Cancel').click() })
expect(S()).toEqual(before)
expect(useUI.getState().toastMsg).toBe('')
})
it('does not ask when only weekdays outside the plan are occupied', () => {
useStore.setState(s => ({ S: { ...s.S, week: { 2: 'mine', 4: 'mine' } } })) // Tue + Thu
choose('5×5') // wants Mon/Wed/Fri
expect(useUI.getState().sheets).toHaveLength(0)
expect(nameOn(1)).toBe('5×5 A')
})
})
describe('loadStarterPlan', () => {
it('appends independent routines each time the same plan is loaded', () => {
loadStarterPlan('ppl')
const first = S().routines.slice(1).map(r => r.id)
loadStarterPlan('ppl')
const second = S().routines.slice(4).map(r => r.id)
expect(S().routines).toHaveLength(7)
expect(new Set([...first, ...second]).size).toBe(6)
expect(second.some(id => first.includes(id))).toBe(false)
})
it('refuses a plan it does not know and changes nothing', () => {
const before = structuredClone(S())
expect(loadStarterPlan('nope')).toBe(false)
expect(loadStarterPlan(undefined)).toBe(false)
expect(S()).toEqual(before)
expect(useUI.getState().toastMsg).toBe('')
})
})
+4
View File
@@ -14,6 +14,10 @@ export const DEF = {
theme: 'dark', accent: 'lime', body: 'male', targetW: null,
bodyweight: [], routines: [], week: {}, dayPlan: {},
exWeights: {}, workouts: [], active: null, customEx: [], gifSize: 'full',
// How the active workout is laid out — 'cards' (one exercise at a time with Prev/Next)
// or 'list' (every exercise stacked and scrollable). Purely presentational: profiles
// written before this setting existed overlay onto DEF and keep the 'cards' behaviour.
workoutView: 'cards',
// effort: which per-set effort scale is logged — 'none' | 'rir' | 'rpe'. null, not 'none', so
// that a profile which never chose (loaded state is overlaid on DEF, on every path: local,
// server pull, backup import) still falls back to the `showRir` boolean this replaced and
+28 -5
View File
@@ -13,6 +13,16 @@ const cancelPushRestTimer = () => { if (useStore.getState().user) api('/api/push
const notificationsSupported = () => typeof window !== 'undefined' && 'Notification' in window
let requestRestNotificationPermissionP = null
// Set the moment the tab goes hidden, never cleared here — timerTick/workTick read and
// clear it themselves once they're running visible again. Lets a completion tick tell
// "the countdown hit zero while the app was actually open" from "it hit zero while
// backgrounded/closed and we're only just catching up now that it's open again" — the
// latter must skip beep/vibrate/flash/toast and rely solely on the push notification.
let pageHiddenAt = null
if (typeof document !== 'undefined') {
document.addEventListener('visibilitychange', () => { if (document.hidden) pageHiddenAt = Date.now() })
}
const requestRestNotificationPermission = async () => {
if (!notificationsSupported()) return false
if (Notification.permission === 'granted') return true
@@ -59,7 +69,7 @@ export const useUI = create((set, get) => ({
timer: null, // rest countdown between sets — { left, total, endsAt, forIdx }
// forIdx: index of the active entry whose set started the rest (undefined when unknown)
work: null, // work countdown DURING a timed set (issue #16) — { left, total, endsAt, label }
timerFlashId: 0, // changing the id remounts the four-pulse visual alert
timerFlashId: 0, // changing the id retriggers the theme-blink visual alert
flashTimer() {
if (!useStore.getState().S.timerFlash) return
@@ -94,11 +104,20 @@ export const useUI = create((set, get) => ({
const tm = get().timer
if (!tm) return
const left = Math.max(0, Math.round((tm.endsAt - Date.now()) / 1000))
const seenLive = !document.hidden && pageHiddenAt === null
if (!document.hidden) pageHiddenAt = null
if (left === tm.left) return
const snd = useStore.getState().S.sound
if (left <= 0) {
beep(snd, 880, 0.15); beep(snd, 880, 0.15, 0.25); beep(snd, 1320, 0.4, 0.5)
vibrate([200, 100, 200]); get().flashTimer(); maybeRestNotification(); get().toast(t('Rest over — next set!')); get().stopRest(); return
if (seenLive) {
beep(snd, 880, 0.15); beep(snd, 880, 0.15, 0.25); beep(snd, 1320, 0.4, 0.5)
vibrate([200, 100, 200]); get().flashTimer()
}
// The toast stays even when the rest ran out while the app was hidden: a guest, or anyone
// without push permission, gets no notification, and a countdown that silently vanishes
// on reopen reads like a bug. Only the loud parts (beep, vibration, flash) are gated.
get().toast(t('Rest over — next set!'))
maybeRestNotification(); get().stopRest(); return
}
if (left <= 3) beep(snd, 660, 0.1)
set({ timer: { ...tm, left } })
@@ -149,11 +168,15 @@ export const useUI = create((set, get) => ({
const wk = get().work
if (!wk) return
const left = Math.max(0, Math.round((wk.endsAt - Date.now()) / 1000))
const seenLive = !document.hidden && pageHiddenAt === null
if (!document.hidden) pageHiddenAt = null
if (left === wk.left) return
const snd = useStore.getState().S.sound
if (left <= 0) {
beep(snd, 880, 0.15); beep(snd, 880, 0.15, 0.25); beep(snd, 1320, 0.4, 0.5)
vibrate([200, 100, 200]); get().flashTimer()
if (seenLive) {
beep(snd, 880, 0.15); beep(snd, 880, 0.15, 0.25); beep(snd, 1320, 0.4, 0.5)
vibrate([200, 100, 200]); get().flashTimer()
}
const done = workDone
get().stopWork()
if (done) done(wk.total)
+31
View File
@@ -64,4 +64,35 @@ describe('opt-in timer screen flash', () => {
vi.advanceTimersByTime(1000)
expect(useUI.getState().timerFlashId).toBe(1)
})
const goHidden = () => { Object.defineProperty(document, 'hidden', { value: true, configurable: true }); document.dispatchEvent(new Event('visibilitychange')) }
const goVisible = () => { Object.defineProperty(document, 'hidden', { value: false, configurable: true }); document.dispatchEvent(new Event('visibilitychange')) }
afterEach(() => goVisible()) // leave document.hidden the way every other test expects it
it('does not flash a rest that expires while the app is hidden, even once reopened', () => {
useStore.setState({ S: { ...useStore.getState().S, timerFlash: true } })
useUI.getState().startRest(90)
goHidden()
vi.setSystemTime(Date.now() + 91_000) // deadline passes with no ticks — the app was actually closed/suspended
goVisible() // reopening re-fires visibilitychange, which is how the bug used to trigger
expect(useUI.getState().timerFlashId).toBe(0)
expect(useUI.getState().timer).toBe(null)
})
it('does not flash a timed exercise that finishes while the app is hidden', () => {
useStore.setState({ S: { ...useStore.getState().S, timerFlash: true } })
useUI.getState().startWork(90, 'Plank', vi.fn())
goHidden()
vi.setSystemTime(Date.now() + 91_000)
goVisible()
expect(useUI.getState().timerFlashId).toBe(0)
expect(useUI.getState().work).toBe(null)
})
it('still flashes a rest that expires normally while the app stays visible', () => {
useStore.setState({ S: { ...useStore.getState().S, timerFlash: true } })
useUI.getState().startRest(1)
vi.advanceTimersByTime(1000)
expect(useUI.getState().timerFlashId).toBe(1)
})
})
+3 -3
View File
@@ -4,7 +4,7 @@ import { useStore } from '../store/useStore.js'
import { effectiveRoutine, effectiveRoutineId, nextTrainingDay, streakWeeks, lastBW, setsDoneActive } from '../lib/history.js'
import { fmtNum, fmtDate, todayISO, isoOf, weekKey, weekStartOf, weekDayOffset, DAYS, DAYN } from '../lib/format.js'
import { t, dateLocale } from '../lib/i18n.js'
import { bwSheet, goalSheet, dayOverrideSheet, calendarSheet, startFlow, loadStarterPlan, bwDeltaColor } from '../sheets.jsx'
import { bwSheet, goalSheet, dayOverrideSheet, calendarSheet, startFlow, starterPlanSheet, bwDeltaColor } from '../sheets.jsx'
import LineChart from '../components/LineChart.jsx'
import Icon from '../components/Icon.jsx'
import { Button } from '../components/ui.jsx'
@@ -117,8 +117,8 @@ export default function Home() {
<span className="lrow-i"><Icon name="sparkles" /></span>
<div className="big" style={{ fontSize: 22 }}>{t('Welcome!')}</div>
</div>
<div className="muted small" style={{ marginBottom: 12 }}>{t('Set up your weekly routine to get going — or load a ready-made Push / Pull / Legs plan.')}</div>
<Button variant="primary" icon="sparkles" onClick={loadStarterPlan}>{t('Load starter plan (PPL)')}</Button>
<div className="muted small" style={{ marginBottom: 12 }}>{t('Set up your weekly routine to get going — or load a ready-made starter plan.')}</div>
<Button variant="primary" icon="sparkles" onClick={starterPlanSheet}>{t('Load starter plan')}</Button>
<div style={{ height: 8 }} /><Button onClick={() => nav('/plan')}>{t('Build my own plan')}</Button>
</div>
)}
+5 -1
View File
@@ -1,4 +1,5 @@
import { useRef, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useStore } from '../store/useStore.js'
import { EXDB, BODYPARTS, allExercises, equipmentOf, matchExercise } from '../lib/exercises.js'
import { activeProfile, exAvailable } from '../lib/equipment.js'
@@ -12,6 +13,7 @@ import { Button } from '../components/ui.jsx'
import { tappable, useRevealActiveChip } from '../lib/use-sheet-keyboard.js'
export default function Library() {
const nav = useNavigate()
const S = useStore(s => s.S)
const [q, setQ] = useState('')
const [bp, setBp] = useState('')
@@ -30,7 +32,9 @@ export default function Library() {
useRevealActiveChip(eqStrip, eqOn)
return <>
<div className="hdr"><div><h1>{t('Exercises')}</h1><div className="sub">{t('{0} exercises with animations', EXDB.length)}</div></div></div>
<div className="hdr"><div><h1>{t('Exercises')}</h1><div className="sub">{t('{0} exercises with animations', EXDB.length)}</div></div>
<Button size="sm" variant="tinted" icon="target" onClick={() => nav('/muscles')}>{t('By muscle')}</Button>
</div>
<div className="search" style={{ marginBottom: 10 }}><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…')} value={q} onChange={e => { setQ(e.target.value); setShown(40) }} /></div>
{profile && <div className="small dim row" style={{ margin: '-4px 2px 10px', gap: 6, alignItems: 'center' }}>
+15
View File
@@ -0,0 +1,15 @@
import { useNavigate } from 'react-router-dom'
import { t } from '../lib/i18n.js'
import MuscleExplorer from '../components/MuscleExplorer.jsx'
import { exerciseDetailSheet, addToRoutineSheet } from '../sheets.jsx'
import Icon from '../components/Icon.jsx'
export default function Muscles() {
const nav = useNavigate()
return <>
<div className="hdr"><button className="iconbtn" onClick={() => nav('/library')} aria-label={t('Exercises')}><Icon name="chevronLeft" /></button>
<div style={{ flex: 1, marginLeft: 12 }}><h1>{t('Explore muscles')}</h1><div className="sub">{t('Choose a muscle to see exercises that train it.')}</div></div></div>
<MuscleExplorer onDetail={exerciseDetailSheet} onPlan={addToRoutineSheet} />
</>
}
+2 -2
View File
@@ -2,7 +2,7 @@ import { useNavigate } from 'react-router-dom'
import { useStore } from '../store/useStore.js'
import { DAYN, weekOrder, weekStartOf, uid, exCount } from '../lib/format.js'
import { t } from '../lib/i18n.js'
import { dayAssignSheet, loadStarterPlan, planToolsSheet } from '../sheets.jsx'
import { dayAssignSheet, starterPlanSheet, planToolsSheet } from '../sheets.jsx'
import Icon from '../components/Icon.jsx'
import { Button } from '../components/ui.jsx'
import { tappable } from '../lib/use-sheet-keyboard.js'
@@ -66,7 +66,7 @@ export default function Plan() {
<div className="grow"><div className="tt">{r.name}</div><div className="ss">{exCount(r.ex.length)}</div></div>
<Icon name="chevronRight" className="chev" /></div>)}</div> : <>
<div className="empty"><div className="ico"><Icon name="clipboard" /></div>{t('No routines yet.')}<br />{t('Create one or load the starter plan.')}</div>
<Button icon="sparkles" onClick={loadStarterPlan}>{t('Load starter plan (Push / Pull / Legs)')}</Button>
<Button icon="sparkles" onClick={starterPlanSheet}>{t('Load starter plan')}</Button>
</>}
</div></div>
</>
+18 -2
View File
@@ -1,16 +1,18 @@
import { useNavigate, useParams } from 'react-router-dom'
import { useEffect, useRef, useState } from 'react'
import { useStore } from '../store/useStore.js'
import { useUI } from '../store/useUI.js'
import { exOr } from '../lib/exercises.js'
import { activeProfile, exAvailable } from '../lib/equipment.js'
import { uid } from '../lib/format.js'
import { t, exerciseNameFor } from '../lib/i18n.js'
import { supersetUnits, moveSupersetUnit, cleanupSg, exLine } from '../lib/history.js'
import { supersetUnits, moveSupersetUnit, cleanupSg, exLine, defaultConfig } from '../lib/history.js'
import { Thumb } from '../components/Media.jsx'
import { glyphPicker, exercisePicker, exConfigSheet, confirmSheet } from '../sheets.jsx'
import Icon from '../components/Icon.jsx'
import { glyphOf } from '../lib/glyphs.js'
import { Button, Row, SelectRow, Switch } from '../components/ui.jsx'
import { copyRoutine } from '../lib/routines.js'
import { POLICIES_FOR, POLICY_NAME, POLICY_DESC } from '../lib/progression.js'
import BodyMap from '../components/BodyMap.jsx'
import { loadOfRoutine, rankOf, MUSCLE_NAME } from '../lib/muscles.js'
@@ -305,6 +307,7 @@ export default function RoutineEdit() {
const { id } = useParams()
const S = useStore(s => s.S)
const update = useStore(s => s.update)
const toast = useUI(s => s.toast)
const r = S.routines.find(x => x.id === id)
useEffect(() => { if (!r) nav('/plan') }, [!!r])
// Editing here has no explicit "save" — every field change persists immediately. A single
@@ -423,7 +426,20 @@ export default function RoutineEdit() {
})()}
<div className="small dim row" style={{ margin: '10px 2px', gap: 5 }}><Icon name="link" style={{ fontSize: 13 }} />{t('Tap the link button on an exercise to superset it with the one above — you’ll do them back-to-back.')}</div>
<Button variant="primary" onClick={() => exercisePicker(ex => exConfigSheet(ex, null, cfg => edit(x => { x.push({ id: ex.id, ...cfg }) }), null, r))} icon="plus">{t('Add exercise')}</Button>
<Button variant="primary" onClick={() => exercisePicker((ex, quick) => {
if (quick) {
edit(x => x.push({ id: ex.id, ...defaultConfig(ex.id) }))
toast(t('“{0}” added to {1}', exerciseNameFor(ex), r.name))
} else {
exConfigSheet(ex, null, cfg => edit(x => { x.push({ id: ex.id, ...cfg }) }), null, r)
}
})} icon="plus">{t('Add exercise')}</Button>
<div style={{ height: 10 }} />
<Button onClick={() => {
const copy = copyRoutine(r, t('Copy'))
update(s => { s.routines.push(copy) })
nav('/plan/r/' + copy.id)
}}>{t('Copy routine')}</Button>
<div style={{ height: 10 }} />
<Button variant="danger" onClick={() => confirmSheet({
title: t('Delete routine?'), message: t('“{0}” and its exercises will be removed.', r.name), confirmText: t('Delete'), danger: true,
+1 -1
View File
@@ -41,7 +41,7 @@ vi.mock('../lib/wakelock.js', () => ({ wakeLockSupported: () => false }))
vi.mock('../lib/mobile.js', () => ({ MOBILE: false, shareExport: vi.fn(), syncReminder: vi.fn() }))
vi.mock('./MobileOnboarding.jsx', () => ({ ConnectSheet: () => null }))
vi.mock('../sheets.jsx', () => ({
loadStarterPlan: vi.fn(), confirmSheet: vi.fn(), importFromApp: vi.fn(),
starterPlanSheet: vi.fn(), confirmSheet: vi.fn(), importFromApp: vi.fn(),
importFromHevy: vi.fn(), equipmentProfileSheet: vi.fn(),
}))
+10 -2
View File
@@ -11,7 +11,7 @@ import { t, LANGS, INSTR_LANGS } from '../lib/i18n.js'
import { DEMO, REPO } from '../lib/demo.js'
import { MOBILE, shareExport, syncReminder } from '../lib/mobile.js'
import { ConnectSheet } from './MobileOnboarding.jsx'
import { loadStarterPlan, confirmSheet, importFromApp, importFromHevy, equipmentProfileSheet } from '../sheets.jsx'
import { starterPlanSheet, confirmSheet, importFromApp, importFromHevy, equipmentProfileSheet } from '../sheets.jsx'
import Icon from '../components/Icon.jsx'
import { Section, Row, SelectRow, Switch, Segmented, Button, TextField } from '../components/ui.jsx'
@@ -149,6 +149,14 @@ export default function Settings() {
{/* ---------- during a workout ---------- */}
<Section title={t('During a workout')} footer={wakeOK ? t('The screen stays on while a workout is running, so you don’t have to unlock your phone between sets.') : null}>
{/* One exercise at a time (cards with Prev/Next) or the whole session stacked as a
scrollable list. Legacy/unknown values read as cards. */}
<Row icon="list" iconTint="var(--blue)" title={t('Workout view')}>
<Segmented className="seg-inline"
options={[{ value: 'cards', label: t('Cards') }, { value: 'list', label: t('List') }]}
value={S.workoutView === 'list' ? 'list' : 'cards'}
onChange={v => update(s => { s.workoutView = v })} />
</Row>
<SelectRow icon="timer" iconTint="var(--orange)" title={t('Rest timer')}
value={S.restSec} onChange={v => update(s => { s.restSec = v })}
options={[{ value: 0, label: t('Off') }, ...[60, 90, 120, 150, 180].map(v => ({ value: v, label: v + 's' }))]} />
@@ -231,7 +239,7 @@ export default function Settings() {
{/* ---------- data: fill it, bring things over, back it up, wipe it ---------- */}
<Section title={t('Data')}>
<Row icon="sparkles" iconTint="var(--acc)" title={t('Load starter plan (PPL)')} accessory="chevron" onClick={loadStarterPlan} />
<Row icon="sparkles" iconTint="var(--acc)" title={t('Load starter plan')} accessory="chevron" onClick={starterPlanSheet} />
<Row icon="shuffle" iconTint="var(--teal)" title={t('Import from another app')}
subtitle={t('FitNotes, Strong, Hevy — or body weight from Apple Health')}
accessory="chevron" onClick={() => importRef.current.click()} />
@@ -0,0 +1,89 @@
// @vitest-environment happy-dom
import React, { act } from 'react'
import { createRoot } from 'react-dom/client'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import Settings from './Settings.jsx'
globalThis.IS_REACT_ACT_ENVIRONMENT = true
const mocks = vi.hoisted(() => {
const state = { S: null }
state.snapshot = () => ({
S: state.S,
user: null,
update: mut => {
const next = structuredClone(state.S)
mut(next)
state.S = next
},
replaceState: vi.fn(), setUser: vi.fn(), pullState: vi.fn(), pushState: vi.fn(),
signOut: vi.fn(), signOutAll: vi.fn(), resetDemo: vi.fn(), disconnectServer: vi.fn(),
})
return state
})
vi.mock('../store/useStore.js', () => {
const useStore = selector => selector ? selector(mocks.snapshot()) : mocks.snapshot()
useStore.getState = mocks.snapshot
return { useStore, DEF: { reminder: { time: '17:30' } }, hasData: () => false }
})
vi.mock('../store/useUI.js', () => {
const snap = () => ({ toast: vi.fn(), openSheet: vi.fn() })
const useUI = selector => selector ? selector(snap()) : snap()
useUI.getState = snap
return { useUI }
})
vi.mock('react-router-dom', () => ({ useNavigate: () => () => {} }))
vi.mock('../lib/api.js', () => ({
api: vi.fn(), webauthnOK: () => false, passkeyLogin: vi.fn(), passkeyRegister: vi.fn(), IS_ANDROID: false,
}))
vi.mock('../lib/push.js', () => ({ pushSupported: () => false, enablePush: vi.fn(), disablePush: vi.fn(), sendTestPush: vi.fn() }))
vi.mock('../lib/wakelock.js', () => ({ wakeLockSupported: () => false }))
vi.mock('../lib/mobile.js', () => ({ MOBILE: false, shareExport: vi.fn(), syncReminder: vi.fn() }))
vi.mock('./MobileOnboarding.jsx', () => ({ ConnectSheet: () => null }))
vi.mock('../sheets.jsx', () => ({
loadStarterPlan: vi.fn(), starterPlanSheet: vi.fn(), confirmSheet: vi.fn(), importFromApp: vi.fn(),
importFromHevy: vi.fn(), equipmentProfileSheet: vi.fn(),
}))
// The Settings view reads the build-time version constant at render time.
globalThis.__APP_VERSION__ ??= 'test'
let host, root
beforeEach(() => {
mocks.S = {
unit: 'kg', restSec: 90, restPauseSec: 15, sound: false, effort: 'none',
gifSize: 'full', workouts: [], routines: [], exWeights: {},
}
host = document.createElement('div')
document.body.appendChild(host)
root = createRoot(host)
})
afterEach(() => {
act(() => root.unmount())
host.remove()
})
const mount = () => act(() => root.render(<Settings />))
const segButton = label => [...host.querySelectorAll('.seg button')].find(b => b.textContent === label)
describe('Settings — workout view', () => {
it('offers Cards / List and writes workoutView to the store', () => {
mount()
expect(segButton('Cards')).toBeTruthy()
expect(segButton('List')).toBeTruthy()
expect(segButton('Cards').getAttribute('aria-pressed')).toBe('true')
act(() => { segButton('List').click() })
expect(mocks.S.workoutView).toBe('list')
mount()
expect(segButton('List').getAttribute('aria-pressed')).toBe('true')
act(() => { segButton('Cards').click() })
expect(mocks.S.workoutView).toBe('cards')
})
it('shows a legacy/absent value as Cards', () => {
delete mocks.S.workoutView
mount()
expect(segButton('Cards').getAttribute('aria-pressed')).toBe('true')
expect(segButton('List').getAttribute('aria-pressed')).toBe('false')
})
})
+2 -1
View File
@@ -35,7 +35,8 @@ describe('Stats mixed-entry metric contract', () => {
expect(uiSource).toContain('sheetTitle, stackedValue = false')
expect(uiSource).toContain("className={stackedValue ? 'lrow-stack-value' : ''}")
expect(cssSource).toContain('.lrow.lrow-stack-value .lrow-m{grid-column:1;grid-row:1}')
expect(cssSource).toContain('.lrow.lrow-stack-value .lrow-v{grid-column:1;grid-row:2;text-align:left}')
expect(cssSource).toContain('.lrow.lrow-stack-value .lrow-v{grid-column:1;grid-row:2;width:100%;max-width:none;text-align:left}')
expect(cssSource).toContain('flex:0 1 auto;max-width:45%;min-width:0;')
expect(cssSource).toContain('overflow:hidden;text-overflow:ellipsis;white-space:nowrap')
})
})
+157 -66
View File
@@ -4,17 +4,17 @@ import { useStore } from '../store/useStore.js'
import { useUI } from '../store/useUI.js'
import { exOr } from '../lib/exercises.js'
import { usesBar, barWeightFor, plateSplit } from '../lib/bar.js'
import { effectiveRoutine, lastEntryFor, bestWeightFor, buildSets, freestyleConfig, defaultConfig, setsDoneActive, supersetUnits, unitOf, setLabel, modeOf, isBw, isPerSide, sideReps, repStep, EFFORT, effortOf, stepEffort, capEffort, cascadeWeight, insertWarmupRow, removeRowAt, pairAdjacent, unpairSuperset, cleanupSg, applyIntensifierPlan, pinnedNoteFor, exNoteFor } from '../lib/history.js'
import { effectiveRoutine, lastEntryFor, bestWeightFor, bestWeightForEntry, buildSets, freestyleConfig, defaultConfig, setsDoneActive, supersetUnits, unitOf, setLabel, modeOf, isBw, isPerSide, sideReps, repStep, EFFORT, effortOf, stepEffort, capEffort, cascadeWeight, insertWarmupRow, removeRowAt, pairAdjacent, unpairSuperset, cleanupSg, applyIntensifierPlan, pinnedNoteFor, exNoteFor } from '../lib/history.js'
import { fmtNum, fmtDate, todayISO, exCount, DAYN } from '../lib/format.js'
import { beep, vibrate } from '../lib/sound.js'
import { t, exerciseNameFor } from '../lib/i18n.js'
import { api } from '../lib/api.js'
import { insertionIndexAfterCurrentUnit, nextUnfinishedUnit, setProgressHighWater, supersetFlowStep, restAfterSet, restOnRecheck, restSecFor } from '../lib/supersetFlow.js'
import Media from '../components/Media.jsx'
import { startFlow, exercisePicker, exConfigSheet, exerciseDetailSheet, topWeightSheet, finishWorkout, workoutCompleteSheet, confirmSheet, exerciseNoteSheet, sessionNoteSheet, swapActiveWorkoutExercise, barWeightSheet } from '../sheets.jsx'
import { startFlow, exercisePicker, exConfigSheet, exerciseDetailSheet, finishWorkout, workoutCompleteSheet, confirmSheet, exerciseNoteSheet, sessionNoteSheet, swapActiveWorkoutExercise, barWeightSheet } from '../sheets.jsx'
import Icon from '../components/Icon.jsx'
import { Button, Check, NumberField } from '../components/ui.jsx'
import { nextPrescription, applyPrescription, defaultIncrement } from '../lib/progression.js'
import { nextPrescription, applyPrescription, defaultIncrement, weightIncrement, stepWeight } from '../lib/progression.js'
import { progressionGuidance } from '../lib/progression-copy.js'
import { glyphOf } from '../lib/glyphs.js'
import { isWarmupRow, isDropSet, isRestPauseSet, dropsOf, clustersOf, addDrop, addCluster, removeDropAt, removeClusterAt, setDropAt, setClusterAt, nextDropWeight, nextBurstReps } from '../lib/workout-model.js'
@@ -107,8 +107,7 @@ function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemov
// Only worth surfacing while there is still work left: once the exercise is finished, a note
// telling you what to do in it is behind you, and the block is already long.
const pinnedNote = entry.sets.some(s => !s.done) ? pinnedNoteFor(S, entry.id) : null
// The same number the "confirm your working weight" sheet calls your best, so the two
// never disagree inside one session: heaviest logged set, or the working weight you kept.
// The number is the heaviest logged set, or the working weight you kept.
const best = cardio ? 0 : Math.max(bestWeightFor(S, entry.id), (S.exWeights[entry.id] || {}).w || 0)
// What the progression policy decided for this session, and why (issue #17). Computed when
// the session was built so the reason matches the numbers already in the rows.
@@ -120,7 +119,8 @@ function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemov
const cfg = { ...(entry.target || {}), id: entry.id }
const bw = !cardio && isBw(cfg)
const added = bw && entry.sets.some(s => s.w > 0)
const loadCol = { f: 'w', step: 2.5, dec: true, hd: bw ? t('Added ({0})', S.unit) : t('Weight ({0})', S.unit) }
const loadStep = mode === 'reps' ? weightIncrement(cfg, S.unit) : 2.5
const loadCol = { f: 'w', step: loadStep, dec: true, hd: bw ? t('Added ({0})', S.unit) : t('Weight ({0})', S.unit) }
// The reps column is the total in every mode, unilateral included — the stepper walks in
// twos there so the number you land on is one you can actually split evenly.
const repCol = { f: 'r', step: repStep(cfg), dec: false, hd: t('Reps') }
@@ -139,8 +139,16 @@ function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemov
// The effort column walks its own scale — see stepEffort. Weight and reps step up from 0
// with no ceiling, as they always did.
const bump = (s, i, col, dir) => {
if (col.eff) return onField(i, col.f, stepEffort(col.eff, s[col.f], dir))
onField(i, col.f, Math.max(0, Math.round(((s[col.f] || 0) + dir * col.step) * 100) / 100))
// Read the current value directly from the store rather than from the render-time snapshot.
// In a superset both ExerciseBlock instances share the same store subscription, so when one
// member's field changes the partner re-renders too, replacing the closure's `s` reference
// with a fresh clone before the next tap fires. Reading from the store avoids that stale-
// closure problem entirely and keeps every tap operating on the real current value.
const fresh = useStore.getState().S.active?.entries[entryIdx]?.sets[i]
const cur = fresh ? fresh[col.f] : s[col.f]
if (col.eff) return onField(i, col.f, stepEffort(col.eff, cur, dir))
if (mode === 'reps' && col.f === 'w') return onField(i, col.f, stepWeight(cur, col.step, dir))
onField(i, col.f, Math.max(0, Math.round(((cur || 0) + dir * col.step) * 100) / 100))
}
// Uses the shared stepper markup so a set row picks up the same control styling
// as every other +/- field in the app.
@@ -155,11 +163,11 @@ function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemov
)
// A smaller stepper for a drop's weight/reps or a burst's reps — editing what the plan (or a
// live "+ Drop"/"+ Burst" tap) already put on the row, not typing into a fresh field.
const miniStepper = (value, step, dec, onChange) => (
const miniStepper = (value, step, dec, onChange, snapWeightStep = false) => (
<div className="stp mini">
<button aria-label="Decrease" onClick={() => onChange(Math.max(0, Math.round(((value || 0) - step) * 100) / 100))}><Icon name="minus" /></button>
<button aria-label="Decrease" onClick={() => onChange(snapWeightStep ? stepWeight(value, step, -1) : Math.max(0, Math.round(((value || 0) - step) * 100) / 100))}><Icon name="minus" /></button>
<span className="val"><NumberField decimal={dec} value={value ?? ''} onChange={onChange} /></span>
<button aria-label="Increase" onClick={() => onChange(Math.max(0, Math.round(((value || 0) + step) * 100) / 100))}><Icon name="plus" /></button>
<button aria-label="Increase" onClick={() => onChange(snapWeightStep ? stepWeight(value, step, 1) : Math.max(0, Math.round(((value || 0) + step) * 100) / 100))}><Icon name="plus" /></button>
</div>
)
return <>
@@ -252,7 +260,7 @@ function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemov
{dropsOf(s).map((d, di) => (
<div className="subrow" key={'d' + di}>
<span className="subn">{t('Drop {0}', di + 1)}</span>
{miniStepper(d.w, 2.5, true, v => setDropField(i, di, 'w', v))}
{miniStepper(d.w, loadStep, true, v => setDropField(i, di, 'w', v), true)}
{miniStepper(d.r, 1, false, v => setDropField(i, di, 'r', v))}
<button className="iconbtn" aria-label={t('Remove drop')} onClick={() => removeDrop(i, di)}><Icon name="xmark" /></button>
</div>
@@ -320,6 +328,12 @@ function ActiveWorkout() {
const unit = A.entries.length ? unitOf(units, cur) : []
const unitIdx = units.findIndex(u => u === unit)
const isSuperset = unit.length > 1
// Cards show one unit at a time with Prev/Next + swipe; list stacks every unit so the
// whole session is visible and scrollable (Settings → During a workout → Workout view).
// Every set handler below is already entry-index parameterised, so list mode only changes
// what is rendered — completion, rest, top-weight and auto-advance share one path.
// Unknown/absent values read as cards, keeping every pre-existing profile as it was.
const listMode = S.workoutView === 'list'
// Superset flow: center the actionable row when completing a set moves to the partner or
// back to the first exercise of the next round. Entry-bound maps keep repeated exercise IDs
// distinct, while each rendered set index identifies the existing row within that entry.
@@ -360,13 +374,13 @@ function ActiveWorkout() {
}
})
useEffect(() => {
if (!isSuperset) return
if (!isSuperset || listMode) return
const entry = A.entries[cur]
const firstIncomplete = entry?.sets.findIndex(s => !s.done) ?? -1
const setIdx = firstIncomplete >= 0 ? firstIncomplete : (entry?.sets.length ?? 0) - 1
const el = (setIdx >= 0 && setRefs.current.get(entry)?.get(setIdx)) || exRefs.current.get(entry)
if (el && typeof el.scrollIntoView === 'function') el.scrollIntoView({ behavior: 'smooth', block: 'center' })
}, [cur, isSuperset, A.entries.length])
}, [cur, isSuperset, listMode, A.entries.length])
const total = A.entries.reduce((n, e) => n + e.sets.length, 0)
const done = setsDoneActive(A)
@@ -423,6 +437,17 @@ function ActiveWorkout() {
}, true)
}
// One prop object per entry so the card and list layouts share the exact same wiring.
const blockProps = idx => ({
onToggle: i => toggle(idx, i),
onField: (i, f, v) => setField(idx, i, f, v),
onAddSet: () => addSet(idx),
onRemoveSet: () => removeSet(idx),
onAddWarmup: () => addWarmup(idx),
onRemoveSetAt: i => removeSetAt(idx, i),
onStartTimed: i => startTimed(idx, i),
onProgressionSettings: () => openProgressionSettings(idx),
})
const navigateUnit = direction => {
const targetFor = active => {
if (!active || !Array.isArray(active.entries) || !Number.isInteger(active.cur)) return null
@@ -437,6 +462,10 @@ function ActiveWorkout() {
if (target != null) s.active.cur = target
})
}
// List mode shows every unit at once, so the "current" exercise is chosen by tapping
// "Set current" on its header instead of Prev/Next. The bottom Move/Swap/Remove actions
// keep operating on it, and completing sets still advances it on its own.
const focusUnit = firstIdx => update(s => { if (s.active) s.active.cur = firstIdx })
const onSwipePointerDown = event => {
if (swipe.current || (event.pointerType && event.pointerType !== 'touch' && event.pointerType !== 'pen')) return
if (event.target.closest?.(SWIPE_IGNORED_TARGETS)) return
@@ -459,28 +488,43 @@ function ActiveWorkout() {
const state = useStore.getState().S
const entry = state.active?.entries?.[idx]
if (!entry) return
const activeId = state.active.id
const entryId = entry.id
const entryCount = state.active.entries.length
const routine = state.routines.find(r => r.id === state.active.routineId)
exConfigSheet(exOr(entry.id), entry.target, cfg => update(s => {
const activeEntry = s.active?.entries?.[idx]
if (!activeEntry) return
const full = { ...cfg, id: activeEntry.id }
const activeRoutine = s.routines.find(r => r.id === s.active.routineId)
const step = defaultIncrement(activeEntry.id, s.unit)
// A config without a set count keeps the rows the session already has.
if (!(full.sets > 0)) full.sets = activeEntry.sets.filter(x => !isWarmupRow(x)).length || 1
const plan = nextPrescription(s, full, activeRoutine)
// The sheet edits sets, reps, weight and warm-ups as well as the rule — so the rows are
// rebuilt from the new config the way the session was, and only what you already logged
// is kept in place (done warm-ups first, then done work sets, then the fresh remainder).
const fresh = applyIntensifierPlan(applyPrescription(buildSets(s, full, { step }), plan, step), full)
const doneWarm = activeEntry.sets.filter(x => x.done && isWarmupRow(x))
const doneWork = activeEntry.sets.filter(x => x.done && !isWarmupRow(x))
const freshWarm = fresh.filter(isWarmupRow)
const freshWork = fresh.filter(x => !isWarmupRow(x))
activeEntry.target = { ...cfg }
activeEntry.plan = plan
activeEntry.sets = [...doneWarm, ...freshWarm.slice(doneWarm.length), ...doneWork, ...freshWork.slice(doneWork.length)]
}), null, routine)
exConfigSheet(exOr(entryId), entry.target, cfg => {
// Store updates clone the state tree. If this exact object is no longer at the captured
// index, the list changed while the sheet was open; an id check alone cannot distinguish
// duplicate occurrences of the same exercise, so fail closed before cloning again.
// Every store write clones the tree (the bar-weight stepper inside this very sheet does
// one), so object identity is useless here. Same workout, same list length and the same
// exercise at the captured index is what "nothing shifted" means.
const current = useStore.getState().S
if (current.active?.id !== activeId || current.active.entries?.length !== entryCount || current.active.entries?.[idx]?.id !== entryId) return
update(s => {
const activeEntry = s.active?.id === activeId ? s.active.entries?.[idx] : null
// The sheet may outlive its workout or entry. Never apply its result to whatever later
// happens to occupy the same index.
if (!activeEntry || activeEntry.id !== entryId) return
const full = { ...cfg, id: activeEntry.id }
const activeRoutine = s.routines.find(r => r.id === s.active.routineId)
const step = defaultIncrement(activeEntry.id, s.unit)
// A config without a set count keeps the rows the session already has.
if (!(full.sets > 0)) full.sets = activeEntry.sets.filter(x => !isWarmupRow(x)).length || 1
const plan = nextPrescription(s, full, activeRoutine)
// The sheet edits sets, reps, weight and warm-ups as well as the rule — so the rows are
// rebuilt from the new config the way the session was, and only what you already logged
// is kept in place (done warm-ups first, then done work sets, then the fresh remainder).
const fresh = applyIntensifierPlan(applyPrescription(buildSets(s, full, { step, useTarget: plan.kind === 'off' }), plan, step), full)
const doneWarm = activeEntry.sets.filter(x => x.done && isWarmupRow(x))
const doneWork = activeEntry.sets.filter(x => x.done && !isWarmupRow(x))
const freshWarm = fresh.filter(isWarmupRow)
const freshWork = fresh.filter(x => !isWarmupRow(x))
activeEntry.target = { ...cfg }
activeEntry.plan = plan
activeEntry.sets = [...doneWarm, ...freshWarm.slice(doneWarm.length), ...doneWork, ...freshWork.slice(doneWork.length)]
})
}, null, routine)
}
// Remove a whole exercise from the session. The confirmation always asks first; in a
@@ -530,25 +574,28 @@ function ActiveWorkout() {
const toggle = (idx, i) => {
const m = modeAt(idx)
const cardioEntry = m === 'cardio'
let askTop = false, exJustDone = false, workoutDone = false, checked = false
mutEntry(idx, e => {
let exJustDone = false, workoutDone = false, checked = false
update(s => {
const e = s.active.entries[idx]
e.sets[i].done = !e.sets[i].done
checked = e.sets[i].done
if (e.sets[i].done) {
beep(S.sound, 1040, 0.12); vibrate(30)
const unitDone = unit.every(ui => (ui === idx ? e : A.entries[ui]).sets.every(x => x.done))
// The unit that owns the ticked set — not the marked one. Since !92 the marker no longer
// follows a finished exercise, and in list mode any exercise can be worked on, so judging
// the marker's unit here declared the workout complete after one set elsewhere.
const ownUnit = unitOf(units, idx)
const unitDone = ownUnit.every(ui => (ui === idx ? e : A.entries[ui]).sets.every(x => x.done))
if (unitDone) workoutDone = !nextUnfinishedUnit(A.entries, supersetUnits(A.entries), idx)
// Only loaded reps training has a "working weight" worth confirming — a bodyweight
// plank has nothing to put in that slider, and neither does a set of push-ups
// (issue #32: the fewest taps that still record what happened).
const loaded = m === 'reps' && !(isBw({ ...(e.target || {}), id: e.id }) && !e.sets.some(x => x.w > 0))
if (e.sets.every(x => x.done)) { exJustDone = true; if (loaded && !e.asked) { e.asked = true; askTop = true } }
if (e.sets.every(x => x.done)) {
exJustDone = true
// topW is captured now; exWeights only at the finish (doFinishWorkout), so a typo you
// correct before finishing, or a discarded workout, never becomes the remembered best.
e.topW = bestWeightForEntry(e) || null
}
}
})
// reps: topWeight first (it chains into the finish/continue prompt on the last unit).
// cardio/timed or already-confirmed: go straight to the prompt.
if (askTop) topWeightSheet(idx)
else if (workoutDone) workoutCompleteSheet()
}, true)
if (workoutDone) workoutCompleteSheet()
else if (exJustDone && cardioEntry) useUI.getState().toast(t('Cardio logged'))
else if (exJustDone && m === 'time') useUI.getState().toast(t('Hold logged'))
@@ -584,7 +631,6 @@ function ActiveWorkout() {
// stopRest() first so a rest that belongs after this set replaces the one that was running.
if (freshUnitDone) stopRest()
if (!freshUnit || freshUnit.length <= 1) {
if (freshUnitDone && !askTop && nextUnit?.length) update(s => { if (s.active) s.active.cur = nextUnit[0] })
if (!restBeforeWarmup && restAfterSet({ unitDone: freshUnitDone, lastUnit: freshWorkoutDone })) startRest(restSec, idx)
return
}
@@ -592,11 +638,7 @@ function ActiveWorkout() {
const step = supersetFlowStep(fresh.entries, freshUnit, idx)
if (!step) return
if (step.unitDone) {
if (nextUnit?.length) {
// The top-weight sheet's explicit "Just close" path owns the choice not to advance.
if (!askTop) update(s => { if (s.active) s.active.cur = nextUnit[0] })
if (!restBeforeWarmup) startRest(restSec, idx)
}
if (nextUnit?.length && !restBeforeWarmup) startRest(restSec, idx)
} else {
if (step.nextIdx != null) update(s => { if (s.active) s.active.cur = step.nextIdx })
if (step.roundDone) startRest(restSec, idx)
@@ -640,7 +682,43 @@ function ActiveWorkout() {
<div className="wprog"><i style={{ width: (total ? done / total * 100 : 0) + '%' }} /></div>
{A.backfill && <div className="muted small" style={{ marginBottom: 8 }}>{t('Logging a past workout — no rest timers.')}</div>}
{A.entries.length ? <>
{A.entries.length ? (listMode ? (
<div className="workout-list" data-testid="workout-list">
{units.map((u, ui) => {
const multi = u.length > 1
const isCur = u.includes(cur)
return <section key={u.join('-')} className={'wl-unit' + (isCur ? ' cur' : '')} data-exidx={u[0]}>
<div className="wl-hd">
<span className="muted small">{multi ? t('Superset {0} / {1}', ui + 1, units.length) : t('Exercise {0} / {1}', ui + 1, units.length)}</span>
{isCur
? <span className="tag acc">{t('Current')}</span>
: <button className="chip" onClick={() => focusUnit(u[0])}>{t('Set current')}</button>}
</div>
{multi ? (
<div className="ss-card">
<div className="ss-hd" style={{ justifyContent: 'space-between' }}>
<span className="row" style={{ gap: 5 }}><Icon name="link" />{t('Superset · do these back-to-back, rest when done')}</span>
<Button size="xs" variant="ghost" icon="link" title={t('Unpair')} onClick={() => unpairAt(u[0])}>{t('Unpair')}</Button>
</div>
{u.map((idx, k) => {
const entry = A.entries[idx]
return <div key={idx} ref={el => bindExRef(entry, el)} className="ss-ex" data-exidx={idx}>
{k > 0 && <div className="ss-amp">+</div>}
<ExerciseBlock entryIdx={idx} compact onSetRowRef={(setIdx, el) => bindSetRef(entry, setIdx, el)}
{...blockProps(idx)} />
</div>
})}
</div>
) : (
<ExerciseBlock entryIdx={u[0]}
onPairPrev={u[0] > 0 ? () => pairAt(u[0] - 1, u[0]) : null}
onPairNext={u[0] < A.entries.length - 1 ? () => pairAt(u[0], u[0] + 1) : null}
{...blockProps(u[0])} />
)}
</section>
})}
</div>
) : <>
<div className="muted small" style={{ marginBottom: 6 }}>{isSuperset ? t('Superset {0} / {1}', unitIdx + 1, units.length) : t('Exercise {0} / {1}', unitIdx + 1, units.length)}</div>
<div className="workout-swipe-surface" data-testid="workout-swipe-surface"
onPointerDown={onSwipePointerDown}
@@ -660,38 +738,51 @@ function ActiveWorkout() {
return <div key={idx} ref={el => bindExRef(entry, el)} className="ss-ex" data-exidx={idx}>
{k > 0 && <div className="ss-amp">+</div>}
<ExerciseBlock entryIdx={idx} compact onSetRowRef={(setIdx, el) => bindSetRef(entry, setIdx, el)}
onToggle={i => toggle(idx, i)} onField={(i, f, v) => setField(idx, i, f, v)} onAddSet={() => addSet(idx)} onRemoveSet={() => removeSet(idx)} onAddWarmup={() => addWarmup(idx)} onRemoveSetAt={i => removeSetAt(idx, i)} onStartTimed={i => startTimed(idx, i)} onProgressionSettings={() => openProgressionSettings(idx)} />
{...blockProps(idx)} />
</div>
})}
</div>
) : (
<ExerciseBlock entryIdx={cur} onToggle={i => toggle(cur, i)} onField={(i, f, v) => setField(cur, i, f, v)} onAddSet={() => addSet(cur)} onRemoveSet={() => removeSet(cur)} onAddWarmup={() => addWarmup(cur)} onRemoveSetAt={i => removeSetAt(cur, i)} onStartTimed={i => startTimed(cur, i)} onPairPrev={onPairPrev} onPairNext={onPairNext} onProgressionSettings={() => openProgressionSettings(cur)} />
<ExerciseBlock entryIdx={cur} onPairPrev={onPairPrev} onPairNext={onPairNext} {...blockProps(cur)} />
)}
</div>
</> : <div className="empty"><div className="ico"><Icon name="shuffle" /></div>{t('Freestyle workout — add your first exercise.')}</div>}
</>) : <div className="empty"><div className="ico"><Icon name="shuffle" /></div>{t('Freestyle workout — add your first exercise.')}</div>}
<div style={{ height: 12 }} />
<div className="row">
{!listMode && <div className="row">
<Button icon="chevronLeft" disabled={unitIdx <= 0} onClick={() => navigateUnit(-1)}>{t('Prev')}</Button>
<Button trailingIcon="chevronRight" disabled={unitIdx < 0 || unitIdx >= units.length - 1} onClick={() => navigateUnit(1)}>{t('Next')}</Button>
</div>
<div style={{ height: 10 }} />
<Button onClick={() => exercisePicker(ex => {
</div>}
{!listMode && <div style={{ height: 10 }} />}
{listMode && A.entries.length > 0 && <div className="muted small" style={{ marginBottom: 6 }}>{t('Move, swap and remove below act on the exercise marked {0}.', t('Current'))}</div>}
<Button onClick={() => exercisePicker((ex, quick) => {
const routine = S.routines.find(r => r.id === A.routineId)
const freestyle = !A.routineId
// Freestyle has no routine prescription to apply: show the last target in the config
// sheet and carry its completed rows forward. A planned session keeps its existing path.
// sheet and carry its completed rows forward. A planned session uses its configured
// target when progression is off, while progression-enabled sessions keep their path.
const seed = freestyle ? freestyleConfig(S, { id: ex.id, ...defaultConfig(ex.id) }) : null
exConfigSheet(ex, null, cfg => update(s => {
const commit = cfg => update(s => {
const full = { ...cfg, id: ex.id }
const plan = freestyle ? null : nextPrescription(s, full, s.routines.find(r => r.id === s.active.routineId))
const sets = buildSets(s, full, { step: defaultIncrement(ex.id, s.unit), ...(freestyle ? { preferLast: true } : {}) })
const sets = buildSets(s, full, {
step: defaultIncrement(ex.id, s.unit),
...(freestyle ? { preferLast: true } : {}),
...(plan?.kind === 'off' ? { useTarget: true } : {})
})
const progressed = freestyle ? sets : applyPrescription(sets, plan, defaultIncrement(ex.id, s.unit))
const insertAt = insertionIndexAfterCurrentUnit(supersetUnits(s.active.entries), s.active.cur, s.active.entries.length)
s.active.entries.splice(insertAt, 0, { id: ex.id, target: { ...cfg }, plan, sets: applyIntensifierPlan(progressed, full) })
s.active.cur = insertAt
useUI.getState().shiftRestOwner(insertAt, 1)
}), null, routine, seed)
})
// The "+" on a picker row reads as "add this now" — routed through the same detail
// sheet before, so it added nothing until you'd scrolled past it and found the real
// button. Quick-add commits with the same default (or, freestyle, last-session) config
// the sheet would have opened with; tapping the row still opens that sheet for anyone
// who wants to set sets/reps first.
if (quick) { commit(seed || defaultConfig(ex.id)); useUI.getState().toast(t('“{0}” added to {1}', exerciseNameFor(ex), routine ? routine.name : t('Freestyle'))) }
else exConfigSheet(ex, null, commit, null, routine, seed)
})} icon="plus">{t('Add exercise')}</Button>
{A.entries.length > 0 && <>
<div style={{ height: 6 }} />
+206
View File
@@ -0,0 +1,206 @@
import React, { act } from 'react'
import { createRoot } from 'react-dom/client'
import { parseHTML } from 'linkedom'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import Workout from './Workout.jsx'
// This suite pins down the superset stepper regression: one tap on a +/- button must move the
// value by exactly one step. The bug was a stale closure — in a superset both ExerciseBlock
// instances share the same store subscription, so updating one member's field re-renders the
// partner and replaces the render-time `s` snapshot the button handler had closed over. The
// fix reads the current value from the store at call time. The mocked `update` below clones the
// whole state on every write (structuredClone), which is exactly what invalidates those
// snapshots, so this environment reproduces the original two-taps-per-increment behaviour.
const mocks = vi.hoisted(() => {
const state = {
S: null,
startRest: vi.fn(),
stopRest: vi.fn(),
stopWork: vi.fn(),
toast: vi.fn(),
}
state.storeSnapshot = () => ({
S: state.S,
user: null,
update: mut => {
const next = structuredClone(state.S)
mut(next)
state.S = next
},
})
state.uiSnapshot = () => ({
timer: null,
work: null,
startRest: state.startRest,
stopRest: state.stopRest,
stopWork: state.stopWork,
shiftRestOwner: vi.fn(),
startWork: vi.fn(),
toast: state.toast,
})
return state
})
vi.mock('../store/useStore.js', () => {
const useStore = selector => selector(mocks.storeSnapshot())
useStore.getState = mocks.storeSnapshot
return { useStore }
})
vi.mock('../store/useUI.js', () => {
const useUI = selector => selector ? selector(mocks.uiSnapshot()) : mocks.uiSnapshot()
useUI.getState = mocks.uiSnapshot
return { useUI }
})
vi.mock('react-router-dom', () => ({ useNavigate: () => () => {} }))
vi.mock('../sheets.jsx', () => ({
startFlow: vi.fn(),
exercisePicker: vi.fn(),
exConfigSheet: vi.fn(),
exerciseDetailSheet: vi.fn(),
topWeightSheet: vi.fn(),
finishWorkout: vi.fn(),
workoutCompleteSheet: vi.fn(),
confirmSheet: vi.fn(),
swapActiveWorkoutExercise: vi.fn(),
barWeightSheet: vi.fn(),
exerciseNoteSheet: vi.fn(),
sessionNoteSheet: vi.fn(),
}))
vi.mock('../components/Media.jsx', () => ({ default: () => null }))
vi.mock('../lib/api.js', () => ({
api: vi.fn(() => Promise.resolve({})),
IS_APPLE: false, IS_ANDROID: false, BIO: 'biometrics',
}))
let dom
let root
let container
function exercise(id, sets, extra = {}) {
return {
id,
target: { mode: 'reps', reps: 5, weight: 60, bodyweight: false },
sets: sets.map(done => ({ w: 60, r: 5, done })),
...extra,
}
}
function workout(entries, cur = 0) {
return {
unit: 'kg', restSec: 90, sound: false, effort: 'none', gifSize: 'full',
workouts: [], exWeights: {}, routines: [],
active: { id: 'active', name: 'Test workout', start: Date.now(), cur, entries },
}
}
function installDom() {
const parsed = parseHTML('<!doctype html><html><body><div id="root"></div></body></html>')
dom = parsed.window
globalThis.window = dom
globalThis.document = dom.document
Object.defineProperty(globalThis, 'navigator', { configurable: true, value: dom.navigator })
for (const key of ['HTMLElement', 'Node', 'Element', 'Event', 'Blob']) globalThis[key] = dom[key]
dom.Element.prototype.scrollIntoView = vi.fn()
globalThis.IS_REACT_ACT_ENVIRONMENT = true
container = document.getElementById('root')
root = createRoot(container)
}
async function mount(entries, cur = 0) {
mocks.S = workout(entries, cur)
installDom()
await act(async () => { root.render(React.createElement(Workout)) })
}
async function unmount() {
if (!root) return
await act(async () => { root.unmount() })
root = null
container = null
dom = null
}
// The +/- controls live in `.stp` cells, one per editable column. For a plain reps set the
// order is [weight, reps]; this returns the Increase/Decrease button for a given column of a
// given set row inside a given exercise block (addressed by its data-exidx wrapper).
function stepperButton(exidx, setRow, col, direction) {
const block = container.querySelector(`[data-exidx="${exidx}"]`)
expect(block).toBeTruthy()
const row = block.querySelectorAll('.setrow')[setRow]
expect(row).toBeTruthy()
const cell = row.querySelectorAll('.stp')[col]
expect(cell).toBeTruthy()
return cell.querySelector(`button[aria-label="${direction}"]`)
}
async function tap(button) {
expect(button).toBeTruthy()
await act(async () => { button.dispatchEvent(new dom.Event('click', { bubbles: true })) })
}
beforeEach(() => {
vi.clearAllMocks()
})
afterEach(async () => {
await unmount()
})
describe('superset stepper — one tap moves one step', () => {
// Weight steps by 2.5. A single tap on the first exercise of a superset must land on 62.5,
// not stay at 60 waiting for a second tap.
it('increments a superset member weight by one step per tap', async () => {
await mount([
exercise('press', [false], { sg: 'group' }),
exercise('row', [false], { sg: 'group' }),
])
await tap(stepperButton(0, 0, 0, 'Increase'))
expect(mocks.S.active.entries[0].sets[0].w).toBe(62.5)
})
// Reps step by 1 and do not cascade, so they isolate the stepper from weight's carry-through.
// Three taps must reach 8 (5 -> 6 -> 7 -> 8); the stale closure made every tap after the
// first re-apply against last render's value, so the count would lag behind the taps.
it('advances reps by exactly one per tap across repeated taps', async () => {
await mount([
exercise('press', [false], { sg: 'group' }),
exercise('row', [false], { sg: 'group' }),
])
await tap(stepperButton(0, 0, 1, 'Increase'))
await tap(stepperButton(0, 0, 1, 'Increase'))
await tap(stepperButton(0, 0, 1, 'Increase'))
expect(mocks.S.active.entries[0].sets[0].r).toBe(8)
})
// The partner exercise shares the subscription that gets replaced on every write. Tapping its
// stepper after the first exercise has already been bumped must still act on the partner's own
// current value, not a snapshot from before the clone.
it('steps the partner exercise correctly after the first member was changed', async () => {
await mount([
exercise('press', [false], { sg: 'group' }),
exercise('row', [false], { sg: 'group' }),
])
await tap(stepperButton(0, 0, 1, 'Increase'))
await tap(stepperButton(1, 0, 1, 'Increase'))
expect(mocks.S.active.entries[0].sets[0].r).toBe(6)
expect(mocks.S.active.entries[1].sets[0].r).toBe(6)
})
// Decrement walks the same path and must not undershoot or need a double tap either.
it('decrements a superset member weight by one step per tap', async () => {
await mount([
exercise('press', [false], { sg: 'group' }),
exercise('row', [false], { sg: 'group' }),
])
await tap(stepperButton(0, 0, 0, 'Decrease'))
expect(mocks.S.active.entries[0].sets[0].w).toBe(57.5)
})
})
+261 -16
View File
@@ -3,6 +3,7 @@ import { createRoot } from 'react-dom/client'
import { parseHTML } from 'linkedom'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import Workout from './Workout.jsx'
import { nextPrescription } from '../lib/progression.js'
const mocks = vi.hoisted(() => {
const state = {
@@ -137,6 +138,13 @@ async function toggleSet(index) {
await act(async () => { checkbox.dispatchEvent(new dom.Event('click', { bubbles: true })) })
}
async function pressNext() {
const button = [...container.querySelectorAll('button')]
.find(button => button.textContent.trim() === 'Next')
expect(button).toBeTruthy()
await act(async () => { button.dispatchEvent(new dom.Event('click', { bubbles: true })) })
}
async function pressProgression(index = 0) {
const button = container.querySelectorAll('.progline')[index]
expect(button).toBeTruthy()
@@ -205,8 +213,50 @@ describe('Workout set completion flow', () => {
expect(mocks.startRest).not.toHaveBeenCalled()
})
it('auto-captures a completed weighted exercise without prompting, leaving navigation to Next', async () => {
await mount([exercise('plain-bench', [false]), exercise('next', [false])])
await toggleSet(0)
expect(mocks.S.active.entries[0].topW).toBe(60)
expect(mocks.S.exWeights['plain-bench']).toBeUndefined() // written at the finish, not while ticking
expect(mocks.topWeightSheet).not.toHaveBeenCalled()
expect(mocks.S.active.cur).toBe(0)
expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number))
await pressNext()
expect(mocks.S.active.cur).toBe(1)
})
it('auto-captures superset members without prompting, then leaves the completed unit for Next', async () => {
const group = 'superset-1'
await mount([
exercise('superset-a', [false], { sg: group }),
exercise('superset-b', [false], { sg: group }),
exercise('next', [false]),
])
await toggleSet(0)
expect(mocks.topWeightSheet).not.toHaveBeenCalled()
expect(mocks.S.active.cur).toBe(1)
expect(mocks.startRest).not.toHaveBeenCalled()
await rerender()
await toggleSet(1)
expect(mocks.topWeightSheet).not.toHaveBeenCalled()
expect(mocks.S.active.cur).toBe(1)
expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number))
await pressNext()
expect(mocks.S.active.cur).toBe(2)
})
it.each(['warmup', 'warm-up', 'warm_up'])(
'does not start transition rest before an incomplete %s row in the next ordinary exercise',
'does not navigate or start transition rest before an incomplete %s row in the next ordinary exercise',
async phase => {
await mount([
exercise('current', [false], { asked: true }),
@@ -221,12 +271,12 @@ describe('Workout set completion flow', () => {
await toggleSet(0)
expect(mocks.S.active.cur).toBe(1)
expect(mocks.S.active.cur).toBe(0)
expect(mocks.startRest).not.toHaveBeenCalled()
},
)
it('does not start transition rest when a completed superset advances to an incomplete warm-up', async () => {
it('does not navigate or start transition rest when a completed superset meets an incomplete warm-up', async () => {
await mount([
exercise('superset-a', [true], { sg: 'group', asked: true }),
exercise('superset-b', [false], { sg: 'group', asked: true }),
@@ -241,11 +291,11 @@ describe('Workout set completion flow', () => {
await toggleSet(1)
expect(mocks.S.active.cur).toBe(2)
expect(mocks.S.active.cur).toBe(1)
expect(mocks.startRest).not.toHaveBeenCalled()
})
it('does not start transition rest before a warm-up while top-weight confirmation owns navigation', async () => {
it('leaves the completed ordinary exercise selected without transition rest before an incomplete warm-up', async () => {
await mount([
exercise('current-loaded', [false]),
exercise('next', [false, false], {
@@ -259,7 +309,7 @@ describe('Workout set completion flow', () => {
await toggleSet(0)
expect(mocks.topWeightSheet).toHaveBeenCalledWith(0)
expect(mocks.topWeightSheet).not.toHaveBeenCalled()
expect(mocks.S.active.cur).toBe(0)
expect(mocks.startRest).not.toHaveBeenCalled()
})
@@ -284,7 +334,7 @@ describe('Workout set completion flow', () => {
expect(mocks.startRest).not.toHaveBeenCalled()
})
it('leaves a completed superset selected while its top-weight sheet owns the advance choice', async () => {
it('leaves a completed superset selected without opening a top-weight sheet', async () => {
const group = 'superset-1'
await mount([
exercise('superset-a', [true, true, true], { sg: group, asked: true }),
@@ -293,12 +343,12 @@ describe('Workout set completion flow', () => {
], 1)
await toggleSet(5)
expect(mocks.topWeightSheet).toHaveBeenCalledWith(1)
expect(mocks.topWeightSheet).not.toHaveBeenCalled()
expect(mocks.S.active.cur).toBe(1)
expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number))
})
it('skips completed intervening units and selects the next unfinished superset as one unit', async () => {
it('does not auto-select an unfinished superset after completing an ordinary exercise', async () => {
await mount([
exercise('current-hold', [false], { asked: true, target: { mode: 'time', sec: 30, weight: 0 } }),
exercise('already-done', [true], { asked: true }),
@@ -308,13 +358,13 @@ describe('Workout set completion flow', () => {
await toggleSet(0)
expect(mocks.S.active.cur).toBe(2)
expect(mocks.S.active.cur).toBe(0)
expect(mocks.workoutCompleteSheet).not.toHaveBeenCalled()
expect(mocks.toast).toHaveBeenCalledWith('Hold logged')
expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number))
})
it('wraps to earlier unfinished work instead of showing a false completion prompt', async () => {
it('does not auto-select earlier unfinished work after completing an ordinary exercise', async () => {
await mount([
exercise('pending-earlier', [false], { asked: true }),
exercise('current-hold', [false], { asked: true, target: { mode: 'time', sec: 30, weight: 0 } }),
@@ -322,12 +372,12 @@ describe('Workout set completion flow', () => {
await toggleSet(0)
expect(mocks.S.active.cur).toBe(0)
expect(mocks.S.active.cur).toBe(1)
expect(mocks.workoutCompleteSheet).not.toHaveBeenCalled()
expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number))
})
it('keeps top-weight confirmation in control without declaring completion while work remains', async () => {
it('leaves a completed ordinary exercise selected without declaring completion while work remains', async () => {
await mount([
exercise('current-loaded', [false]),
exercise('pending', [false], { asked: true }),
@@ -335,9 +385,10 @@ describe('Workout set completion flow', () => {
await toggleSet(0)
expect(mocks.topWeightSheet).toHaveBeenCalledWith(0)
expect(mocks.topWeightSheet).not.toHaveBeenCalled()
expect(mocks.workoutCompleteSheet).not.toHaveBeenCalled()
expect(mocks.S.active.cur).toBe(0)
expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number))
})
it('shows workout completion only when no unfinished unit remains', async () => {
@@ -349,6 +400,7 @@ describe('Workout set completion flow', () => {
await toggleSet(0)
expect(mocks.workoutCompleteSheet).toHaveBeenCalledOnce()
expect(mocks.S.active.cur).toBe(1)
expect(mocks.startRest).not.toHaveBeenCalled()
})
})
@@ -360,7 +412,7 @@ describe('Workout add exercise flow', () => {
active: { routineId: 'routine-1' },
routines: [{ id: 'routine-1', ex: [] }],
}],
])('inserts after the current unit and continues to pending work in a %s session', async (_label, overrides) => {
])('inserts after the current unit and leaves the inserted exercise selected after completion in a %s session', async (_label, overrides) => {
await mount([
exercise('current', [true], { asked: true }),
exercise('pending', [false], { asked: true }),
@@ -378,7 +430,7 @@ describe('Workout add exercise flow', () => {
await toggleSet(0)
expect(mocks.S.active.entries[1].sets[0].done).toBe(true)
expect(mocks.S.active.cur).toBe(2)
expect(mocks.S.active.cur).toBe(1)
expect(mocks.workoutCompleteSheet).not.toHaveBeenCalled()
})
@@ -401,6 +453,69 @@ describe('Workout add exercise flow', () => {
})
})
describe('active workout weight controls', () => {
const press = async (label, selector) => {
const control = container.querySelector(selector)
const button = control?.querySelector(`button[aria-label="${label}"]`)
expect(button).toBeTruthy()
await act(async () => { button.dispatchEvent(new dom.Event('click', { bubbles: true })) })
await rerender()
}
it('uses the configured reps weight step for manual increases and decreases, with the default fallback', async () => {
await mount([exercise('plain-bench', [false], {
target: { mode: 'reps', reps: 5, weight: 60, bodyweight: false, inc: 1 },
})])
await press('Increase', '.setrow .stp.w')
expect(mocks.S.active.entries[0].sets[0].w).toBe(61)
await press('Decrease', '.setrow .stp.w')
expect(mocks.S.active.entries[0].sets[0].w).toBe(60)
await unmount()
await mount([exercise('plain-bench', [false])])
await press('Increase', '.setrow .stp.w')
expect(mocks.S.active.entries[0].sets[0].w).toBe(62.5)
})
it('matches automatic progression rounding for a fractional configured step', async () => {
const target = { mode: 'reps', sets: 1, reps: 5, weight: 60, bodyweight: false, inc: 1.25 }
const automatic = nextPrescription({
unit: 'kg',
workouts: [{ d: '2026-08-30', entries: [{ id: 'plain-bench', target, sets: [{ w: 60, r: 5, done: true }] }] }],
}, { id: 'plain-bench', ...target })
await mount([exercise('plain-bench', [false], { target, sets: [{ w: 60, r: 5, done: false }] })])
await press('Increase', '.setrow .stp.w')
expect(automatic.weight).toBe(61.3)
expect(mocks.S.active.entries[0].sets[0].w).toBe(automatic.weight)
})
it('uses the configured reps weight step for drop-set weight controls', async () => {
await mount([exercise('plain-bench', [false], {
target: { mode: 'reps', reps: 5, weight: 60, bodyweight: false, inc: 1 },
sets: [{ w: 60, r: 5, done: false, type: 'dropset', drops: [{ w: 50, r: 5 }] }],
})])
await press('Increase', '.subrow .stp')
expect(mocks.S.active.entries[0].sets[0].drops[0].w).toBe(51)
})
it('keeps timed seconds and optional timed weight on their existing steps', async () => {
await mount([exercise('timed-plank', [false], {
target: { mode: 'time', sec: 30, weight: 60, bodyweight: false, inc: 1 },
sets: [{ sec: 30, w: 60, done: false }],
})])
await press('Increase', '.setrow .stp.w')
expect(mocks.S.active.entries[0].sets[0].sec).toBe(35)
await press('Increase', '.setrow .stp.r')
expect(mocks.S.active.entries[0].sets[0].w).toBe(62.5)
})
})
describe('Workout discard timer lifecycle', () => {
it('preserves active timers while discard is awaiting confirmation', async () => {
const timer = { left: 30, total: 90, endsAt: Date.now() + 30_000 }
@@ -477,6 +592,47 @@ describe('progression guidance', () => {
expect(mocks.S.active.cur).toBe(0)
})
it('does not save into a different duplicate occurrence after the entry list shifts', async () => {
const plan = {
policy: 'linear', kind: 'up', weight: 62.5,
why: ['Every rep last time — {0} {1} more.', 2.5, 'kg'],
}
const first = exercise('plain-bench', [false], { plan, target: { mode: 'reps', reps: 5, weight: 60, marker: 'first' } })
const second = exercise('plain-bench', [false], { plan, target: { mode: 'reps', reps: 8, weight: 80, marker: 'second' } })
const third = exercise('plain-bench', [false], { plan, target: { mode: 'reps', reps: 10, weight: 100, marker: 'third' } })
await mount([first, second, third], 1)
await pressProgression()
const save = mocks.exConfigSheet.mock.calls[0][2]
mocks.S.active.entries.splice(0, 1)
await act(async () => { save({ ...second.target, prog: 'double', repsMin: 6 }) })
expect(mocks.S.active.entries.map(entry => entry.target.marker)).toEqual(['second', 'third'])
expect(mocks.S.active.entries[0].target.prog).toBeUndefined()
expect(mocks.S.active.entries[1].target.prog).toBeUndefined()
})
it('does not save through a sheet left open from a replaced workout', async () => {
const plan = {
policy: 'linear', kind: 'up', weight: 62.5,
why: ['Every rep last time — {0} {1} more.', 2.5, 'kg'],
}
const original = exercise('plain-bench', [false], { plan })
await mount([original])
await pressProgression()
const save = mocks.exConfigSheet.mock.calls[0][2]
const replacement = exercise('plain-bench', [false], {
plan,
target: { mode: 'reps', reps: 10, weight: 100, marker: 'replacement' },
})
mocks.S.active = { ...mocks.S.active, id: 'replacement-workout', entries: [replacement] }
await act(async () => { save({ ...original.target, prog: 'double', repsMin: 6 }) })
expect(mocks.S.active.entries[0].target).toEqual(replacement.target)
expect(mocks.S.active.entries[0].target.prog).toBeUndefined()
})
it('leaves the active entry unchanged when progression settings are cancelled', async () => {
const entry = exercise('plain-bench', [true, false], {
plan: {
@@ -697,3 +853,92 @@ describe('active exercise swap control', () => {
expect(mocks.swapActiveWorkoutExercise).toHaveBeenCalledWith(1)
})
})
describe('workout list view', () => {
const units = () => [...container.querySelectorAll('.wl-unit')]
const focusButton = unit => [...unit.querySelectorAll('button')].find(b => b.textContent.trim() === 'Set current')
it('stacks every exercise, labels each unit, and hides card navigation', async () => {
await mount([exercise('plain-bench', [false, false]), exercise('plain-row', [false])], 0, { workoutView: 'list' })
expect(container.querySelector('[data-testid="workout-list"]')).toBeTruthy()
expect(container.querySelector('[data-testid="workout-swipe-surface"]')).toBeNull()
expect(units().length).toBe(2)
// Every set in the session is visible at once: 2 + 1 checkboxes, not just the current one.
expect(container.querySelectorAll('[role="checkbox"]').length).toBe(3)
expect(units().map(u => u.querySelector('.wl-hd .muted')?.textContent)).toEqual([
'Exercise 1 / 2', 'Exercise 2 / 2',
])
expect(units()[0].textContent).toContain('Current')
expect(focusButton(units()[1])).toBeTruthy()
const navButtons = [...container.querySelectorAll('button')]
.filter(b => b.textContent.trim() === 'Prev' || b.textContent.trim() === 'Next')
expect(navButtons.length).toBe(0)
})
it('marks the current unit and moves the mark with Set current', async () => {
await mount([exercise('plain-bench', [false]), exercise('plain-row', [false])], 0, { workoutView: 'list' })
await act(async () => { focusButton(units()[1]).dispatchEvent(new dom.Event('click', { bubbles: true })) })
expect(mocks.S.active.cur).toBe(1)
await rerender()
expect(units()[0].textContent).not.toContain('Current')
expect(units()[1].textContent).toContain('Current')
expect(focusButton(units()[0])).toBeTruthy()
})
// Since !92 finishing an exercise no longer moves the current marker on its own (cards use
// Next, the list uses "Set current"); completion still starts the rest like cards do.
it('completing a set in list mode starts the rest and leaves the current marker in place, like cards do', async () => {
await mount([
exercise('plain-bench', [false], { asked: true }),
exercise('plain-row', [false], { asked: true }),
], 0, { workoutView: 'list' })
await toggleSet(0)
expect(mocks.S.active.entries[0].sets[0].done).toBe(true)
expect(mocks.S.active.cur).toBe(0)
expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number))
})
it('does not declare the workout complete after a set of a non-current exercise while sets remain', async () => {
// The marker stays on the finished bench (!92); ticking the first of three row sets must
// not open the completion sheet — the row's own unit still has two sets to go.
await mount([
exercise('plain-bench', [true], { asked: true }),
exercise('plain-row', [false, false, false], { asked: true }),
], 0, { workoutView: 'list' })
await toggleSet(1)
expect(mocks.S.active.entries[1].sets[0].done).toBe(true)
expect(mocks.workoutCompleteSheet).not.toHaveBeenCalled()
expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number))
})
it('renders a superset as one grouped unit with its own unpair control', async () => {
await mount([
exercise('bench', [false], { sg: 'g1', asked: true }),
exercise('row', [false], { sg: 'g1', asked: true }),
exercise('squat', [false], { asked: true }),
], 0, { workoutView: 'list' })
expect(units().length).toBe(2)
expect(units()[0].querySelector('.ss-card')).toBeTruthy()
expect(units()[1].querySelector('.ss-card')).toBeNull()
expect(units().map(u => u.querySelector('.wl-hd .muted')?.textContent)).toEqual([
'Superset 1 / 2', 'Exercise 2 / 2',
])
})
it('defaults to cards when the setting is absent (pre-existing profiles)', async () => {
await mount([exercise('plain-bench', [false]), exercise('plain-row', [false])])
expect(container.querySelector('[data-testid="workout-list"]')).toBeNull()
expect(container.querySelector('[data-testid="workout-swipe-surface"]')).toBeTruthy()
// Only the current exercise's sets are on screen.
expect(container.querySelectorAll('[role="checkbox"]').length).toBe(1)
})
})
+51
View File
@@ -0,0 +1,51 @@
// @vitest-environment happy-dom
// Home and Plan both offer the starter plan to someone who has no routines yet. Both used to
// wire the button straight to the loader, which quietly handed the click event in as the plan
// id and loaded nothing at all — so both entry points are pinned here.
import React, { act } from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { createRoot } from 'react-dom/client'
import { useStore } from '../store/useStore.js'
import { starterPlanSheet } from '../sheets.jsx'
import Home from './Home.jsx'
import Plan from './Plan.jsx'
vi.mock('react-router-dom', () => ({ useNavigate: () => () => {} }))
vi.mock('../sheets.jsx', () => ({
starterPlanSheet: vi.fn(), bwSheet: vi.fn(), goalSheet: vi.fn(), dayOverrideSheet: vi.fn(),
calendarSheet: vi.fn(), startFlow: vi.fn(), bwDeltaColor: () => '',
dayAssignSheet: vi.fn(), planToolsSheet: vi.fn(),
}))
let host, root
beforeEach(() => {
globalThis.IS_REACT_ACT_ENVIRONMENT = true
starterPlanSheet.mockClear()
useStore.setState(s => ({ S: { ...s.S, routines: [], week: {}, active: null }, user: null }))
host = document.createElement('div')
document.body.appendChild(host)
root = createRoot(host)
})
afterEach(() => {
act(() => root.unmount())
host.remove()
})
const starterButton = () => [...host.querySelectorAll('button')].find(b => b.textContent === 'Load starter plan')
describe.each([['Home', Home], ['Plan', Plan]])('%s empty state', (_name, View) => {
it('opens the starter plan chooser instead of loading one plan blind', () => {
act(() => root.render(<View />))
const button = starterButton()
expect(button).toBeTruthy()
act(() => { button.click() })
expect(starterPlanSheet).toHaveBeenCalledTimes(1)
})
it('drops the offer once the user has routines', () => {
useStore.setState(s => ({ S: { ...s.S, routines: [{ id: 'r', name: 'Mine', emoji: 'star', ex: [] }] } }))
act(() => root.render(<View />))
expect(starterButton()).toBeFalsy()
})
})
+1 -1
View File
@@ -44,7 +44,7 @@ vi.mock('../lib/wakelock.js', () => ({ wakeLockSupported: () => false }))
vi.mock('../lib/mobile.js', () => ({ MOBILE: false, shareExport: vi.fn(), syncReminder: vi.fn() }))
vi.mock('./MobileOnboarding.jsx', () => ({ ConnectSheet: () => null }))
vi.mock('../sheets.jsx', () => ({
loadStarterPlan: vi.fn(), confirmSheet: vi.fn(), importFromApp: vi.fn(),
starterPlanSheet: vi.fn(), confirmSheet: vi.fn(), importFromApp: vi.fn(),
importFromHevy: vi.fn(), equipmentProfileSheet: vi.fn(),
dayAssignSheet: vi.fn(), planToolsSheet: vi.fn(),
}))
+13 -5
View File
@@ -67,12 +67,13 @@ the server's stderr.
## Tools
Eight read-only tools in v1:
Nine read-only tools in v1:
| Tool | What it answers |
|---|---|
| `list_routines` | What routines are saved in my profile? (names + exercise counts) |
| `get_routine` | What does the Push Day routine prescribe? (sets/reps/weight per exercise) |
| `get_routine` | What does the Push Day routine prescribe? (sets/reps/weight and rest per exercise) |
| `preview_session` | What will the app actually put on screen when I start this routine — after the progression policy and my history have overridden the plan? |
| `get_week_plan` | What's on my plan this week, including today with any date-specific override? |
| `list_workouts` | Recent sessions — newest first, with dates, sets done/planned, volume, duration, PRs. |
| `get_workout` | Full set-by-set breakdown of one session, by `workout_id` or by date. On a day with two sessions the date alone returns both ids to pick from rather than guessing at one. |
@@ -80,6 +81,13 @@ Eight read-only tools in v1:
| `estimate_1rm` | All-time best 1RM for an exercise + the trend, or a PR table across all exercises. |
| `muscle_balance` | Which muscles I've trained this week/month/all-time, ranked + which I've neglected. |
`get_routine` and `preview_session` answer two different questions, and confusing them is the
easiest way for a coach to give wrong advice. `get_routine` reports what the routine *stores*.
`preview_session` reports what the athlete will actually *see*: a routine holding "squat 3×8 @
60 kg" opens at 75 kg if the policy deloaded from the last logged session, and the rep counts
come from history, not the plan. The routine's own numbers are the last fallback the session
builder consults, not the first. Ask `preview_session` before naming a weight.
Each tool returns JSON the LLM can format as it likes; structured fields (sets, dates, levels)
are pre-formatted into human-readable labels in `src/labels.js` so the LLM doesn't need to
re-interpret them.
@@ -112,7 +120,7 @@ dependencies landed in `frontend/`, no public exports changed.
cd mcp && npm test
```
32 cases seeding state from `frontend/src/lib/demoSeed.js` (the same deterministic fixture
58 cases seeding state from `frontend/src/lib/demoSeed.js` (the same deterministic fixture
the public demo runs on). Pins JSON shape and the user-facing edge cases: rest-day override,
missing routine, zero-workout history, no synced state, superset links, three 1RM formulas.
"Today" is pinned via `vi.useFakeTimers({ now: ..., toFake: ['Date'] })` so date-dependent
@@ -122,8 +130,8 @@ their own 92 tests in `frontend/src/lib/*.test.js`.
## Roadmap
- **Done (Phase 1):** read-only stdio, 8 tools, direct `./data` access.
- **Phase 1.5:** a `progression_next` tool (what does the policy prescribe next?). No new
deps; small surface area.
- **Done (Phase 1.5):** `preview_session` — the policy's next prescription, the opening set
rows it produces, and which of plan / confirmed weight / history each number came from.
- **Phase 2:** read+write over stdio. Requires a long-lived token auth path minted from the
admin dashboard (new `./data/tokens.json`) and a write-lock against the web UI's read-modify-
write of `state-<uid>.json`. Tools: `log_workout`, `add_bodyweight`, `edit_routine`,
+159 -4
View File
@@ -4,10 +4,10 @@
import { z } from 'zod'
import { getState, getUser } from './state.js'
import {
setLabel, exLine, muscleName, policyName, friendlyDuration, ratio, muscleOrder
fmt, setLabel, exLine, muscleName, policyName, friendlyDuration, ratio, muscleOrder
} from './labels.js'
import {
modeOf, workoutVolume, setsDone, effectiveRoutine, effectiveRoutineId
modeOf, workoutVolume, setsDone, effectiveRoutine, effectiveRoutineId, lastEntryFor
} from '../../frontend/src/lib/history.js'
import { exOr } from '../../frontend/src/lib/exercises.js'
import { isWarmupRow } from '../../frontend/src/lib/workout-model.js'
@@ -16,6 +16,7 @@ import {
} from '../../frontend/src/lib/onerm.js'
import { loadOfWorkouts, rankOf, levelsOf } from '../../frontend/src/lib/muscles.js'
import { policyFor } from '../../frontend/src/lib/progression.js'
import { buildSessionEntries } from '../../frontend/src/lib/session-start.js'
/* ---------- helpers ---------- */
@@ -105,7 +106,7 @@ export const listRoutines = {
/** get_routine — the full exercise list for one routine, including set/rep targets. */
export const getRoutine = {
name: 'get_routine',
description: 'Get the full exercise list for a single routine (the same view the routine editor shows). Returns mode (reps/time/cardio), set/rep/weight targets, superset links, and any per-exercise custom increment you can override. Use routine_id from list_routines.',
description: 'Get the full exercise list for a single routine (the same view the routine editor shows). Returns mode (reps/time/cardio), set/rep/weight targets, superset links, any per-exercise custom increment you can override, and each exercise\'s own rest in seconds (absent means it inherits the global rest timer). Use routine_id from list_routines.',
schema: { routine_id: z.string().min(1) },
handler: ({ routine_id }) => {
const S = getState()
@@ -138,6 +139,9 @@ export const getRoutine = {
speed: mode === 'cardio' ? (cfg.speed || 0) : undefined,
weight: cfg.weight != null ? cfg.weight : undefined,
increment: cfg.inc != null ? cfg.inc : undefined,
// The exercise's own rest (issue #10). Absent means it inherits the global rest
// timer; a superset rests once, taking the longest its members ask for.
rest_sec: cfg.restSec > 0 ? cfg.restSec : undefined,
policy: policyFor(cfg, r, mode),
policy_override: cfg.prog || null,
superset_group: cfg.sg || null,
@@ -407,10 +411,161 @@ export const muscleBalance = {
}
}
/* ---------- preview_session ---------- */
// Where a number on the session screen actually came from. A routine's own sets/reps/weight
// are the LAST fallback, not the first: buildSets() prefers the confirmed working weight and
// the previous session's reps, and applyPrescription() then overwrites the weight with
// whatever the progression policy decided. Reporting the winner is the whole point of this
// tool — "the plan says 60" is not an answer to "what will the app show me".
function sourceOf(S, cfg, plan, field) {
// Progression off (or a deload routine): the session is built from the routine's own target,
// exactly as session-start.js does with useTarget — history and the confirmed weight are ignored.
if (!plan || plan.kind === 'off') return 'routine_plan'
const decided = plan.kind !== 'first' && plan[field] != null
if (decided) return 'progression'
if (field === 'weight') {
const conf = (S.exWeights || {})[cfg.id]
if (conf && conf.w > 0) return 'confirmed_weight'
}
return lastEntryFor(S, cfg.id) ? 'last_session' : 'routine_plan'
}
const SOURCE_TEXT = {
progression: 'the progression policy overrode the routine',
confirmed_weight: 'your confirmed working weight for this exercise',
last_session: 'carried over from the last time you did this exercise',
routine_plan: "the routine's own target"
}
/** preview_session — what starting this routine will actually put on screen. */
export const previewSession = {
name: 'preview_session',
description:
'Preview the session a routine will actually open with — the numbers the user will see after the progression policy and their training history have overridden the routine\'s own targets. This is NOT the same as get_routine: a routine storing "squat 3x8 @ 60kg" can open at 75kg because the policy deloaded from the last logged session, and reps carry from history rather than from the plan. Always call this (not get_routine) before telling someone what weight they are about to lift, or before judging whether an edit to a routine had any effect. Returns, per exercise, the planned target, the policy\'s decision and its stated reason, the opening set rows, and where each number came from. Defaults to today\'s scheduled routine.',
schema: {
routine_id: z.string().min(1).optional().describe('Routine to preview. Defaults to the routine scheduled for `date`.'),
date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional().describe('Date the session would be started on, YYYY-MM-DD. Affects which routine is scheduled and any one-off day override. Defaults to today.')
},
handler: ({ routine_id, date }) => {
const S = getState()
if (!S) return noState()
const now = new Date()
const iso = date || (now.getFullYear() + '-' + String(now.getMonth() + 1).padStart(2, '0') + '-' + String(now.getDate()).padStart(2, '0'))
let r
if (routine_id) {
r = (S.routines || []).find(x => x.id === routine_id)
if (!r) { const e = new Error(`no routine with id ${JSON.stringify(routine_id)}`); e.code = 'ENOENT'; throw e }
} else {
r = effectiveRoutine(S, iso)
if (!r) return { date: iso, routine_id: null, routine_name: null, rest_day: true, note: 'no routine is scheduled for this date (rest day)', exercises: [] }
}
const unit = S.unit || 'kg'
// The same builder the app starts a session with (sheets.jsx beginWorkout → session-start.js):
// prescription, step, progression-off targets, deload routines and warm-up ramps all come from
// there, so the preview cannot drift from what the screen shows.
const built = buildSessionEntries(S, r).entries
const exercises = (r.ex || []).map((cfg, i) => {
const ex = exerciseOf(cfg.id, S)
const mode = modeOf({ ...cfg, id: cfg.id })
const plan = built[i].plan
const rows = built[i].sets
const work = rows.filter(s => !isWarmupRow(s))
const openW = work.length ? (work[0].w || 0) : 0
const openR = work.length ? (work[0].r || 0) : 0
const openSec = work.length ? (work[0].sec || 0) : 0
const openMin = work.length ? (work[0].min || 0) : 0
const wSrc = sourceOf(S, cfg, plan, 'weight')
const rSrc = sourceOf(S, cfg, plan, 'reps')
return {
position: i + 1,
id: cfg.id,
name: ex.n,
mode,
policy: plan.policy,
policy_name: policyName(plan.policy),
planned: {
sets: cfg.sets || 1,
reps: mode === 'reps' ? (cfg.reps || 0) : undefined,
sec: mode === 'time' ? (cfg.sec || 0) : undefined,
min: mode === 'cardio' ? (cfg.min || 0) : undefined,
weight: cfg.weight != null ? cfg.weight : undefined,
summary: exLine(cfg, unit)
},
prescription: {
kind: plan.kind,
weight: plan.weight != null ? plan.weight : undefined,
reps: plan.reps != null ? plan.reps : undefined,
sets: plan.sets != null ? plan.sets : undefined,
sec: plan.sec != null ? plan.sec : undefined,
why: plan.why ? fmt(plan.why[0], plan.why.slice(1)) : null
},
opening_sets: rows.map(s => ({
phase: isWarmupRow(s) ? 'warmup' : 'work',
type: s.type || 'straight',
label: setLabel(cfg.id, { ...s, done: undefined }, { ...cfg, id: cfg.id }),
w: Number(s.w) || 0,
r: Number(s.r) || 0,
sec: Number(s.sec) || 0,
min: Number(s.min) || 0,
speed: Number(s.speed) || 0
})),
weight_source: wSrc,
weight_source_text: SOURCE_TEXT[wSrc],
reps_source: mode === 'reps' ? rSrc : undefined,
reps_source_text: mode === 'reps' ? SOURCE_TEXT[rSrc] : undefined,
// The headline: did editing the routine change anything the user will see? Tracked per
// dimension — a bodyweight exercise whose weight is 0 either way still counts when the
// rep target moved, and saying which one moved saves the caller diffing it themselves.
changed: [
...(mode === 'reps' && cfg.weight != null && openW !== cfg.weight ? ['weight'] : []),
...(mode === 'reps' && (cfg.reps || 0) > 0 && openR !== cfg.reps ? ['reps'] : []),
...(mode === 'time' && (cfg.sec || 0) > 0 && openSec !== cfg.sec ? ['sec'] : []),
...(mode === 'cardio' && (cfg.min || 0) > 0 && openMin !== cfg.min ? ['min'] : [])
],
differs_from_plan:
(mode === 'reps' && cfg.weight != null && openW !== cfg.weight) ||
(mode === 'reps' && (cfg.reps || 0) > 0 && openR !== cfg.reps) ||
(mode === 'time' && (cfg.sec || 0) > 0 && openSec !== cfg.sec) ||
(mode === 'cardio' && (cfg.min || 0) > 0 && openMin !== cfg.min)
}
})
const differing = exercises.filter(e => e.differs_from_plan)
return {
date: iso,
routine_id: r.id,
routine_name: r.name,
unit,
policy: policyFor(null, r, 'reps'),
policy_name: policyName(policyFor(null, r, 'reps')),
exercises,
// Surfaced separately so a coach reading this cannot miss it: these are the exercises
// where what the routine stores and what the athlete will see are two different numbers.
overridden_count: differing.length,
overridden: differing.map(e => ({
name: e.name,
planned_weight: e.planned.weight,
opening_weight: e.opening_sets.filter(s => s.phase === 'work')[0]?.w ?? null,
planned_reps: e.planned.reps,
opening_reps: e.opening_sets.filter(s => s.phase === 'work')[0]?.r ?? null,
planned_sec: e.planned.sec,
opening_sec: e.opening_sets.filter(s => s.phase === 'work')[0]?.sec ?? null,
planned_min: e.planned.min,
opening_min: e.opening_sets.filter(s => s.phase === 'work')[0]?.min ?? null,
changed: e.changed,
reason: e.prescription.why || e.weight_source_text
}))
}
}
}
/* ---------- registration list ---------- */
export const TOOLS = [
listRoutines, getRoutine, getWeekPlan, listWorkouts, getWorkout, getBodyweight, estimate1rm, muscleBalance
listRoutines, getRoutine, previewSession, getWeekPlan, listWorkouts, getWorkout, getBodyweight, estimate1rm, muscleBalance
]
function noState() {
+185
View File
@@ -129,6 +129,17 @@ describe('get_routine', () => {
expect(r.exercises[0]).toMatchObject({ reps: 8, reps_min: 8, reps_max: 12 })
})
test('reports an exercise\'s own rest, and leaves it out when it inherits the timer', () => {
S.routines[0].ex[0].restSec = 180
delete S.routines[0].ex[1]?.restSec
const r = call('get_routine', { routine_id: S.routines[0].id })
expect(r.exercises[0].rest_sec).toBe(180)
// An exercise with no rest of its own inherits the global timer. Absent says that;
// a zero would read as "no rest at all", which is a different prescription.
expect(JSON.parse(JSON.stringify(r)).exercises[1]).not.toHaveProperty('rest_sec')
})
test('projects routine and exercise progression rules from prog', () => {
S.routines[0].prog = 'greyskull'
S.routines[0].ex[0].prog = 'double'
@@ -663,3 +674,177 @@ describe('shared: no-state fallback', () => {
// failure rather than inherits null silently.
afterAll(() => { _seedStateForTests(S = freshState()) })
})
/* ---------- preview_session ---------- */
// The gap this tool exists to close: a routine stores sets/reps/weight, but those are the
// LAST fallback the session builder consults. These tests pin the precedence — progression
// beats the confirmed working weight, which beats the routine's own number — because getting
// it backwards is how a coach ends up telling someone to squat a weight the app never shows.
describe('preview_session', () => {
const WD = new Date(FAKE_TODAY_ISO + 'T12:00:00Z').getDay()
// One routine, one exercise, scheduled for the pinned "today". Nothing from the demo seed,
// so the arithmetic below is checkable by hand.
// Linear by default: with progression off the app opens the routine's own numbers (see the
// two tests at the end), so history-vs-plan precedence is only observable under a policy.
function only(cfg, { prog = 'linear', workouts = [], exWeights = {}, routine = {} } = {}) {
S.routines = [{ id: 'r-preview', name: 'Preview', emoji: 'barbell', prog, ex: [cfg], ...routine }]
S.week = { [WD]: 'r-preview' }
S.dayPlan = {}
S.workouts = workouts
S.exWeights = exWeights
_seedStateForTests(S)
}
test('defaults to the routine scheduled for today', () => {
only({ id: '0025', sets: 3, reps: 8, weight: 50 })
const r = call('preview_session')
expect(r.date).toBe(FAKE_TODAY_ISO)
expect(r.routine_name).toBe('Preview')
expect(r.exercises).toHaveLength(1)
expect(r.exercises[0].name).toBe('barbell bench press')
})
test('with no history and no confirmed weight, the routine\'s own number is what opens', () => {
only({ id: '0025', sets: 3, reps: 8, weight: 50 })
const e = call('preview_session').exercises[0]
expect(e.weight_source).toBe('routine_plan')
expect(e.opening_sets.map(s => s.w)).toEqual([50, 50, 50])
expect(e.opening_sets.map(s => s.r)).toEqual([8, 8, 8])
expect(e.differs_from_plan).toBe(false)
expect(call('preview_session').overridden_count).toBe(0)
})
test('a confirmed working weight beats the routine\'s number', () => {
only({ id: '0025', sets: 2, reps: 8, weight: 50 }, { exWeights: { '0025': { w: 72.5, d: '2026-07-20' } } })
const e = call('preview_session').exercises[0]
expect(e.weight_source).toBe('confirmed_weight')
expect(e.opening_sets.every(s => s.w === 72.5)).toBe(true)
expect(e.changed).toEqual(['weight'])
})
test('the progression policy beats both, and its reason is reported', () => {
// Every rep hit at 60 last time under linear progression → +2.5, regardless of the 100
// the routine stores.
only({ id: '0025', sets: 3, reps: 5, weight: 100 }, {
prog: 'linear',
exWeights: { '0025': { w: 100, d: '2026-07-20' } },
workouts: [{
id: 'w1', d: '2026-07-20', routineId: 'r-preview', name: 'Preview',
entries: [{
id: '0025',
target: { id: '0025', sets: 3, reps: 5, weight: 60 },
sets: [{ w: 60, r: 5, done: true }, { w: 60, r: 5, done: true }, { w: 60, r: 5, done: true }]
}]
}]
})
const out = call('preview_session')
const e = out.exercises[0]
expect(e.prescription.kind).toBe('up')
expect(e.weight_source).toBe('progression')
expect(e.opening_sets.every(s => s.w === 62.5)).toBe(true)
expect(e.prescription.why).toMatch(/Every rep last time/)
expect(e.changed).toEqual(['weight'])
expect(out.overridden_count).toBe(1)
expect(out.overridden[0]).toMatchObject({
name: 'barbell bench press', planned_weight: 100, opening_weight: 62.5
})
expect(out.overridden[0].reason).toMatch(/Every rep last time/)
})
test('reps carry from the last session even when the routine asks for something else', () => {
only({ id: '0025', sets: 2, reps: 12, weight: 60 }, {
workouts: [{
id: 'w1', d: '2026-07-20', routineId: 'r-preview', name: 'Preview',
entries: [{
id: '0025',
target: { id: '0025', sets: 2, reps: 5, weight: 60 },
sets: [{ w: 60, r: 5, done: true }, { w: 60, r: 5, done: true }]
}]
}]
})
const e = call('preview_session').exercises[0]
expect(e.opening_sets.map(s => s.r)).toEqual([5, 5]) // not the 12 the routine stores
expect(e.reps_source).toBe('last_session')
expect(e.changed).toContain('reps')
})
test('planned drop sets show up on the opening rows', () => {
only({ id: '0025', sets: 2, reps: 10, weight: 50, intensifier: { type: 'dropset', count: 1, pct: 20 } })
const e = call('preview_session').exercises[0]
expect(e.opening_sets.every(s => s.type === 'dropset')).toBe(true)
})
test('an explicit routine_id overrides the schedule', () => {
only({ id: '0025', sets: 3, reps: 8, weight: 50 })
const other = { id: 'r-other', name: 'Other', prog: 'off', ex: [{ id: '0043', sets: 5, reps: 5, weight: 80 }] }
S.routines.push(other)
_seedStateForTests(S)
expect(call('preview_session', { routine_id: 'r-other' }).routine_name).toBe('Other')
})
test('a rest day returns no exercises rather than an error', () => {
only({ id: '0025', sets: 3, reps: 8, weight: 50 })
S.week = {}
_seedStateForTests(S)
const r = call('preview_session')
expect(r.rest_day).toBe(true)
expect(r.exercises).toEqual([])
})
test('with progression off the routine\'s own numbers open, whatever history says (matches session-start.js)', () => {
only({ id: '0025', sets: 3, reps: 8, weight: 50 }, {
prog: 'off',
exWeights: { '0025': { w: 72.5, d: '2026-07-20' } },
workouts: [{
id: 'w1', d: '2026-07-20', routineId: 'r-preview', name: 'Preview',
entries: [{ id: '0025', target: { id: '0025', sets: 3, reps: 5, weight: 60 }, sets: [{ w: 60, r: 5, done: true }] }]
}]
})
const out = call('preview_session')
const e = out.exercises[0]
expect(e.prescription.kind).toBe('off')
expect(e.opening_sets.map(s => [s.w, s.r])).toEqual([[50, 8], [50, 8], [50, 8]])
expect(e.weight_source).toBe('routine_plan')
expect(e.reps_source).toBe('routine_plan')
expect(e.differs_from_plan).toBe(false)
expect(out.overridden_count).toBe(0)
})
test('a deload routine (excludeFromProgression) opens its own numbers even under a policy', () => {
only({ id: '0025', sets: 3, reps: 5, weight: 50 }, {
prog: 'linear', routine: { excludeFromProgression: true },
workouts: [{
id: 'w1', d: '2026-07-20', routineId: 'r-preview', name: 'Preview',
entries: [{ id: '0025', target: { id: '0025', sets: 3, reps: 5, weight: 60 }, sets: [{ w: 60, r: 5, done: true }, { w: 60, r: 5, done: true }, { w: 60, r: 5, done: true }] }]
}]
})
const e = call('preview_session').exercises[0]
expect(e.prescription.kind).toBe('off')
expect(e.opening_sets.every(s => s.w === 50 && s.r === 5)).toBe(true)
expect(e.weight_source).toBe('routine_plan')
})
test('a timed exercise that progressed is listed as overridden too', () => {
only({ id: '0025', mode: 'time', sets: 3, sec: 30, inc: 10 }, {
prog: 'time',
workouts: [{
id: 'w1', d: '2026-07-20', routineId: 'r-preview', name: 'Preview',
entries: [{ id: '0025', target: { id: '0025', mode: 'time', sets: 3, sec: 30 }, sets: [{ sec: 45, done: true }, { sec: 45, done: true }, { sec: 45, done: true }] }]
}]
})
const out = call('preview_session')
const e = out.exercises[0]
expect(e.prescription.kind).toBe('up')
expect(e.changed).toEqual(['sec'])
expect(e.differs_from_plan).toBe(true)
expect(out.overridden[0].opening_sec).toBeGreaterThan(30)
})
test('an unknown routine_id is an error, not an empty session', () => {
only({ id: '0025', sets: 3, reps: 8, weight: 50 })
expect(() => call('preview_session', { routine_id: 'nope' })).toThrow(/no routine with id/)
})
})