Merge !107: feat(checkin): track one-sided exercises per side (L/R)

This commit is contained in:
Duarte Santos committed 2026-09-07 19:38:14 +02:00
commit 30e91cd06a
21 files changed
+636 -37

No files matched your search

+20
View File
@@ -735,6 +735,26 @@ h4.sec{
.effpick .effpick-free .stp .num::placeholder{color:var(--label-3);font-weight:500}
.setrow.done .n{background:var(--acc);color:var(--on-acc)}
.setrow.done{opacity:.45}
/* one-sided (unilateral) sets (issue #60): the set number sits beside a two-row L/R stack, each
side its own weight/reps/effort + done tick. The two inner rows reuse .setrow so their columns
line up with the header exactly like a straight set — only the leading .n circle is replaced by
a small L/R badge of the same width. */
.setrow-side{display:flex;align-items:center;gap:8px;padding:4px 0;position:relative}
.setrow-side+.setrow-side::before{content:'';position:absolute;left:32px;right:0;top:0;height:var(--hair);background:var(--sep)}
.setrow-side>.n{align-self:center}
.setrow-side .side-rows{flex:1;min-width:0;display:flex;flex-direction:column}
/* inner side rows: no leading number circle (the badge takes its place), no top hairline between
the two sides of the same set — they read as one unit. */
.setrow-side .setrow.side{padding:4px 0}
.setrow-side .setrow.side+.setrow.side::before{display:none}
.sidetag{
width:24px;height:24px;border-radius:8px;background:var(--surface-2);color:var(--label-3);
display:flex;align-items:center;justify-content:center;font-size:11px;font-weight:600;flex:none;
}
.setrow.side.done .sidetag{background:var(--acc);color:var(--on-acc)}
.setrow.side.done{opacity:.45}
/* drop-set drops / rest-pause bursts riding on a work row, editable like the row itself
(issue: drop-sets & rest-pause) */
.subrow{display:flex;align-items:center;gap:6px;padding:3px 0 3px 32px}
+51 -16
View File
@@ -1,7 +1,7 @@
// Pure helpers over the state object S (ported 1:1 from the vanilla app).
import { todayISO, isoOf, weekKey, weekStartOf, fmtNum } from './format.js'
import { isCardio, isBodyweightEq } from './exercises.js'
import { phaseForSet, modeForSet, modeForEntry, isWarmupRow, normalizeMode, extraVolumeOf, nextDropWeight, splitBurstReps } from './workout-model.js'
import { phaseForSet, modeForSet, modeForEntry, isWarmupRow, normalizeMode, extraVolumeOf, nextDropWeight, splitBurstReps, makeSideSet, isSideSet, syncSideAggregate } 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') => {
@@ -110,16 +110,21 @@ export function setLabel(id, s, cfg) {
const mode = modeOf(c)
if (mode === 'cardio') return `${s.min || 0} min @ ${fmtNum(s.speed || 0)} km/h`
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
// straight set reads as — reused for each side of a unilateral set below.
const oneSide = side => {
const reps = side.r || 0
return bw ? (side.w > 0 ? `+${fmtNum(side.w)} × ` : '') + reps : `${fmtNum(side.w || 0)}×${reps}`
}
// 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.
if (isSideSet(s)) {
return `${t('L')} ${oneSide(s.sides.L)}${effortTail(s.sides.L)} · ${t('R')} ${oneSide(s.sides.R)}${effortTail(s.sides.R)}`
}
// Bodyweight reads as what you did — "12", or "+10 × 12" once there is a belt involved —
// rather than "0×12", which says a set was performed with no weight and means nothing.
// A per-side set needs no mark here: the number logged is the total, the same as every
// other set in the app.
const reps = s.r || 0
if (isBw({ ...c, id: c.id ?? id })) {
const load = s.w > 0 ? `+${fmtNum(s.w)} × ` : ''
return `${load}${reps}` + effortTail(s)
}
return `${fmtNum(s.w || 0)}×${reps}` + effortTail(s)
return oneSide(s) + effortTail(s)
}
// Default config for a freshly added exercise.
export function defaultConfig(id, mode) {
@@ -372,11 +377,26 @@ function buildWorkSets(S, cfg, options = {}) {
const w = useTarget
? (cfg.weight > 0 ? cfg.weight : (lastRegular && lastRegular.r > 0 ? lastRegular.w : cfg.weight))
: preferLast && usable ? usable.w : (conf && conf.w > 0 ? conf.w : (usable ? usable.w : cfg.weight))
sets.push({ w, r: usable ? usable.r : cfg.reps, done: false })
const row = { w, r: usable ? usable.r : cfg.reps, done: false }
// A unilateral exercise logs each side on its own (issue #60): the row splits into L/R,
// each seeded with half the total reps at the same weight. When "last time" was itself a
// per-side set, carry its two sides over verbatim so an asymmetry you logged persists.
if (isPerSide(cfg)) sets.push(usable && isSideSet(usable) ? seedSideFromLast(row, usable) : makeSideSet(row))
else sets.push(row)
}
return sets
}
// Seed a fresh per-side row from a previous per-side set: same reps/weight each side, nothing
// done, no effort carried (that is logged afresh each session). Falls back to an even split if
// the previous row was not actually per-side.
function seedSideFromLast(row, prev) {
const base = makeSideSet(row)
if (!isSideSet(prev)) return base
const carry = s => ({ w: Number(s?.w) || 0, r: Number(s?.r) || 0, done: false })
return syncSideAggregate({ ...base, sides: { L: carry(prev.sides.L), R: carry(prev.sides.R) } })
}
/**
* Stamp every work row with the exercise's planned intensifier and pre-fill its drops/clusters,
* already computed and editable — the plan designs the set, not a button pressed mid-workout.
@@ -392,12 +412,19 @@ export function applyIntensifierPlan(sets, cfg) {
if (kind === 'dropset') {
const count = Math.max(1, Math.round(cfg.intensifier.count) || 1)
const pct = cfg.intensifier.pct
// Stamp a descending chain of drops onto a row (or one side of a per-side row): each drop is
// pct% lighter than the last, at that row/side's own rep count.
const withDrops = row => {
const drops = []
let w = row.w || 0
for (let k = 0; k < count; k++) { w = nextDropWeight(w, pct); drops.push({ w, r: row.r }) }
return { ...row, type: 'dropset', drops }
}
return sets.map(s => {
if (isWarmupRow(s)) return s
const drops = []
let w = s.w || 0
for (let k = 0; k < count; k++) { w = nextDropWeight(w, pct); drops.push({ w, r: s.r }) }
return { ...s, type: 'dropset', drops }
// A unilateral set drops per side (issue #60): stamp each side, then resync the aggregate.
if (isSideSet(s)) return syncSideAggregate({ ...s, sides: { L: withDrops(s.sides.L), R: withDrops(s.sides.R) } })
return withDrops(s)
})
}
// Rest-pause trains as exactly two sets, not one per configured `sets` count: a warm-up at
@@ -430,14 +457,22 @@ export function workoutVolume(w) {
}))
return v
}
// A unilateral row counts as two toward the "x / y sets" progress — one per side — since each
// side is logged and ticked on its own (issue #60). Every other row counts as one.
export const setUnits = s => (isSideSet(s) ? 2 : 1)
// How many of a row's units are done: both sides independently for a per-side row, else 0/1.
export const doneUnits = s => (isSideSet(s) ? (s.sides.L.done ? 1 : 0) + (s.sides.R.done ? 1 : 0) : (s.done ? 1 : 0))
// Total completion-units across a session's rows (both sides of every unilateral set counted).
export const setUnitsTotal = entries => (entries || []).reduce((n, e) => n + (e.sets || []).reduce((m, s) => m + setUnits(s), 0), 0)
export function setsDone(w) {
let n = 0
w.entries.forEach(e => e.sets.forEach(s => { if (s.done) n++ }))
w.entries.forEach(e => e.sets.forEach(s => { n += doneUnits(s) }))
return n
}
export function setsDoneActive(A) {
let n = 0
if (A) A.entries.forEach(e => e.sets.forEach(s => { if (s.done) n++ }))
if (A) A.entries.forEach(e => e.sets.forEach(s => { n += doneUnits(s) }))
return n
}
export const lastBW = S => (S.bodyweight.length ? S.bodyweight[S.bodyweight.length - 1] : null)
+63 -1
View File
@@ -1,5 +1,6 @@
import { describe, it, expect } from 'vitest'
import { nextTrainingDay, modeOf, isTimed, fmtSec, setLabel, defaultConfig, buildSets, freestyleConfig, exLine, workoutVolume, bestWeightFor, bestWeightForEntry, effortOf, stepEffort, capEffort, isBw, isPerSide, sideReps, repStep, cascadeWeight, insertWarmupRow, removeRowAt, workSetsDone, pairAdjacent, unpairSuperset, supersetUnits, applyIntensifierPlan, pinnedNoteFor, exNoteFor } from './history.js'
import { nextTrainingDay, modeOf, isTimed, fmtSec, setLabel, defaultConfig, buildSets, freestyleConfig, exLine, workoutVolume, bestWeightFor, bestWeightForEntry, effortOf, stepEffort, capEffort, isBw, isPerSide, sideReps, repStep, cascadeWeight, insertWarmupRow, removeRowAt, workSetsDone, setsDone, setsDoneActive, setUnits, doneUnits, setUnitsTotal, pairAdjacent, unpairSuperset, supersetUnits, applyIntensifierPlan, pinnedNoteFor, exNoteFor } from './history.js'
import { makeSideSet, setSideField, toggleSide } from './workout-model.js'
import { EXDB } from './exercises.js'
// Real ids out of the shipped catalogue, so the body-part fallback is exercised for real.
@@ -1019,3 +1020,64 @@ describe('nextTrainingDay', () => {
expect(nextTrainingDay(off, TUE)).toMatchObject({ weekday: 5 })
})
})
/* ---------- one-sided (unilateral) sets, logged per side (issue #60) ---------- */
// A per-side row carries its two sides and a scalar aggregate. These pin that the display shows
// both sides, and — crucially — that every aggregate-reading consumer (volume, best weight, the
// x/y-sets counters) treats the row correctly without knowing sides exist.
describe('setLabel — per side', () => {
it('shows both sides so an asymmetry is visible, not a single combined total', () => {
const s = setSideField(setSideField(makeSideSet({ w: 15, r: 16 }), 'R', 'r', 7), 'L', 'r', 8)
expect(setLabel(LIFT, s, { id: LIFT, side: true })).toBe('L 15×8 · R 15×7')
})
it('keeps each side effort tail and reads bodyweight sides as reps alone', () => {
let s = makeSideSet({ w: 0, r: 16 })
s = setSideField(s, 'L', 'rir', 1)
expect(setLabel(BW, s, { id: BW, side: true })).toBe('L 8 (RIR 1) · R 8')
})
})
describe('per-side aggregate stays readable by existing consumers', () => {
it('workoutVolume counts both sides via the row total, unchanged from a straight set', () => {
// 15×8 per side = 15×16 total = 240, exactly what a straight {w:15,r:16} would score.
const side = { ...makeSideSet({ w: 15, r: 16 }), done: true }
const synced = toggleSide(toggleSide(makeSideSet({ w: 15, r: 16 }), 'L'), 'R') // both done
const w = { entries: [{ id: LIFT, sets: [synced] }] }
expect(synced.done).toBe(true)
expect(workoutVolume(w)).toBe(240)
// and a straight equivalent scores the same
expect(workoutVolume({ entries: [{ id: LIFT, sets: [{ w: 15, r: 16, done: true }] }] })).toBe(240)
})
it('bestWeightForEntry reads the aggregate weight of a completed per-side set', () => {
const s = toggleSide(toggleSide(setSideField(makeSideSet({ w: 15, r: 16 }), 'R', 'w', 17.5), 'L'), 'R')
expect(bestWeightForEntry({ id: LIFT, target: { id: LIFT, side: true }, sets: [s] })).toBe(17.5)
})
})
describe('per-side set counters', () => {
it('setUnits counts a per-side row as two, a straight row as one', () => {
expect(setUnits(makeSideSet({ w: 15, r: 16 }))).toBe(2)
expect(setUnits({ w: 15, r: 16 })).toBe(1)
})
it('doneUnits counts each finished side independently', () => {
const none = makeSideSet({ w: 15, r: 16 })
expect(doneUnits(none)).toBe(0)
expect(doneUnits(toggleSide(none, 'L'))).toBe(1)
expect(doneUnits(toggleSide(toggleSide(none, 'L'), 'R'))).toBe(2)
expect(doneUnits({ w: 15, r: 16, done: true })).toBe(1)
})
it('setUnitsTotal / setsDoneActive account for both sides across the session', () => {
const A = { entries: [
{ id: LIFT, sets: [toggleSide(makeSideSet({ w: 15, r: 16 }), 'L'), makeSideSet({ w: 15, r: 16 })] }, // 2 rows × 2 sides = 4 units, 1 side done
{ id: LIFT, sets: [{ w: 60, r: 8, done: true }] }, // 1 straight, done
] }
expect(setUnitsTotal(A.entries)).toBe(5)
expect(setsDoneActive(A)).toBe(2)
expect(setsDone({ entries: A.entries })).toBe(2)
})
})
+2 -2
View File
@@ -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(626)
expect(inherited).toHaveLength(616)
expect(inherited).toHaveLength(619)
// 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('3db560d7104c324bcc54c94867c5f1e2b7f5eedf393d55e424b1c8d0bd5e7901')
expect(fingerprint, 'pt-PT inheritance changed; review the inherited pt-BR wording').toBe('3f014849b963a9ef4fa3ef79ee9f3c9b790ca28b8c28447f78812d6af4729bc2')
})
test('does not leak European Portuguese UI terms', () => {
+157 -1
View File
@@ -56,7 +56,14 @@ export function clustersOf(set) {
* `clustersOf(set)` here as well would double-count the same reps twice.
*/
export function extraVolumeOf(set) {
const drops = dropsOf(set)
const source = objectOf(set)
// A per-side set carries its drops on each side (issue #60), so the extra volume is the sum of
// both sides' drops — the row itself has no `drops`. dropsOf reads a side's own {type,drops}.
if (isSideSet(source)) {
return [source.sides.L, source.sides.R].reduce(
(v, side) => v + dropsOf(side).reduce((n, d) => n + (Number(d?.w) || 0) * (Number(d?.r) || 0), 0), 0)
}
const drops = dropsOf(source)
return drops.reduce((v, d) => v + (Number(d?.w) || 0) * (Number(d?.r) || 0), 0)
}
@@ -128,6 +135,155 @@ export function splitBurstReps(total) {
return bursts
}
// --- one-sided (unilateral) sets (issue #60) -------------------------------------------------
//
// A unilateral exercise (cfg.side, see history.js isPerSide) is trained one limb at a time, and
// asymmetries are the whole point of tracking it — a stronger right that carries a weaker left is
// exactly what a single combined row hides. So a per-side row logs each side on its own: weight,
// reps, effort and its own done tick, held in `sides: { L, R }`.
//
// Like `drops`/`clusters`, this rides on the row while the row's own `w`/`r`/`done`/effort stay a
// correct aggregate of the two sides — so volume, 1RM, PRs, progression, recovery, history and the
// coach keep reading a row's scalar fields and need not know sides exist:
// r = L.r + R.r (the both-sides total, exactly what those readers expect of a per-side set)
// w = max(L.w, R.w) (the heavier side; the two are usually equal)
// done = L.done && R.done (a set counts done only once both sides are)
// effort= the harder side's rating (lower RIR / higher RPE), for the history tail only
// `syncSideAggregate` recomputes those scalars from `sides` after any per-side edit.
export function isSideSet(set) {
const s = objectOf(set)
return !!(s.sides && typeof s.sides === 'object' && s.sides.L && s.sides.R)
}
const sideOf = value => {
const v = objectOf(value)
const out = { w: Number(v.w) || 0, r: Number(v.r) || 0, done: v.done === true }
if (v.rir != null) out.rir = v.rir
if (v.rpe != null) out.rpe = v.rpe
// A side can carry its own intensifier (issue #60): drop-sets and rest-pause bursts are logged
// per limb, exactly like the main set, so the same {type, drops, clusters} shape rides on the
// side. Reuses the row-level helpers below (addDrop/dropsOf/…), which read this very shape.
if (v.type === 'dropset' || v.type === 'restpause') out.type = v.type
if (Array.isArray(v.drops)) out.drops = v.drops
if (Array.isArray(v.clusters)) out.clusters = v.clusters
return out
}
// Build a per-side row from a plain row: each side starts as half the row's total reps (a unilateral
// target is always even, so the split is whole) at the same weight, carrying nothing done yet.
export function makeSideSet(row = {}) {
const base = objectOf(row)
const half = Math.round((Number(base.r) || 0) / 2)
const w = Number(base.w) || 0
const side = () => ({ w, r: half, done: false })
const next = { ...base, sides: { L: side(), R: side() } }
// effort/done/reps on the parent become derived — drop any straight-set leftovers so the row
// carries one source of truth, then recompute the aggregate.
delete next.rir; delete next.rpe
return syncSideAggregate(next)
}
// Recompute the row's scalar mirror from its two sides. No-op (returns a shallow copy) for a row
// that is not per-side, so callers can pipe every edit through it unconditionally.
export function syncSideAggregate(row) {
const base = objectOf(row)
if (!isSideSet(base)) return { ...base }
const L = sideOf(base.sides.L)
const R = sideOf(base.sides.R)
const out = { ...base, sides: { L, R }, r: L.r + R.r, w: Math.max(L.w, R.w), done: L.done && R.done }
// The row's effort tail shows the harder side: fewer reps in reserve (lower RIR) or a higher RPE.
// Only one scale is ever in play, matching how a straight row carries rir XOR rpe.
delete out.rir; delete out.rpe
const rirs = [L.rir, R.rir].filter(v => v != null)
const rpes = [L.rpe, R.rpe].filter(v => v != null)
if (rirs.length) out.rir = Math.min(...rirs)
else if (rpes.length) out.rpe = Math.max(...rpes)
// Drops/clusters live on the sides now, so the row itself never carries them — only the shared
// `type` so isDropSet/isRestPauseSet still classify the set. extraVolumeOf reads the sides.
delete out.drops; delete out.clusters; delete out.type
const sideType = setType(L) !== 'straight' ? setType(L) : setType(R)
if (sideType !== 'straight') out.type = sideType
return out
}
// Patch one field on one side ('L'|'R'), returning a new row with the aggregate resynced. A null
// value clears an optional field (effort), mirroring how a straight row drops the key.
export function setSideField(row, side, field, value) {
const base = objectOf(row)
if (!isSideSet(base) || (side !== 'L' && side !== 'R')) return { ...base }
const cur = { ...sideOf(base.sides[side]) }
if (value == null && (field === 'rir' || field === 'rpe')) delete cur[field]
else cur[field] = value
return syncSideAggregate({ ...base, sides: { ...base.sides, [side]: cur } })
}
// Flip one side's done tick, resyncing the row's own done (true only when both sides are).
export function toggleSide(row, side) {
const base = objectOf(row)
if (!isSideSet(base) || (side !== 'L' && side !== 'R')) return { ...base }
const cur = { ...sideOf(base.sides[side]), done: !sideOf(base.sides[side]).done }
return syncSideAggregate({ ...base, sides: { ...base.sides, [side]: cur } })
}
// --- per-side intensifiers (drop-sets / rest-pause) --------------------------------------------
//
// On a unilateral set the intensifier is logged per limb too. The structure stays symmetric —
// both sides always carry the same number of drops/bursts — while each side's weights and reps
// are edited independently, mirroring how the main set works. These reuse the side-agnostic
// helpers above (addDrop/dropsOf/setDropAt/…) on each side object, then resync the aggregate.
// Apply an editing fn to a single side and resync (used to edit one side's drop/burst).
function patchSide(row, side, fn) {
const base = objectOf(row)
if (!isSideSet(base) || (side !== 'L' && side !== 'R')) return { ...base }
return syncSideAggregate({ ...base, sides: { ...base.sides, [side]: fn(sideOf(base.sides[side])) } })
}
// Apply an editing fn to both sides and resync (used to add/remove a drop/burst symmetrically).
function patchBothSides(row, fn) {
const base = objectOf(row)
if (!isSideSet(base)) return { ...base }
return syncSideAggregate({ ...base, sides: { L: fn(sideOf(base.sides.L), 'L'), R: fn(sideOf(base.sides.R), 'R') } })
}
// Append a drop to both sides, each seeded from its own side's weight (pct lighter) and reps.
export function addSideDrop(row, pct) {
return patchBothSides(row, side => {
const drops = dropsOf(side)
const base = drops.length ? drops[drops.length - 1].w : (side.w || 0)
return addDrop(side, { w: nextDropWeight(base, pct), r: side.r })
})
}
export function removeSideDropAt(row, i) {
return patchBothSides(row, side => removeDropAt(side, i))
}
export function setSideDropAt(row, side, i, patch) {
return patchSide(row, side, sd => setDropAt(sd, i, patch))
}
// Append a rest-pause burst to both sides, each seeded from its own side's rep count. The side's
// own `r` grows by the added burst, mirroring the non-per-side rule that a rest-pause row's `r`
// is the running total across its bursts.
export function addSideCluster(row, restSec) {
return patchBothSides(row, side => {
const clusters = clustersOf(side)
const base = clusters.length ? clusters[clusters.length - 1].r : (side.r || 0)
const added = nextBurstReps(base)
return { ...addCluster(side, { r: added, restSec }), r: (side.r || 0) + added }
})
}
export function removeSideClusterAt(row, i) {
return patchBothSides(row, side => {
const removed = clustersOf(side)[i]?.r || 0
return { ...removeClusterAt(side, i), r: Math.max(0, (side.r || 0) - removed) }
})
}
export function setSideClusterAt(row, side, i, r) {
return patchSide(row, side, sd => {
const delta = (Number(r) || 0) - (clustersOf(sd)[i]?.r || 0)
return { ...setClusterAt(sd, i, { r }), r: Math.max(0, (sd.r || 0) + delta) }
})
}
export function normalizeMode(value, fallback = 'reps') {
const token = typeof value === 'string' ? value.trim().toLowerCase() : ''
if (MODES.includes(token)) return token
+166
View File
@@ -4,6 +4,8 @@ import {
setType, isDropSet, isRestPauseSet, dropsOf, clustersOf, extraVolumeOf,
addDrop, addCluster, removeDropAt, removeClusterAt, setDropAt, setClusterAt,
nextDropWeight, nextBurstReps, splitBurstReps,
isSideSet, makeSideSet, syncSideAggregate, setSideField, toggleSide,
addSideDrop, removeSideDropAt, setSideDropAt, addSideCluster, removeSideClusterAt, setSideClusterAt,
} from './workout-model.js'
describe('phaseForSet / isWarmupRow', () => {
@@ -69,6 +71,14 @@ describe('extraVolumeOf', () => {
expect(extraVolumeOf({ w: 100, r: 5 })).toBe(0)
expect(extraVolumeOf({ phase: 'warmup', w: 20, r: 8 })).toBe(0)
})
it('sums both sides drops for a per-side drop-set (issue #60)', () => {
let s = addSideDrop(makeSideSet({ w: 20, r: 16 }), 20) // each side: one 16×8 drop
expect(extraVolumeOf(s)).toBe(16 * 8 * 2) // L + R
// an asymmetric edit is reflected
s = setSideDropAt(s, 'R', 0, { w: 10, r: 6 })
expect(extraVolumeOf(s)).toBe(16 * 8 + 10 * 6)
})
})
describe('addDrop / addCluster', () => {
@@ -179,3 +189,159 @@ describe('modeForSet / modeForEntry stay reps-mode for drop-sets and rest-pause
expect(modeForEntry(entry)).toBe('reps')
})
})
// One-sided (unilateral) sets: each side logged on its own, with the row's scalar w/r/done/effort
// kept as a correct aggregate so every other consumer (volume, 1RM, PRs, progression, counters)
// reads a per-side row exactly as it always read a straight one (issue #60).
describe('isSideSet', () => {
it('is true only for a row carrying both L and R sides', () => {
expect(isSideSet({ sides: { L: { w: 10, r: 8 }, R: { w: 10, r: 8 } } })).toBe(true)
expect(isSideSet({ w: 10, r: 8 })).toBe(false)
expect(isSideSet({ sides: { L: { w: 10, r: 8 } } })).toBe(false)
expect(isSideSet(null)).toBe(false)
})
})
describe('makeSideSet', () => {
it('splits the row total evenly across two sides at the same weight, nothing done', () => {
const s = makeSideSet({ w: 15, r: 16, done: false })
expect(isSideSet(s)).toBe(true)
expect(s.sides.L).toEqual({ w: 15, r: 8, done: false })
expect(s.sides.R).toEqual({ w: 15, r: 8, done: false })
// aggregate mirror: r = both sides, w = the (equal) weight, not done yet
expect(s.r).toBe(16)
expect(s.w).toBe(15)
expect(s.done).toBe(false)
})
it('drops any straight-set effort so the row carries a single source of truth', () => {
const s = makeSideSet({ w: 20, r: 10, rir: 2 })
expect(s.rir).toBeUndefined()
expect(s.rpe).toBeUndefined()
})
})
describe('syncSideAggregate', () => {
it('recomputes r as the sum, w as the heavier side, done only when both sides are', () => {
const row = { sides: { L: { w: 15, r: 8, done: true }, R: { w: 17.5, r: 6, done: false } } }
const s = syncSideAggregate(row)
expect(s.r).toBe(14)
expect(s.w).toBe(17.5)
expect(s.done).toBe(false)
const bothDone = syncSideAggregate({ sides: { L: { w: 15, r: 8, done: true }, R: { w: 15, r: 8, done: true } } })
expect(bothDone.done).toBe(true)
})
it('takes the harder side for the row effort — lower RIR, higher RPE', () => {
const rir = syncSideAggregate({ sides: { L: { w: 15, r: 8, rir: 3 }, R: { w: 15, r: 8, rir: 1 } } })
expect(rir.rir).toBe(1)
expect(rir.rpe).toBeUndefined()
const rpe = syncSideAggregate({ sides: { L: { w: 15, r: 8, rpe: 7 }, R: { w: 15, r: 8, rpe: 9 } } })
expect(rpe.rpe).toBe(9)
expect(rpe.rir).toBeUndefined()
})
it('leaves a non-per-side row alone (returns a copy)', () => {
const s = syncSideAggregate({ w: 20, r: 10, done: true })
expect(s).toEqual({ w: 20, r: 10, done: true })
expect(isSideSet(s)).toBe(false)
})
})
describe('setSideField', () => {
it('patches one side and resyncs the aggregate', () => {
const base = makeSideSet({ w: 15, r: 16 })
const s = setSideField(base, 'R', 'w', 17.5)
expect(s.sides.R.w).toBe(17.5)
expect(s.sides.L.w).toBe(15)
expect(s.w).toBe(17.5) // aggregate = heavier side
})
it('clears an effort field on null, mirroring how a straight row drops the key', () => {
let s = setSideField(makeSideSet({ w: 15, r: 16 }), 'L', 'rir', 2)
expect(s.sides.L.rir).toBe(2)
expect(s.rir).toBe(2)
s = setSideField(s, 'L', 'rir', null)
expect(s.sides.L.rir).toBeUndefined()
expect(s.rir).toBeUndefined()
})
it('ignores an unknown side without throwing', () => {
const base = makeSideSet({ w: 15, r: 16 })
expect(isSideSet(setSideField(base, 'X', 'w', 20))).toBe(true)
})
})
describe('toggleSide', () => {
it('flips one side and marks the row done only once both sides are', () => {
let s = makeSideSet({ w: 15, r: 16 })
expect(s.done).toBe(false)
s = toggleSide(s, 'L')
expect(s.sides.L.done).toBe(true)
expect(s.done).toBe(false) // R still open
s = toggleSide(s, 'R')
expect(s.sides.R.done).toBe(true)
expect(s.done).toBe(true) // both sides done → row done
s = toggleSide(s, 'L')
expect(s.done).toBe(false) // un-tick one side → row no longer done
})
})
// Per-side intensifiers: a unilateral set's drop-sets and rest-pause bursts are logged per limb
// too (issue #60). The structure stays symmetric (both sides carry the same count) while each
// side's numbers are edited independently; drops/clusters live on the sides, and the aggregate's
// extra volume sums both.
describe('addSideDrop / removeSideDropAt / setSideDropAt', () => {
it('adds a drop to both sides, each seeded from its own side weight and reps', () => {
let s = makeSideSet({ w: 20, r: 16 }) // sides: 20×8 each
s = setSideField(s, 'R', 'w', 18) // make the sides asymmetric first
s = addSideDrop(s, 20) // 20% lighter
expect(s.sides.L.drops).toEqual([{ w: 16, r: 8 }]) // 20 → 16
expect(s.sides.R.drops).toEqual([{ w: 14.5, r: 8 }]) // 18 → 14.4 → rounds to 14.5
expect(s.type).toBe('dropset') // aggregate mirrors the intensifier type
expect(s.drops).toBeUndefined() // drops live on the sides, not the row
})
it('edits one side drop independently, leaving the other side untouched', () => {
let s = addSideDrop(makeSideSet({ w: 20, r: 16 }), 20)
s = setSideDropAt(s, 'L', 0, { w: 12 })
expect(s.sides.L.drops[0].w).toBe(12)
expect(s.sides.R.drops[0].w).toBe(16)
})
it('removes a drop from both sides, reverting to straight when the last goes', () => {
let s = addSideDrop(makeSideSet({ w: 20, r: 16 }), 20)
s = removeSideDropAt(s, 0)
expect(s.sides.L.drops).toEqual([])
expect(s.sides.R.drops).toEqual([])
expect(s.type).toBeUndefined() // no side is a drop-set anymore
})
})
describe('addSideCluster / removeSideClusterAt / setSideClusterAt', () => {
it('adds a burst to both sides and grows each side reps by its own added burst', () => {
let s = makeSideSet({ w: 20, r: 16 }) // 8 per side
s = addSideCluster(s, 15) // nextBurstReps(8) = 4
expect(s.sides.L.clusters).toEqual([{ r: 4, restSec: 15 }])
expect(s.sides.L.r).toBe(12) // 8 + 4
expect(s.sides.R.r).toBe(12)
expect(s.r).toBe(24) // aggregate total across both sides
expect(s.type).toBe('restpause')
})
it('editing one side burst keeps that side reps in step and leaves the other alone', () => {
let s = addSideCluster(makeSideSet({ w: 20, r: 16 }), 15) // L/R: r 12, burst 4
s = setSideClusterAt(s, 'L', 0, 6) // +2 on L
expect(s.sides.L.clusters[0].r).toBe(6)
expect(s.sides.L.r).toBe(14) // 12 + 2
expect(s.sides.R.r).toBe(12) // untouched
})
it('removing a burst subtracts its reps from that side', () => {
let s = addSideCluster(makeSideSet({ w: 20, r: 16 }), 15) // r 12 each
s = removeSideClusterAt(s, 0)
expect(s.sides.L.clusters).toEqual([])
expect(s.sides.L.r).toBe(8) // back to the base
expect(s.type).toBeUndefined()
})
})
+4
View File
@@ -42,6 +42,9 @@ export default {
'rescheduled': 'verschoben',
'Prev': 'Zurück',
'Next': 'Weiter',
// Side badges on a unilateral set's L/R rows (issue #60).
'L': 'L',
'R': 'R',
'Move up': 'Nach oben',
'Move down': 'Nach unten',
// --- days & months ---
@@ -694,6 +697,7 @@ export default {
'{0} reps in every set — add a set and go back to {1}.': '{0} Wiederholungen in jedem Satz — ein Satz kommt dazu, zurück auf {1}.',
'{0} sets of {1} — time to add weight or move to a harder variation.': '{0} Sätze mit {1} — Zeit für Zusatzgewicht oder eine schwerere Variante.',
'{0} per side': '{0} pro Seite',
'Per side': 'Pro Seite',
'You still log the total: {0} is {1} per side.': 'Du trägst weiterhin die Gesamtzahl ein: {0} sind {1} pro Seite.',
// --- AI Coach ---
+3
View File
@@ -41,6 +41,8 @@ export default {
'rescheduled': 'reprogramado',
'Prev': 'Anterior',
'Next': 'Siguiente',
'L': 'I',
'R': 'D',
'Move up': 'Subir',
'Move down': 'Bajar',
'Sunday': 'Domingo', 'Monday': 'Lunes', 'Tuesday': 'Martes', 'Wednesday': 'Miércoles',
@@ -677,6 +679,7 @@ export default {
'{0} reps in every set — add a set and go back to {1}.': '{0} reps en todas las series: añade una serie y vuelve a {1}.',
'{0} sets of {1} — time to add weight or move to a harder variation.': '{0} series de {1}: toca añadir peso o pasar a una variante más difícil.',
'{0} per side': '{0} por lado',
'Per side': 'Por lado',
'You still log the total: {0} is {1} per side.': 'Sigues registrando el total: {0} son {1} por lado.',
// --- AI Coach ---
+3
View File
@@ -41,6 +41,8 @@ export default {
'rescheduled': 'reprogrammé',
'Prev': 'Préc.',
'Next': 'Suiv.',
'L': 'G',
'R': 'D',
'Move up': 'Monter',
'Move down': 'Descendre',
'Sunday': 'Dimanche', 'Monday': 'Lundi', 'Tuesday': 'Mardi', 'Wednesday': 'Mercredi',
@@ -677,6 +679,7 @@ export default {
'{0} reps in every set — add a set and go back to {1}.': '{0} répétitions sur toutes les séries — une série en plus, retour à {1}.',
'{0} sets of {1} — time to add weight or move to a harder variation.': '{0} séries de {1} — il est temps d’ajouter du poids ou de passer à une variante plus dure.',
'{0} per side': '{0} par côté',
'Per side': 'Par côté',
'You still log the total: {0} is {1} per side.': 'Tu notes toujours le total : {0}, c’est {1} par côté.',
// --- AI Coach ---
+3
View File
@@ -41,6 +41,8 @@ export default {
'rescheduled': 'बदला गया',
'Prev': 'पिछला',
'Next': 'अगला',
'L': 'बा',
'R': 'दा',
'Move up': 'ऊपर ले जाएँ',
'Move down': 'नीचे ले जाएँ',
'Sunday': 'रविवार', 'Monday': 'सोमवार', 'Tuesday': 'मंगलवार', 'Wednesday': 'बुधवार',
@@ -677,6 +679,7 @@ export default {
'{0} reps in every set — add a set and go back to {1}.': 'हर सेट में {0} रेप्स — एक सेट जोड़ें और वापस {1} पर।',
'{0} sets of {1} — time to add weight or move to a harder variation.': '{1} रेप्स के {0} सेट — अब वज़न बढ़ाने या किसी कठिन वैरिएशन पर जाने का समय।',
'{0} per side': 'प्रति तरफ़ {0}',
'Per side': 'प्रति तरफ़',
'You still log the total: {0} is {1} per side.': 'आप कुल ही दर्ज करते हैं: {0} यानी प्रति तरफ़ {1}।',
// --- AI Coach ---
+3
View File
@@ -43,6 +43,8 @@ export default {
'rescheduled': 'áthelyezve',
'Prev': 'Előző',
'Next': 'Következő',
'L': 'B',
'R': 'J',
// --- days & months ---
'Sunday': 'Vasárnap', 'Monday': 'Hétfő', 'Tuesday': 'Kedd', 'Wednesday': 'Szerda',
'Thursday': 'Csütörtök', 'Friday': 'Péntek', 'Saturday': 'Szombat',
@@ -656,6 +658,7 @@ export default {
'{0} reps in every set — add a set and go back to {1}.': '{0} ismétlés minden sorozatban — egy sorozat hozzáadva, vissza {1}-re.',
'{0} sets of {1} — time to add weight or move to a harder variation.': '{0} sorozat {1} ismétléssel — ideje súlyt hozzáadni vagy nehezebb variációra váltani.',
'{0} per side': '{0} oldalanként',
'Per side': 'Oldalanként',
'You still log the total: {0} is {1} per side.': 'Továbbra is az összeset rögzíted: {0} az {1} oldalanként.',
'{0} sets · {1} work': '{0} sorozat · {1} munka',
'Make superset with previous': 'Szuperszett az előzővel',
+3
View File
@@ -41,6 +41,8 @@ export default {
'rescheduled': 'riprogrammato',
'Prev': 'Prec.',
'Next': 'Succ.',
'L': 'S',
'R': 'D',
'Move up': 'Sposta su',
'Move down': 'Sposta giù',
'Sunday': 'Domenica', 'Monday': 'Lunedì', 'Tuesday': 'Martedì', 'Wednesday': 'Mercoledì',
@@ -677,6 +679,7 @@ export default {
'{0} reps in every set — add a set and go back to {1}.': '{0} ripetizioni in ogni serie — aggiungi una serie e torna a {1}.',
'{0} sets of {1} — time to add weight or move to a harder variation.': '{0} serie da {1} — è ora di aggiungere peso o passare a una variante più difficile.',
'{0} per side': '{0} per lato',
'Per side': 'Per lato',
'You still log the total: {0} is {1} per side.': 'Registri sempre il totale: {0} sono {1} per lato.',
// --- AI Coach ---
+3
View File
@@ -41,6 +41,8 @@ export default {
'rescheduled': '변경됨',
'Prev': '이전',
'Next': '다음',
'L': '좌',
'R': '우',
'Move up': '위로 이동',
'Move down': '아래로 이동',
'Sunday': '일요일', 'Monday': '월요일', 'Tuesday': '화요일', 'Wednesday': '수요일',
@@ -677,6 +679,7 @@ export default {
'{0} reps in every set — add a set and go back to {1}.': '모든 세트 {0}회 달성 — 세트를 추가하고 {1}회로 돌아갑니다.',
'{0} sets of {1} — time to add weight or move to a harder variation.': '{1}회 {0}세트 — 이제 무게를 올리거나 더 어려운 동작으로 넘어가세요.',
'{0} per side': '한쪽당 {0}회',
'Per side': '한쪽당',
'You still log the total: {0} is {1} per side.': '기록은 그대로 합계로 합니다: {0}회는 한쪽당 {1}회입니다.',
// --- AI Coach ---
+3
View File
@@ -41,6 +41,8 @@ export default {
'rescheduled': 'przełożono',
'Prev': 'Wstecz',
'Next': 'Dalej',
'L': 'L',
'R': 'P',
'Move up': 'Przenieś w górę',
'Move down': 'Przenieś w dół',
'Sunday': 'Niedziela', 'Monday': 'Poniedziałek', 'Tuesday': 'Wtorek', 'Wednesday': 'Środa',
@@ -677,6 +679,7 @@ export default {
'{0} reps in every set — add a set and go back to {1}.': 'Wszystkie serie po {0} powt. — dodaj serię i wróć do {1}.',
'{0} sets of {1} — time to add weight or move to a harder variation.': '{0} × {1} powt. — czas dodać ciężar albo przejść na trudniejszy wariant.',
'{0} per side': '{0} na stronę',
'Per side': 'Na stronę',
'You still log the total: {0} is {1} per side.': 'Nadal zapisujesz łączną liczbę: {0} to {1} na stronę.',
// --- AI Coach ---
+3
View File
@@ -41,6 +41,8 @@ export default {
'rescheduled': 'reagendado',
'Prev': 'Anterior',
'Next': 'Seguinte',
'L': 'E',
'R': 'D',
'Move up': 'Mover para cima',
'Move down': 'Mover para baixo',
'Sunday': 'Domingo', 'Monday': 'Segunda-feira', 'Tuesday': 'Terça-feira', 'Wednesday': 'Quarta-feira',
@@ -677,6 +679,7 @@ export default {
'{0} reps in every set — add a set and go back to {1}.': '{0} repetições em todas as séries — acrescenta uma série e volta a {1}.',
'{0} sets of {1} — time to add weight or move to a harder variation.': '{0} séries de {1} — hora de acrescentar peso ou passar a uma variação mais difícil.',
'{0} per side': '{0} por lado',
'Per side': 'Por lado',
'You still log the total: {0} is {1} per side.': 'Continuas a registar o total: {0} são {1} por lado.',
// --- AI Coach ---
+3
View File
@@ -41,6 +41,8 @@ export default {
'rescheduled': 'перенесено',
'Prev': 'Назад',
'Next': 'Далее',
'L': 'Л',
'R': 'П',
'Move up': 'Переместить вверх',
'Move down': 'Переместить вниз',
'Sunday': 'Воскресенье', 'Monday': 'Понедельник', 'Tuesday': 'Вторник', 'Wednesday': 'Среда',
@@ -677,6 +679,7 @@ export default {
'{0} reps in every set — add a set and go back to {1}.': 'Во всех подходах {0} повт. — добавь подход и вернись к {1}.',
'{0} sets of {1} — time to add weight or move to a harder variation.': '{0} × {1} — пора добавить вес или перейти к более сложному варианту.',
'{0} per side': '{0} на сторону',
'Per side': 'На сторону',
'You still log the total: {0} is {1} per side.': 'Ты по-прежнему записываешь общее число: {0} — это {1} на сторону.',
// --- AI Coach ---
+3
View File
@@ -43,6 +43,8 @@ export default {
'rescheduled': 'เลื่อนแล้ว',
'Prev': 'ก่อนหน้า',
'Next': 'ถัดไป',
'L': 'ซ',
'R': 'ข',
// --- days & months ---
'Sunday': 'วันอาทิตย์', 'Monday': 'วันจันทร์', 'Tuesday': 'วันอังคาร', 'Wednesday': 'วันพุธ',
'Thursday': 'วันพฤหัสบดี', 'Friday': 'วันศุกร์', 'Saturday': 'วันเสาร์',
@@ -656,6 +658,7 @@ export default {
'{0} reps in every set — add a set and go back to {1}.': 'ทำได้ {0} ครั้งในทุกเซ็ต — เพิ่มเซ็ตและกลับไปที่ {1}',
'{0} sets of {1} — time to add weight or move to a harder variation.': '{0} เซ็ตของ {1} — ถึงเวลาเพิ่มน้ำหนักหรือเปลี่ยนไปท่าที่ยากขึ้น',
'{0} per side': '{0} ต่อข้าง',
'Per side': 'ต่อข้าง',
'You still log the total: {0} is {1} per side.': 'บันทึกจำนวนรวมตามปกติ: {0} คือ {1} ต่อข้าง',
'{0} sets · {1} work': '{0} เซ็ต · เซ็ตหลัก {1}',
'Make superset with previous': 'รวมเป็นซูเปอร์เซ็ตกับท่าก่อนหน้า',
+3
View File
@@ -41,6 +41,8 @@ export default {
'rescheduled': 'ertelendi',
'Prev': 'Önceki',
'Next': 'Sonraki',
'L': 'L',
'R': 'R',
'Move up': 'Yukarı taşı',
'Move down': 'Aşağı taşı',
'Sunday': 'Pazar', 'Monday': 'Pazartesi', 'Tuesday': 'Salı', 'Wednesday': 'Çarşamba',
@@ -677,6 +679,7 @@ export default {
'{0} reps in every set — add a set and go back to {1}.': 'Her sette {0} tekrar — bir set ekle ve {1} tekrara dön.',
'{0} sets of {1} — time to add weight or move to a harder variation.': '{1} tekrarlık {0} set — ağırlık ekleme ya da daha zor bir varyasyona geçme zamanı.',
'{0} per side': 'Taraf başına {0}',
'Per side': 'Taraf başına',
'You still log the total: {0} is {1} per side.': 'Toplamı kaydetmeye devam ediyorsun: {0}, taraf başına {1} demek.',
// --- AI Coach ---
+3
View File
@@ -41,6 +41,8 @@ export default {
'rescheduled': '已改期',
'Prev': '上一个',
'Next': '下一个',
'L': '左',
'R': '右',
'Move up': '上移',
'Move down': '下移',
'Sunday': '星期日', 'Monday': '星期一', 'Tuesday': '星期二', 'Wednesday': '星期三',
@@ -677,6 +679,7 @@ export default {
'{0} reps in every set — add a set and go back to {1}.': '每组都做到 {0} 次——加一组,次数回到 {1}。',
'{0} sets of {1} — time to add weight or move to a harder variation.': '{0} 组 × {1} 次——该加重量或换更难的变式了。',
'{0} per side': '每侧 {0} 次',
'Per side': '每侧',
'You still log the total: {0} is {1} per side.': '你记录的仍然是总数:{0} 表示每侧 {1} 次。',
// --- AI Coach ---
+2 -2
View File
@@ -4,7 +4,7 @@ import { useUI } from './store/useUI.js'
import { EXDB, EXIDX, BODYPARTS, isCardio, isBodyweightEq, allExercises, equipmentOf, smOf, matchExercise, exOr } from './lib/exercises.js'
import { activeProfile, exAvailable, ALL_EQUIPMENT, newProfile } from './lib/equipment.js'
import { fmtDate, fmtNum, fmtVol, fmtDur, durPart, todayISO, isoOf, uid, exCount, DAYN, DAYS, weekOrder, weekStartOf, weekDayOffset, MONTHS_LONG, ACCENTS } from './lib/format.js'
import { lastEntryFor, bestWeightFor, bestWeightForEntry, buildSets, effectiveRoutineId, workoutVolume, setsDone, setsDoneActive, lastBW, supersetUnits, unitOf, setLabel, defaultConfig, cleanupSg, modeOf, effortOf, EFFORT, capEffort, stepEffort, isBw, isPerSide, sideReps, workSetsDone, applyIntensifierPlan, MAX_PLANNED_WARMUPS, NOTE_MAX } from './lib/history.js'
import { lastEntryFor, bestWeightFor, bestWeightForEntry, buildSets, effectiveRoutineId, workoutVolume, setsDone, setsDoneActive, setUnitsTotal, lastBW, supersetUnits, unitOf, setLabel, defaultConfig, cleanupSg, modeOf, effortOf, EFFORT, capEffort, stepEffort, isBw, isPerSide, sideReps, workSetsDone, applyIntensifierPlan, MAX_PLANNED_WARMUPS, NOTE_MAX } from './lib/history.js'
import { usesBar, barWeightFor, defaultBarWeight, hasBarOverride } from './lib/bar.js'
import { toScale, rirOf, EFFORT_PRESETS, effortColor } from './lib/effort.js'
import { beep, vibrate } from './lib/sound.js'
@@ -1949,7 +1949,7 @@ export function finishWorkout() {
const A = S().active
if (!A) return
const done = setsDoneActive(A)
const total = A.entries.reduce((n, e) => n + e.sets.length, 0)
const total = setUnitsTotal(A.entries)
if (!done) { confirmSheet({ title: t('Nothing logged yet'), message: t('You haven’t checked off any sets. Finish the workout anyway?'), confirmText: t('Finish anyway'), onConfirm: doFinishWorkout }); return }
if (done < total) { confirmSheet({ title: t('Finish early?'), message: t(total - done === 1 ? '{0} set still unchecked. Finish the workout now?' : '{0} sets still unchecked. Finish the workout now?', total - done), confirmText: t('Finish workout'), onConfirm: doFinishWorkout }); return }
doFinishWorkout()
+135 -15
View File
@@ -5,7 +5,7 @@ import { workoutControls } from '../lib/workout-controls.js'
import { useUI } from '../store/useUI.js'
import { exOr } from '../lib/exercises.js'
import { usesBar, barWeightFor, plateSplit } from '../lib/bar.js'
import { effectiveRoutine, lastEntryFor, bestWeightFor, bestWeightForEntry, buildSets, freestyleConfig, defaultConfig, setsDoneActive, supersetUnits, unitOf, setLabel, modeOf, isBw, isPerSide, sideReps, repStep, EFFORT, effortOf, stepEffort, capEffort, cascadeWeight, insertWarmupRow, removeRowAt, pairAdjacent, unpairSuperset, cleanupSg, applyIntensifierPlan, pinnedNoteFor, exNoteFor } from '../lib/history.js'
import { effectiveRoutine, 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 } from '../lib/history.js'
import { fmtNum, fmtDate, todayISO, exCount, DAYN } from '../lib/format.js'
import { beep, vibrate } from '../lib/sound.js'
import { t, exerciseNameFor } from '../lib/i18n.js'
@@ -19,7 +19,7 @@ import { Button, Check, NumberField } from '../components/ui.jsx'
import { nextPrescription, applyPrescription, defaultIncrement, weightIncrement, stepWeight } from '../lib/progression.js'
import { progressionGuidance } from '../lib/progression-copy.js'
import { glyphOf } from '../lib/glyphs.js'
import { isWarmupRow, isDropSet, isRestPauseSet, dropsOf, clustersOf, addDrop, addCluster, removeDropAt, removeClusterAt, setDropAt, setClusterAt, nextDropWeight, nextBurstReps } from '../lib/workout-model.js'
import { isWarmupRow, isDropSet, isRestPauseSet, dropsOf, clustersOf, addDrop, addCluster, removeDropAt, removeClusterAt, setDropAt, setClusterAt, nextDropWeight, nextBurstReps, isSideSet, makeSideSet, setSideField, toggleSide, addSideDrop, removeSideDropAt, setSideDropAt, addSideCluster, removeSideClusterAt, setSideClusterAt } from '../lib/workout-model.js'
import { canMoveActiveWorkoutUnit, moveActiveWorkoutUnit } from '../lib/active-workout-order.js'
const SWIPE_MIN_DISTANCE = 48
@@ -65,7 +65,7 @@ function Elapsed({ start }) {
}
/* ---------- one exercise block (reps: weight×reps · time: a held duration · cardio: duration+speed) ---------- */
function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemoveSet, onAddWarmup, onRemoveSetAt, onStartTimed, onPairPrev, onPairNext, onSetRowRef, onProgressionSettings, onSwap, onMoveUp, onMoveDown, canMoveUp, canMoveDown, onRemoveExercise, busy }) {
function ExerciseBlock({ entryIdx, compact, onToggle, onToggleSide, onField, onAddSet, onRemoveSet, onAddWarmup, onRemoveSetAt, onStartTimed, onPairPrev, onPairNext, onSetRowRef, onProgressionSettings, onSwap, onMoveUp, onMoveDown, canMoveUp, canMoveDown, onRemoveExercise, busy }) {
const S = useStore(s => s.S)
const update = useStore(s => s.update)
const working = useUI(s => s.work)
@@ -75,6 +75,11 @@ function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemov
// filled in by applyIntensifierPlan; these only add/edit/remove entries live from here on.
const mutSet = (i, fn) => update(s => { const row = s.active.entries[entryIdx].sets[i]; s.active.entries[entryIdx].sets[i] = fn(row) }, true)
const addDropRow = i => mutSet(i, row => {
// A unilateral set drops per side (issue #60): addSideDrop seeds each side from its own weight.
if (isSideSet(row)) {
const pct = entry.target?.intensifier?.type === 'dropset' ? entry.target.intensifier.pct : undefined
return addSideDrop(row, pct)
}
const drops = dropsOf(row)
const base = drops.length ? drops[drops.length - 1].w : (row.w || 0)
const pct = entry.target?.intensifier?.type === 'dropset' ? entry.target.intensifier.pct : undefined
@@ -84,19 +89,30 @@ function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemov
// applyIntensifierPlan/history.js) — clusters are the breakdown of that total, not extra on
// top of it — so adding, removing or editing one keeps `r` in step by the same delta.
const addBurstRow = i => mutSet(i, row => {
const restSec = entry.target?.intensifier?.type === 'restpause' ? entry.target.intensifier.restSec : (S.restPauseSec || 15)
if (isSideSet(row)) return addSideCluster(row, restSec) // per side, each keeps its own r in step
const clusters = clustersOf(row)
const base = clusters.length ? clusters[clusters.length - 1].r : (row.r || 0)
const restSec = entry.target?.intensifier?.type === 'restpause' ? entry.target.intensifier.restSec : (S.restPauseSec || 15)
const added = nextBurstReps(base)
return { ...addCluster(row, { r: added, restSec }), r: (row.r || 0) + added }
})
const removeDrop = (i, di) => mutSet(i, row => removeDropAt(row, di))
// Per-side weight/reps/effort edits (issue #60): patch one side of a unilateral row, keeping
// the row's aggregate (r/w/done/effort) in step via the model helper so every other reader
// stays right. The done tick goes through onToggleSide → toggle() instead, so ticking a side
// still fires the rest timer / auto-advance / workout-complete flow.
const setSide = (i, side, field, v) => mutSet(i, row => setSideField(row, side, field, v))
// Drop/burst edits accept an optional `side` ('L'|'R'): present for a per-side row (edits that
// one limb's drop/burst), absent for a straight row (edits the row's own).
const removeDrop = (i, di) => mutSet(i, row => isSideSet(row) ? removeSideDropAt(row, di) : removeDropAt(row, di))
const removeCluster = (i, ci) => mutSet(i, row => {
if (isSideSet(row)) return removeSideClusterAt(row, ci)
const removed = clustersOf(row)[ci]?.r || 0
return { ...removeClusterAt(row, ci), r: Math.max(0, (row.r || 0) - removed) }
})
const setDropField = (i, di, field, v) => mutSet(i, row => setDropAt(row, di, { [field]: v }))
const setClusterField = (i, ci, v) => mutSet(i, row => {
const setDropField = (i, di, field, v, side) => mutSet(i, row =>
isSideSet(row) ? setSideDropAt(row, side, di, { [field]: v }) : setDropAt(row, di, { [field]: v }))
const setClusterField = (i, ci, v, side) => mutSet(i, row => {
if (isSideSet(row)) return setSideClusterAt(row, side, ci, v)
const delta = (Number(v) || 0) - (clustersOf(row)[ci]?.r || 0)
return { ...setClusterAt(row, ci, { r: v }), r: Math.max(0, (row.r || 0) + delta) }
})
@@ -120,6 +136,9 @@ function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemov
// config brings it back, now labelled as the addition it is.
const cfg = { ...(entry.target || {}), id: entry.id }
const bw = !cardio && isBw(cfg)
// A unilateral exercise logs each side on its own (issue #60): work rows render as an L and an
// R sub-row, each with its own weight/reps/effort and done tick. Warm-ups stay single.
const perSide = mode === 'reps' && isPerSide(cfg)
const added = bw && entry.sets.some(s => s.w > 0)
const loadStep = mode === 'reps' ? weightIncrement(cfg, S.unit) : 2.5
const loadCol = { f: 'w', step: loadStep, dec: true, hd: bw ? t('Added ({0})', S.unit) : t('Weight ({0})', S.unit) }
@@ -243,6 +262,79 @@ function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemov
</div>
)
}
// Per-side versions of the weight/reps stepper and the effort picker. Same markup and stepping
// rules as the row-level `cell`/`effortCell`, but bound to one side of a unilateral row and
// routed through setSide so the aggregate stays correct. Reads the live side value from the
// store for the same stale-closure reason `bump` does.
const sideBump = (i, side, col, dir) => {
const fresh = useStore.getState().S.active?.entries[entryIdx]?.sets[i]?.sides?.[side]
const cur = fresh ? fresh[col.f] : 0
if (col.f === 'w') return setSide(i, side, col.f, stepWeight(cur, col.step, dir))
// Reps step by one per side: repCol's step of two keeps the *combined* total evenly
// splittable, but here each side is logged directly, so one tap is one rep.
const step = col.f === 'r' ? 1 : col.step
setSide(i, side, col.f, Math.max(0, Math.round(((cur || 0) + dir * step) * 100) / 100))
}
const sideCell = (sd, i, side, col, cls) => (
<div className={'stp ' + cls + (wc.steppers ? '' : ' plain')}>
{wc.steppers && <button aria-label="Decrease" onClick={() => sideBump(i, side, col, -1)}><Icon name="minus" /></button>}
<span className="val"><NumberField decimal={col.dec} value={sd[col.f] ?? ''}
onChange={v => setSide(i, side, col.f, v)} /></span>
{wc.steppers && <button aria-label="Increase" onClick={() => sideBump(i, side, col, 1)}><Icon name="plus" /></button>}
</div>
)
const sideEffortCell = (sd, i, side, col) => {
const v = sd[col.f] ?? null
const rir = col.eff === 'rpe' ? (v == null ? null : 10 - v) : v
const color = effortColor(rir)
const open = () => effortPickerSheet(col.eff, v, nv => setSide(i, side, col.f, nv))
if (v == null) return <button className="effcell is-empty" aria-label={col.hd} onClick={open}>{col.hd}</button>
const step = dir => setSide(i, side, col.f, stepEffort(col.eff, v, dir))
return (
<div className={'stp effcell-stp' + (wc.steppers ? '' : ' plain')}
style={color ? { color, borderColor: color, background: `color-mix(in srgb, ${color} 20%, var(--surface-2))` } : undefined}>
{wc.steppers && <button aria-label="Decrease" onClick={() => step(-1)}><Icon name="minus" /></button>}
<button className="val" aria-label={col.hd} onClick={open}>{fmtNum(v)}</button>
{wc.steppers && <button aria-label="Increase" onClick={() => step(1)}><Icon name="plus" /></button>}
</div>
)
}
// One side's row: the L or R badge, then the same weight/reps/effort controls as a straight
// row but bound to that side, and the side's own done tick.
const sideRow = (s, i, side, col1, col2, col3) => {
const sd = (s.sides && s.sides[side]) || { w: 0, r: 0, done: false }
return <div className={'setrow side' + (sd.done ? ' done' : '') + (col3 ? ' eff3' : '')}>
<span className="sidetag" aria-hidden="true">{side === 'L' ? t('L') : t('R')}</span>
{sideCell(sd, i, side, col1, 'w')}
{col2 && sideCell(sd, i, side, col2, 'r')}
{col3 && sideEffortCell(sd, i, side, col3)}
<Check checked={sd.done} onChange={() => onToggleSide(i, side)} />
</div>
}
// A side's own drop-set/rest-pause sub-rows (issue #60): the intensifier is logged per limb, so
// the drops and bursts hang under that side's row, each editable, exactly like a straight set's
// do under its row. Reads the side object, not the aggregate.
const sideExtras = (s, i, side) => {
const sd = (s.sides && s.sides[side]) || {}
return <>
{dropsOf(sd).map((d, di) => (
<div className="subrow" key={'d' + di}>
<span className="subn">{t('Drop {0}', di + 1)}</span>
{miniStepper(d.w, loadStep, true, v => setDropField(i, di, 'w', v, side), true)}
{miniStepper(d.r, 1, false, v => setDropField(i, di, 'r', v, side))}
<button className="iconbtn" aria-label={t('Remove drop')} onClick={() => removeDrop(i, di)}><Icon name="xmark" /></button>
</div>
))}
{clustersOf(sd).map((c, ci) => (
<div className="subrow" key={'c' + ci}>
<span className="subn">{t('Burst {0}', ci + 1)}</span>
{miniStepper(c.r, 1, false, v => setClusterField(i, ci, v, side))}
<span className="dim small">{c.restSec}s</span>
<button className="iconbtn" aria-label={t('Remove burst')} onClick={() => removeCluster(i, ci)}><Icon name="xmark" /></button>
</div>
))}
</>
}
// A smaller stepper for a drop's weight/reps or a burst's reps — editing what the plan (or a
// live "+ Drop"/"+ Burst" tap) already put on the row, not typing into a fresh field.
const miniStepper = (value, step, dec, onChange, snapWeightStep = false) => (
@@ -268,9 +360,10 @@ function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemov
</div>}
<div className="row" style={{ gap: 6, flexWrap: 'wrap', marginBottom: 8 }}>
{cardio && <span className="tag acc"><Icon name="figureRun" />{t('Cardio')}</span>}
{/* You log the total; this is the split, so the set in front of you is unambiguous
without the rep count having to mean two different things (issue #31). */}
{!cardio && !timed && isPerSide(cfg) && <span className="tag acc nocap"><Icon name="shuffle" />{t('{0} per side', fmtNum(sideReps(entry.sets.find(s => !s.done)?.r ?? entry.sets[0]?.r)))}</span>}
{/* A unilateral exercise is logged per side directly (the L/R rows below), so the old
"{n} per side" chip — which halved the combined total for display — is gone: the split
is no longer derived, it is what you enter. The tag only flags that this is per-side. */}
{!cardio && !timed && isPerSide(cfg) && <span className="tag acc nocap"><Icon name="shuffle" />{t('Per side')}</span>}
{(ex.tg || ex.bp) && <span className="tag">{t(ex.tg || ex.bp)}</span>}
{ex.eq && <span className="tag">{t(ex.eq)}</span>}
{best > 0 && <span className="tag nocap">{t('Best:')} {fmtNum(best)} {S.unit}</span>}
@@ -311,6 +404,19 @@ function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemov
return <div key={i}>
{isFirstWarmup && <div className="setph">{t('Warm-up')}</div>}
{!warm && warmBefore && <div className="setsep" />}
{perSide && !warm && isSideSet(s) ? (
// Unilateral work set: the number sits beside a two-row L/R stack, each side logged
// and ticked on its own (issue #60).
<div ref={el => onSetRowRef?.(i, el)} className={'setrow-side' + (s.done ? ' done' : '')}>
<button type="button" className="n" aria-label={t('Set {0}', phaseNum)} title={t('More')} onClick={() => openSetMenu(s, i)}>{phaseNum}</button>
<div className="side-rows">
{sideRow(s, i, 'L', col1, col2, col3)}
{sideExtras(s, i, 'L')}
{sideRow(s, i, 'R', col1, col2, col3)}
{sideExtras(s, i, 'R')}
</div>
</div>
) : (
<div ref={el => onSetRowRef?.(i, el)} className={'setrow' + (s.done ? ' done' : '') + (col3 ? ' eff3' : '')}>
<button type="button" className="n" aria-label={t('Set {0}', phaseNum)} title={t('More')} onClick={() => openSetMenu(s, i)}>{phaseNum}</button>
{cell(s, i, col1, 'w')}
@@ -322,6 +428,7 @@ function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemov
onClick={() => onStartTimed(i)}><Icon name="play" /></button>}
<Check checked={s.done} onChange={() => onToggle(i)} />
</div>
)}
{/* Drop-sets and rest-pause bursts extend this same row — no long rest, no new set.
A planned exercise arrives with these already filled in (applyIntensifierPlan);
every value here is just as editable as the main row's own weight/reps. */}
@@ -452,7 +559,7 @@ function ActiveWorkout() {
if (el && typeof el.scrollIntoView === 'function') el.scrollIntoView({ behavior: 'smooth', block: 'center' })
}, [cur, isSuperset, listMode, A.entries.length])
const total = A.entries.reduce((n, e) => n + e.sets.length, 0)
const total = setUnitsTotal(A.entries)
const done = setsDoneActive(A)
const mutEntry = (idx, fn) => update(s => { fn(s.active.entries[idx]) }, true)
@@ -472,7 +579,16 @@ function ActiveWorkout() {
const m = modeOf({ ...(e.target || {}), id: e.id })
if (m === 'cardio') e.sets.push({ min: l ? l.min : (e.target.min || 20), speed: l ? l.speed : (e.target.speed || 8), done: false })
else if (m === 'time') e.sets.push({ sec: l ? l.sec : (e.target.sec || 45), w: l ? (l.w || 0) : (e.target.weight || 0), done: false })
else e.sets.push({ w: l ? l.w : 0, r: l ? l.r : e.target.reps, done: false })
else {
const row = { w: l ? l.w : 0, r: l ? l.r : e.target.reps, done: false }
// A unilateral exercise keeps adding per-side rows (issue #60): seed each side from the
// previous set's own side when it had one, else split the row's total evenly.
e.sets.push(isPerSide({ ...(e.target || {}), id: e.id })
? (l && isSideSet(l)
? makeSideSet({ w: l.sides.L.w, r: (l.sides.L.r || 0) * 2 })
: makeSideSet(row))
: row)
}
})
const removeSet = idx => mutEntry(idx, e => { if (e.sets.length > 1) e.sets.pop() })
const addWarmup = idx => mutEntry(idx, e => {
@@ -521,6 +637,7 @@ function ActiveWorkout() {
onRemoveExercise: () => confirmRemoveExercise(idx),
busy: !!work,
onToggle: i => toggle(idx, i),
onToggleSide: (i, side) => toggle(idx, i, side),
onField: (i, f, v) => setField(idx, i, f, v),
onAddSet: () => addSet(idx),
onRemoveSet: () => removeSet(idx),
@@ -652,13 +769,16 @@ function ActiveWorkout() {
})
}
const toggle = (idx, i) => {
const toggle = (idx, i, side) => {
const m = modeAt(idx)
const cardioEntry = m === 'cardio'
let exJustDone = false, workoutDone = false, checked = false
update(s => {
const e = s.active.entries[idx]
e.sets[i].done = !e.sets[i].done
// A per-side tick flips just that side; the row's own `done` (both sides) is then
// recomputed by toggleSide, so every completion check below still reads a single boolean.
if (side) e.sets[i] = toggleSide(e.sets[i], side)
else e.sets[i].done = !e.sets[i].done
checked = e.sets[i].done
if (e.sets[i].done) {
beep(S.sound, 1040, 0.12); vibrate(30)
@@ -738,7 +858,7 @@ function ActiveWorkout() {
const u = supersetUnits(A2.entries)
const c = Math.min(A2.cur, Math.max(0, A2.entries.length - 1))
const ui = u.findIndex(x => x.includes(c))
const tot = A2.entries.reduce((n, e) => n + e.sets.length, 0)
const tot = setUnitsTotal(A2.entries)
api('/api/activity', { method: 'POST', body: JSON.stringify({
active, name: A2.name, exIdx: ui + 1, exTotal: u.length,
setsDone: setsDoneActive(A2), setsTotal: tot, startedAt: A2.start