From 95f8346124ab3df1a7804715aa9ee1f3fc157c20 Mon Sep 17 00:00:00 2001 From: Duarte Santos Date: Sun, 30 Aug 2026 14:28:12 +0200 Subject: [PATCH] =?UTF-8?q?curated2:=20log=20a=20past=20workout=20?= =?UTF-8?q?=E2=80=94=20History=20entry=20point,=20date/time/duration/routi?= =?UTF-8?q?ne=20sheet,=20replace-or-add=20prompt,=20workout=20screen=20wit?= =?UTF-8?q?hout=20clock=20or=20rest=20timers,=20no=20PRs=20or=20confirmed?= =?UTF-8?q?=20weights=20on=20finish?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- frontend/src/sheets.backfill.test.jsx | 66 ++++++++++++++++ frontend/src/sheets.jsx | 110 +++++++++++++++++++++----- frontend/src/views/History.jsx | 4 +- frontend/src/views/Workout.jsx | 8 +- 4 files changed, 167 insertions(+), 21 deletions(-) create mode 100644 frontend/src/sheets.backfill.test.jsx diff --git a/frontend/src/sheets.backfill.test.jsx b/frontend/src/sheets.backfill.test.jsx new file mode 100644 index 0000000..af0da25 --- /dev/null +++ b/frontend/src/sheets.backfill.test.jsx @@ -0,0 +1,66 @@ +// @vitest-environment happy-dom +import React, { act } from 'react' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { createRoot } from 'react-dom/client' +import { useStore } from './store/useStore.js' +import { useUI } from './store/useUI.js' +import { logPastWorkoutSheet } from './sheets.jsx' +import { todayISO } from './lib/format.js' + +const mounted = [] +function type(el, value) { + Object.getOwnPropertyDescriptor(el.constructor.prototype, 'value').set.call(el, value) + el.dispatchEvent(new Event('input', { bubbles: true })) +} +function mountTopSheet() { + const sheet = useUI.getState().sheets.at(-1) + const host = document.createElement('div') + document.body.appendChild(host) + const root = createRoot(host) + mounted.push(root) + act(() => root.render(sheet.render(() => useUI.getState().closeSheet(sheet.id)))) + return host +} +const button = (host, text) => [...host.querySelectorAll('button')].find(b => b.textContent.trim() === text) + +describe('log a past workout', () => { + beforeEach(() => { + globalThis.IS_REACT_ACT_ENVIRONMENT = true + useUI.setState({ sheets: [], toasts: [] }) + useStore.setState(s => ({ S: { ...s.S, active: null, routines: [], workouts: [{ id: 'old', d: todayISO(), start: 1, end: 2, name: 'Old', entries: [], prs: [] }] } })) + document.body.innerHTML = '' + }) + afterEach(() => { act(() => { mounted.splice(0).forEach(root => root.unmount()) }) }) + + it('refuses while a workout is running', () => { + const toast = vi.fn() + useUI.setState({ toast }) + useStore.setState(s => ({ S: { ...s.S, active: { id: 'a', entries: [] } } })) + logPastWorkoutSheet() + expect(useUI.getState().sheets).toHaveLength(0) + expect(toast).toHaveBeenCalledWith('Finish the current workout first.') + }) + + it('asks what to do when the day already has a workout', () => { + logPastWorkoutSheet() + const host = mountTopSheet() + expect(host.querySelector('h3').textContent).toBe('Log a past workout') + act(() => { type(host.querySelector('input[type=date]'), todayISO()) }) + act(() => { button(host, 'Continue').click() }) + const prompt = mountTopSheet() + expect(prompt.textContent).toContain('There is already a workout on that day.') + expect(['Replace', 'Add as second workout', 'Cancel'].map(t => !!button(prompt, t))).toEqual([true, true, true]) + expect(useStore.getState().S.active).toBeNull() + }) + + it('starts a backfilled session straight away on a free day', () => { + logPastWorkoutSheet() + const host = mountTopSheet() + act(() => { type(host.querySelector('input[type=date]'), '2020-01-02') }) + act(() => { button(host, 'Continue').click() }) + const A = useStore.getState().S.active + expect(A.d).toBe('2020-01-02') + expect(new Date(A.start).getHours()).toBe(18) + expect(A.backfill).toEqual({ durationMin: 60, replaceId: null }) + }) +}) diff --git a/frontend/src/sheets.jsx b/frontend/src/sheets.jsx index 39d8e2e..2b1211f 100644 --- a/frontend/src/sheets.jsx +++ b/frontend/src/sheets.jsx @@ -3,7 +3,7 @@ import { useStore } from './store/useStore.js' import { useUI } from './store/useUI.js' import { EXDB, EXIDX, BODYPARTS, isCardio, isBodyweightEq, allExercises, equipmentOf, smOf, matchExercise, exOr } from './lib/exercises.js' import { activeProfile, exAvailable, ALL_EQUIPMENT, newProfile } from './lib/equipment.js' -import { fmtDate, fmtNum, fmtVol, fmtDur, durPart, todayISO, uid, exCount, DAYN, MONTHS_LONG, ACCENTS } from './lib/format.js' +import { fmtDate, fmtNum, fmtVol, fmtDur, durPart, todayISO, isoOf, uid, exCount, DAYN, MONTHS_LONG, ACCENTS } from './lib/format.js' import { lastEntryFor, bestWeightFor, buildSets, effectiveRoutineId, workoutVolume, setsDone, setsDoneActive, lastBW, supersetUnits, unitOf, setLabel, defaultConfig, cleanupSg, modeOf, effortOf, isBw, isPerSide, sideReps, workSetsDone, applyIntensifierPlan, MAX_PLANNED_WARMUPS, NOTE_MAX } from './lib/history.js' import { beep, vibrate } from './lib/sound.js' import { t, instrFor, exerciseNameFor, getLang, INSTR_LANGS } from './lib/i18n.js' @@ -27,6 +27,8 @@ import { buildCompletedWorkout } from './lib/finish-workout.js' import { isWarmupRow } from './lib/workout-model.js' import { nextUnfinishedUnit } from './lib/supersetFlow.js' import { swapActiveExercise } from './lib/active-exercise-swap.js' +import { buildSessionEntries } from './lib/session-start.js' +import { workoutsOn, backfillStart, backfillEnd, completeBackfill } from './lib/backfill.js' const S = () => useStore.getState().S const update = (...a) => useStore.getState().update(...a) @@ -1366,16 +1368,7 @@ export function startFlow(routineId) { export function beginWorkout(routineId, bw) { const st = S() const r = routineId ? st.routines.find(x => x.id === routineId) : null - // The prescription is applied as the session is built, so you walk up to the bar with the - // right weight already on the screen instead of being told about it afterwards. `plan` is - // kept on the entry purely so the workout can explain the number it chose. - const excluded = r?.excludeFromProgression === true - const entries = (r ? r.ex : []).map(cfg => { - const plan = excluded ? { policy: 'off', kind: 'off' } : nextPrescription(st, cfg, r) - const step = defaultIncrement(cfg.id, st.unit) - const sets = applyIntensifierPlan(applyPrescription(buildSets(st, cfg, { step, useTarget: excluded }), plan, step), cfg) - return { id: cfg.id, sg: cfg.sg, target: { ...cfg }, plan, sets } - }) + const { entries, excluded } = buildSessionEntries(st, r) update(s => { s.active = { id: uid(), d: todayISO(), start: Date.now(), routineId, @@ -1386,6 +1379,80 @@ export function beginWorkout(routineId, bw) { useUI.getState().stopRest() nav('/workout') } + +/* ============================ log a past workout ============================ */ +// The same screen as a live session, pointed at another day. `backfill` on the active +// session is what tells the workout screen to drop the clock and the rest timers, and tells +// the finish path to file the workout where its date belongs instead of at the end. +function LogPastWorkout({ close }) { + const st = useStore(s => s.S) + const yesterday = new Date(); yesterday.setDate(yesterday.getDate() - 1) + const [date, setDate] = useState(isoOf(yesterday)) + const [time, setTime] = useState('18:00') + const [dur, setDur] = useState(60) + const [routineId, setRoutineId] = useState('') + const today = todayISO() + const options = [{ value: '', label: t('Freestyle') }, ...st.routines.map(r => ({ value: r.id, label: r.name }))] + + const go = replaceId => { + close() + beginBackfill({ iso: date, time, durationMin: dur, routineId: routineId || null, replaceId }) + } + const submit = () => { + if (!date || date > today) { toast(t('Pick a day up to today')); return } + const existing = workoutsOn(st, date) + if (!existing.length) { go(null); return } + ui().openSheet(c => { c(); go(id) }} onAdd={() => { c(); go(null) }} />, { kind: 'center' }) + } + + return <> +

