Skip to content

Open-source gym & body-weight tracker, now in the App Store (iPhone + Apple Watch) and as an Android APK. Plan routines, log workouts, see which muscles are trained, import from Strong/Hevy/FitNotes. Self-host it or use it on the phone alone.

Merge the plan and library batch: a compact + on a planned day, replace an exercise in the routine editor, print or save one routine as PDF, a search result count, cardio speed in mph, a drag grip on computers (#276, #110, #282, !31)

Duarte Santosde70710c6873
diff --cc frontend/src/index.css
index fce2fe23d,9fdd2ebe3..14aab6f5a
--- a/frontend/src/index.css
+++ b/frontend/src/index.css
@@@ -558,12 -577,22 +577,22 @@@ body.chips-dragging *{cursor:inherit
}
/* legacy .search wrapper */
.search{position:relative}
-.search .input{padding-left:35px;background:var(--surface-2);border-radius:10px}
+.search .input{padding-inline-start:35px;background:var(--surface-2);border-radius:10px}
:root[data-theme="light"] .search .input{background:rgba(118,118,128,.12)}
.search>svg{
- position:absolute;left:11px;top:50%;transform:translateY(-50%);z-index:1;
+ position:absolute;inset-inline-start:11px;top:50%;transform:translateY(-50%);z-index:1;
width:16px;height:16px;stroke:var(--label-3);fill:none;stroke-width:2.1;stroke-linecap:round;
}
+ /* The live result count (Library and the exercise picker, from GitLab !31): a pill at the end
+ of the field while a search or filter narrows the list. The field makes room for it only while
+ it is there, so a long placeholder is not cut short for nothing. */
+ .search.has-count .input{padding-right:62px}
+ .search .search-count{
+ position:absolute;right:9px;top:50%;transform:translateY(-50%);
+ font-size:12px;font-weight:600;line-height:1.4;color:var(--label-2);
+ background:var(--surface-3);padding:2px 8px;border-radius:99px;
+ font-variant-numeric:tabular-nums;pointer-events:none;user-select:none;
+ }
/* --- switch --- */
.sw{
diff --cc frontend/src/lib/history.js
index 19d30bcaa,62a4bcbd8..8d0607148
--- a/frontend/src/lib/history.js
+++ b/frontend/src/lib/history.js
@@@ -1,7 -1,8 +1,8 @@@
// Pure helpers over the state object S (ported 1:1 from the vanilla app).
import { todayISO, isoOf, weekKey, weekStartOf, fmtNum } from './format.js'
+ import { fmtSpeed } from './speed.js'
import { isCardio, isBodyweightEq, isAssisted, betterWeight } from './exercises.js'
-import { phaseForSet, modeForSet, modeForEntry, isWarmupRow, normalizeMode, completedVolumeOf, nextDropWeight, splitBurstReps, makeSideSet, isSideSet, syncSideAggregate } from './workout-model.js'
+import { phaseForSet, modeForSet, modeForEntry, isWarmupRow, normalizeMode, completedVolumeOf, hasCompletedWork, nextDropWeight, splitBurstReps, makeSideSet, isSideSet, syncSideAggregate, WEIGHT_ORIGIN_MANUAL, dropsOf, clustersOf } from './workout-model.js'
const objectOf = value => value && typeof value === 'object' && !Array.isArray(value) ? value : {}
// Completed-state-independent work rows whose authoritative mode matches the requested mode.
const workRowsForMode = (entry = {}, mode = 'reps') => {
@@@ -111,28 -113,14 +113,28 @@@ export function setLabel(id, s, cfg, sp
// A set saved by an older build carries no target with it; the set's own fields still say what
// it was — seconds for a timed set, minutes for cardio — so those are not read back as "0 reps".
if (!cfg && !(s.r > 0)) { if (s.min > 0 || s.speed > 0) mode = 'cardio'; else if (s.sec > 0) mode = 'time' }
- if (mode === 'cardio') return `${s.min || 0} min @ ${fmtNum(s.speed || 0)} km/h`
+ if (mode === 'cardio') return `${s.min || 0} min @ ${fmtSpeed(s.speed || 0, speedUnit)}`
if (mode === 'time') return fmtSec(s.sec) + (s.w > 0 ? ` · ${fmtNum(s.w)}` : '')
const bw = isBw({ ...c, id: c.id ?? id })
+ const load = (w, reps) => (bw ? (w > 0 ? `+${fmtNum(w)} × ` : '') + reps : `${fmtNum(w || 0)}×${reps}`)
+ // A rest-pause set's reps read as its bursts, "60×10+4+2", the way the protocol is written
+ // down. The row's own `r` is the total either way; a planned set's bursts already add up to it
+ // (applyIntensifierPlan), while bursts added live sit on top of the activation set, which is
+ // then whatever the total leaves over. Bursts that do not fit the total are not shown.
+ const repsOf = side => {
+ const reps = side.r || 0
+ const bursts = clustersOf(side).map(b => Number(b?.r) || 0).filter(r => r > 0)
+ const sum = bursts.reduce((a, b) => a + b, 0)
+ if (!bursts.length || sum > reps) return reps
+ return (reps > sum ? [reps - sum, ...bursts] : bursts).join('+')
+ }
// One side's "weight×reps" (or bodyweight "reps" / "+belt × reps"), the same shape a whole
- // straight set reads as — reused for each side of a unilateral set below.
+ // straight set reads as — reused for each side of a unilateral set below. A drop-set's drops
+ // follow it ("100×8 ↘ 80×6"): the volume of the workout counts them, so the list has to show
+ // them, or the total includes weight nobody can see where it came from.
const oneSide = side => {
- const reps = side.r || 0
- return bw ? (side.w > 0 ? `+${fmtNum(side.w)} × ` : '') + reps : `${fmtNum(side.w || 0)}×${reps}`
+ const drops = dropsOf(side).filter(d => (Number(d?.r) || 0) > 0)
+ return load(side.w, repsOf(side)) + drops.map(d => ' ↘ ' + load(Number(d.w) || 0, Number(d.r))).join('')
}
// A unilateral set logged per side (issue #60) reads "L 15×8 · R 15×7" — the asymmetry is the
// whole point, so both sides are shown rather than a single combined total.
diff --cc frontend/src/lib/plan-share.js
index afda0f4b2,a2c3d2555..179406f37
--- a/frontend/src/lib/plan-share.js
+++ b/frontend/src/lib/plan-share.js
@@@ -12,8 -12,9 +12,9 @@@ import { EXIDX, isBodyweightEq } from '
import { modeOf, fmtSec, isBw, isPerSide, sideReps, MAX_PLANNED_WARMUPS } from './history.js'
import { deriveSessionName } from './session-merge.js'
import { uid, todayISO, DAYN, weekOrder, weekStartOf, fmtNum, exCount } from './format.js'
-import { t, exerciseNameFor } from './i18n-core.js'
+import { t, exerciseNameFor, exerciseNameClass, getLang, RTL_LANGS } from './i18n-core.js'
import { convertWeight } from './units.js'
+ import { fmtSpeed, speedUnitOf } from './speed.js'
import { MUSCLES, inMuscleOrder } from './muscles.js'
const PLAN_FMT = 1
@@@ -322,7 -326,7 +326,7 @@@ function routineHTML(r, unit, { bare =
const name = ex ? exerciseNameFor(ex) : t('Unknown exercise')
const part = ex && ex.bp && ex.bp !== 'cardio' ? `<span class="part">${esc(ex.bp)}</span>` : ''
const note = e.note ? `<div class="ex-note">${esc(e.note)}</div>` : ''
- return `<div class="ex"><div class="ex-row"><div class="ex-n ${ex ? exerciseNameClass(ex) : ''}">${esc(name)}${part}</div><div class="ex-s">${esc(scheme(e, unit))}</div></div>${note}</div>`
- return `<div class="ex"><div class="ex-row"><div class="ex-n">${esc(name)}${part}</div><div class="ex-s">${esc(scheme(e, unit, speedUnit))}</div></div>${note}</div>`
++ return `<div class="ex"><div class="ex-row"><div class="ex-n ${ex ? exerciseNameClass(ex) : ''}">${esc(name)}${part}</div><div class="ex-s">${esc(scheme(e, unit, speedUnit))}</div></div>${note}</div>`
}).join('')
return u.length > 1
? `<div class="ss"><div class="ss-tag">${esc(t('Superset'))}</div><div class="ss-items">${items}</div></div>`
@@@ -347,16 -351,25 +351,25 @@@ function weekHTML(S)
return `<div class="week">${rows}</div>`
}
- /** Full self-contained HTML for the print/PDF view. */
- export function planPrintHTML(S, owner) {
+ /**
+ * Full self-contained HTML for the print/PDF view. With `routineId` it is that one routine on
+ * its own page (#282) — the session you take to the gym, not the week around it — so the week
+ * schedule is left out and the routine's name is the page title.
+ */
+ export function planPrintHTML(S, owner, { routineId } = {}) {
const unit = S.unit || 'kg'
- const routines = (S.routines || []).filter(r => r.ex && r.ex.length)
+ const single = routineId ? (S.routines || []).find(r => r.id === routineId) || null : null
+ const routines = routineId ? [single].filter(Boolean) : (S.routines || []).filter(r => r.ex && r.ex.length)
const body = routines.length
- ? routines.map(r => routineHTML(r, unit)).join('')
+ ? routines.map(r => routineHTML(r, unit, { bare: !!single, speedUnit: speedUnitOf(S) })).join('')
: `<p class="none">${esc(t('No routines yet.'))}</p>`
- const sub = [owner, todayISO()].filter(Boolean).map(esc).join(' · ')
+ const title = single ? single.name : t('Weekly Training Plan')
+ const sub = [single ? exCount(single.ex.length) : null, owner, todayISO()].filter(Boolean).map(esc).join(' · ')
+ const week = routineId ? '' : `<h3 class="block">${esc(t('Week schedule'))}</h3>
+ ${weekHTML(S)}
+ <h3 class="block">${esc(t('Routines'))}</h3>`
- return `<!doctype html><html><head><meta charset="utf-8">
+ return `<!doctype html><html lang="${getLang()}" dir="${RTL_LANGS.has(getLang()) ? 'rtl' : 'ltr'}"><head><meta charset="utf-8">
- <title>${esc(t('Weekly Training Plan'))}</title>
+ <title>${esc(title)}</title>
<style>
@page { margin: 16mm 15mm; }
* { box-sizing: border-box; }
diff --cc frontend/src/lib/pt-br-locale.test.js
index 9f2c8504a,3fa94ecdd..60357613b
--- a/frontend/src/lib/pt-br-locale.test.js
+++ b/frontend/src/lib/pt-br-locale.test.js
@@@ -27,21 -27,11 +27,21 @@@ describe('Brazilian Portuguese locale'
.sort(byCodeUnit)
const fingerprint = createHash('sha256').update(JSON.stringify(inherited)).digest('hex')
- expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(680)
- expect(inherited).toHaveLength(677)
- // If this fails, review the changed keys and wording before accepting a new hash. From
+ // Every override names a real source string, so the two sets partition pt-PT's keys between
+ // them and the fingerprint below covers everything not overridden. A typo'd override key
+ // would otherwise sit in the file translating nothing.
+ const stray = Object.keys(PT_BR_OVERRIDES).filter(key => !(key in pt))
+ expect(stray, 'override keys that are not pt-PT keys').toEqual([])
+ expect(Object.keys(PT_BR_OVERRIDES).length + inherited.length).toBe(Object.keys(pt).length)
+ // …and each one really reaches the pack, whatever the spread order does.
+ for (const [key, value] of Object.entries(PT_BR_OVERRIDES)) expect(ptBR[key], key).toBe(value)
+
+ // The counts themselves are read off the pack rather than pinned here: a new UI string lands
+ // in pt.js and pt-BR.js together and moves both, and a number in a test that every new string
+ // has to be taught is a number nobody reads. What the numbers stood for is asserted above.
+ // If the hash fails, review the changed keys and wording before accepting a new one. From
// frontend/: node scripts/pt-br-inheritance-fingerprint.mjs --list
- expect(fingerprint, 'pt-PT inheritance changed; review the inherited pt-BR wording').toBe('4d5518e63f7c98ecaff9f42e1a655243f2b2970b69db97e743d9a8a9804ecbe1')
- expect(fingerprint, 'pt-PT inheritance changed; review the inherited pt-BR wording').toBe('732475e14c37965032b06880235dc174afe45c845ccf17cec50d422674db7512')
++ expect(fingerprint, 'pt-PT inheritance changed; review the inherited pt-BR wording').toBe('2e0935fb1e2cf1185e473b07ef176c5e03ae330a3836d35af99eb6b1a7a31707')
})
test('does not leak European Portuguese UI terms', () => {
diff --cc frontend/src/lib/routines.js
index 8ca81ae61,e540dade7..d2179d75c
--- a/frontend/src/lib/routines.js
+++ b/frontend/src/lib/routines.js
@@@ -14,29 -17,58 +17,85 @@@ export function copyRoutine(routine, su
return copy
}
+/**
+ * Delete a routine and every pointer to it, in place on a store draft. A weekday holds a list of
+ * routine ids, so the deleted one is pulled from each day and the key dropped when it empties
+ * (never store []); a day that never named it is left exactly as it was. A per-date reschedule
+ * (dayPlan) naming it goes too: left behind, the day still counts as overridden and wears a
+ * "rescheduled" badge for good with no way to clear it.
+ *
+ * Plan's swipe, RoutineEdit's button and the Coach's remove-routine all delete through here, so
+ * the next thing that learns to point at a routine is cleaned up in one place, not three.
+ * Returns the dropped dayPlan entries ({ iso: id }), which the Coach records so a revert can put
+ * them back.
+ */
+export function deleteRoutine(s, id) {
+ s.routines = s.routines.filter(r => r.id !== id)
+ Object.keys(s.week || {}).forEach(d => {
+ const ids = [].concat(s.week[d])
+ if (!ids.includes(id)) return
+ const next = ids.filter(rid => rid !== id)
+ if (next.length) s.week[d] = next; else delete s.week[d]
+ })
+ const dropped = {}
+ Object.keys(s.dayPlan || {}).forEach(iso => {
+ if (s.dayPlan[iso] === id) { dropped[iso] = id; delete s.dayPlan[iso] }
+ })
+ return dropped
+}
++
+ /**
+ * A routine slot with another exercise in it (#110): the machine you planned around is gone, or
+ * a variation takes over the lift for a block. The slot keeps its place and what was set up for
+ * it — sets, reps, weight, rest, warm-ups, the progression rule, the note, its superset — and only
+ * the exercise changes. The old way (remove, add, configure again) lost all of that.
+ *
+ * Some things cannot come along. A cardio slot is minutes at a speed and a lifting slot is sets
+ * of reps at a load, so between the two only the note, the rest and the superset carry over and
+ * the rest starts from the new exercise's defaults. A load means something else once the new
+ * exercise is bodyweight where the old one was not, or the other way round: 60 kg on a bench is
+ * not 60 kg added to a push-up. The same goes for an assistance machine, where the number is
+ * help rather than load: 40 kg off a pull-up is not 40 kg on a pulldown. There the weight goes
+ * back to 0. The bodyweight, assisted and per-side flags describe the movement, not the
+ * prescription, so they are dropped and the new exercise follows its own, the way the Coach's
+ * swap does (lib/coach.js): a split squat's "per side" would split a back squat's reps into L/R.
+ *
+ * What is not carried is history. Progress belongs to a routine and an exercise together (#216),
+ * so the new exercise starts on its own line — its own sessions in this routine, and until there
+ * are any, the slot's numbers — and the old exercise keeps its sessions, ready if it comes back.
+ * That is also why the old exercise's weight gives way to the new one's own wherever the new one
+ * has been logged (`S`, and the routine `rid` the slot is in): the next session reads a slot
+ * weight that differs from the one its last session was planned at as a deliberate edit, and
+ * opens there (#275, nextPrescription). An 80 kg barbell bench carried onto dumbbells trained at
+ * 30 would open the dumbbells at 80 — and only when the two rep schemes differed, because a
+ * plan whose sets and reps match just carries on. With the new exercise's own planned weight in
+ * the slot, its history decides either way. One never logged keeps the slot's weight, since
+ * there is nothing better to start from.
+ *
+ * Picking the exercise that is already in the slot replaces nothing, and changes nothing.
+ */
+ export function replaceSlotExercise(slot, id, S, rid) {
+ const old = slot || {}
+ if (old.id === id) return { ...old }
+ if ((modeOf(old) === 'cardio') !== isCardio(id)) {
+ const kept = ['sg', 'note', 'restSec'].filter(key => old[key] != null)
+ return { id, ...defaultConfig(id), ...Object.fromEntries(kept.map(key => [key, old[key]])) }
+ }
+ const { id: _replaced, bodyweight: _flag, assisted: _assisted, side: _side, ...carried } = old
+ const out = { id, ...carried }
+ if (isCardio(id)) return out
+ if (isBw(old) !== isBodyweightEq(id)) {
+ out.weight = 0
+ // A rep ceiling belongs to bodyweight work: it adds sets where there is no load to add.
+ delete out.repsMax
+ }
+ if (isAssisted(old) !== isAssisted(id)) out.weight = 0
+ // The session the next prescription will read for this slot (nextPrescription), so the weight
+ // put here is the one that session was planned at: the restart rule then sees no edit and
+ // holds at what was lifted, or the plan carries on from it. A session saved before plans were
+ // stamped has no planned weight, and what was lifted in it is the nearest thing.
+ const mode = modeOf(out)
+ const last = S ? sessionsFor(S, id, out, rid).filter(s => s.mode === mode).at(-1) : null
+ if (last) out.weight = last.planned?.weight ?? last.weight ?? 0
+ return out
+ }
diff --cc frontend/src/locales/pt-BR.js
index f63dde8ba,b1d644157..6646b0b0f
--- a/frontend/src/locales/pt-BR.js
+++ b/frontend/src/locales/pt-BR.js
@@@ -719,53 -709,7 +719,54 @@@ export const PT_BR_OVERRIDES =
'First time in this routine — starting from its own target.': 'Primeira vez nesta rotina — você começa pela meta dela.',
'No weight logged last time — enter what you lift and progression takes it from there.': 'Nenhum peso registrado na última vez — informe quanto você levanta e a progressão segue a partir daí.',
'reps from your last session': 'reps da sua última sessão',
+ 'Save as routine?': 'Salvar como rotina?',
+ 'Save as routine': 'Salvar como rotina',
+ 'Create an independent routine from these exercise targets. Your workout history is kept.': 'Criar uma rotina independente a partir destes objetivos. O histórico de treinos será mantido.',
+ 'Keep timing after target': 'Continuar contando após o objetivo',
+ 'Timed sets continue up to 15 extra minutes. Tap Done to log the actual duration.': 'As séries cronometradas continuam por até 15 minutos extras. Toque em Concluído para registrar a duração real.',
+ 'Edit workout': 'Editar treino',
+ 'Workout updated': 'Treino atualizado',
+ 'Save workout changes?': 'Salvar alterações do treino?',
+ 'Save your edits to this workout, or keep the original record.': 'Salve as alterações deste treino ou mantenha o registro original.',
+ 'Save changes': 'Salvar alterações',
+ "Don't save": 'Não salvar',
+ 'Keep editing': 'Continuar editando',
+ 'This workout was deleted on another device. Your edits are still here.': 'Este treino foi excluído em outro dispositivo. Suas alterações continuam aqui.',
+ 'Close editor': 'Fechar editor',
+ 'Editing a saved workout. Date and duration stay unchanged.': 'Você está editando um treino salvo. A data e a duração permanecem iguais.',
+ // --- demo build (v1.3.7) ---
+ 'A two-day rotation across three sessions a week, built around the equipment you listed. Compounds first, one pull for every press, and enough overlap between the days that nothing goes two weeks without being trained.': 'Uma rotação de dois dias em três sessões por semana, montada em torno do equipamento que você informou. Primeiro os exercícios compostos, uma puxada para cada empurrão e sobreposição suficiente entre os dias para que nada fique duas semanas sem ser treinado.',
+ 'Body weight has been flat for four weeks while the goal is to gain. That is a kitchen problem rather than a training one — the plan is not what is holding it back.': 'O peso corporal está estagnado há quatro semanas enquanto o objetivo é ganhar. Isso é um problema de cozinha, não de treino — não é o plano que está segurando.',
+ 'Demo data reset': 'Dados da demo redefinidos',
+ 'Direct arm work, since you asked for it.': 'Trabalho direto de braços, já que você pediu.',
+ 'Every top set on this one came in at RPE 9.5 or above for three sessions and the weight has not moved. Swapping the movement for four weeks usually breaks that stall faster than grinding the same one.': 'Todas as séries principais deste exercício ficaram em RPE 9,5 ou mais por três sessões e o peso não se mexeu. Trocar o movimento por quatro semanas costuma destravar essa estagnação mais rápido do que insistir no mesmo.',
+ 'Example data, stored only in this browser — change anything you like.': 'Dados de exemplo, salvos somente neste navegador — mude o que quiser.',
+ 'No training history yet — starting conservatively.': 'Ainda não há histórico de treino — começando com cautela.',
+ 'Passkey sign-in, sync across your devices, your own data.': 'Login com chave de acesso, sincronização entre seus dispositivos, seus próprios dados.',
+ 'Puts the example plan, workouts and weigh-ins back the way they started.': 'Redefine o plano, os treinos e as pesagens de exemplo como estavam no início.',
+ 'Reset': 'Redefinir',
+ 'Reset demo data': 'Redefinir dados da demo',
+ 'Reset demo data?': 'Redefinir os dados da demo?',
+ 'Revised as you asked. Everything you did not question is exactly as it was.': 'Revisado como você pediu. Tudo o que você não questionou está exatamente como estava.',
+ 'Self-host it in a minute →': 'Hospede você mesmo em um minuto →',
+ 'Self-host openGym': 'Hospedar o openGym por conta própria',
+ 'Sessions have been running about fifteen minutes over. This is the accessory with the least to lose from one set fewer.': 'As sessões estão passando uns quinze minutos do previsto. Este é o exercício acessório que menos perde com uma série a menos.',
+ 'The two big lower-body and pressing patterns first, while you are fresh.': 'Primeiro os dois grandes padrões de membros inferiores e de empurrar, enquanto você está descansado.',
+ 'This demo runs entirely in your browser on example data — nothing is sent anywhere. Passkey sign-in and sync across your devices come with the openGym server, which you get by self-hosting it.': 'Esta demo roda inteiramente no seu navegador com dados de exemplo — nada é enviado para lugar nenhum. O login com chave de acesso e a sincronização entre seus dispositivos vêm com o servidor openGym, que você obtém hospedando-o por conta própria.',
+ 'Three things worth changing, and one worth knowing about. Everything else is working — the squat and the pulls are both progressing on schedule.': 'Três coisas que vale a pena mudar e uma que vale a pena saber. Todo o resto está funcionando — o agachamento e as puxadas estão progredindo como previsto.',
+ 'You have moved this session to Saturday three weeks running. Better the plan says so than that you keep overriding it.': 'Você mudou esta sessão para sábado três semanas seguidas. Melhor o plano dizer isso do que você ficar alterando toda vez.',
+ 'You’re in the demo': 'Você está na demo',
+ // a missed day logged afterwards (#284) — pt-PT's "Registar" reads as Portugal; "Marcar todas
+ // as séries como feitas" is shared and inherits
+ 'Log this workout': 'Registrar este treino',
+ // last time or best set under each exercise (#173) — pt-PT's "Por baixo" and tu-forms read as
+ // Portugal; "Melhor série" is shared and inherits
+ 'Show last time instead': 'Mostrar a última vez',
+ 'Show your best set instead': 'Mostrar sua melhor série',
+ 'Shown under each exercise': 'Abaixo de cada exercício',
+ 'What you did the last time, in that routine.': 'O que você fez da última vez nessa rotina.',
+ 'Your heaviest set of the exercise, from any workout.': 'Sua série mais pesada do exercício, de qualquer treino.',
+ 'Replaced with “{0}”': 'Substituído por “{0}”',
}
export default { ...pt, ...PT_BR_OVERRIDES }
diff --cc frontend/src/sheets.jsx
index 0f440bb25,d44479ea1..02cc17ec1
--- a/frontend/src/sheets.jsx
+++ b/frontend/src/sheets.jsx
@@@ -28,9 -28,9 +28,10 @@@ import { exerciseHistory } from './lib/
import { policyFor, defaultIncrement, POLICIES_FOR, POLICY_NAME, POLICY_DESC, MAX_BW_SETS, weightIncrement } from './lib/progression.js'
import { normalizeRepRange } from './lib/rep-range.js'
import { MOBILE, shareExport, printHtml } from './lib/mobile.js'
+ import { speedUnitOf, toSpeed, fromSpeed } from './lib/speed.js'
import { buildCompletedWorkout } from './lib/finish-workout.js'
import { isWarmupRow, hasCompletedWork } from './lib/workout-model.js'
+import { saveSessionAsRoutine } from './lib/session-routines.js'
import { nextUnfinishedUnit } from './lib/supersetFlow.js'
import { swapActiveExercise } from './lib/active-exercise-swap.js'
import { useSheetKeyboard, useRevealActiveChip, tappable } from './lib/use-sheet-keyboard.js'
@@@ -1839,44 -1706,24 +1854,44 @@@ function WorkoutDetail({ w, close })
const text = latest.current.trim().slice(0, NOTE_MAX)
if (text === initial.current) return
update(s => {
- const rec = s.workouts.find(x => x.id === w.id)
- if (!rec) return // deleted from this very sheet
+ const rec = s.workouts.find(x => sameWorkout(x, w))
+ if (!rec || text === (rec.note || '')) return // deleted from this very sheet, or already saved
if (text) rec.note = text; else delete rec.note
+ stampWorkout(rec)
})
}, [])
- // A combined session's entries carry a `rid`; group them into per-routine sections in merge
- // order. A legacy single-routine workout (one routineIds, or no rid anywhere) renders flat.
+ const nameOf = e => (EXIDX[e.id] ? exerciseNameFor(EXIDX[e.id]) : (e.n || e.id))
+ // Tapping an exercise opens its history (Discord 'Improvement ideas'): from one session to the
+ // curve it sits on, which is the question a past workout raises most often.
const entryRow = (e, i) => {
const ex = EXIDX[e.id]
- return <div key={i} className="row" style={{ marginBottom: 12, alignItems: 'flex-start' }}>
+ return <div key={i} className="row wd-ex" style={{ alignItems: 'flex-start' }} {...tappable(() => exerciseHistorySheet(e.id))}>
{ex && <Thumb ex={ex} />}
- <div className="grow"><div className="tt capitalize" style={{ fontWeight: 600 }}>{ex ? exerciseNameFor(ex) : (e.n || e.id)} {w.prs && w.prs.includes(e.id) && <span className="pr"><Icon name="trophy" />PR</span>}</div>
+ <div className="grow"><div className={`tt ${exerciseNameClass(ex)}`} style={{ fontWeight: 600 }}>{nameOf(e)} {w.prs && w.prs.includes(e.id) && <span className="pr"><Icon name="trophy" />PR</span>}</div>
- <div className="ss">{e.sets.filter(hasCompletedWork).map(s => setLabel(e.id, s, e.target)).join(' · ') || t('no sets')}</div>
+ <div className="ss">{e.sets.filter(hasCompletedWork).map(s => setLabel(e.id, s, e.target, speedUnitOf(st))).join(' · ') || t('no sets')}</div>
{e.note && <div className="small dim" style={{ marginTop: 3 }}>
- {e.notePin && <Icon name="flag" style={{ fontSize: 12, marginRight: 4, verticalAlign: '-1px', color: 'var(--yellow)' }} />}{e.note}
+ {e.notePin && <Icon name="flag" style={{ fontSize: 12, marginInlineEnd: 4, verticalAlign: '-1px', color: 'var(--yellow)' }} />}{e.note}
</div>}</div>
+ <Icon name="chevronRight" className="chev" style={{ alignSelf: 'center' }} />
+ </div>
+ }
+ // Exercises done as a superset stay together under a "Superset" label and one bar, the way the
+ // routine editor shows them (Discord: "supersets aren't shown at all"). Adjacent entries with
+ // the same tag, as in the workout itself; a workout finished before the tag was kept has none.
+ const entryRows = items => supersetUnits(items.map(([e]) => e)).map(unit => {
+ if (unit.length < 2) return entryRow(...items[unit[0]])
+ return <div key={'ss' + items[unit[0]][1]} className="wd-ss">
+ <div className="ss-label"><Icon name="link" />{t('Superset')}</div>
+ {unit.map(k => entryRow(...items[k]))}
</div>
+ })
+ // Copied with the note as it stands in the box, which may not be saved yet.
+ const copyAsText = async () => {
+ const rec = { ...(st.workouts.find(x => sameWorkout(x, w)) || w), note: note.trim() }
+ toast(await copyText(workoutText(rec, { unit: st.unit, nameOf })) ? t('Copied') : t('Could not copy'))
}
+ // A combined session's entries carry a `rid`; group them into per-routine sections in merge
+ // order. A legacy single-routine workout (one routineIds, or no rid anywhere) renders flat.
const groups = []
w.entries.forEach((e, i) => {
const key = e.rid || '__none'
diff --cc frontend/src/views/CoachChat.jsx
index d25401105,15f900f70..96441c1f9
--- a/frontend/src/views/CoachChat.jsx
+++ b/frontend/src/views/CoachChat.jsx
@@@ -625,10 -626,10 +626,10 @@@ function ProposalDetail({ entry, S })
{kind === 'create' && b && <>
<WeekStrip days={weekDays} />
- {b.routines.length > 1 && <div className="pcard-tabs" style={{ paddingLeft: 0, paddingRight: 0 }}>
+ {b.routines.length > 1 && <div className="pcard-tabs" style={{ paddingInline: 0 }}>
{b.routines.map((x, i) => <button key={x.id || i} className={'pcard-tab' + (i === tab ? ' on' : '')} onClick={() => setTab(i)}>{x.emoji} {x.name}</button>)}
</div>}
- {r && <RoutineBlock r={r} unit={S.unit} />}
+ {r && <RoutineBlock r={r} unit={S.unit} speedUnit={speedUnitOf(S)} />}
<p className="pcard-sum" style={{ fontSize: 13 }}>{entry.scheduled ? t('Your week was set to this schedule.') : t('Imported without changing your week.')}</p>
</>}
{kind === 'create' && !b && <p className="pcard-sum">{t('This plan was imported before the app kept proposals; only its summary is left.')}</p>}
diff --cc frontend/src/views/Library.jsx
index 4545c3734,7433aa6d9..16726888f
--- a/frontend/src/views/Library.jsx
+++ b/frontend/src/views/Library.jsx
@@@ -5,8 -5,8 +5,8 @@@ import { EXDB, BODYPARTS, allExercises
import { MUSCLE_NAME } from '../lib/muscles.js'
import { activeProfile, exAvailable } from '../lib/equipment.js'
import { bestWeightFor } from '../lib/history.js'
- import { fmtNum } from '../lib/format.js'
+ import { fmtNum, exCount } from '../lib/format.js'
-import { t, exerciseNameFor } from '../lib/i18n.js'
+import { t, exerciseNameFor, exerciseNameClass } from '../lib/i18n.js'
import { Thumb } from '../components/Media.jsx'
import { exerciseDetailSheet, addToRoutineSheet, customExSheet } from '../sheets.jsx'
import Icon from '../components/Icon.jsx'
diff --cc frontend/src/views/RoutineEdit.jsx
index 0babfa4ba,41a0ea980..aa39a7e8a
--- a/frontend/src/views/RoutineEdit.jsx
+++ b/frontend/src/views/RoutineEdit.jsx
@@@ -4,8 -4,8 +4,8 @@@ import { useStore } from '../store/useS
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 { uid, capWords } from '../lib/format.js'
-import { t, exerciseNameFor } from '../lib/i18n.js'
+import { t, exerciseNameFor, exerciseNameClass } from '../lib/i18n.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'
@@@ -13,7 -13,10 +13,10 @@@ import Icon from '../components/Icon.js
import { glyphOf } from '../lib/glyphs.js'
import { Button, Row, SelectRow, Switch } from '../components/ui.jsx'
import SwipeToDelete from '../components/SwipeToDelete.jsx'
- import { copyRoutine, deleteRoutine } from '../lib/routines.js'
-import { copyRoutine, replaceSlotExercise } from '../lib/routines.js'
++import { copyRoutine, deleteRoutine, replaceSlotExercise } from '../lib/routines.js'
+ import { planPrintHTML, printPlan } from '../lib/plan-share.js'
+ import { MOBILE, printHtml } from '../lib/mobile.js'
+ import { speedUnitOf } from '../lib/speed.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'
@@@ -402,10 -446,13 +451,13 @@@ export default function RoutineEdit()
deleteLabel={t('Remove from routine')}
onDelete={() => edit(x => { x.splice(i, 1); cleanupSg(x) })}
onClick={() => {
- exConfigSheet(ex, e, cfg => edit(x => { x[i] = { id: x[i].id, sg: x[i].sg, ...cfg } }), () => edit(x => { x.splice(i, 1); cleanupSg(x) }), r)
+ exConfigSheet(ex, e, cfg => edit(x => { x[i] = { id: x[i].id, sg: x[i].sg, ...cfg } }), () => edit(x => { x.splice(i, 1); cleanupSg(x) }), r, null, () => replace(i))
}}>
+ {/* Shown on pointer devices only (index.css .routine-grip); the Move buttons and the
+ long press stay the way in for a keyboard and a finger. */}
+ <span className="routine-grip" data-drag-handle aria-hidden="true" title={t('Reorder exercises')}><Icon name="grip" /></span>
<Thumb ex={ex} />
- <div className="grow"><div className={`tt ${exerciseNameClass(ex)}`}>{exerciseNameFor(ex)}</div><div className="ss">{exLine(e, S.unit)}</div>
- <div className="grow"><div className="tt capitalize">{exerciseNameFor(ex)}</div><div className="ss">{exLine(e, S.unit, speedUnitOf(S))}</div>
++ <div className="grow"><div className={`tt ${exerciseNameClass(ex)}`}>{exerciseNameFor(ex)}</div><div className="ss">{exLine(e, S.unit, speedUnitOf(S))}</div>
{e.note && <div className="small dim" style={{ marginTop: 2 }}>{e.note}</div>}</div>
{noEquip && <span className="tag" style={{ color: 'var(--orange)', borderColor: 'var(--orange)' }} title={t('Needs {0} — not in your active profile', t(ex.eq))}><Icon name="warning" /></span>}
<div style={{ display: 'flex', flexDirection: 'column', gap: 2, flex: 'none', alignItems: 'center' }}>
diff --cc frontend/src/views/Stats.jsx
index 0297a86d7,c21869191..0a5fb4c01
--- a/frontend/src/views/Stats.jsx
+++ b/frontend/src/views/Stats.jsx
@@@ -2,10 -2,11 +2,11 @@@ import { useEffect, useMemo, useState
import { useNavigate } from 'react-router-dom'
import { useStore } from '../store/useStore.js'
import { EXIDX, matchExercise, betterWeight } from '../lib/exercises.js'
-import { lastBW, streakWeeks, setLabel, modeOf, effortOf, metricModeForEntry, metricRowsForEntry, bestWeightForEntry } from '../lib/history.js'
+import { lastBW, streakWeeks, setLabel, modeOf, effortOf, entriesForExercise, metricEntriesForExercise, metricModeForEntry, bestWeightForEntry, completedRepsOf, workoutDay } from '../lib/history.js'
import { fmtNum, fmtDate, fmtVol, todayISO, weekStartOf } from '../lib/format.js'
+ import { speedUnitOf, speedLabel, toSpeed } from '../lib/speed.js'
import { t, exerciseNameFor, getLang } from '../lib/i18n.js'
-import { bwSheet, goalSheet, calendarSheet, workoutDetailSheet, exerciseHistorySheet, WorkoutRow, bwDeltaColor } from '../sheets.jsx'
+import { bwSheet, goalSheet, calendarSheet, workoutDetailSheet, exerciseHistorySheet, WorkoutRow, bwDeltaColor, weighInsSheet } from '../sheets.jsx'
import LineChart from '../components/LineChart.jsx'
import Heatmap from '../components/Heatmap.jsx'
import Icon from '../components/Icon.jsx'
@@@ -344,16 -334,16 +345,18 @@@ export default function Stats()
desc: snapshot.desc || entry?.desc || '',
}
}
+ // Cardio is charted and ranked in the profile's speed unit; the sets keep km/h (lib/speed.js).
+ const speedUnit = speedUnitOf(S)
const currentOf = id => {
for (let i = workouts.length - 1; i >= 0; i--) {
- const en = workouts[i].entries.find(e => e.id === id)
- if (!en) continue
- const mode = metricModeForEntry(en) || modeOf({ id })
- const rows = metricRowsForEntry(en, mode)
- const mx = mode === 'reps' ? bestWeightForEntry(en) : Math.max(0, ...rows.map(s => mode === 'cardio' ? toSpeed(s.speed || 0, speedUnit) : mode === 'time' ? (s.sec || 0) : (s.w || 0)))
+ const data = metricDataOf(workouts[i], id)
+ if (!data.mode) continue
+ const mode = data.mode
+ const rows = data.rows
+ const mx = mode === 'reps'
+ ? data.best
- : Math.max(0, ...rows.map(s => mode === 'cardio' ? (s.speed || 0) : mode === 'time' ? (s.sec || 0) : (s.w || 0)))
- if (mx > 0) return { mx, unit: mode === 'cardio' ? 'km/h' : mode === 'time' ? 's' : S.unit }
++ : Math.max(0, ...rows.map(s => mode === 'cardio' ? toSpeed(s.speed || 0, speedUnit) : mode === 'time' ? (s.sec || 0) : (s.w || 0)))
+ if (mx > 0) return { mx, unit: mode === 'cardio' ? speedLabel(speedUnit) : mode === 'time' ? 's' : S.unit }
// Unloaded reps work still has a current figure — its rep count. Without this the whole
// picker label went blank and the exercise sorted to the bottom as if it had no history.
if (mode === 'reps') {
@@@ -388,10 -376,13 +391,10 @@@
// them (issue #5). When nothing in an exercise's history was ever loaded, the progress IS
// the rep count, so plot that. Add a weighted set later and it switches back to weight on
// its own, which is also the honest reading: that is when load became the thing improving.
- const repsOnly = curEx && curMode === 'reps' && !workouts.some(w => {
- const en = w.entries.find(e => e.id === curEx)
- return en && bestWeightForEntry(en) > 0
- })
- const bestRepsOf = en => Math.max(0, ...metricRowsForEntry(en, 'reps').map(s => Number(s.r) || 0))
+ const repsOnly = curEx && curMode === 'reps' && !workouts.some(w =>
+ entriesForExercise(w, curEx).some(en => bestWeightForEntry(en) > 0))
- const metric = s => curCardio ? (s.speed || 0) : curTimed ? (s.sec || 0) : (s.w || 0)
- const exUnit = curCardio ? 'km/h' : curTimed ? 's' : repsOnly ? t('reps') : S.unit
+ const metric = s => curCardio ? toSpeed(s.speed || 0, speedUnit) : curTimed ? (s.sec || 0) : (s.w || 0)
+ const exUnit = curCardio ? speedLabel(speedUnit) : curTimed ? 's' : repsOnly ? t('reps') : S.unit
let exPts = [], exList = [], exBest = 0
if (curEx) {
workouts.forEach(w => {
diff --cc frontend/src/views/Workout.jsx
index 19f32d345,d7488291e..7beb6c4ec
--- a/frontend/src/views/Workout.jsx
+++ b/frontend/src/views/Workout.jsx
@@@ -8,8 -7,9 +8,9 @@@ import { exOr, betterWeight } from '../
import { usesBar, barWeightFor, plateSplit } from '../lib/bar.js'
import { effectiveRoutines, effectiveRoutineIds, lastEntryFor, bestWeightFor, bestWeightForEntry, buildSets, freestyleConfig, defaultConfig, setsDoneActive, setUnitsTotal, supersetUnits, unitOf, setLabel, modeOf, isBw, isPerSide, repStep, EFFORT, effortOf, stepEffort, capEffort, cascadeWeight, insertWarmupRow, removeRowAt, pairAdjacent, unpairSuperset, cleanupSg, applyIntensifierPlan, pinnedNoteFor, exNoteFor, setsRepsOf } from '../lib/history.js'
import { fmtNum, capWords, fmtDate, todayISO, exCount, DAYN } from '../lib/format.js'
+ import { speedUnitOf, toSpeed, fromSpeed } from '../lib/speed.js'
import { beep, vibrate, unlock } from '../lib/sound.js'
-import { t, exerciseNameFor } from '../lib/i18n.js'
+import { t, exerciseNameFor, exerciseNameClass } from '../lib/i18n.js'
import { api, appBase } from '../lib/api.js'
import { insertionIndexAfterCurrentUnit, nextUnfinishedUnit, setProgressHighWater, supersetFlowStep, restAfterSet, restOnRecheck, restSecFor, warmupRestSecFor } from '../lib/supersetFlow.js'
import Media from '../components/Media.jsx'