Combine routines (ENG-9) phase 3: start-flow wiring + resolver call sites
startFlow / beginWorkout now take string | string[] | null and route through buildCombinedEntries; callers pass [r.id], effectiveRoutineIds(...) or [] as appropriate. Every effectiveRoutine(S,iso) render site that showed one routine now iterates effectiveRoutines / checks effectiveRoutineIds. - sheets.jsx: beginWorkout / beginBackfill write s.active.routineIds + derived name, no routineId / excludeFromProgression; swapTo resolves the slot's routine from its entry rid and carries rid onto the replacement; DayOverride / Calendar use the plural resolver (dayPlan stays scalar — overriding a combined date collapses it, per spec §8); DayAssign writes a one-element list. - active-exercise-swap.js: split-insert carries current.rid like it carries sg. - Workout.jsx: StartChooser id-set exclusion + startFlow(list); add-exercise and progression-settings resolve the routine from the current entry's rid and stamp rid on a freehand add. - TabBar / Home: onStart(effectiveRoutineIds(...)); Home plannedPerWeek counts scheduled days not routines; today card name joins the day's routines. - mobile.js buildReminderNotifications: names all of a combined day's routines, or a count past two. - RoutineEdit delete-cleanup pulls the id from each week list, drops an emptied key. api/server.js effectiveRoutineId reads the first of the list. Tests: sheets.combine.test.jsx (beginWorkout with a routine-id list); mobile.test.js combined-day reminder. Existing suites stay green on the tolerant-reader path. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01JVbWJtoyQU4WgwFR4eAKgy
This commit is contained in:
1 parent
8b917b6331
commit
3dd2092a8d
10 files changed
+190
-62
No files matched your search
+2
-1
@@ -204,12 +204,13 @@ function cancelRestTimer(userId) {
|
||||
|
||||
// "Workout planned today" reminder — one per user per day, at their chosen time.
|
||||
// Duplicated (not imported) from frontend/src/lib/history.js effectiveRoutineId — tiny pure helper, not worth sharing across the two runtimes.
|
||||
// A weekday can hold a routine-id list (combine routines); the reminder only needs the first.
|
||||
function effectiveRoutineId(S, iso) {
|
||||
const ov = S.dayPlan?.[iso];
|
||||
if (ov === 'rest') return null;
|
||||
if (ov && S.routines?.some(r => r.id === ov)) return ov;
|
||||
const wd = new Date(iso + 'T12:00:00').getDay();
|
||||
return S.week?.[wd] || null;
|
||||
return [].concat(S.week?.[wd] || []).find(id => S.routines?.some(r => r.id === id)) || null;
|
||||
}
|
||||
// Computes "now" in an arbitrary IANA zone (e.g. "Europe/Lisbon") instead of the server's own —
|
||||
// each user's reminder fires by their own clock, wherever they and their phone actually are.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useLocation, useNavigate } from 'react-router-dom'
|
||||
import { useStore } from '../store/useStore.js'
|
||||
import { effectiveRoutine } from '../lib/history.js'
|
||||
import { effectiveRoutineIds, effectiveRoutines } from '../lib/history.js'
|
||||
import { todayISO } from '../lib/format.js'
|
||||
import { t } from '../lib/i18n.js'
|
||||
import Icon from './Icon.jsx'
|
||||
@@ -17,8 +17,9 @@ export default function TabBar({ onStart }) {
|
||||
|
||||
const startWorkout = () => {
|
||||
if (!S.active) {
|
||||
const r = effectiveRoutine(S, todayISO())
|
||||
if (r && r.ex.length) { onStart(r.id); return }
|
||||
// A weekday can hold several routines; start the combined session if any of them has
|
||||
// exercises, otherwise fall through to the picker.
|
||||
if (effectiveRoutines(S, todayISO()).some(r => r.ex.length)) { onStart(effectiveRoutineIds(S, todayISO())); return }
|
||||
}
|
||||
nav('/workout')
|
||||
}
|
||||
|
||||
@@ -37,6 +37,9 @@ export function swapActiveExercise(active, index, replacement, {
|
||||
const insertAt = keepGroup ? index + 1 : (unit.length > 1 ? unit.at(-1) + 1 : index + 1)
|
||||
active.entries.splice(insertAt, 0, {
|
||||
...replacement,
|
||||
// A swap does not change which routine the slot belongs to — carry its `rid` the same
|
||||
// way `sg` is carried, so a combined session's WorkoutDetail groups stay contiguous.
|
||||
...(current.rid ? { rid: current.rid } : {}),
|
||||
...(keepGroup ? { sg: current.sg } : {})
|
||||
})
|
||||
active.cur = insertAt
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
// web bundles; the Capacitor plugins are only ever imported behind it.
|
||||
import { t } from './i18n-core.js'
|
||||
import { isoOf, todayISO } from './format.js'
|
||||
import { effectiveRoutineId } from './history.js'
|
||||
import { effectiveRoutineIds } from './history.js'
|
||||
|
||||
export const MOBILE = import.meta.env.VITE_MOBILE === '1'
|
||||
|
||||
@@ -108,16 +108,17 @@ export function buildReminderNotifications(S, now = new Date()) {
|
||||
day.setDate(date.getDate() + offset)
|
||||
const iso = isoOf(day)
|
||||
if (completed.has(iso)) continue
|
||||
const rid = effectiveRoutineId(state, iso)
|
||||
const routine = routines.find(x => x.id === rid)
|
||||
if (!routine) continue
|
||||
// A weekday can hold several routines; name them all, or fall back to a count.
|
||||
const dayRoutines = effectiveRoutineIds(state, iso).map(id => routines.find(x => x.id === id)).filter(Boolean)
|
||||
if (!dayRoutines.length) continue
|
||||
const label = dayRoutines.length <= 2 ? dayRoutines.map(r => r.name).join(' + ') : t('{0} routines', dayRoutines.length)
|
||||
const at = new Date(day)
|
||||
at.setHours(hour, minute, 0, 0)
|
||||
if (at <= now) continue
|
||||
notifications.push({
|
||||
id: REMINDER_ID_BASE + offset,
|
||||
title: t('Workout day'),
|
||||
body: t('{0} is on the plan today — let’s go!', routine.name),
|
||||
body: t('{0} is on the plan today — let’s go!', label),
|
||||
schedule: { at, allowWhileIdle: true },
|
||||
})
|
||||
}
|
||||
|
||||
@@ -59,4 +59,19 @@ describe('buildReminderNotifications', () => {
|
||||
expect(notifications.some(n => iso(n.schedule.at) === iso(now))).toBe(false)
|
||||
expect(notifications.some(n => iso(n.schedule.at) === iso(new Date(2026, 5, 8)))).toBe(true)
|
||||
})
|
||||
|
||||
it('names both routines of a combined day, and reads a legacy scalar day the same', () => {
|
||||
const now = new Date(2026, 5, 1, 7, 0) // Monday
|
||||
const combined = buildReminderNotifications(state({ week: { 1: ['push', 'pull'] } }), now)[0]
|
||||
expect(combined.body).toContain('Push + Pull')
|
||||
|
||||
const legacy = buildReminderNotifications(state({ week: { 1: 'push' } }), now)[0]
|
||||
expect(legacy.body).toContain('Push')
|
||||
})
|
||||
|
||||
it('falls back to a count for three or more routines on one day', () => {
|
||||
const now = new Date(2026, 5, 1, 7, 0)
|
||||
const n = buildReminderNotifications(state({ week: { 1: ['push', 'pull', 'legs'] } }), now)[0]
|
||||
expect(n.body).toContain('3 routines')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,69 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { act } from 'react'
|
||||
import { beforeEach, describe, expect, it } from 'vitest'
|
||||
import { beginWorkout } from './sheets.jsx'
|
||||
import { EXDB } from './lib/exercises.js'
|
||||
import { DEF, useStore } from './store/useStore.js'
|
||||
import { useUI } from './store/useUI.js'
|
||||
|
||||
const clone = v => JSON.parse(JSON.stringify(v))
|
||||
const ids = EXDB.filter(e => e.bp !== 'cardio').slice(0, 3).map(e => e.id)
|
||||
|
||||
function install(routines, week = {}) {
|
||||
const S = clone(DEF)
|
||||
S.routines = routines
|
||||
S.week = week
|
||||
S.active = null
|
||||
S.workouts = []
|
||||
useStore.setState({ S, user: null })
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
localStorage.clear()
|
||||
useUI.setState({ sheets: [] })
|
||||
install([
|
||||
{ id: 'strength', name: 'Strength', emoji: '🏋️', prog: 'off', ex: [{ id: ids[0], sets: 3, reps: 5, weight: 60 }] },
|
||||
{ id: 'core', name: 'Core', emoji: '🧘', prog: 'off', ex: [{ id: ids[1], sets: 3, reps: 12, weight: 0 }, { id: ids[2], sets: 3, reps: 10, weight: 0 }] },
|
||||
{ id: 'rehab', name: 'Rehab', emoji: '🩹', excludeFromProgression: true, ex: [{ id: ids[1], sets: 2, reps: 15, weight: 5 }] },
|
||||
])
|
||||
})
|
||||
|
||||
describe('beginWorkout with a routine-id list', () => {
|
||||
it('concatenates the routines’ entries in order, stamps rid, derives the name', () => {
|
||||
act(() => beginWorkout(['strength', 'core'], null))
|
||||
const a = useStore.getState().S.active
|
||||
expect(a.routineIds).toEqual(['strength', 'core'])
|
||||
expect(a.name).toBe('Strength + Core')
|
||||
expect(a.entries.map(e => e.rid)).toEqual(['strength', 'core', 'core'])
|
||||
expect(a).not.toHaveProperty('routineId')
|
||||
expect(a).not.toHaveProperty('excludeFromProgression')
|
||||
})
|
||||
|
||||
it('a single-element list is an ordinary single-routine session', () => {
|
||||
act(() => beginWorkout(['strength'], null))
|
||||
const a = useStore.getState().S.active
|
||||
expect(a.routineIds).toEqual(['strength'])
|
||||
expect(a.name).toBe('Strength')
|
||||
expect(a.entries.every(e => e.rid === 'strength')).toBe(true)
|
||||
})
|
||||
|
||||
it('an empty list is a freestyle session — no entries, no rid', () => {
|
||||
act(() => beginWorkout([], null))
|
||||
const a = useStore.getState().S.active
|
||||
expect(a.routineIds).toEqual([])
|
||||
expect(a.name).toBe('Freestyle')
|
||||
expect(a.entries).toEqual([])
|
||||
})
|
||||
|
||||
it('carries a merged excluded routine’s per-entry noProg', () => {
|
||||
act(() => beginWorkout(['strength', 'rehab'], null))
|
||||
const a = useStore.getState().S.active
|
||||
expect(a.entries.find(e => e.rid === 'rehab').noProg).toBe(true)
|
||||
expect(a.entries.find(e => e.rid === 'strength').noProg).toBeUndefined()
|
||||
})
|
||||
|
||||
it('drops an unknown id and de-dupes a repeat (first wins)', () => {
|
||||
act(() => beginWorkout(['core', 'gone', 'core'], null))
|
||||
expect(useStore.getState().S.active.routineIds).toEqual(['core'])
|
||||
})
|
||||
})
|
||||
+47
-29
@@ -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, effectiveRoutineIds, 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 { 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'
|
||||
@@ -35,6 +35,7 @@ import { swapActiveExercise } from './lib/active-exercise-swap.js'
|
||||
import { useSheetKeyboard, useRevealActiveChip, tappable } from './lib/use-sheet-keyboard.js'
|
||||
import { isFav, toggleFav, sortFavouritesFirst } from './lib/favourites.js'
|
||||
import { buildSessionEntries } from './lib/session-start.js'
|
||||
import { buildCombinedEntries, deriveSessionName } from './lib/session-merge.js'
|
||||
import { workoutsOn, backfillStart, backfillEnd, completeBackfill } from './lib/backfill.js'
|
||||
|
||||
const S = () => useStore.getState().S
|
||||
@@ -950,20 +951,25 @@ export function swapActiveWorkoutExercise(index) {
|
||||
picker.close()
|
||||
const full = { ...cfg, id: ex.id }
|
||||
const st = S()
|
||||
const current = st.active?.entries?.[index]
|
||||
if (!current) return
|
||||
// A swap is an in-place substitution — routine identity is unchanged, so the replacement
|
||||
// keeps the slot's own `rid` and reads its prescription from that routine (not a
|
||||
// session-wide one). A slot with no `rid` is freestyle.
|
||||
const slotRoutine = current.rid ? st.routines.find(r => r.id === current.rid) : null
|
||||
const freestyle = !slotRoutine
|
||||
// Same rows the add flow builds: last time's loads and, in a planned session, the
|
||||
// prescription — swapping barbell for dumbbell bench must not start you at an empty bar.
|
||||
const freestyle = !st.active?.routineId
|
||||
const step = modeOf(full) === 'reps' ? weightIncrement(full, st.unit) : defaultIncrement(ex.id, st.unit)
|
||||
const plan = freestyle ? null : nextPrescription(st, full, st.routines.find(r => r.id === st.active.routineId))
|
||||
const plan = freestyle ? null : nextPrescription(st, full, slotRoutine)
|
||||
const built = buildSets(st, full, { step, ...(freestyle ? { preferLast: true } : {}), ...(plan?.kind === 'off' ? { useTarget: true } : {}) })
|
||||
const replacement = {
|
||||
id: ex.id,
|
||||
target: { ...cfg },
|
||||
plan,
|
||||
sets: applyIntensifierPlan(freestyle ? built : applyPrescription(built, plan, step), full)
|
||||
sets: applyIntensifierPlan(freestyle ? built : applyPrescription(built, plan, step), full),
|
||||
...(current.rid ? { rid: current.rid } : {}),
|
||||
}
|
||||
const current = S().active?.entries?.[index]
|
||||
if (!current) return
|
||||
|
||||
const apply = options => {
|
||||
// A timed callback closes over entry/set indexes. Invalidate it, and the current rest,
|
||||
@@ -1505,9 +1511,12 @@ function PlanImport({ bundle, close }) {
|
||||
function DayOverride({ iso, close }) {
|
||||
const st = useStore(s => s.S)
|
||||
const wd = new Date(iso + 'T12:00:00').getDay()
|
||||
const weeklyR = st.routines.find(r => r.id === st.week[wd])
|
||||
const weeklyNames = [].concat(st.week[wd] || []).map(id => st.routines.find(r => r.id === id)?.name).filter(Boolean)
|
||||
const hasOvr = st.dayPlan[iso] !== undefined
|
||||
const effId = effectiveRoutineId(st, iso)
|
||||
// A weekday can hold several routines; the per-date override stays single-pick, so picking
|
||||
// one here collapses a combined day to it (docs/COMBINE_ROUTINES.md §8). The check marks
|
||||
// show everything currently planned for the day.
|
||||
const effIds = effectiveRoutineIds(st, iso)
|
||||
const set = v => {
|
||||
update(s => { if (!v) delete s.dayPlan[iso]; else s.dayPlan[iso] = v })
|
||||
close()
|
||||
@@ -1515,13 +1524,13 @@ function DayOverride({ iso, close }) {
|
||||
}
|
||||
return <>
|
||||
<h3>{fmtDate(iso, true)}</h3>
|
||||
<div className="muted small" style={{ marginBottom: 12 }}>{t('Weekly plan:')} {weeklyR ? weeklyR.name : t('Rest')}{hasOvr && <span style={{ color: 'var(--orange)' }}> · {t('changed for this day')}</span>}<br />{t('Sick, missed a day or want a different session? Pick what to train instead.')}</div>
|
||||
<div className="muted small" style={{ marginBottom: 12 }}>{t('Weekly plan:')} {weeklyNames.length ? deriveSessionName(weeklyNames) : t('Rest')}{hasOvr && <span style={{ color: 'var(--orange)' }}> · {t('changed for this day')}</span>}<br />{t('Sick, missed a day or want a different session? Pick what to train instead.')}</div>
|
||||
<div className="list">
|
||||
{st.routines.map(r => <div key={r.id} className="item" {...tappable(() => set(r.id))}>
|
||||
<span className="lrow-i"><Icon name={glyphOf(r.emoji)} /></span>
|
||||
<div className="grow"><div className="tt">{r.name}</div><div className="ss">{exCount(r.ex.length)}</div></div>
|
||||
{effId === r.id && <Icon name="check" className="accent" />}</div>)}
|
||||
<div className="item" {...tappable(() => set('rest'))}><span className="lrow-i" style={{ background: 'var(--surface-3)' }}><Icon name="moon" /></span><div className="grow"><div className="tt">{t('Rest / skip this day')}</div></div>{effId === null && <Icon name="check" className="accent" />}</div>
|
||||
{effIds.includes(r.id) && <Icon name="check" className="accent" />}</div>)}
|
||||
<div className="item" {...tappable(() => set('rest'))}><span className="lrow-i" style={{ background: 'var(--surface-3)' }}><Icon name="moon" /></span><div className="grow"><div className="tt">{t('Rest / skip this day')}</div></div>{effIds.length === 0 && <Icon name="check" className="accent" />}</div>
|
||||
{hasOvr && <div className="item" {...tappable(() => set(''))}><span className="lrow-i" style={{ background: 'var(--surface-3)' }}><Icon name="reset" /></span><div className="grow"><div className="tt">{t('Back to weekly plan')}</div></div></div>}
|
||||
</div>
|
||||
</>
|
||||
@@ -1530,15 +1539,18 @@ export const dayOverrideSheet = iso => ui().openSheet(close => <DayOverride iso=
|
||||
|
||||
function DayAssign({ day, close }) {
|
||||
const st = useStore(s => s.S)
|
||||
const set = v => { update(s => { if (v) s.week[day] = v; else delete s.week[day] }); close() }
|
||||
// A weekday holds a routine-id list; this single-pick sheet sets the day to exactly one
|
||||
// routine (or rest). The inline per-day management on the Plan screen is what appends.
|
||||
const cur = [].concat(st.week[day] || [])
|
||||
const set = v => { update(s => { if (v) s.week[day] = [v]; else delete s.week[day] }); close() }
|
||||
return <>
|
||||
<h3>{t(DAYN[day])}</h3>
|
||||
<div className="list">
|
||||
<div className="item" {...tappable(() => set(''))}><span className="lrow-i" style={{ background: 'var(--surface-3)' }}><Icon name="moon" /></span><div className="grow"><div className="tt">{t('Rest day')}</div></div>{!st.week[day] && <Icon name="check" className="accent" />}</div>
|
||||
<div className="item" {...tappable(() => set(''))}><span className="lrow-i" style={{ background: 'var(--surface-3)' }}><Icon name="moon" /></span><div className="grow"><div className="tt">{t('Rest day')}</div></div>{!cur.length && <Icon name="check" className="accent" />}</div>
|
||||
{st.routines.map(r => <div key={r.id} className="item" {...tappable(() => set(r.id))}>
|
||||
<span className="lrow-i"><Icon name={glyphOf(r.emoji)} /></span>
|
||||
<div className="grow"><div className="tt">{r.name}</div><div className="ss">{exCount(r.ex.length)}</div></div>
|
||||
{st.week[day] === r.id && <Icon name="check" className="accent" />}</div>)}
|
||||
{cur.includes(r.id) && <Icon name="check" className="accent" />}</div>)}
|
||||
</div>
|
||||
</>
|
||||
}
|
||||
@@ -1617,8 +1629,8 @@ function Calendar({ start, close }) {
|
||||
for (let i = 0; i < startOffset; i++) cells.push(<div key={'e' + i} />)
|
||||
for (let d = 1; d <= daysIn; d++) {
|
||||
const iso = y + '-' + String(mo + 1).padStart(2, '0') + '-' + String(d).padStart(2, '0')
|
||||
const ws = byDay[iso], effId = effectiveRoutineId(st, iso), ovr = st.dayPlan[iso] !== undefined
|
||||
const dotCls = ws ? 'done' : ovr && effId ? 'ovr' : effId ? 'plan' : ''
|
||||
const ws = byDay[iso], planned = effectiveRoutineIds(st, iso).length > 0, ovr = st.dayPlan[iso] !== undefined
|
||||
const dotCls = ws ? 'done' : ovr && planned ? 'ovr' : planned ? 'plan' : ''
|
||||
cells.push(<button key={d} className={'cal-d' + (ws ? ' has' : '') + (iso === todayISO() ? ' today' : '')} onClick={() => {
|
||||
if (!ws) { close(); dayOverrideSheet(iso); return }
|
||||
if (ws.length === 1) { close(); workoutDetailSheet(ws[0]); return }
|
||||
@@ -1657,21 +1669,25 @@ export function WorkoutRow({ w, onClick }) {
|
||||
}
|
||||
|
||||
/* ============================ workout lifecycle ============================ */
|
||||
export function startFlow(routineId) {
|
||||
bwSheet({ required: true, onDone: bw => beginWorkout(routineId, bw) })
|
||||
// `routineIds` accepts `string | string[] | null` — `[r.id]` for one routine,
|
||||
// `effectiveRoutineIds(...)` for today's planned session, `[]` / null for explicit freestyle.
|
||||
export function startFlow(routineIds) {
|
||||
bwSheet({ required: true, onDone: bw => beginWorkout(routineIds, bw) })
|
||||
}
|
||||
export function beginWorkout(routineId, bw) {
|
||||
export function beginWorkout(routineIds, bw) {
|
||||
const st = S()
|
||||
const r = routineId ? st.routines.find(x => x.id === routineId) : null
|
||||
const { entries, excluded } = buildSessionEntries(st, r)
|
||||
const { entries, routineIds: rids, routines } = buildCombinedEntries(st, routineIds)
|
||||
update(s => {
|
||||
s.active = {
|
||||
id: uid(), d: todayISO(), start: Date.now(), routineId,
|
||||
name: r ? r.name : t('Freestyle'), bw: bw || null, cur: 0, entries,
|
||||
id: uid(), d: todayISO(), start: Date.now(),
|
||||
// A session tracks its routines as a list; per-entry `rid` carries which one each
|
||||
// exercise came from. No top-level `excludeFromProgression` — per-entry `noProg` does it.
|
||||
routineIds: rids,
|
||||
name: routines.length ? deriveSessionName(routines.map(r => r.name)) : t('Freestyle'),
|
||||
bw: bw || null, cur: 0, entries,
|
||||
// Snapshot the layout at start so the header ⋮ can change it for this session only —
|
||||
// changing the saved default (Settings → Workout view) mid-session leaves it alone.
|
||||
workoutView: st.workoutView || 'cards',
|
||||
...(excluded ? { excludeFromProgression: true } : {})
|
||||
}
|
||||
})
|
||||
useUI.getState().stopRest()
|
||||
@@ -1736,18 +1752,20 @@ export function logPastWorkoutSheet() {
|
||||
if (S().active) { toast(t('Finish the current workout first.')); return }
|
||||
ui().openSheet(close => <LogPastWorkout close={close} />)
|
||||
}
|
||||
// Backfill stays single-routine (the LogPastWorkout UI is one picker), but it emits the new
|
||||
// shape: a one-element (or empty) routine list, per-entry rid, no top-level routineId.
|
||||
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)
|
||||
const { entries, routineIds: rids, routines } = buildCombinedEntries(st, routineId ? [routineId] : [])
|
||||
update(s => {
|
||||
s.active = {
|
||||
id: uid(), d: iso, start: backfillStart(iso, time), routineId,
|
||||
name: r ? r.name : t('Freestyle'), bw: null, cur: 0, entries,
|
||||
id: uid(), d: iso, start: backfillStart(iso, time),
|
||||
routineIds: rids,
|
||||
name: routines.length ? deriveSessionName(routines.map(r => r.name)) : t('Freestyle'),
|
||||
bw: null, cur: 0, entries,
|
||||
backfill: { durationMin, replaceId: replaceId || null },
|
||||
// Same layout snapshot as a live session (see beginWorkout).
|
||||
workoutView: st.workoutView || 'cards',
|
||||
...(excluded ? { excludeFromProgression: true } : {})
|
||||
}
|
||||
})
|
||||
useUI.getState().stopRest()
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useState } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useStore } from '../store/useStore.js'
|
||||
import { effectiveRoutine, effectiveRoutineId, nextTrainingDay, streakWeeks, lastBW, setsDoneActive } from '../lib/history.js'
|
||||
import { effectiveRoutines, effectiveRoutineIds, nextTrainingDay, streakWeeks, lastBW, setsDoneActive } from '../lib/history.js'
|
||||
import { fmtNum, fmtDate, todayISO, isoOf, weekKey, weekStartOf, weekDayOffset, DAYS, DAYN } from '../lib/format.js'
|
||||
import { t, dateLocale } from '../lib/i18n.js'
|
||||
import { bwSheet, goalSheet, dayOverrideSheet, calendarSheet, startFlow, starterPlanSheet, bwDeltaColor } from '../sheets.jsx'
|
||||
@@ -19,10 +19,14 @@ export default function Home() {
|
||||
const [weekOffset, setWeekOffset] = useState(0)
|
||||
|
||||
const today = new Date()
|
||||
const routine = effectiveRoutine(S, todayISO())
|
||||
// A weekday can hold several routines. `todayRoutines` is the whole day; `routine` is the
|
||||
// first, kept for the one-routine glyph. The derived session name joins them (§9).
|
||||
const todayRoutines = effectiveRoutines(S, todayISO())
|
||||
const routine = todayRoutines[0] || null
|
||||
const todayName = todayRoutines.map(r => r.name).join(' + ')
|
||||
const todayOvr = S.dayPlan[todayISO()] !== undefined
|
||||
// On a rest day, saying when you train next beats leaving the row as a full stop.
|
||||
const next = !S.active && !routine ? nextTrainingDay(S, todayISO()) : null
|
||||
const next = !S.active && !todayRoutines.length ? nextTrainingDay(S, todayISO()) : null
|
||||
const bw = lastBW(S)
|
||||
const prevBW = S.bodyweight.length > 1 ? S.bodyweight[S.bodyweight.length - 2] : null
|
||||
const delta = bw && prevBW ? bw.w - prevBW.w : null
|
||||
@@ -40,7 +44,7 @@ export default function Home() {
|
||||
for (let i = 0; i < 7; i++) {
|
||||
const d = new Date(wkStart); d.setDate(wkStart.getDate() + i)
|
||||
const iso = isoOf(d)
|
||||
const eff = effectiveRoutineId(S, iso), ovr = S.dayPlan[iso] !== undefined, done = doneDays.has(iso)
|
||||
const eff = effectiveRoutineIds(S, iso).length > 0, ovr = S.dayPlan[iso] !== undefined, done = doneDays.has(iso)
|
||||
const dot = done ? ' done' : ovr && eff ? ' ovr' : eff ? ' plan' : ''
|
||||
strip.push(<div key={i} className={'wday' + (iso === todayISO() ? ' today' : '')} {...tappable(() => dayOverrideSheet(iso))}>
|
||||
<div className="lbl">{t(DAYS[d.getDay()])}</div><div className="num">{d.getDate()}</div><div className={'dot' + dot} /></div>)
|
||||
@@ -49,11 +53,12 @@ export default function Home() {
|
||||
const wkLabel = weekOffset === 0 ? t('This week') : `${wkStart.getDate()} ${wkStart.toLocaleDateString(dateLocale(), { month: 'short' })} – ${wkEnd.getDate()} ${wkEnd.toLocaleDateString(dateLocale(), { month: 'short' })}`
|
||||
|
||||
const wThisWeek = S.workouts.filter(w => weekKey(w.d, ws) === weekKey(todayISO(), ws)).length
|
||||
const plannedPerWeek = Object.keys(S.week).filter(k => S.week[k]).length
|
||||
// Days scheduled, not routines — a combined day counts as 1, matching wThisWeek (one w).
|
||||
const plannedPerWeek = Object.values(S.week).filter(ids => ids?.length).length
|
||||
const bwPoints = S.bodyweight.slice(-30).map(b => ({ t: b.t || new Date(b.d).getTime(), y: b.w, d: b.d }))
|
||||
|
||||
// today's session shown right under the week strip
|
||||
const onToday = () => { if (S.active) nav('/workout'); else if (routine) startFlow(routine.id); else dayOverrideSheet(todayISO()) }
|
||||
const onToday = () => { if (S.active) nav('/workout'); else if (todayRoutines.length) startFlow(effectiveRoutineIds(S, todayISO())); else dayOverrideSheet(todayISO()) }
|
||||
|
||||
return <div className="narrow">
|
||||
<div className="hdr">
|
||||
@@ -83,7 +88,7 @@ export default function Home() {
|
||||
<div className="lbl2">{t('Today')}</div>
|
||||
<div className="ttl">{S.active ? t('{0} — in progress', S.active.name)
|
||||
: doneToday ? (doneToday.name ? t('{0} — done', doneToday.name) : t('Workout done'))
|
||||
: routine ? routine.name : t('Rest day')}{todayOvr && routine && !doneToday ? ' · ' + t('rescheduled') : ''}</div>
|
||||
: routine ? todayName : t('Rest day')}{todayOvr && routine && !doneToday ? ' · ' + t('rescheduled') : ''}</div>
|
||||
{next && !doneToday && <div className="ss">{t('Next session: {0}, {1}', t(DAYN[next.weekday]), next.routine.name)}</div>}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -446,7 +446,12 @@ export default function RoutineEdit() {
|
||||
onConfirm: () => {
|
||||
update(s => {
|
||||
s.routines = s.routines.filter(x => x.id !== id)
|
||||
Object.keys(s.week).forEach(k => { if (s.week[k] === id) delete s.week[k] })
|
||||
// A weekday holds a routine-id list: pull the deleted id from each day, drop the
|
||||
// key when it empties (never store []). dayPlan stays scalar.
|
||||
Object.keys(s.week).forEach(k => {
|
||||
const next = [].concat(s.week[k]).filter(rid => rid !== id)
|
||||
if (next.length) s.week[k] = next; else delete s.week[k]
|
||||
})
|
||||
Object.keys(s.dayPlan).forEach(k => { if (s.dayPlan[k] === id) delete s.dayPlan[k] })
|
||||
})
|
||||
nav('/plan')
|
||||
|
||||
@@ -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 { effectiveRoutines, effectiveRoutineIds, lastEntryFor, bestWeightFor, bestWeightForEntry, buildSets, freestyleConfig, defaultConfig, setsDoneActive, supersetUnits, unitOf, setLabel, modeOf, isBw, isPerSide, sideReps, repStep, EFFORT, effortOf, stepEffort, capEffort, cascadeWeight, insertWarmupRow, removeRowAt, pairAdjacent, unpairSuperset, cleanupSg, applyIntensifierPlan, pinnedNoteFor, exNoteFor } from '../lib/history.js'
|
||||
import { fmtNum, fmtDate, todayISO, exCount, DAYN } from '../lib/format.js'
|
||||
import { beep, vibrate } from '../lib/sound.js'
|
||||
import { t, exerciseNameFor } from '../lib/i18n.js'
|
||||
@@ -30,26 +30,29 @@ const SWIPE_IGNORED_TARGETS = 'button,input,textarea,select,a,[role="button"],[r
|
||||
function StartChooser() {
|
||||
const nav = useNavigate()
|
||||
const S = useStore(s => s.S)
|
||||
const todayR = effectiveRoutine(S, todayISO())
|
||||
const todayIds = effectiveRoutineIds(S, todayISO())
|
||||
const todayRoutines = effectiveRoutines(S, todayISO())
|
||||
const todayName = todayRoutines.map(r => r.name).join(' + ')
|
||||
const todayOvr = S.dayPlan[todayISO()] !== undefined
|
||||
const others = S.routines.filter(r => r !== todayR)
|
||||
const idSet = new Set(todayIds)
|
||||
const others = S.routines.filter(r => !idSet.has(r.id))
|
||||
return <div className="narrow">
|
||||
<div className="hdr"><div><h1>{t('Start workout')}</h1><div className="sub">{t(DAYN[new Date().getDay()])} — {todayR ? t('today is {0}', todayR.name) : t('rest day, but no one’s stopping you')}</div></div></div>
|
||||
{todayR && <div className="card" style={{ borderColor: 'var(--acc)' }}>
|
||||
<div className="hdr"><div><h1>{t('Start workout')}</h1><div className="sub">{t(DAYN[new Date().getDay()])} — {todayRoutines.length ? t('today is {0}', todayName) : t('rest day, but no one’s stopping you')}</div></div></div>
|
||||
{todayRoutines.length > 0 && <div className="card" style={{ borderColor: 'var(--acc)' }}>
|
||||
<h2 className="accent">{t("Today's plan")}{todayOvr ? ' · ' + t('rescheduled') : ''}</h2>
|
||||
<div className="row between" style={{ marginBottom: 12 }}>
|
||||
<div><div className="big">{todayR.name}</div><div className="muted small">{exCount(todayR.ex.length)}</div></div>
|
||||
<span className="lrow-i" style={{ width: 38, height: 38, borderRadius: 9, fontSize: 22 }}><Icon name={glyphOf(todayR.emoji)} /></span>
|
||||
<div><div className="big">{todayName}</div><div className="muted small">{exCount(todayRoutines.reduce((n, r) => n + r.ex.length, 0))}</div></div>
|
||||
<span className="lrow-i" style={{ width: 38, height: 38, borderRadius: 9, fontSize: 22 }}><Icon name={glyphOf(todayRoutines[0].emoji)} /></span>
|
||||
</div>
|
||||
<Button variant="primary" icon="play" onClick={() => startFlow(todayR.id)}>{t('Start {0}', todayR.name)}</Button>
|
||||
<Button variant="primary" icon="play" onClick={() => startFlow(todayIds)}>{t('Start {0}', todayName)}</Button>
|
||||
</div>}
|
||||
{others.length > 0 && <><h4 className="sec">{t('Other routines')}</h4>
|
||||
<div className="list">{others.map(r => <div key={r.id} className="item" onClick={() => startFlow(r.id)}>
|
||||
<div className="list">{others.map(r => <div key={r.id} className="item" onClick={() => startFlow([r.id])}>
|
||||
<span className="lrow-i"><Icon name={glyphOf(r.emoji)} /></span>
|
||||
<div className="grow"><div className="tt">{r.name}</div><div className="ss">{exCount(r.ex.length)}</div></div>
|
||||
<span className="tag acc">{t('Start')}</span></div>)}</div></>}
|
||||
<div style={{ height: 14 }} />
|
||||
<Button icon="shuffle" onClick={() => startFlow(null)}>{t('Freestyle workout (pick as you go)')}</Button>
|
||||
<Button icon="shuffle" onClick={() => startFlow([])}>{t('Freestyle workout (pick as you go)')}</Button>
|
||||
{!S.routines.length && <><div style={{ height: 10 }} /><Button variant="primary" onClick={() => nav('/plan')}>{t('Build a plan first')}</Button></>}
|
||||
</div>
|
||||
}
|
||||
@@ -586,7 +589,9 @@ function ActiveWorkout() {
|
||||
const activeId = state.active.id
|
||||
const entryId = entry.id
|
||||
const entryCount = state.active.entries.length
|
||||
const routine = state.routines.find(r => r.id === state.active.routineId)
|
||||
// A combined session's entries each carry a `rid`; progression settings read from that
|
||||
// entry's own routine, not a session-wide one.
|
||||
const routine = state.routines.find(r => r.id === entry.rid)
|
||||
exConfigSheet(exOr(entryId), entry.target, cfg => {
|
||||
// Store updates clone the state tree. If this exact object is no longer at the captured
|
||||
// index, the list changed while the sheet was open; an id check alone cannot distinguish
|
||||
@@ -602,7 +607,7 @@ function ActiveWorkout() {
|
||||
// happens to occupy the same index.
|
||||
if (!activeEntry || activeEntry.id !== entryId) return
|
||||
const full = { ...cfg, id: activeEntry.id }
|
||||
const activeRoutine = s.routines.find(r => r.id === s.active.routineId)
|
||||
const activeRoutine = s.routines.find(r => r.id === activeEntry.rid)
|
||||
const step = modeOf(full) === 'reps' ? weightIncrement(full, s.unit) : defaultIncrement(activeEntry.id, s.unit)
|
||||
// A config without a set count keeps the rows the session already has.
|
||||
if (!(full.sets > 0)) full.sets = activeEntry.sets.filter(x => !isWarmupRow(x)).length || 1
|
||||
@@ -859,15 +864,20 @@ function ActiveWorkout() {
|
||||
{!listMode && <div style={{ height: 10 }} />}
|
||||
{wc.exerciseButtons && listMode && A.entries.length > 0 && <div className="muted small" style={{ marginBottom: 6 }}>{t('Move, swap and remove below act on the exercise marked {0}.', t('Current'))}</div>}
|
||||
<Button onClick={() => exercisePicker((ex, quick) => {
|
||||
const routine = S.routines.find(r => r.id === A.routineId)
|
||||
const freestyle = !A.routineId
|
||||
// A freehand add inherits the current unit's routine (its `rid`) so it lands in that
|
||||
// routine's block in a combined session and gets a real prescription; a routine-less
|
||||
// freestyle session has no `rid` to inherit. `noProg` is never set independently here —
|
||||
// the only mid-session route to an excluded entry is "Add routine".
|
||||
const curRid = A.entries[A.cur]?.rid
|
||||
const routine = curRid ? S.routines.find(r => r.id === curRid) : null
|
||||
const freestyle = !routine
|
||||
// Freestyle has no routine prescription to apply: show the last target in the config
|
||||
// sheet and carry its completed rows forward. A planned session uses its configured
|
||||
// target when progression is off, while progression-enabled sessions keep their path.
|
||||
const seed = freestyle ? freestyleConfig(S, { id: ex.id, ...defaultConfig(ex.id) }) : null
|
||||
const commit = cfg => update(s => {
|
||||
const full = { ...cfg, id: ex.id }
|
||||
const plan = freestyle ? null : nextPrescription(s, full, s.routines.find(r => r.id === s.active.routineId))
|
||||
const plan = freestyle ? null : nextPrescription(s, full, routine)
|
||||
const sets = buildSets(s, full, {
|
||||
step: modeOf(full) === 'reps' ? weightIncrement(full, s.unit) : defaultIncrement(ex.id, s.unit),
|
||||
...(freestyle ? { preferLast: true } : {}),
|
||||
@@ -875,7 +885,7 @@ function ActiveWorkout() {
|
||||
})
|
||||
const progressed = freestyle ? sets : applyPrescription(sets, plan, modeOf(full) === 'reps' ? weightIncrement(full, s.unit) : defaultIncrement(ex.id, s.unit))
|
||||
const insertAt = insertionIndexAfterCurrentUnit(supersetUnits(s.active.entries), s.active.cur, s.active.entries.length)
|
||||
s.active.entries.splice(insertAt, 0, { id: ex.id, target: { ...cfg }, plan, sets: applyIntensifierPlan(progressed, full) })
|
||||
s.active.entries.splice(insertAt, 0, { id: ex.id, target: { ...cfg }, plan, sets: applyIntensifierPlan(progressed, full), ...(curRid ? { rid: curRid } : {}) })
|
||||
s.active.cur = insertAt
|
||||
useUI.getState().shiftRestOwner(insertAt, 1)
|
||||
})
|
||||
|
||||
Reference in new issue
Block a user