{t('Log a past workout')}

+
{t('Logged on the usual workout screen, without timers.')}
+ + setDate(e.target.value)} /> + + setTime(e.target.value)} /> + setDur(Math.max(1, Math.round(v)))} /> +
+ +
+ + +} +// Three ways out when the day already has a workout. Replacing with several on that day means +// picking which one; the rest of the day is left alone. +function SameDayChoice({ iso, existing, onReplace, onAdd, close }) { + return
+

{fmtDate(iso, true)}

+
{t('There is already a workout on that day.')}
+ {existing.map(w =>
+ +
)} + +
+ +
+} +export function logPastWorkoutSheet() { + if (S().active) { toast(t('Finish the current workout first.')); return } + ui().openSheet(close => ) +} +function beginBackfill({ iso, time, durationMin, routineId, replaceId }) { + const st = S() + const r = routineId ? st.routines.find(x => x.id === routineId) : null + const { entries, excluded } = buildSessionEntries(st, r) + update(s => { + s.active = { + id: uid(), d: iso, start: backfillStart(iso, time), routineId, + name: r ? r.name : t('Freestyle'), bw: null, cur: 0, entries, + backfill: { durationMin, replaceId: replaceId || null }, + ...(excluded ? { excludeFromProgression: true } : {}) + } + }) + useUI.getState().stopRest() + nav('/workout') +} function TopWeight({ entryIdx, close }) { const st = useStore(s => s.S) const A = st.active @@ -1582,9 +1649,12 @@ function doFinishWorkout() { const st = S() const A = st.active if (!A) return + const past = !!A.backfill const prs = [] const e1prs = [] - A.entries.forEach(e => { + // A workout logged into the past cannot claim records against the history that came after + // it, so a backfilled session reports none and leaves the confirmed weights alone. + if (!past) A.entries.forEach(e => { const mx = Math.max(0, ...e.sets.filter(s => s.done && !isWarmupRow(s)).map(s => s.w)) if (mx > 0 && mx > bestWeightFor(st, e.id)) prs.push(e.id) // A heavier estimate without a heavier top set is its own kind of progress — @@ -1593,17 +1663,21 @@ function doFinishWorkout() { if (rec && !prs.includes(e.id)) e1prs.push({ id: e.id, ...rec }) }) const w = buildCompletedWorkout(A, { - end: Date.now(), + end: past ? backfillEnd(A) : Date.now(), prs, snapshotFor: e => EXIDX[e.id]?.custom ? exerciseMuscleSnapshot(EXIDX[e.id]) : null, }) w.vol = workoutVolume(w) update(s => { - w.entries.forEach(e => { - const mx = Math.max(0, ...e.sets.filter(x => x.done && !isWarmupRow(x)).map(x => x.w || 0), e.topW || 0) - if (mx > 0) { const cur = s.exWeights[e.id]; if (!cur || mx > cur.w) s.exWeights[e.id] = { w: mx, d: w.d } } - }) - s.workouts.push(w) + if (past) { + s.workouts = completeBackfill(s.workouts, A, w) + } else { + w.entries.forEach(e => { + const mx = Math.max(0, ...e.sets.filter(x => x.done && !isWarmupRow(x)).map(x => x.w || 0), e.topW || 0) + if (mx > 0) { const cur = s.exWeights[e.id]; if (!cur || mx > cur.w) s.exWeights[e.id] = { w: mx, d: w.d } } + }) + s.workouts.push(w) + } s.active = null }) useStore.getState().autoBackupNow() diff --git a/frontend/src/views/History.jsx b/frontend/src/views/History.jsx index c1447bc..6e99655 100644 --- a/frontend/src/views/History.jsx +++ b/frontend/src/views/History.jsx @@ -1,7 +1,8 @@ import { useNavigate } from 'react-router-dom' import { useStore } from '../store/useStore.js' import { t } from '../lib/i18n.js' -import { WorkoutRow, workoutDetailSheet } from '../sheets.jsx' +import { WorkoutRow, workoutDetailSheet, logPastWorkoutSheet } from '../sheets.jsx' +import { Button } from '../components/ui.jsx' import Icon from '../components/Icon.jsx' export default function History() { @@ -10,6 +11,7 @@ export default function History() { return <>

{t('History')}

{t('{0} workouts', S.workouts.length)}
+ {S.workouts.length ?
{[...S.workouts].reverse().map(w => workoutDetailSheet(w)} />)}
:
{t('No workouts yet.')}
} diff --git a/frontend/src/views/Workout.jsx b/frontend/src/views/Workout.jsx index 444d773..fafab26 100644 --- a/frontend/src/views/Workout.jsx +++ b/frontend/src/views/Workout.jsx @@ -290,8 +290,11 @@ function ActiveWorkout() { const nav = useNavigate() const S = useStore(s => s.S) const update = useStore(s => s.update) - const { startRest, stopRest, stopWork, work } = useUI() + const { startRest: liveRest, stopRest, stopWork, work } = useUI() const A = S.active + // A past workout has no rest to time — the sets were done days ago. The work timer for + // timed sets stays, since counting a hold is how its duration gets entered. + const startRest = A.backfill ? () => {} : liveRest const units = supersetUnits(A.entries) const cur = Number.isInteger(A.cur) ? Math.min(Math.max(A.cur, 0), Math.max(0, A.entries.length - 1)) @@ -613,10 +616,11 @@ function ActiveWorkout() { return
-
{A.name}
· {t('{0} sets', done + '/' + total)}
+
{A.name}
{A.backfill ? fmtDate(A.d, true) : } · {t('{0} sets', done + '/' + total)}
+ {A.backfill &&
{t('Logging a past workout — no rest timers.')}
} {A.entries.length ? <>
{isSuperset ? t('Superset {0} / {1}', unitIdx + 1, units.length) : t('Exercise {0} / {1}', unitIdx + 1, units.length)}