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.

Cardio speed reads and is typed in mph for imperial users, and stays stored in km/h (Discord "miles per hour")

Duarte Santos84257853a653
diff --git a/frontend/src/lib/history.js b/frontend/src/lib/history.js
index 18316f8e1..62a4bcbd8 100644
--- a/frontend/src/lib/history.js
+++ b/frontend/src/lib/history.js
@@ -1,5 +1,6 @@
// 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'
const objectOf = value => value && typeof value === 'object' && !Array.isArray(value) ? value : {}
@@ -105,13 +106,14 @@ const effortTail = s => {
// One-line summary of a logged set. `cfg` carries the mode when the caller has it (a routine
// entry or a workout entry); passing an id alone keeps the old body-part behaviour.
-export function setLabel(id, s, cfg) {
+// `speedUnit` is the profile's (lib/speed.js speedUnitOf); without one a cardio set reads km/h.
+export function setLabel(id, s, cfg, speedUnit) {
const c = cfg || { id }
let mode = modeOf(c)
// 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 })
// One side's "weight×reps" (or bodyweight "reps" / "+belt × reps"), the same shape a whole
@@ -159,13 +161,13 @@ export function setsRepsOf(cfg) {
}
// One-line summary of a planned exercise ("3 × 10 · 60 kg"), shared by the routine editor
-// and the plan export so a mode is described the same way everywhere.
-export function exLine(cfg, unit) {
+// and the plan export so a mode is described the same way everywhere. `speedUnit` as setLabel.
+export function exLine(cfg, unit, speedUnit) {
const mode = modeOf(cfg)
const n = cfg.sets || 1
// Added weight reads as added: "+10 kg" on a dip belt, "60 kg" on a barbell.
const load = cfg.weight ? ' · ' + (isBw(cfg) ? '+' : '') + fmtNum(cfg.weight) + ' ' + unit : ''
- if (mode === 'cardio') return `${n} × ${cfg.min || 20} min @ ${fmtNum(cfg.speed || 8)} km/h`
+ if (mode === 'cardio') return `${n} × ${cfg.min || 20} min @ ${fmtSpeed(cfg.speed || 8, speedUnit)}`
if (mode === 'time') return `${setsRepsOf(cfg)}${load}`
// This is the line with room for it, so the split is spelled out: "3 × 16 · 8/side".
const split = isPerSide(cfg) ? ' · ' + t('{0}/side', repsOf(cfg, v => fmtNum(sideReps(v)))) : ''
diff --git a/frontend/src/lib/plan-share.js b/frontend/src/lib/plan-share.js
index e481eb7c6..a2c3d2555 100644
--- a/frontend/src/lib/plan-share.js
+++ b/frontend/src/lib/plan-share.js
@@ -14,6 +14,7 @@ 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 { convertWeight } from './units.js'
+import { fmtSpeed, speedUnitOf } from './speed.js'
import { MUSCLES, inMuscleOrder } from './muscles.js'
const PLAN_FMT = 1
@@ -289,12 +290,13 @@ export function mergePlan(s, bundle, { schedule } = {}) {
const esc = str => String(str == null ? '' : str)
.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;')
-// One exercise's scheme, e.g. "3 × 10 · 60 kg", "3 × 0:45" or "2 × 20 min @ 8 km/h".
-function scheme(e, unit) {
+// One exercise's scheme, e.g. "3 × 10 · 60 kg", "3 × 0:45" or "2 × 20 min @ 8 km/h" — the speed
+// in the profile's unit (lib/speed.js), like the weight.
+function scheme(e, unit, speedUnit) {
const sets = e.sets || 1
const mode = modeOf(e)
if (mode === 'cardio') {
- const body = `${e.min || 20} min @ ${fmtNum(e.speed || 8)} km/h`
+ const body = `${e.min || 20} min @ ${fmtSpeed(e.speed || 8, speedUnit)}`
return sets > 1 ? `${sets} × ${body}` : body
}
let s = mode === 'time' ? `${sets} × ${fmtSec(e.sec || 45)}` : `${sets} × ${e.reps ?? 10}`
@@ -317,14 +319,14 @@ function units(ex) {
// `bare` leaves out the routine's own heading, for a page that is this one routine and already
// names it at the top.
-function routineHTML(r, unit, { bare = false } = {}) {
+function routineHTML(r, unit, { bare = false, speedUnit } = {}) {
const rows = units(r.ex).map(u => {
const items = u.map(e => {
const ex = EXIDX[e.id]
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">${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>`
}).join('')
return u.length > 1
? `<div class="ss"><div class="ss-tag">${esc(t('Superset'))}</div><div class="ss-items">${items}</div></div>`
@@ -359,7 +361,7 @@ export function planPrintHTML(S, owner, { routineId } = {}) {
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, { bare: !!single })).join('')
+ ? routines.map(r => routineHTML(r, unit, { bare: !!single, speedUnit: speedUnitOf(S) })).join('')
: `<p class="none">${esc(t('No routines yet.'))}</p>`
const title = single ? single.name : t('Weekly Training Plan')
const sub = [single ? exCount(single.ex.length) : null, owner, todayISO()].filter(Boolean).map(esc).join(' · ')
diff --git a/frontend/src/lib/pt-br-locale.test.js b/frontend/src/lib/pt-br-locale.test.js
index b89a4f3a3..3fa94ecdd 100644
--- a/frontend/src/lib/pt-br-locale.test.js
+++ b/frontend/src/lib/pt-br-locale.test.js
@@ -28,10 +28,10 @@ describe('Brazilian Portuguese locale', () => {
const fingerprint = createHash('sha256').update(JSON.stringify(inherited)).digest('hex')
expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(680)
- expect(inherited).toHaveLength(675)
+ expect(inherited).toHaveLength(677)
// 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('a173a05c6ada8fed6f9ee9f4e4f1745bc8f96b9b68c506bddaa4a499b6ff3643')
+ expect(fingerprint, 'pt-PT inheritance changed; review the inherited pt-BR wording').toBe('732475e14c37965032b06880235dc174afe45c845ccf17cec50d422674db7512')
})
test('does not leak European Portuguese UI terms', () => {
diff --git a/frontend/src/lib/speed.js b/frontend/src/lib/speed.js
new file mode 100644
index 000000000..3d6028038
--- /dev/null
+++ b/frontend/src/lib/speed.js
@@ -0,0 +1,41 @@
+// Cardio speed in km/h or mph (Discord "miles per hour").
+//
+// Speed is stored in km/h, always: in a routine, in a logged set, in a shared plan file and in
+// what the Coach and the MCP bridge read. Only what is shown and what is typed follow the
+// profile's speed unit. Switching the unit therefore rewrites nothing, two devices on different
+// settings never disagree about a number, and a plan shared between a km/h and an mph profile
+// needs no conversion. The weight unit works the other way round (lib/units.js walks every
+// stored weight), because a load has to land on plates in the unit you load; a speed does not.
+import { fmtNum } from './format.js'
+
+// Exact: the international mile is 1609.344 m.
+export const KMH_PER_MPH = 1.609344
+
+/**
+ * The unit speeds are shown in: 'kmh' or 'mph'. Until the profile chooses one (Settings →
+ * General) it follows the weight unit — a profile in pounds reads mph — so imperial users get
+ * miles without looking for a setting, and a kg lifter on an mph treadmill can still pick it.
+ */
+export const speedUnitOf = S => (S?.speedUnit === 'mph' || S?.speedUnit === 'kmh' ? S.speedUnit : S?.unit === 'lb' ? 'mph' : 'kmh')
+
+/** The unit's short label, as the numbers carry it: "km/h" or "mph". */
+export const speedLabel = unit => (unit === 'mph' ? 'mph' : 'km/h')
+
+/*
+ * km/h to the unit on screen and back. In km/h both are the identity, so a profile that never
+ * chose mph sees and stores exactly what it always did. In mph the stored km/h is kept to
+ * hundredths: that is fine enough that any speed typed in mph with up to two decimals reads
+ * back as typed (the stored value is at most 0.005 km/h, 0.0031 mph, off, and the display
+ * rounds to hundredths), and it keeps a typed "6" from being stored as 9.656064.
+ */
+export function toSpeed(kmh, unit) {
+ if (unit !== 'mph' || kmh == null || kmh === '' || !Number.isFinite(Number(kmh))) return kmh
+ return Math.round(Number(kmh) / KMH_PER_MPH * 100) / 100
+}
+export function fromSpeed(value, unit) {
+ if (unit !== 'mph' || value == null || value === '' || !Number.isFinite(Number(value))) return value
+ return Math.round(Number(value) * KMH_PER_MPH * 100) / 100
+}
+
+/** "8 km/h" or "5 mph" — a stored km/h speed, shown in `unit`. */
+export const fmtSpeed = (kmh, unit) => `${fmtNum(toSpeed(Number(kmh) || 0, unit))} ${speedLabel(unit)}`
diff --git a/frontend/src/lib/speed.test.js b/frontend/src/lib/speed.test.js
new file mode 100644
index 000000000..1d5a4f31a
--- /dev/null
+++ b/frontend/src/lib/speed.test.js
@@ -0,0 +1,99 @@
+// Cardio speed in km/h or mph (Discord "miles per hour"): stored in km/h, shown and typed in
+// the profile's unit, and exact both ways for what a person types.
+import { afterEach, describe, it, expect } from 'vitest'
+import { KMH_PER_MPH, speedUnitOf, speedLabel, toSpeed, fromSpeed, fmtSpeed } from './speed.js'
+import { setLabel, exLine } from './history.js'
+import { planPrintHTML } from './plan-share.js'
+import { setWeightDecimals } from './format.js'
+
+const BIKE = '2138' // stationary bike, cardio
+
+afterEach(() => setWeightDecimals(1))
+
+describe('speedUnitOf', () => {
+ it('follows the weight unit until the profile chooses', () => {
+ expect(speedUnitOf({ unit: 'kg' })).toBe('kmh')
+ expect(speedUnitOf({ unit: 'lb' })).toBe('mph')
+ expect(speedUnitOf({})).toBe('kmh')
+ expect(speedUnitOf(null)).toBe('kmh')
+ expect(speedUnitOf({ unit: 'lb', speedUnit: null })).toBe('mph')
+ })
+ it('keeps a choice either way round', () => {
+ expect(speedUnitOf({ unit: 'kg', speedUnit: 'mph' })).toBe('mph')
+ expect(speedUnitOf({ unit: 'lb', speedUnit: 'kmh' })).toBe('kmh')
+ // Anything else is not a choice.
+ expect(speedUnitOf({ unit: 'lb', speedUnit: 'knots' })).toBe('mph')
+ })
+ it('labels the numbers', () => {
+ expect(speedLabel('kmh')).toBe('km/h')
+ expect(speedLabel('mph')).toBe('mph')
+ expect(speedLabel(undefined)).toBe('km/h')
+ })
+})
+
+describe('toSpeed / fromSpeed', () => {
+ it('uses the exact mile', () => {
+ expect(KMH_PER_MPH).toBe(1.609344)
+ expect(toSpeed(1.609344, 'mph')).toBe(1)
+ expect(toSpeed(8, 'mph')).toBe(4.97)
+ expect(fromSpeed(6, 'mph')).toBe(9.66)
+ expect(fromSpeed(10, 'mph')).toBe(16.09)
+ })
+
+ it('is the identity in km/h, so a km/h profile stores exactly what it always did', () => {
+ for (const v of [0, 8, 9.656064, 10.25, 12.3456]) {
+ expect(toSpeed(v, 'kmh')).toBe(v)
+ expect(fromSpeed(v, 'kmh')).toBe(v)
+ expect(toSpeed(v, undefined)).toBe(v)
+ }
+ })
+
+ it('reads back every mph speed typed with up to two decimals exactly as typed', () => {
+ const off = []
+ for (let i = 0; i <= 4000; i++) {
+ const typed = i / 100
+ const back = toSpeed(fromSpeed(typed, 'mph'), 'mph')
+ if (back !== typed) off.push([typed, back])
+ }
+ expect(off).toEqual([])
+ })
+
+ it('stores km/h to the hundredth, not the full float', () => {
+ expect(fromSpeed(6.2, 'mph')).toBe(9.98)
+ expect(String(fromSpeed(3.3, 'mph'))).toBe('5.31')
+ })
+
+ it('passes an empty field through untouched', () => {
+ for (const v of [null, undefined, '']) {
+ expect(toSpeed(v, 'mph')).toBe(v)
+ expect(fromSpeed(v, 'mph')).toBe(v)
+ }
+ })
+})
+
+describe('speed in labels', () => {
+ it('formats a stored km/h speed in the unit on screen', () => {
+ expect(fmtSpeed(8, 'kmh')).toBe('8 km/h')
+ expect(fmtSpeed(8, 'mph')).toBe('5 mph')
+ setWeightDecimals(2)
+ expect(fmtSpeed(8, 'mph')).toBe('4.97 mph')
+ })
+
+ it('reads a logged cardio set and a planned cardio slot in mph', () => {
+ const set = { min: 30, speed: 9.66, done: true }
+ const target = { id: BIKE, sets: 1, min: 30, speed: 9.66 }
+ expect(setLabel(BIKE, set, target, 'mph')).toBe('30 min @ 6 mph')
+ expect(setLabel(BIKE, set, target)).toBe('30 min @ 9.7 km/h')
+ // A set saved by an older build, with no target: read from its own fields.
+ expect(setLabel(BIKE, set, null, 'mph')).toBe('30 min @ 6 mph')
+ expect(exLine({ id: BIKE, sets: 2, min: 20, speed: 16.09 }, 'lb', 'mph')).toBe('2 × 20 min @ 10 mph')
+ expect(exLine({ id: BIKE, sets: 2, min: 20, speed: 16.09 }, 'kg')).toBe('2 × 20 min @ 16.1 km/h')
+ })
+
+ it('prints a plan in the profile\'s speed unit', () => {
+ const routines = [{ id: 'c', name: 'Cardio', ex: [{ id: BIKE, sets: 1, min: 25, speed: 16.09 }] }]
+ expect(planPrintHTML({ unit: 'lb', week: {}, routines }, '')).toContain('25 min @ 10 mph')
+ expect(planPrintHTML({ unit: 'kg', week: {}, routines }, '')).toContain('25 min @ 16.1 km/h')
+ expect(planPrintHTML({ unit: 'kg', speedUnit: 'mph', week: {}, routines }, '', { routineId: 'c' })).toContain('25 min @ 10 mph')
+ })
+})
diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.js
index 63ac3fd89..7b84b16f2 100644
--- a/frontend/src/locales/de.js
+++ b/frontend/src/locales/de.js
@@ -107,6 +107,7 @@ export default {
'Intervals': 'Intervalle',
'Minutes': 'Minuten',
'Speed (km/h)': 'Tempo (km/h)',
+ 'Speed (mph)': 'Tempo (mph)',
'Sets': 'Sätze',
'Reps': 'Wdh.',
'Weight ({0})': 'Gewicht ({0})',
@@ -331,6 +332,7 @@ export default {
'Keep screen awake': 'Bildschirm anlassen',
'The screen stays on while a workout is running, so you don’t have to unlock your phone between sets.': 'Der Bildschirm bleibt an, solange ein Workout läuft — so musst du zwischen den Sätzen nicht entsperren.',
'Weight unit': 'Gewichtseinheit',
+ 'Speed unit': 'Geschwindigkeitseinheit',
'Week starts on': 'Woche beginnt am',
'Weight decimals': 'Nachkommastellen',
'How precisely weights are shown.': 'Wie genau Gewichte angezeigt werden.',
diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js
index 85cba1a8c..2dc70d4d1 100644
--- a/frontend/src/locales/es.js
+++ b/frontend/src/locales/es.js
@@ -102,6 +102,7 @@ export default {
'Intervals': 'Intervalos',
'Minutes': 'Minutos',
'Speed (km/h)': 'Velocidad (km/h)',
+ 'Speed (mph)': 'Velocidad (mph)',
'Sets': 'Series',
'Reps': 'Reps',
'Weight ({0})': 'Peso ({0})',
@@ -316,6 +317,7 @@ export default {
'Keep screen awake': 'Mantener la pantalla encendida',
'The screen stays on while a workout is running, so you don’t have to unlock your phone between sets.': 'La pantalla se mantiene encendida mientras hay un entrenamiento en curso, así no tienes que desbloquear el móvil entre series.',
'Weight unit': 'Unidad de peso',
+ 'Speed unit': 'Unidad de velocidad',
'Week starts on': 'La semana empieza el',
'Weight decimals': 'Decimales del peso',
'How precisely weights are shown.': 'Con qué precisión se muestran los pesos.',
diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.js
index 52b9df7ab..122f6e21a 100644
--- a/frontend/src/locales/fr.js
+++ b/frontend/src/locales/fr.js
@@ -102,6 +102,7 @@ export default {
'Intervals': 'Intervalles',
'Minutes': 'Minutes',
'Speed (km/h)': 'Vitesse (km/h)',
+ 'Speed (mph)': 'Vitesse (mph)',
'Sets': 'Séries',
'Reps': 'Reps',
'Weight ({0})': 'Poids ({0})',
@@ -316,6 +317,7 @@ export default {
'Keep screen awake': 'Garder l’écran allumé',
'The screen stays on while a workout is running, so you don’t have to unlock your phone between sets.': 'L’écran reste allumé tant qu’une séance est en cours, pas besoin de déverrouiller ton téléphone entre les séries.',
'Weight unit': 'Unité de poids',
+ 'Speed unit': 'Unité de vitesse',
'Week starts on': 'La semaine commence le',
'Weight decimals': 'Décimales du poids',
'How precisely weights are shown.': 'Avec quelle précision les poids sont affichés.',
diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.js
index 54ba8c528..6b8189275 100644
--- a/frontend/src/locales/hi.js
+++ b/frontend/src/locales/hi.js
@@ -102,6 +102,7 @@ export default {
'Intervals': 'इंटरवल',
'Minutes': 'मिनट',
'Speed (km/h)': 'गति (किमी/घं)',
+ 'Speed (mph)': 'गति (मील/घं)',
'Sets': 'सेट',
'Reps': 'रेप्स',
'Weight ({0})': 'वज़न ({0})',
@@ -316,6 +317,7 @@ export default {
'Keep screen awake': 'स्क्रीन चालू रखें',
'The screen stays on while a workout is running, so you don’t have to unlock your phone between sets.': 'वर्कआउट चलने के दौरान स्क्रीन चालू रहती है, ताकि सेट के बीच फ़ोन अनलॉक न करना पड़े।',
'Weight unit': 'वज़न की इकाई',
+ 'Speed unit': 'गति की इकाई',
'Week starts on': 'सप्ताह शुरू होता है',
'Weight decimals': 'वज़न के दशमलव',
'How precisely weights are shown.': 'वज़न कितनी सटीकता से दिखें।',
diff --git a/frontend/src/locales/hu.js b/frontend/src/locales/hu.js
index 629b9079c..da8bdc901 100644
--- a/frontend/src/locales/hu.js
+++ b/frontend/src/locales/hu.js
@@ -105,6 +105,7 @@ export default {
'Intervals': 'Intervallumok',
'Minutes': 'Perc',
'Speed (km/h)': 'Sebesség (km/h)',
+ 'Speed (mph)': 'Sebesség (mph)',
'Sets': 'Sorozatok',
'Reps': 'Ism.',
'Weight ({0})': 'Súly ({0})',
@@ -323,6 +324,7 @@ export default {
'Keep screen awake': 'Képernyő ébren tartása',
'The screen stays on while a workout is running, so you don’t have to unlock your phone between sets.': 'A képernyő edzés közben bekapcsolva marad, így sorozatok között nem kell feloldanod a telefonod.',
'Weight unit': 'Súlymértékegység',
+ 'Speed unit': 'Sebesség mértékegysége',
'Week starts on': 'A hét kezdőnapja',
'Weight decimals': 'Súly tizedesjegyei',
'How precisely weights are shown.': 'Milyen pontosan jelenjen meg a súly.',
diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.js
index e7a515a1c..d90d425aa 100644
--- a/frontend/src/locales/it.js
+++ b/frontend/src/locales/it.js
@@ -102,6 +102,7 @@ export default {
'Intervals': 'Intervalli',
'Minutes': 'Minuti',
'Speed (km/h)': 'Velocità (km/h)',
+ 'Speed (mph)': 'Velocità (mph)',
'Sets': 'Serie',
'Reps': 'Rip.',
'Weight ({0})': 'Peso ({0})',
@@ -316,6 +317,7 @@ export default {
'Keep screen awake': 'Mantieni lo schermo acceso',
'The screen stays on while a workout is running, so you don’t have to unlock your phone between sets.': 'Lo schermo resta acceso mentre un allenamento è in corso, così non devi sbloccare il telefono tra una serie e l’altra.',
'Weight unit': 'Unità di peso',
+ 'Speed unit': 'Unità di velocità',
'Week starts on': 'La settimana inizia il',
'Weight decimals': 'Decimali del peso',
'How precisely weights are shown.': 'Con quanta precisione vengono mostrati i pesi.',
diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.js
index faaae4872..db23c61e9 100644
--- a/frontend/src/locales/ko.js
+++ b/frontend/src/locales/ko.js
@@ -102,6 +102,7 @@ export default {
'Intervals': '인터벌',
'Minutes': '분',
'Speed (km/h)': '속도 (km/h)',
+ 'Speed (mph)': '속도 (mph)',
'Sets': '세트',
'Reps': '횟수',
'Weight ({0})': '무게 ({0})',
@@ -316,6 +317,7 @@ export default {
'Keep screen awake': '화면 켜두기',
'The screen stays on while a workout is running, so you don’t have to unlock your phone between sets.': '운동이 진행되는 동안 화면이 켜져 있어 세트 사이에 잠금을 해제할 필요가 없습니다.',
'Weight unit': '무게 단위',
+ 'Speed unit': '속도 단위',
'Week starts on': '주 시작 요일',
'Weight decimals': '무게 소수점',
'How precisely weights are shown.': '무게를 얼마나 정밀하게 표시할지.',
diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.js
index a0768410b..a7a096441 100644
--- a/frontend/src/locales/pl.js
+++ b/frontend/src/locales/pl.js
@@ -102,6 +102,7 @@ export default {
'Intervals': 'Interwały',
'Minutes': 'Minuty',
'Speed (km/h)': 'Prędkość (km/h)',
+ 'Speed (mph)': 'Prędkość (mph)',
'Sets': 'Serie',
'Reps': 'Powt.',
'Weight ({0})': 'Ciężar ({0})',
@@ -316,6 +317,7 @@ export default {
'Keep screen awake': 'Nie wygaszaj ekranu',
'The screen stays on while a workout is running, so you don’t have to unlock your phone between sets.': 'Ekran pozostaje włączony w trakcie treningu, więc nie musisz odblokowywać telefonu między seriami.',
'Weight unit': 'Jednostka wagi',
+ 'Speed unit': 'Jednostka prędkości',
'Week starts on': 'Tydzień zaczyna się w',
'Weight decimals': 'Miejsca dziesiętne ciężaru',
'How precisely weights are shown.': 'Jak dokładnie pokazywać ciężary.',
diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.js
index 71533b633..8f0de6f6f 100644
--- a/frontend/src/locales/pt.js
+++ b/frontend/src/locales/pt.js
@@ -102,6 +102,7 @@ export default {
'Intervals': 'Intervalos',
'Minutes': 'Minutos',
'Speed (km/h)': 'Velocidade (km/h)',
+ 'Speed (mph)': 'Velocidade (mph)',
'Sets': 'Séries',
'Reps': 'Reps',
'Weight ({0})': 'Peso ({0})',
@@ -316,6 +317,7 @@ export default {
'Keep screen awake': 'Manter o ecrã ligado',
'The screen stays on while a workout is running, so you don’t have to unlock your phone between sets.': 'O ecrã fica ligado enquanto há um treino a decorrer, para não teres de desbloquear o telemóvel entre séries.',
'Weight unit': 'Unidade de peso',
+ 'Speed unit': 'Unidade de velocidade',
'Week starts on': 'Início da semana',
'Weight decimals': 'Casas decimais do peso',
'How precisely weights are shown.': 'Com que precisão os pesos são mostrados.',
diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.js
index 280caddeb..eb5b9ad0f 100644
--- a/frontend/src/locales/ru.js
+++ b/frontend/src/locales/ru.js
@@ -102,6 +102,7 @@ export default {
'Intervals': 'Интервалы',
'Minutes': 'Минуты',
'Speed (km/h)': 'Скорость (км/ч)',
+ 'Speed (mph)': 'Скорость (миль/ч)',
'Sets': 'Подходы',
'Reps': 'Повт.',
'Weight ({0})': 'Вес ({0})',
@@ -316,6 +317,7 @@ export default {
'Keep screen awake': 'Не гасить экран',
'The screen stays on while a workout is running, so you don’t have to unlock your phone between sets.': 'Экран не гаснет, пока идёт тренировка, — не нужно разблокировать телефон между подходами.',
'Weight unit': 'Единица веса',
+ 'Speed unit': 'Единица скорости',
'Week starts on': 'Неделя начинается с',
'Weight decimals': 'Знаки после запятой',
'How precisely weights are shown.': 'Насколько точно показывать вес.',
diff --git a/frontend/src/locales/th.js b/frontend/src/locales/th.js
index cd6493954..013b6f652 100644
--- a/frontend/src/locales/th.js
+++ b/frontend/src/locales/th.js
@@ -105,6 +105,7 @@ export default {
'Intervals': 'อินเทอร์วัล',
'Minutes': 'นาที',
'Speed (km/h)': 'ความเร็ว (กม./ชม.)',
+ 'Speed (mph)': 'ความเร็ว (ไมล์/ชม.)',
'Sets': 'เซ็ต',
'Reps': 'ครั้ง',
'Weight ({0})': 'น้ำหนัก ({0})',
@@ -323,6 +324,7 @@ export default {
'Keep screen awake': 'ไม่ให้จอปิด',
'The screen stays on while a workout is running, so you don’t have to unlock your phone between sets.': 'จอจะไม่ปิดขณะออกกำลังกาย จะได้ไม่ต้องปลดล็อกโทรศัพท์ระหว่างเซ็ต',
'Weight unit': 'หน่วยน้ำหนัก',
+ 'Speed unit': 'หน่วยความเร็ว',
'Week starts on': 'สัปดาห์เริ่มวัน',
'Weight decimals': 'ทศนิยมของน้ำหนัก',
'How precisely weights are shown.': 'แสดงน้ำหนักละเอียดแค่ไหน',
diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.js
index 9a19cb8d7..81bef9003 100644
--- a/frontend/src/locales/tr.js
+++ b/frontend/src/locales/tr.js
@@ -102,6 +102,7 @@ export default {
'Intervals': 'Aralıklar',
'Minutes': 'Dakika',
'Speed (km/h)': 'Hız (km/sa)',
+ 'Speed (mph)': 'Hız (mil/sa)',
'Sets': 'Set',
'Reps': 'Tekrar',
'Weight ({0})': 'Ağırlık ({0})',
@@ -316,6 +317,7 @@ export default {
'Keep screen awake': 'Ekranı açık tut',
'The screen stays on while a workout is running, so you don’t have to unlock your phone between sets.': 'Antrenman sürerken ekran açık kalır, böylece setler arasında telefonunu açmak zorunda kalmazsın.',
'Weight unit': 'Ağırlık birimi',
+ 'Speed unit': 'Hız birimi',
'Week starts on': 'Hafta başlangıcı',
'Weight decimals': 'Ağırlık ondalığı',
'How precisely weights are shown.': 'Ağırlıklar ne kadar hassas gösterilsin.',
diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.js
index f7793562f..c92ea027b 100644
--- a/frontend/src/locales/zh.js
+++ b/frontend/src/locales/zh.js
@@ -102,6 +102,7 @@ export default {
'Intervals': '间歇数',
'Minutes': '分钟',
'Speed (km/h)': '速度(km/h)',
+ 'Speed (mph)': '速度(mph)',
'Sets': '组数',
'Reps': '次数',
'Weight ({0})': '重量({0})',
@@ -316,6 +317,7 @@ export default {
'Keep screen awake': '保持屏幕常亮',
'The screen stays on while a workout is running, so you don’t have to unlock your phone between sets.': '训练进行时屏幕保持常亮,组间无需再解锁手机。',
'Weight unit': '重量单位',
+ 'Speed unit': '速度单位',
'Week starts on': '一周开始于',
'Weight decimals': '重量小数位',
'How precisely weights are shown.': '重量显示的精确程度。',
diff --git a/frontend/src/sheets.jsx b/frontend/src/sheets.jsx
index 7dc867dd6..cabc3fd5f 100644
--- a/frontend/src/sheets.jsx
+++ b/frontend/src/sheets.jsx
@@ -28,6 +28,7 @@ import { exerciseHistory } from './lib/exercise-history.js'
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 { nextUnfinishedUnit } from './lib/supersetFlow.js'
@@ -681,7 +682,7 @@ function ExerciseDetail({ ex, close }) {
{(ex.secondaries?.length ? ex.secondaries : smOf(ex)).slice(0, 3).map((s, i) => <span key={i} className="tag">{t(MUSCLE_NAME[s] || s)}</span>)}
</div>
{ex.desc && <div className="exnote">{ex.desc}</div>}
- {best > 0 && <div className="small row" style={{ marginBottom: 6, gap: 5 }}><Icon name="trophy" style={{ fontSize: 14, color: 'var(--yellow)' }} />{t('Best:')} <b className="accent" style={{ whiteSpace: 'nowrap' }}>{fmtNum(best)} {st.unit}</b>{last ? ` · ${t('last')} ${fmtDate(last.d)}: ${last.sets.map(s => setLabel(ex.id, s, last.target)).join(', ')}` : ''}</div>}
+ {best > 0 && <div className="small row" style={{ marginBottom: 6, gap: 5 }}><Icon name="trophy" style={{ fontSize: 14, color: 'var(--yellow)' }} />{t('Best:')} <b className="accent" style={{ whiteSpace: 'nowrap' }}>{fmtNum(best)} {st.unit}</b>{last ? ` · ${t('last')} ${fmtDate(last.d)}: ${last.sets.map(s => setLabel(ex.id, s, last.target, speedUnitOf(st))).join(', ')}` : ''}</div>}
<Button variant="primary" icon="plus" style={{ margin: '10px 0 4px' }} onClick={() => addToRoutineSheet(ex)}>{t('Add to my plan')}</Button>
{last && <Button icon="history" style={{ marginTop: 4 }} onClick={() => exerciseHistorySheet(ex.id)}>{t('History')}</Button>}
{ex.custom && <div className="row" style={{ gap: 8, marginTop: 8 }}>
@@ -741,7 +742,7 @@ function ExerciseHistory({ exId }) {
{h.sessions.map(s => <div key={s.id} className="item" style={{ alignItems: 'flex-start' }}>
<div className="grow">
<div className="tt">{fmtDate(s.d, true)} {s.pr && <span className="pr"><Icon name="trophy" />PR</span>}</div>
- <div className="ss">{s.sets.map(x => setLabel(exId, x, s.target)).join(' · ')}</div>
+ <div className="ss">{s.sets.map(x => setLabel(exId, x, s.target, speedUnitOf(st))).join(' · ')}</div>
{tail(s) && <div className="small dim" style={{ marginTop: 3 }}>{tail(s)}</div>}
</div>
{s.value != null && s.value > 0 && <b className="accent nocap" style={{ whiteSpace: 'nowrap' }}>{fmtNum(s.value)} {unit}</b>}
@@ -1182,6 +1183,7 @@ function ProgressionFields({ ex, mode, c, setC, routine, unit, perSide }) {
function ExConfig({ ex, existing, onSave, onDelete, onReplace, close, routine, initial }) {
const st = useStore(s => s.S)
const cardio = isCardio(ex.id)
+ const speedUnit = speedUnitOf(st)
const seed = existing || initial || defaultConfig(ex.id)
const [c, setC] = useState(() => {
const cfg = { ...seed }
@@ -1288,7 +1290,9 @@ function ExConfig({ ex, existing, onSave, onDelete, onReplace, close, routine, i
{cardio ? <>
<Stepper label={t('Intervals')} value={c.sets} step={1} decimal={false} onChange={v => setC(x => ({ ...x, sets: v }))} />
<Stepper label={t('Minutes')} value={c.min} step={1} decimal={false} onChange={v => setC(x => ({ ...x, min: v }))} />
- <Stepper label={t('Speed (km/h)')} value={c.speed} step={0.5} onChange={v => setC(x => ({ ...x, speed: v }))} />
+ {/* Typed and stepped in the profile's unit, kept in km/h (lib/speed.js). */}
+ <Stepper label={speedUnit === 'mph' ? t('Speed (mph)') : t('Speed (km/h)')} value={toSpeed(c.speed, speedUnit)} step={0.5}
+ onChange={v => setC(x => ({ ...x, speed: fromSpeed(v, speedUnit) }))} />
</> : mode === 'time' ? <>
<Stepper label={t('Sets')} value={c.sets} step={1} decimal={false} onChange={v => setC(x => ({ ...x, sets: v }))} />
<Stepper label={t('Seconds')} value={c.sec} step={5} decimal={false} onChange={v => setC(x => ({ ...x, sec: v }))} />
@@ -1711,7 +1715,7 @@ function WorkoutDetail({ w, close }) {
return <div key={i} className="row" style={{ marginBottom: 12, alignItems: 'flex-start' }}>
{ex && <Thumb ex={ex} />}
<div className="grow"><div className="tt capitalize" style={{ fontWeight: 600 }}>{ex ? exerciseNameFor(ex) : (e.n || e.id)} {w.prs && w.prs.includes(e.id) && <span className="pr"><Icon name="trophy" />PR</span>}</div>
- <div className="ss">{e.sets.filter(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}
</div>}</div>
diff --git a/frontend/src/sheets.speed.test.jsx b/frontend/src/sheets.speed.test.jsx
new file mode 100644
index 000000000..1d52045f9
--- /dev/null
+++ b/frontend/src/sheets.speed.test.jsx
@@ -0,0 +1,54 @@
+// @vitest-environment happy-dom
+// A cardio exercise's settings in mph (Discord "miles per hour"): the speed stepper reads and
+// steps in the profile's unit, and the routine keeps km/h.
+import React, { act } from 'react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { createRoot } from 'react-dom/client'
+import { EXIDX } from './lib/exercises.js'
+import { DEF, useStore } from './store/useStore.js'
+import { useUI } from './store/useUI.js'
+import { exConfigSheet } from './sheets.jsx'
+
+const mounted = []
+function open(settings, existing) {
+ useStore.setState({ S: { ...structuredClone(DEF), ...settings }, user: null })
+ const onSave = vi.fn()
+ exConfigSheet(EXIDX['2138'], existing, onSave, null, null)
+ 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))))
+ const speed = [...host.querySelectorAll('.stp-w')].find(w => w.querySelector('.stp-l')?.textContent.startsWith('Speed'))
+ const save = [...host.querySelectorAll('button')].find(b => b.textContent.trim() === 'Save')
+ return { speed, save, onSave }
+}
+
+beforeEach(() => {
+ globalThis.IS_REACT_ACT_ENVIRONMENT = true
+ useUI.setState({ sheets: [] })
+ document.body.innerHTML = ''
+})
+afterEach(() => { act(() => { mounted.splice(0).forEach(root => root.unmount()) }) })
+
+describe('cardio settings speed', () => {
+ it('reads and steps in mph for a profile in pounds, and saves km/h', () => {
+ const { speed, save, onSave } = open({ unit: 'lb' }, { sets: 1, min: 20, speed: 8 })
+ expect(speed.querySelector('.stp-l').textContent).toBe('Speed (mph)')
+ expect(speed.querySelector('input').value).toBe('4.97')
+ act(() => speed.querySelector('button[aria-label="Increase"]').click())
+ expect(speed.querySelector('input').value).toBe('5.47')
+ act(() => save.click())
+ expect(onSave).toHaveBeenCalledWith(expect.objectContaining({ min: 20, speed: 8.8 }))
+ })
+
+ it('is unchanged in km/h', () => {
+ const { speed, save, onSave } = open({ unit: 'kg' }, { sets: 1, min: 20, speed: 8 })
+ expect(speed.querySelector('.stp-l').textContent).toBe('Speed (km/h)')
+ expect(speed.querySelector('input').value).toBe('8')
+ act(() => speed.querySelector('button[aria-label="Increase"]').click())
+ act(() => save.click())
+ expect(onSave).toHaveBeenCalledWith(expect.objectContaining({ speed: 8.5 }))
+ })
+})
diff --git a/frontend/src/store/useStore.js b/frontend/src/store/useStore.js
index b97f9cc7b..5d989adf9 100644
--- a/frontend/src/store/useStore.js
+++ b/frontend/src/store/useStore.js
@@ -72,6 +72,9 @@ export const DEF = {
// Decimals on displayed weights: 1 by default, 2 for anyone loading quarter plates or
// microplates (issue #139). Display only — nothing is stored or rounded differently.
wdec: 1,
+ // Cardio speed shown in 'kmh' or 'mph'. null follows the weight unit (lb reads mph). Display
+ // only as well: every speed is stored in km/h (lib/speed.js).
+ speedUnit: null,
// Per-exercise bar weight overrides, keyed by exercise id, in the profile unit (see
// lib/bar.js). Personal equipment, so it syncs with the account but never travels in a
// shared plan. Logged weights stay the total — this only feeds the plate math.
diff --git a/frontend/src/views/CoachChat.jsx b/frontend/src/views/CoachChat.jsx
index c5bcea349..15f900f70 100644
--- a/frontend/src/views/CoachChat.jsx
+++ b/frontend/src/views/CoachChat.jsx
@@ -19,6 +19,7 @@ import { useUI } from '../store/useUI.js'
import { t } from '../lib/i18n.js'
import { fmtDate, fmtNum, DAYS } from '../lib/format.js'
import { exLine } from '../lib/history.js'
+import { speedUnitOf } from '../lib/speed.js'
import { DEMO } from '../lib/demo.js'
import { MOBILE } from '../lib/mobile.js'
import {
@@ -330,7 +331,7 @@ function PlanCard({ p, S, update, toast, nav, refresh }) {
{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)} />}
<div className="pcard-row">
<span className="lrow-m"><span className="lrow-t">{t('Use this weekly schedule')}</span><span className="lrow-s">{t('Replaces your current week. Days this plan leaves empty become rest days.')}</span></span>
@@ -350,11 +351,11 @@ const WeekStrip = ({ days }) => <div className="pcard-week">
{[1, 2, 3, 4, 5, 6, 0].map(d => <div key={d} className={'pcard-wd' + (days.has(d) ? ' on' : '')}>{t(DAYS[d])}</div>)}
</div>
-const RoutineBlock = ({ r, unit }) => <div className="pcard-rt">
+const RoutineBlock = ({ r, unit, speedUnit }) => <div className="pcard-rt">
<div className="pcard-rt-h"><b>{r.emoji} {r.name}</b><span>{t('{0} exercises', r.ex.length)}</span></div>
{!!r.why && <div className="pcard-why">{r.why}</div>}
{r.ex.map((e, i) => <div key={i} className="pcard-ex">
- <div className="pcard-ex-r"><span className="pcard-ex-n">{exName(e.id)}</span><span className="pcard-ex-l">{exLine(e, unit)}</span></div>
+ <div className="pcard-ex-r"><span className="pcard-ex-n">{exName(e.id)}</span><span className="pcard-ex-l">{exLine(e, unit, speedUnit)}</span></div>
{!!e.why && <div className="pcard-ex-w">{e.why}</div>}
</div>)}
</div>
@@ -628,7 +629,7 @@ function ProposalDetail({ entry, S }) {
{b.routines.length > 1 && <div className="pcard-tabs" style={{ paddingLeft: 0, paddingRight: 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 --git a/frontend/src/views/RoutineEdit.jsx b/frontend/src/views/RoutineEdit.jsx
index f54ec22fe..968eb1312 100644
--- a/frontend/src/views/RoutineEdit.jsx
+++ b/frontend/src/views/RoutineEdit.jsx
@@ -16,6 +16,7 @@ import SwipeToDelete from '../components/SwipeToDelete.jsx'
import { copyRoutine, 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'
@@ -429,7 +430,7 @@ export default function RoutineEdit() {
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))
}}>
<Thumb ex={ex} />
- <div className="grow"><div className="tt capitalize">{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>
{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 --git a/frontend/src/views/Settings.jsx b/frontend/src/views/Settings.jsx
index a82efcf33..d3f2b0545 100644
--- a/frontend/src/views/Settings.jsx
+++ b/frontend/src/views/Settings.jsx
@@ -3,6 +3,7 @@ import { useNavigate } from 'react-router-dom'
import { useStore, DEF, hasData } from '../store/useStore.js'
import { workoutControls } from '../lib/workout-controls.js'
import { convertStateUnit } from '../lib/units.js'
+import { speedUnitOf } from '../lib/speed.js'
import { useUI } from '../store/useUI.js'
import { ACCENTS, todayISO, localTZ, weekStartOf, MONDAY, SUNDAY } from '../lib/format.js'
import { effortOf } from '../lib/history.js'
@@ -261,6 +262,14 @@ export default function Settings() {
options={[{ value: 'kg', label: 'kg' }, { value: 'lb', label: 'lb' }]}
value={S.unit} onChange={v => switchUnit(v)} />
</Row>
+ {/* Cardio speed (Discord "miles per hour"). Unlike the weight unit this converts nothing:
+ speeds stay stored in km/h and only what is shown and typed follows it (lib/speed.js).
+ Until chosen it follows the weight unit, so a profile in pounds already reads mph. */}
+ <Row icon="figureRun" iconTint="var(--teal)" title={t('Speed unit')}>
+ <Segmented className="seg-inline"
+ options={[{ value: 'kmh', label: 'km/h' }, { value: 'mph', label: 'mph' }]}
+ value={speedUnitOf(S)} onChange={v => update(s => { s.speedUnit = v })} />
+ </Row>
{/* Display only: one decimal reads fine for plate-loadable numbers, two for anyone whose
per-side figure lands on .25 or .75, or who loads microplates (issue #139). Nothing is
stored or rounded differently — lib/format.js fmtNum just prints what is already there. */}
diff --git a/frontend/src/views/Settings.speed.test.jsx b/frontend/src/views/Settings.speed.test.jsx
new file mode 100644
index 000000000..0922930ef
--- /dev/null
+++ b/frontend/src/views/Settings.speed.test.jsx
@@ -0,0 +1,94 @@
+// @vitest-environment happy-dom
+// Settings → General → Speed unit (Discord "miles per hour"): follows the weight unit until
+// chosen, and choosing converts nothing — speeds stay stored in km/h.
+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, isAndroid: () => Promise.resolve(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 — speed unit', () => {
+ it('shows km/h for a kg profile and mph for a pound profile until one is chosen', () => {
+ mount()
+ expect(segButton('km/h').getAttribute('aria-pressed')).toBe('true')
+ act(() => root.unmount())
+ root = createRoot(host)
+ mocks.S.unit = 'lb'
+ mount()
+ expect(segButton('mph').getAttribute('aria-pressed')).toBe('true')
+ })
+
+ it('stores the choice and nothing else', () => {
+ mocks.S.routines = [{ id: 'c', name: 'Cardio', ex: [{ id: '2138', sets: 1, min: 20, speed: 8 }] }]
+ const before = structuredClone(mocks.S)
+ mount()
+ act(() => { segButton('mph').click() })
+ expect(mocks.S.speedUnit).toBe('mph')
+ expect({ ...mocks.S, speedUnit: undefined }).toEqual({ ...before, speedUnit: undefined })
+ mount()
+ expect(segButton('mph').getAttribute('aria-pressed')).toBe('true')
+ act(() => { segButton('km/h').click() })
+ expect(mocks.S.speedUnit).toBe('kmh')
+ })
+})
diff --git a/frontend/src/views/Stats.jsx b/frontend/src/views/Stats.jsx
index 3af72bb3b..c21869191 100644
--- a/frontend/src/views/Stats.jsx
+++ b/frontend/src/views/Stats.jsx
@@ -4,6 +4,7 @@ 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 { 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 LineChart from '../components/LineChart.jsx'
@@ -333,14 +334,16 @@ 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' ? (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 }
+ 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)))
+ 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') {
@@ -378,8 +381,8 @@ export default function Stats() {
return en && bestWeightForEntry(en) > 0
})
const bestRepsOf = en => Math.max(0, ...metricRowsForEntry(en, 'reps').map(s => Number(s.r) || 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 => {
@@ -487,7 +490,7 @@ export default function Stats() {
: <LineChart points={onE1 ? e1ChartPts : topPts} h={150} unit={exUnit} color="var(--blue)" />}
</div>
<div style={{ marginTop: 8 }}>{exList.map((p, i) => <div key={i} className="row between small" style={{ padding: '6px 0', borderBottom: 'var(--hair) solid var(--sep)' }}>
- <span className="muted">{fmtDate(p.d, true)}</span><span>{p.sets.map(s => setLabel(curEx, s, p.target)).join(' ')}</span></div>)}</div>
+ <span className="muted">{fmtDate(p.d, true)}</span><span>{p.sets.map(s => setLabel(curEx, s, p.target, speedUnit)).join(' ')}</span></div>)}</div>
<div className="small dim" style={{ marginTop: 8 }}>
{onEff ? t('Average effort per workout') : onE1 ? t('Estimated 1RM per workout') : curCardio ? t('Top speed per workout') : curTimed ? t('Longest hold per workout') : repsOnly ? t('Most reps in a set per workout') : t('Best set weight per workout')}
{onEff ? '' : <> · {t('Best:')}{' '}<b className="accent">{fmtNum(onE1 ? e1Best.est : exBest)} {onE1 ? S.unit : exUnit}</b></>}
diff --git a/frontend/src/views/Stats.speed.test.jsx b/frontend/src/views/Stats.speed.test.jsx
new file mode 100644
index 000000000..14c1ffbeb
--- /dev/null
+++ b/frontend/src/views/Stats.speed.test.jsx
@@ -0,0 +1,54 @@
+// @vitest-environment happy-dom
+// Stats charts cardio at its top speed per workout — in mph for a profile that reads mph
+// (Discord "miles per hour"), from the km/h the sets are stored in.
+import React, { act } from 'react'
+import { createRoot } from 'react-dom/client'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import Stats from './Stats.jsx'
+
+const mocks = vi.hoisted(() => ({ charts: [], S: null }))
+vi.mock('../store/useStore.js', () => ({ useStore: selector => selector({ S: mocks.S }) }))
+vi.mock('react-router-dom', () => ({ useNavigate: () => () => {} }))
+vi.mock('../sheets.jsx', () => ({
+ bwSheet: () => {}, goalSheet: () => {}, calendarSheet: () => {}, workoutDetailSheet: () => {}, exerciseHistorySheet: () => {},
+ WorkoutRow: () => null, bwDeltaColor: () => 'inherit',
+}))
+vi.mock('../components/LineChart.jsx', () => ({ default: props => { mocks.charts.push(props); return null } }))
+vi.mock('../components/Heatmap.jsx', () => ({ default: () => null }))
+vi.mock('../components/BodyMap.jsx', () => ({ default: () => null }))
+
+globalThis.IS_REACT_ACT_ENVIRONMENT = true
+const BIKE = '2138'
+const session = (d, speeds) => ({
+ id: d, d, start: Date.parse(d + 'T10:00:00Z'), end: Date.parse(d + 'T10:40:00Z'), name: 'Cardio',
+ entries: [{ id: BIKE, target: { id: BIKE, sets: speeds.length, min: 20, speed: 8 }, sets: speeds.map(speed => ({ min: 20, speed, done: true })) }],
+})
+let root, host
+afterEach(() => { act(() => root.unmount()); host.remove(); mocks.charts = [] })
+
+function mount(settings) {
+ mocks.S = { body: 'male', effort: 'none', targetW: null, bodyweight: [], routines: [], exWeights: {}, ...settings,
+ workouts: [session('2026-09-01', [8, 9.66]), session('2026-09-08', [16.09])] }
+ host = document.createElement('div')
+ document.body.appendChild(host)
+ root = createRoot(host)
+ act(() => root.render(<Stats />))
+ return mocks.charts.find(c => c.color === 'var(--blue)')
+}
+
+describe('Stats — cardio speed', () => {
+ it('charts and names the best speed in mph for a pound profile', () => {
+ const chart = mount({ unit: 'lb' })
+ expect(chart.unit).toBe('mph')
+ expect(chart.points.map(p => p.y)).toEqual([6, 10])
+ expect(host.textContent).toContain('10 mph')
+ expect(host.textContent).toContain('20 min @ 10 mph')
+ })
+
+ it('keeps km/h for a kg profile', () => {
+ const chart = mount({ unit: 'kg' })
+ expect(chart.unit).toBe('km/h')
+ expect(chart.points.map(p => p.y)).toEqual([9.66, 16.09])
+ expect(host.textContent).toContain('16.1 km/h')
+ })
+})
diff --git a/frontend/src/views/Workout.jsx b/frontend/src/views/Workout.jsx
index b8a9c365c..d7488291e 100644
--- a/frontend/src/views/Workout.jsx
+++ b/frontend/src/views/Workout.jsx
@@ -7,6 +7,7 @@ import { exOr, betterWeight } from '../lib/exercises.js'
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 { api, appBase } from '../lib/api.js'
@@ -69,6 +70,10 @@ function Elapsed({ start }) {
return <span>{t}</span>
}
+// A set-row column's number as it is shown. Most columns show what is stored; one with a `view`
+// (cardio speed, stored in km/h) converts it for the screen.
+const viewOf = (col, value) => (col.view && value != null && value !== '' ? col.view(value) : value)
+
/* ---------- one exercise block (reps: weight×reps · time: a held duration · cardio: duration+speed) ---------- */
// `compact` shrinks the block for a superset member; `dense` (compact view) goes further and
// drops everything that is not a set you are logging — media, tag chips, the note lines, the
@@ -185,7 +190,11 @@ function ExerciseBlock({ entryIdx, compact, dense, onToggle, onToggleSide, onFie
const col1 = cardio ? { f: 'min', step: 1, dec: false, hd: t('Duration (min)') }
: timed ? { f: 'sec', step: 5, dec: false, hd: t('Seconds') }
: (bw && !added) ? repCol : loadCol
- const col2 = cardio ? { f: 'speed', step: 0.5, dec: true, hd: t('Speed (km/h)') }
+ // Speed is stored in km/h and shown in the profile's unit (lib/speed.js): `view` turns the
+ // stored number into the one on screen, `store` the one typed or stepped back into km/h.
+ const speedUnit = speedUnitOf(S)
+ const col2 = cardio ? { f: 'speed', step: 0.5, dec: true, hd: speedUnit === 'mph' ? t('Speed (mph)') : t('Speed (km/h)'),
+ view: v => toSpeed(v, speedUnit), store: v => fromSpeed(v, speedUnit) }
: timed ? ((bw && !added) ? null : loadCol)
: (bw && !added) ? null : repCol
// Effort (RIR or RPE, whichever the profile logs) only makes sense for weighted rep sets,
@@ -207,7 +216,9 @@ function ExerciseBlock({ entryIdx, compact, dense, onToggle, onToggleSide, onFie
const fresh = useStore.getState().S.active?.entries[entryIdx]?.sets[i]
const cur = fresh ? fresh[col.f] : s[col.f]
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))
+ // The step is in the unit on screen: +0.5 mph, not +0.5 km/h shown as +0.31.
+ const next = Math.max(0, Math.round(((viewOf(col, cur) || 0) + dir * col.step) * 100) / 100)
+ onField(i, col.f, col.store ? col.store(next) : next)
}
// Uses the shared stepper markup so a set row picks up the same control styling
// as every other +/- field in the app.
@@ -218,8 +229,8 @@ function ExerciseBlock({ entryIdx, compact, dense, onToggle, onToggleSide, onFie
const cell = (s, i, col, cls) => (
<div className={'stp ' + cls + (wc.steppers ? '' : ' plain')}>
{wc.steppers && <button aria-label="Decrease" onClick={() => bump(s, i, col, -1)}><Icon name="minus" /></button>}
- <span className="val"><NumberField decimal={col.dec} nullable={col.opt} value={s[col.f] ?? ''}
- onChange={v => onField(i, col.f, v)} /></span>
+ <span className="val"><NumberField decimal={col.dec} nullable={col.opt} value={viewOf(col, s[col.f]) ?? ''}
+ onChange={v => onField(i, col.f, col.store ? col.store(v) : v)} /></span>
{wc.steppers && <button aria-label="Increase" onClick={() => bump(s, i, col, 1)}><Icon name="plus" /></button>}
</div>
)
@@ -261,7 +272,7 @@ function ExerciseBlock({ entryIdx, compact, dense, onToggle, onToggleSide, onFie
const warm = isWarmupRow(s)
menuSheet({
title: (warm ? t('Warm-up') : t('Set {0}', entry.sets.slice(0, i + 1).filter(x => isWarmupRow(x) === warm).length)),
- subtitle: setLabel(entry.id, s, entry.target),
+ subtitle: setLabel(entry.id, s, entry.target, speedUnit),
items: [
!warm && mode === 'reps' && !isRestPauseSet(s) && { icon: 'arrowDown', label: t('Drop set'), sub: t('+ Drop'), onClick: () => addDropRow(i) },
!warm && mode === 'reps' && !isDropSet(s) && { icon: 'bolt', label: t('Rest-pause burst'), sub: t('+ Burst'), onClick: () => addBurstRow(i) },
@@ -430,7 +441,7 @@ function ExerciseBlock({ entryIdx, compact, dense, onToggle, onToggleSide, onFie
</div>}
{entry.note && <div className="exnote">{entry.note}</div>}
{planLine}
- {last && <div className="small dim" style={{ marginBottom: 4 }}>{t('Last time')} ({fmtDate(last.d)}): {last.sets.map(s => setLabel(entry.id, s, last.target)).join(', ')}</div>}
+ {last && <div className="small dim" style={{ marginBottom: 4 }}>{t('Last time')} ({fmtDate(last.d)}): {last.sets.map(s => setLabel(entry.id, s, last.target, speedUnit)).join(', ')}</div>}
{/* Bar + plates for barbell work: what to load per side for the set in front of you
(first undone set; the heaviest row once everything is checked). The logged number
stays the total — this chip is the split, and tapping it edits the bar's own weight
diff --git a/frontend/src/views/Workout.speed.test.jsx b/frontend/src/views/Workout.speed.test.jsx
new file mode 100644
index 000000000..8ab8fb998
--- /dev/null
+++ b/frontend/src/views/Workout.speed.test.jsx
@@ -0,0 +1,85 @@
+// @vitest-environment happy-dom
+// Cardio speed in mph (Discord "miles per hour"): the set row shows, steps and takes typing in
+// the profile's speed unit, and what it stores is always km/h.
+import React, { act } from 'react'
+import { createRoot } from 'react-dom/client'
+import { MemoryRouter } from 'react-router-dom'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import Workout from './Workout.jsx'
+import { DEF, useStore } from '../store/useStore.js'
+
+vi.mock('../lib/sound.js', () => ({ beep: vi.fn(), vibrate: vi.fn(), unlock: vi.fn() }))
+vi.mock('../lib/api.js', () => ({ api: vi.fn(() => Promise.resolve({})) }))
+
+globalThis.IS_REACT_ACT_ENVIRONMENT = true
+const BIKE = '2138' // stationary bike, cardio
+let root, container
+
+function mount(settings = {}) {
+ if (root) unmount()
+ const S = { ...JSON.parse(JSON.stringify(DEF)), ...settings }
+ S.active = {
+ id: 'speed-test', d: '2026-09-23', start: Date.now(), routineId: null, name: 'Cardio', bw: null, cur: 0,
+ entries: [{ id: BIKE, target: { sets: 1, min: 20, speed: 8 }, sets: [{ min: 20, speed: 8, done: false }] }],
+ }
+ useStore.setState({ S, user: null })
+ container = document.createElement('div')
+ document.body.appendChild(container)
+ root = createRoot(container)
+ act(() => root.render(<MemoryRouter><Workout /></MemoryRouter>))
+}
+function unmount() {
+ act(() => root.unmount())
+ container.remove()
+ root = null
+}
+afterEach(() => { if (root) unmount() })
+
+// The speed column is the second stepper of the set row, after the minutes.
+const speedCell = () => container.querySelector('.setrow').querySelectorAll('.stp')[1]
+const shown = () => speedCell().querySelector('input').value
+const header = () => container.querySelector('.sethead .r-sp').textContent
+const stored = () => useStore.getState().S.active.entries[0].sets[0].speed
+const tap = label => act(() => speedCell().querySelector(`button[aria-label="${label}"]`).click())
+function type(value) {
+ const input = speedCell().querySelector('input')
+ act(() => {
+ Object.getOwnPropertyDescriptor(input.constructor.prototype, 'value').set.call(input, value)
+ input.dispatchEvent(new Event('input', { bubbles: true }))
+ })
+}
+
+describe('cardio speed in the set row', () => {
+ it('reads, steps and takes typing in mph for a profile in pounds, and stores km/h', () => {
+ mount({ unit: 'lb' })
+ expect(header()).toBe('Speed (mph)')
+ expect(shown()).toBe('4.97') // 8 km/h
+ // A tap is half a mile an hour, not half a kilometre.
+ tap('Increase')
+ expect(stored()).toBe(8.8)
+ expect(shown()).toBe('5.47')
+ type('6')
+ expect(stored()).toBe(9.66)
+ type('6.5')
+ expect(stored()).toBe(10.46)
+ expect(shown()).toBe('6.5')
+ })
+
+ it('follows a chosen speed unit over the weight unit', () => {
+ mount({ unit: 'kg', speedUnit: 'mph' })
+ expect(header()).toBe('Speed (mph)')
+ mount({ unit: 'lb', speedUnit: 'kmh' })
+ expect(header()).toBe('Speed (km/h)')
+ expect(shown()).toBe('8')
+ })
+
+ it('leaves a km/h profile exactly as it was', () => {
+ mount()
+ expect(header()).toBe('Speed (km/h)')
+ expect(shown()).toBe('8')
+ tap('Increase')
+ expect(stored()).toBe(8.5)
+ type('10.25')
+ expect(stored()).toBe(10.25)
+ })
+})