Merge main (v1.2.14) in coach-providers

Konflikte: zwoelf Locale-Packs (beide Seiten haengen Strings an, sechs doppelte
Schluessel bereinigt), Admin.jsx/admin.css (Coach-Karte bleibt, main-Umbau uebernommen),
Workout/Home/Plan/sheets (main gewinnt), docs.html (Coach-Kapitel war doppelt).
Ungarisch und Thai sind auf main dazugekommen und bekommen die 334 Coach-Strings.
pt-BR-Fingerprint nachgezogen.
This commit is contained in:
Duarte Santos committed 2026-09-03 22:17:29 +02:00
commit 63cf1deaed
121 files changed
+17177 -747

No files matched your search

+1 -1
View File
@@ -203,7 +203,7 @@ export default function Admin() {
<button className="iconbtn" onClick={() => { loadUsers(); loadInvites(); setTick(n => n + 1) }} aria-label="refresh">↻</button>
</div>
<div className="adm-intro">
Everything about running this instance: who uses it, how they get in, and the AI Coach. Nothing here shows anyone's training data beyond counts.
Everything about running this instance: who uses it, how they get in, the AI Coach, and what has happened on it. Nothing here shows anyone's training data beyond counts.
</div>
<div className="tiles" style={{ marginBottom: 12 }}>
+3 -1
View File
@@ -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 <>
<div className="hdr"><button className="iconbtn" onClick={() => nav('/stats')} aria-label={t('Stats')}><Icon name="chevronLeft" /></button>
<div style={{ flex: 1, marginLeft: 12 }}><h1>{t('History')}</h1><div className="sub">{t('{0} workouts', S.workouts.length)}</div></div></div>
<Button icon="plus" onClick={logPastWorkoutSheet} style={{ marginBottom: 12 }}>{t('Log a past workout')}</Button>
{S.workouts.length ? <div className="list">{[...S.workouts].reverse().map(w => <WorkoutRow key={w.id} w={w} onClick={() => workoutDetailSheet(w)} />)}</div>
: <div className="empty"><div className="ico"><Icon name="history" /></div>{t('No workouts yet.')}</div>}
</>
+15 -10
View File
@@ -2,12 +2,13 @@ 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 { fmtNum, fmtDate, todayISO, isoOf, weekKey, DAYS, DAYN } from '../lib/format.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, loadStarterPlan, bwDeltaColor } from '../sheets.jsx'
import LineChart from '../components/LineChart.jsx'
import Icon from '../components/Icon.jsx'
import { Button } from '../components/ui.jsx'
import { tappable } from '../lib/use-sheet-keyboard.js'
import { glyphOf } from '../lib/glyphs.js'
// Home = what to do now + a quick glance. Deep charts & history live in Stats.
@@ -26,24 +27,28 @@ export default function Home() {
const prevBW = S.bodyweight.length > 1 ? S.bodyweight[S.bodyweight.length - 2] : null
const delta = bw && prevBW ? bw.w - prevBW.w : null
const monday = new Date(today); monday.setDate(today.getDate() - ((today.getDay() + 6) % 7) + weekOffset * 7)
const ws = weekStartOf(S)
// The first day of the shown week. Named for the role, not for Monday — which day that is
// is the setting.
const wkStart = new Date(today)
wkStart.setDate(today.getDate() - weekDayOffset(today.getDay(), ws) + weekOffset * 7)
const doneDays = new Set(S.workouts.map(w => w.d))
// The last session logged for today, if any — what the row below reports instead of asking
// you to start the one you already did. Last wins, so a second session names itself.
const doneToday = S.workouts.filter(w => w.d === todayISO()).at(-1) || null
const strip = []
for (let i = 0; i < 7; i++) {
const d = new Date(monday); d.setDate(monday.getDate() + 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 dot = done ? ' done' : ovr && eff ? ' ovr' : eff ? ' plan' : ''
strip.push(<div key={i} className={'wday' + (iso === todayISO() ? ' today' : '')} onClick={() => dayOverrideSheet(iso)}>
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>)
}
const sunday = new Date(monday); sunday.setDate(monday.getDate() + 6)
const wkLabel = weekOffset === 0 ? t('This week') : `${monday.getDate()} ${monday.toLocaleDateString(dateLocale(), { month: 'short' })} – ${sunday.getDate()} ${sunday.toLocaleDateString(dateLocale(), { month: 'short' })}`
const wkEnd = new Date(wkStart); wkEnd.setDate(wkStart.getDate() + 6)
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) === weekKey(todayISO())).length
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
const bwPoints = S.bodyweight.slice(-30).map(b => ({ t: b.t || new Date(b.d).getTime(), y: b.w, d: b.d }))
@@ -68,7 +73,7 @@ export default function Home() {
routine name behind a green Start tag and read as still outstanding (issue #4).
An in-progress session still wins — that one is happening right now. Tapping the
row keeps working, so a second session in one day is a tap away, just not urged. */}
<div className="today-row" onClick={onToday}>
<div className="today-row" {...tappable(onToday)}>
<div className="row" style={{ gap: 9, minWidth: 0 }}>
<span className="lrow-i" style={{ background: S.active ? 'var(--orange)' : doneToday ? 'var(--surface-3)' : routine ? 'var(--acc)' : 'var(--surface-3)' }}>
<Icon name={S.active ? 'timer' : doneToday ? 'checkCircle' : routine ? glyphOf(routine.emoji) : 'moon'}
@@ -79,7 +84,7 @@ export default function Home() {
<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>
{next && <div className="ss">{t('Next session: {0}, {1}', t(DAYN[next.weekday]), next.routine.name)}</div>}
{next && !doneToday && <div className="ss">{t('Next session: {0}, {1}', t(DAYN[next.weekday]), next.routine.name)}</div>}
</div>
</div>
{S.active ? <span className="tag" style={{ color: 'var(--orange)', background: 'color-mix(in srgb,var(--orange) 16%,transparent)' }}>{t('Resume')}</span>
@@ -131,7 +136,7 @@ export default function Home() {
</> : <div className="muted small">{t("No entries yet — log your weight to start the curve. It's also asked before every workout.")}</div>}
</div>
<div className="card tappable" style={{ cursor: 'pointer' }} onClick={() => calendarSheet()}>
<div className="card tappable" style={{ cursor: 'pointer' }} {...tappable(() => calendarSheet())}>
<div className="row between">
<div>
<div className="row" style={{ gap: 7, fontSize: 22, fontWeight: 600, letterSpacing: '-.021em' }}>
+9 -5
View File
@@ -1,4 +1,4 @@
import { useState } from 'react'
import { useRef, useState } from 'react'
import { useStore } from '../store/useStore.js'
import { EXDB, BODYPARTS, allExercises, equipmentOf, matchExercise } from '../lib/exercises.js'
import { activeProfile, exAvailable } from '../lib/equipment.js'
@@ -9,6 +9,7 @@ import { Thumb } from '../components/Media.jsx'
import { exerciseDetailSheet, addToRoutineSheet, customExSheet } from '../sheets.jsx'
import Icon from '../components/Icon.jsx'
import { Button } from '../components/ui.jsx'
import { tappable, useRevealActiveChip } from '../lib/use-sheet-keyboard.js'
export default function Library() {
const S = useStore(s => s.S)
@@ -17,6 +18,7 @@ export default function Library() {
const [eq, setEq] = useState('')
const [showAll, setShowAll] = useState(false) // ignore the active equipment profile for this session
const [shown, setShown] = useState(40)
const bpStrip = useRef(null), eqStrip = useRef(null)
const profile = activeProfile(S)
const base = allExercises(S).filter(e => (!bp || e.bp === bp) && matchExercise(e, q))
const eqFiltered = (profile && !showAll) ? base.filter(e => exAvailable(S, e)) : base
@@ -24,6 +26,8 @@ export default function Library() {
// Drop the equipment filter if the search narrowed it away, so you never hit a dead end.
const eqOn = eqOpts.includes(eq) ? eq : ''
const f = eqOn ? eqFiltered.filter(e => e.eq === eqOn) : eqFiltered
useRevealActiveChip(bpStrip, bp)
useRevealActiveChip(eqStrip, eqOn)
return <>
<div className="hdr"><div><h1>{t('Exercises')}</h1><div className="sub">{t('{0} exercises with animations', EXDB.length)}</div></div></div>
@@ -36,22 +40,22 @@ export default function Library() {
{showAll ? t('Filter by "{0}"', profile.name) : t('Show all equipment')}
</button>
</div>}
<div className="chips" style={{ marginBottom: eqOpts.length > 1 ? 8 : 12 }}>
<div className="chips" ref={bpStrip} style={{ marginBottom: eqOpts.length > 1 ? 8 : 12 }}>
<button className={'chip nocap' + (!bp ? ' on' : '')} onClick={() => { setBp(''); setEq(''); setShown(40) }}>{t('All')}</button>
{BODYPARTS.map(b => <button key={b} className={'chip' + (bp === b ? ' on' : '')} onClick={() => { setBp(b); setEq(''); setShown(40) }}>{t(b)}</button>)}
</div>
{eqOpts.length > 1 && <div className="chips" style={{ marginBottom: 12 }}>
{eqOpts.length > 1 && <div className="chips" ref={eqStrip} style={{ marginBottom: 12 }}>
<button className={'chip nocap' + (!eqOn ? ' on' : '')} onClick={() => { setEq(''); setShown(40) }}>{t('Any equipment')}</button>
{eqOpts.map(x => <button key={x} className={'chip' + (eqOn === x ? ' on' : '')} onClick={() => { setEq(x); setShown(40) }}>{t(x)}</button>)}
</div>}
<div className="list">
<div className="item" onClick={() => customExSheet(null, ex => exerciseDetailSheet(ex), q.trim())}>
<div className="item" {...tappable(() => customExSheet(null, ex => exerciseDetailSheet(ex), q.trim()))}>
<div className="thumb thumb-x"><Icon name="sparkles" /></div>
<div className="grow"><div className="tt">{t('Create your own exercise')}</div><div className="ss">{t('name + body part, no animation')}</div></div><Icon name="plus" className="chev" />
</div>
{f.slice(0, shown).map(e => {
const best = bestWeightFor(S, e.id)
return <div key={e.id} className="item" onClick={() => exerciseDetailSheet(e)}>
return <div key={e.id} className="item" {...tappable(() => exerciseDetailSheet(e))}>
<Thumb ex={e} />
<div className="grow"><div className="tt capitalize">{exerciseNameFor(e)}</div><div className="ss capitalize">{t(e.tg || e.bp)} · {t(e.eq)}</div></div>
{best > 0 && <span className="tag acc">{fmtNum(best)}</span>}
+6 -5
View File
@@ -1,10 +1,11 @@
import { useNavigate } from 'react-router-dom'
import { useStore } from '../store/useStore.js'
import { DAYN, uid, exCount } from '../lib/format.js'
import { DAYN, weekOrder, weekStartOf, uid, exCount } from '../lib/format.js'
import { t } from '../lib/i18n.js'
import { dayAssignSheet, loadStarterPlan, planToolsSheet } from '../sheets.jsx'
import Icon from '../components/Icon.jsx'
import { Button, Row } from '../components/ui.jsx'
import { Button } from '../components/ui.jsx'
import { tappable } from '../lib/use-sheet-keyboard.js'
import { glyphOf, DEFAULT_GLYPH } from '../lib/glyphs.js'
import { DEMO } from '../lib/demo.js'
import { MOBILE } from '../lib/mobile.js'
@@ -47,9 +48,9 @@ export default function Plan() {
<div className="cols"><div>
<h4 className="sec">{t('Week schedule')}</h4>
<div className="list" style={{ display: 'flex', flexDirection: 'column' }}>
{[1, 2, 3, 4, 5, 6, 0].map(d => {
{weekOrder(weekStartOf(S)).map(d => {
const r = S.routines.find(x => x.id === S.week[d])
return <div key={d} className="item" onClick={() => dayAssignSheet(d)}>
return <div key={d} className="item" {...tappable(() => dayAssignSheet(d))}>
<div className="grow"><div className="tt">{t(DAYN[d])}</div></div>
{r ? <span className="tag acc"><Icon name={glyphOf(r.emoji)} />{r.name}</span> : <span className="tag">{t('Rest')}</span>}
<Icon name="chevronRight" className="chev" /></div>
@@ -60,7 +61,7 @@ export default function Plan() {
<h4 className="sec" style={{ margin: 0 }}>{t('Routines')}</h4>
<Button size="sm" variant="tinted" icon="plus" onClick={addRoutine}>{t('New')}</Button>
</div>
{S.routines.length ? <div className="list">{S.routines.map(r => <div key={r.id} className="item" onClick={() => nav('/plan/r/' + r.id)}>
{S.routines.length ? <div className="list">{S.routines.map(r => <div key={r.id} className="item" {...tappable(() => nav('/plan/r/' + 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>
<Icon name="chevronRight" className="chev" /></div>)}</div> : <>
@@ -0,0 +1,450 @@
// @vitest-environment happy-dom
import React, { act } from 'react'
import { createRoot } from 'react-dom/client'
import { MemoryRouter, Route, Routes } from 'react-router-dom'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
const sheets = vi.hoisted(() => ({
exConfigSheet: vi.fn(), exercisePicker: vi.fn(), glyphPicker: vi.fn(), confirmSheet: vi.fn(),
}))
vi.mock('../lib/api.js', () => ({ api: vi.fn(() => Promise.resolve({})) }))
vi.mock('../sheets.jsx', () => sheets)
vi.mock('../components/Media.jsx', () => ({ Thumb: ({ ex }) => <span data-thumb={ex.id} /> }))
vi.mock('../components/BodyMap.jsx', () => ({ default: () => null }))
import RoutineEdit, { ROUTINE_DRAG_SLOP, ROUTINE_LONG_PRESS_MS, reorderRoutineUnit } from './RoutineEdit.jsx'
import { DEF, useStore } from '../store/useStore.js'
globalThis.IS_REACT_ACT_ENVIRONMENT = true
const clone = value => JSON.parse(JSON.stringify(value))
const configured = (id, extra = {}) => ({ id, mode: 'reps', sets: 3, reps: 5, weight: 0, ...extra })
let root
let host
function stateFor(entries) {
const S = clone(DEF)
S.routines = [{ id: 'r1', name: 'Drag routine', emoji: 'dumbbell', prog: 'linear', ex: entries }]
return S
}
function rect(top, height, left = 20, width = 340) {
return { x: left, y: top, left, right: left + width, top, bottom: top + height, width, height }
}
const rows = () => [...host.querySelectorAll('[data-routine-row]')]
function geometry(heights = rows().map(() => 70)) {
const list = host.querySelector('.routine-list')
let top = 100
const tops = [], bottoms = [], centers = []
rows().forEach((row, i) => {
const height = heights[i] ?? 70
tops.push(top); bottoms.push(top + height); centers.push(top + height / 2)
vi.spyOn(row, 'getBoundingClientRect').mockImplementation(() => rect(tops[i], height))
top += height + 10
})
const listRect = rect(80, top - 80)
vi.spyOn(list, 'getBoundingClientRect').mockImplementation(() => listRect)
return { list, tops, bottoms, centers, listRect }
}
function mount(entries) {
useStore.setState({ S: stateFor(entries), user: null })
host = document.createElement('div')
document.body.appendChild(host)
root = createRoot(host)
act(() => root.render(<MemoryRouter initialEntries={['/plan/r/r1']}><Routes><Route path="/plan/r/:id" element={<RoutineEdit />} /></Routes></MemoryRouter>))
return geometry()
}
function remountCurrentState() {
host = document.createElement('div')
document.body.appendChild(host)
root = createRoot(host)
act(() => root.render(<MemoryRouter initialEntries={['/plan/r/r1']}><Routes><Route path="/plan/r/:id" element={<RoutineEdit />} /></Routes></MemoryRouter>))
return geometry()
}
function pointer(target, type, { id = 7, kind = 'touch', primary = true, button = 0, x = 120, y = 120 } = {}) {
const event = new Event(type, { bubbles: true, cancelable: true })
for (const [key, value] of Object.entries({ pointerId: id, pointerType: kind, isPrimary: primary, button, clientX: x, clientY: y })) {
Object.defineProperty(event, key, { configurable: true, value })
}
act(() => target.dispatchEvent(event))
return event
}
function lift(row, y, x = 120) {
pointer(row.querySelector('.item'), 'pointerdown', { x, y })
act(() => vi.advanceTimersByTime(ROUTINE_LONG_PRESS_MS))
}
const exercises = () => useStore.getState().S.routines[0].ex
beforeEach(() => {
vi.useFakeTimers()
vi.spyOn(window, 'requestAnimationFrame').mockImplementation(cb => window.setTimeout(() => cb(Date.now()), 16))
vi.spyOn(window, 'cancelAnimationFrame').mockImplementation(id => window.clearTimeout(id))
localStorage.clear()
Object.values(sheets).forEach(mock => mock.mockReset())
root = null; host = null
})
afterEach(() => {
if (root) act(() => root.unmount())
host?.remove()
vi.clearAllTimers(); vi.restoreAllMocks(); vi.useRealTimers()
})
describe('routine long-press reorder', () => {
it('exports the frozen threshold/slop and keeps a short press as a normal click', () => {
expect(ROUTINE_LONG_PRESS_MS).toBe(380)
expect(ROUTINE_DRAG_SLOP).toBe(8)
const layout = mount([configured('1001'), configured('1002')])
const item = rows()[0].querySelector('.item')
pointer(item, 'pointerdown', { y: layout.centers[0] })
act(() => vi.advanceTimersByTime(379))
expect(host.querySelector('.is-dragging')).toBeNull()
pointer(item, 'pointerup', { y: layout.centers[0] })
act(() => item.click())
expect(sheets.exConfigSheet).toHaveBeenCalledOnce()
expect(exercises().map(e => e.id)).toEqual(['1001', '1002'])
})
it('lifts at exactly 380 ms and yields pre-lift movement strictly over 8 px to scrolling', () => {
let layout = mount([configured('1001'), configured('1002')])
let item = rows()[0].querySelector('.item')
pointer(item, 'pointerdown', { x: 100, y: layout.centers[0] })
const atEight = pointer(item, 'pointermove', { x: 108, y: layout.centers[0] })
expect(atEight.defaultPrevented).toBe(false)
act(() => vi.advanceTimersByTime(380))
expect(rows()[0].classList.contains('is-dragging')).toBe(true)
pointer(item, 'pointercancel', { x: 108, y: layout.centers[0] })
act(() => root.unmount()); host.remove(); root = null; host = null
layout = mount([configured('1001'), configured('1002')])
item = rows()[0].querySelector('.item')
pointer(item, 'pointerdown', { x: 100, y: layout.centers[0] })
const atNine = pointer(item, 'pointermove', { x: 109, y: layout.centers[0] })
act(() => vi.advanceTimersByTime(380))
expect(atNine.defaultPrevented).toBe(false)
expect(host.querySelector('.is-dragging')).toBeNull()
})
it('owns active movement, renders an indicator, and suppresses the compatibility click after cancel', () => {
const layout = mount([configured('1001'), configured('1002'), configured('1003')])
const row = rows()[1], item = row.querySelector('.item')
const capture = vi.fn(), release = vi.fn()
item.setPointerCapture = capture; item.releasePointerCapture = release
lift(row, layout.centers[1])
expect(capture).toHaveBeenCalledWith(7)
expect(row.classList.contains('is-dragging')).toBe(true)
expect(host.querySelector('[data-testid="routine-drop-indicator"]')).toBeTruthy()
const move = pointer(item, 'pointermove', { y: layout.centers[2] })
expect(move.defaultPrevented).toBe(true)
pointer(item, 'pointercancel', { y: layout.centers[2] })
expect(release).toHaveBeenCalledWith(7)
act(() => item.click())
expect(sheets.exConfigSheet).not.toHaveBeenCalled()
expect(exercises().map(e => e.id)).toEqual(['1001', '1002', '1003'])
})
it('moves across measured slots and persists one complete changed order', () => {
const layout = mount([configured('a'), configured('b'), configured('c'), configured('d')])
const before = localStorage.getItem('gym_state_v1')
const writes = vi.spyOn(Storage.prototype, 'setItem')
const row = rows()[0], item = row.querySelector('.item')
lift(row, layout.centers[0])
pointer(item, 'pointermove', { y: layout.centers[2] + 1 })
pointer(item, 'pointerup', { y: layout.centers[2] + 1 })
expect(exercises().map(e => e.id)).toEqual(['b', 'c', 'a', 'd'])
expect(JSON.parse(localStorage.getItem('gym_state_v1')).routines[0].ex.map(e => e.id)).toEqual(['b', 'c', 'a', 'd'])
expect(localStorage.getItem('gym_state_v1')).not.toBe(before)
expect(writes).toHaveBeenCalledTimes(1)
})
it('suppresses the compatibility click after a successful changed drop', () => {
const layout = mount([configured('a'), configured('b'), configured('c')])
const item = rows()[0].querySelector('.item')
lift(rows()[0], layout.centers[0])
pointer(item, 'pointermove', { y: layout.centers[2] + 1 })
pointer(item, 'pointerup', { y: layout.centers[2] + 1 })
expect(exercises().map(e => e.id)).toEqual(['b', 'c', 'a'])
act(() => item.click())
expect(sheets.exConfigSheet).not.toHaveBeenCalled()
})
it('lets a real tap shortly after a drop open the row again', () => {
const layout = mount([configured('a'), configured('b'), configured('c')])
const item = rows()[0].querySelector('.item')
lift(rows()[0], layout.centers[0])
pointer(item, 'pointermove', { y: layout.centers[2] + 1 })
pointer(item, 'pointerup', { y: layout.centers[2] + 1 })
expect(exercises().map(e => e.id)).toEqual(['b', 'c', 'a'])
act(() => vi.advanceTimersByTime(200))
const target = rows()[1].querySelector('.item')
pointer(target, 'pointerdown', { y: layout.centers[1] })
pointer(target, 'pointerup', { y: layout.centers[1] })
act(() => target.click())
expect(sheets.exConfigSheet).toHaveBeenCalledTimes(1)
})
it('never eats a tap that starts with its own pointerdown, even right after a drop', () => {
const layout = mount([configured('a'), configured('b'), configured('c')])
const item = rows()[0].querySelector('.item')
lift(rows()[0], layout.centers[0])
pointer(item, 'pointermove', { y: layout.centers[2] + 1 })
pointer(item, 'pointerup', { y: layout.centers[2] + 1 })
const target = rows()[1].querySelector('.item')
pointer(target, 'pointerdown', { y: layout.centers[1] })
pointer(target, 'pointerup', { y: layout.centers[1] })
act(() => target.click())
expect(sheets.exConfigSheet).toHaveBeenCalledTimes(1)
})
it('moves a whole grouped unit, never splits another group, and preserves every occurrence payload', () => {
const pairA = configured('dup', { sg: 'pair', weight: 11, note: 'first', future: { a: 1 } })
const pairB = configured('dup', { sg: 'pair', weight: 22, note: 'second', future: { b: 2 } })
const layout = mount([pairA, pairB, configured('c'), configured('d')])
const row = rows()[1], item = row.querySelector('.item')
lift(row, layout.centers[1])
expect(rows().slice(0, 2).every(node => node.classList.contains('is-dragging'))).toBe(true)
pointer(item, 'pointermove', { y: layout.listRect.bottom - 1 })
pointer(item, 'pointerup', { y: layout.listRect.bottom - 1 })
expect(exercises()).toEqual([configured('c'), configured('d'), pairA, pairB])
act(() => root.unmount()); host.remove(); root = null; host = null
const splitLayout = mount([configured('a'), configured('b', { sg: 'g' }), configured('c', { sg: 'g' }), configured('tail')])
const tail = rows()[3], tailItem = tail.querySelector('.item')
lift(tail, splitLayout.centers[3])
const betweenMembers = (splitLayout.bottoms[1] + splitLayout.tops[2]) / 2
pointer(tailItem, 'pointermove', { y: betweenMembers })
pointer(tailItem, 'pointerup', { y: betweenMembers })
expect(exercises().map(e => e.id)).toEqual(['a', 'tail', 'b', 'c'])
})
it('moves the selected duplicate occurrence rather than finding by catalogue id', () => {
const first = configured('dup', { weight: 10, reps: 3, note: 'first' })
const second = configured('dup', { weight: 20, reps: 9, note: 'second' })
const layout = mount([first, configured('middle'), second, configured('tail')])
const row = rows()[2], item = row.querySelector('.item')
lift(row, layout.centers[2])
pointer(item, 'pointermove', { y: layout.tops[0] + 1 })
pointer(item, 'pointerup', { y: layout.tops[0] + 1 })
expect(exercises()).toEqual([second, first, configured('middle'), configured('tail')])
})
it('cancels without persistence on outside release, lost capture, Escape, blur, hidden document, or second pointer', () => {
const cancelCases = ['outside', 'lost', 'escape', 'blur', 'hidden', 'second']
for (const cancel of cancelCases) {
if (root) { act(() => root.unmount()); host.remove(); root = null; host = null }
const layout = mount([configured('a'), configured('b'), configured('c')])
const row = rows()[0], item = row.querySelector('.item')
const before = localStorage.getItem('gym_state_v1')
lift(row, layout.centers[0])
pointer(item, 'pointermove', { y: layout.centers[2] })
if (cancel === 'outside') pointer(item, 'pointerup', { x: layout.listRect.right + 20, y: layout.centers[2] })
if (cancel === 'lost') pointer(item, 'lostpointercapture', { y: layout.centers[2] })
if (cancel === 'escape') act(() => document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true })))
if (cancel === 'blur') act(() => window.dispatchEvent(new Event('blur')))
if (cancel === 'hidden') {
Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'hidden' })
act(() => document.dispatchEvent(new Event('visibilitychange')))
Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'visible' })
}
if (cancel === 'second') pointer(rows()[1].querySelector('.item'), 'pointerdown', { id: 8, y: layout.centers[1] })
expect(exercises().map(e => e.id), cancel).toEqual(['a', 'b', 'c'])
expect(localStorage.getItem('gym_state_v1'), cancel).toBe(before)
expect(host.querySelector('.is-dragging'), cancel).toBeNull()
}
})
it('ignores non-primary/control pointers and leaves accessible move buttons working', () => {
const layout = mount([configured('a'), configured('b')])
const down = host.querySelector('button[aria-label="Move down"]')
pointer(down, 'pointerdown', { y: layout.centers[0] })
act(() => vi.advanceTimersByTime(380))
expect(host.querySelector('.is-dragging')).toBeNull()
act(() => down.click())
expect(exercises().map(e => e.id)).toEqual(['b', 'a'])
const item = rows()[0].querySelector('.item')
pointer(item, 'pointerdown', { primary: false, y: layout.centers[0] })
act(() => vi.advanceTimersByTime(380))
expect(host.querySelector('.is-dragging')).toBeNull()
})
it('autoscrolls only after lift and stops frames on cancel', () => {
const layout = mount([configured('a'), configured('b'), configured('c'), configured('d')])
host.style.overflowY = 'auto'
Object.defineProperty(host, 'clientHeight', { configurable: true, value: 320 })
Object.defineProperty(host, 'scrollHeight', { configurable: true, value: 900 })
host.scrollTop = 100
vi.spyOn(host, 'getBoundingClientRect').mockImplementation(() => rect(0, 320))
const row = rows()[2], item = row.querySelector('.item')
pointer(item, 'pointerdown', { y: 310 })
act(() => vi.advanceTimersByTime(16))
expect(host.scrollTop).toBe(100)
act(() => vi.advanceTimersByTime(ROUTINE_LONG_PRESS_MS - 16 + 16))
expect(host.scrollTop).toBeGreaterThan(100)
pointer(item, 'pointercancel', { y: 310 })
const stopped = host.scrollTop
act(() => vi.advanceTimersByTime(64))
expect(host.scrollTop).toBe(stopped)
})
it('fails closed when row geometry disappears during an active drag', () => {
const layout = mount([configured('a'), configured('b'), configured('c')])
const row = rows()[0], item = row.querySelector('.item')
const before = localStorage.getItem('gym_state_v1')
lift(row, layout.centers[0])
rows()[1].getBoundingClientRect.mockReturnValue(undefined)
pointer(item, 'pointermove', { y: layout.centers[2] })
pointer(item, 'pointerup', { y: layout.centers[2] })
expect(exercises().map(e => e.id)).toEqual(['a', 'b', 'c'])
expect(localStorage.getItem('gym_state_v1')).toBe(before)
expect(host.querySelector('.is-dragging')).toBeNull()
})
it('cleans pending and active gestures on unmount without late writes', () => {
const layout = mount([configured('a'), configured('b')])
const item = rows()[0].querySelector('.item')
const before = localStorage.getItem('gym_state_v1')
pointer(item, 'pointerdown', { y: layout.centers[0] })
act(() => root.unmount()); root = null
act(() => vi.advanceTimersByTime(1000))
expect(localStorage.getItem('gym_state_v1')).toBe(before)
const activeLayout = mount([configured('a'), configured('b')])
const activeItem = rows()[0].querySelector('.item')
const release = vi.fn()
activeItem.releasePointerCapture = release
lift(rows()[0], activeLayout.centers[0])
act(() => root.unmount()); root = null
act(() => vi.advanceTimersByTime(1000))
expect(release).toHaveBeenCalledWith(7)
expect(localStorage.getItem('gym_state_v1')).toBe(before)
})
it('covers reverse measured slots and an unchanged original slot', () => {
let layout = mount([configured('a'), configured('b'), configured('c'), configured('d')])
let item = rows()[3].querySelector('.item')
lift(rows()[3], layout.centers[3])
pointer(item, 'pointermove', { y: layout.tops[1] + 1 })
pointer(item, 'pointerup', { y: layout.tops[1] + 1 })
expect(exercises().map(e => e.id)).toEqual(['a', 'd', 'b', 'c'])
act(() => root.unmount()); host.remove(); root = null; host = null
layout = mount([configured('a'), configured('b'), configured('c')])
const before = localStorage.getItem('gym_state_v1')
item = rows()[1].querySelector('.item')
lift(rows()[1], layout.centers[1])
pointer(item, 'pointermove', { y: layout.centers[1] + ROUTINE_DRAG_SLOP + 1 })
pointer(item, 'pointerup', { y: layout.centers[1] + ROUTINE_DRAG_SLOP + 1 })
expect(exercises().map(e => e.id)).toEqual(['a', 'b', 'c'])
expect(localStorage.getItem('gym_state_v1')).toBe(before)
})
it('reads the persisted changed order back after a fresh remount', () => {
const layout = mount([configured('a'), configured('b'), configured('c')])
const item = rows()[0].querySelector('.item')
lift(rows()[0], layout.centers[0])
pointer(item, 'pointermove', { y: layout.centers[2] + 1 })
pointer(item, 'pointerup', { y: layout.centers[2] + 1 })
const saved = JSON.parse(localStorage.getItem('gym_state_v1'))
act(() => root.unmount()); host.remove(); root = null; host = null
useStore.setState({ S: saved, user: null })
remountCurrentState()
expect(exercises().map(e => e.id)).toEqual(['b', 'c', 'a'])
})
it('cancels active ownership for a second pointer outside the list and pending lost capture', () => {
let layout = mount([configured('a'), configured('b'), configured('c')])
let item = rows()[0].querySelector('.item')
const before = localStorage.getItem('gym_state_v1')
lift(rows()[0], layout.centers[0])
pointer(item, 'pointermove', { y: layout.centers[2] })
pointer(document.body, 'pointerdown', { id: 8, y: 20 })
pointer(item, 'pointerup', { y: layout.centers[2] })
expect(exercises().map(e => e.id)).toEqual(['a', 'b', 'c'])
expect(localStorage.getItem('gym_state_v1')).toBe(before)
expect(host.querySelector('.is-dragging')).toBeNull()
act(() => root.unmount()); host.remove(); root = null; host = null
layout = mount([configured('a'), configured('b')])
item = rows()[0].querySelector('.item')
pointer(item, 'pointerdown', { y: layout.centers[0] })
pointer(item, 'lostpointercapture', { y: layout.centers[0] })
act(() => vi.advanceTimersByTime(ROUTINE_LONG_PRESS_MS))
expect(host.querySelector('.is-dragging')).toBeNull()
})
it('cancels when equal serialized exercises acquire a new current routine/list identity', () => {
let layout = mount([configured('a'), configured('b'), configured('c')])
let item = rows()[0].querySelector('.item')
lift(rows()[0], layout.centers[0])
pointer(item, 'pointermove', { y: layout.centers[2] })
act(() => useStore.getState().update(s => {
const current = s.routines[0]
s.routines[0] = { ...current, ex: clone(current.ex) }
}))
pointer(item, 'pointerup', { y: layout.centers[2] })
expect(exercises().map(e => e.id)).toEqual(['a', 'b', 'c'])
expect(host.querySelector('.is-dragging')).toBeNull()
act(() => root.unmount()); host.remove(); root = null; host = null
layout = mount([configured('a'), configured('b')])
item = rows()[0].querySelector('.item')
pointer(item, 'pointerdown', { y: layout.centers[0] })
act(() => useStore.getState().update(s => {
const current = s.routines[0]
s.routines[0] = { ...current, ex: clone(current.ex) }
}))
act(() => vi.advanceTimersByTime(ROUTINE_LONG_PRESS_MS))
expect(host.querySelector('.is-dragging')).toBeNull()
})
it('never owns nested link, Move up, or Move down controls', () => {
const layout = mount([configured('a'), configured('b')])
const controls = [
rows()[1].querySelector('button[title]'),
rows()[1].querySelector('button[aria-label="Move up"]'),
rows()[1].querySelector('button[aria-label="Move down"]'),
]
for (const control of controls) {
pointer(control, 'pointerdown', { y: layout.centers[1] })
act(() => vi.advanceTimersByTime(ROUTINE_LONG_PRESS_MS))
expect(host.querySelector('.is-dragging')).toBeNull()
pointer(control, 'pointerup', { y: layout.centers[1] })
}
})
it('falls back to page/window autoscroll without a nested scroll host', () => {
const layout = mount([configured('a'), configured('b'), configured('c')])
const rootElement = document.documentElement
Object.defineProperty(document, 'scrollingElement', { configurable: true, value: rootElement })
Object.defineProperty(rootElement, 'clientHeight', { configurable: true, value: 300 })
Object.defineProperty(rootElement, 'scrollHeight', { configurable: true, value: 900 })
Object.defineProperty(window, 'innerHeight', { configurable: true, value: 300 })
Object.defineProperty(window, 'scrollY', { configurable: true, writable: true, value: 100 })
const scrollBy = vi.spyOn(window, 'scrollBy').mockImplementation((_, delta) => { window.scrollY += delta })
const item = rows()[2].querySelector('.item')
lift(rows()[2], 295)
act(() => vi.advanceTimersByTime(16))
expect(scrollBy).toHaveBeenCalled()
expect(window.scrollY).toBeGreaterThan(100)
pointer(item, 'pointercancel', { y: 295 })
})
it('invalidates ownership before cleanup synchronously emits lost capture', () => {
const layout = mount([configured('a'), configured('b')])
const item = rows()[0].querySelector('.item')
const release = vi.fn(pointerId => pointer(document, 'lostpointercapture', { id: pointerId, y: layout.centers[0] }))
item.releasePointerCapture = release
lift(rows()[0], layout.centers[0])
act(() => root.unmount()); root = null
expect(release).toHaveBeenCalledTimes(1)
})
})
describe('reorderRoutineUnit', () => {
it('splices complete units at canonical slots and cleans true orphans', () => {
const items = [configured('a', { sg: 'pair' }), configured('b', { sg: 'pair' }), configured('c', { sg: 'orphan' }), configured('d')]
expect(reorderRoutineUnit(items, 3, 1)).toBe(true)
expect(items.map(e => e.id)).toEqual(['a', 'b', 'd', 'c'])
expect(items[0].sg).toBe('pair'); expect(items[1].sg).toBe('pair'); expect(items[3].sg).toBeUndefined()
})
})
+324 -12
View File
@@ -1,20 +1,305 @@
import { useNavigate, useParams } from 'react-router-dom'
import { useEffect } from 'react'
import { useEffect, useRef, useState } from 'react'
import { useStore } from '../store/useStore.js'
import { exOr } from '../lib/exercises.js'
import { activeProfile, exAvailable } from '../lib/equipment.js'
import { uid } from '../lib/format.js'
import { t, exerciseNameFor } from '../lib/i18n.js'
import { supersetUnits, cleanupSg, exLine } from '../lib/history.js'
import { supersetUnits, moveSupersetUnit, cleanupSg, exLine } from '../lib/history.js'
import { Thumb } from '../components/Media.jsx'
import { glyphPicker, exercisePicker, exConfigSheet, confirmSheet } from '../sheets.jsx'
import Icon from '../components/Icon.jsx'
import { glyphOf } from '../lib/glyphs.js'
import { Button, SelectRow } from '../components/ui.jsx'
import { Button, Row, SelectRow, Switch } from '../components/ui.jsx'
import { POLICIES_FOR, POLICY_NAME, POLICY_DESC } from '../lib/progression.js'
import BodyMap from '../components/BodyMap.jsx'
import { loadOfRoutine, rankOf, MUSCLE_NAME } from '../lib/muscles.js'
export const ROUTINE_LONG_PRESS_MS = 380
export const ROUTINE_DRAG_SLOP = 8
const clamp = (value, low, high) => Math.max(low, Math.min(high, value))
// Slots are defined after removing the source unit, so a grouped run can never be split.
export function reorderRoutineUnit(exercises, sourceIndex, targetSlot) {
if (!Array.isArray(exercises) || !exercises.length) return false
const units = supersetUnits(exercises)
const sourcePosition = units.findIndex(unit => unit.includes(sourceIndex))
if (sourcePosition < 0) return false
const remaining = units.filter((_, position) => position !== sourcePosition)
const slot = clamp(Number.isFinite(targetSlot) ? Math.trunc(targetSlot) : sourcePosition, 0, remaining.length)
if (slot === sourcePosition) return false
const source = units[sourcePosition]
const moved = exercises.splice(source[0], source.length)
const insertAt = remaining.slice(0, slot).reduce((count, unit) => count + unit.length, 0)
exercises.splice(insertAt, 0, ...moved)
cleanupSg(exercises)
return true
}
function unitGeometry(list, exercises) {
const rows = new Map([...list.querySelectorAll('[data-routine-row]')]
.map(row => [Number(row.dataset.exIndex), row]))
const units = supersetUnits(exercises)
const geometry = units.map((unit, position) => {
const rects = unit.map(index => rows.get(index)?.getBoundingClientRect()).filter(Boolean)
if (rects.length !== unit.length) return null
const top = Math.min(...rects.map(rect => rect.top))
const bottom = Math.max(...rects.map(rect => rect.bottom))
return { unit, position, top, bottom, center: top + (bottom - top) / 2 }
})
return geometry.every(Boolean) ? geometry : null
}
function scrollHostFor(node) {
for (let parent = node.parentElement; parent && parent !== document.body; parent = parent.parentElement) {
const overflowY = window.getComputedStyle(parent).overflowY
if (/(auto|scroll)/.test(overflowY) && parent.scrollHeight > parent.clientHeight) return parent
}
return window
}
function autoScrollStep(host, clientY) {
const edge = 64
const maxStep = 14
let top, bottom, scrollTop, maxScroll
if (host === window) {
const root = document.scrollingElement || document.documentElement
top = window.visualViewport?.offsetTop || 0
bottom = top + (window.visualViewport?.height || window.innerHeight || root.clientHeight)
scrollTop = window.scrollY || root.scrollTop || 0
maxScroll = Math.max(root.scrollHeight, document.body?.scrollHeight || 0) - (bottom - top)
} else {
const rect = host.getBoundingClientRect()
top = rect.top; bottom = rect.bottom
scrollTop = host.scrollTop; maxScroll = host.scrollHeight - host.clientHeight
}
if (clientY < top + edge && scrollTop > 0) return -Math.ceil(maxStep * clamp((top + edge - clientY) / edge, 0, 1))
if (clientY > bottom - edge && scrollTop < maxScroll) return Math.ceil(maxStep * clamp((clientY - bottom + edge) / edge, 0, 1))
return 0
}
function useRoutineReorder(routineIdentity, exercises, onDrop) {
const listRef = useRef(null)
const gestureRef = useRef(null)
const exercisesRef = useRef(exercises)
const routineIdentityRef = useRef(routineIdentity)
const onDropRef = useRef(onDrop)
const suppressClickRef = useRef(false)
const suppressTimerRef = useRef(null)
const [drag, setDrag] = useState(null)
exercisesRef.current = exercises
routineIdentityRef.current = routineIdentity
onDropRef.current = onDrop
const hasRows = exercises.length > 0
useEffect(() => () => {
suppressClickRef.current = false
window.clearTimeout(suppressTimerRef.current)
}, [])
useEffect(() => {
const list = listRef.current
if (!list) return undefined
let frame = null
setDrag(current => current ? null : current)
const clearFrame = () => {
if (frame != null) window.cancelAnimationFrame(frame)
frame = null
}
const clearTimer = gesture => {
if (gesture?.timer != null) window.clearTimeout(gesture.timer)
if (gesture) gesture.timer = null
}
const matchesSnapshot = gesture => routineIdentityRef.current === gesture.routineIdentity
&& exercisesRef.current === gesture.listIdentity
&& JSON.stringify(exercisesRef.current) === gesture.snapshot
const releaseCapture = gesture => {
const target = gesture?.captureTarget
if (!target?.releasePointerCapture) return
try { target.releasePointerCapture(gesture.pointerId) } catch { /* already released */ }
}
const finish = (gesture, commit, x = gesture?.lastX, y = gesture?.lastY) => {
if (!gesture || gestureRef.current !== gesture) return
clearTimer(gesture)
clearFrame()
gestureRef.current = null
if (!gesture.active) return
releaseCapture(gesture)
suppressClickRef.current = true
window.clearTimeout(suppressTimerRef.current)
// The compatibility click lands synchronously after pointerup; anything
// later is a real tap, so the guard only needs to outlive that one event.
suppressTimerRef.current = window.setTimeout(() => { suppressClickRef.current = false }, 150)
setDrag(null)
const rect = list.getBoundingClientRect()
const inside = x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom
const geometry = unitGeometry(list, exercisesRef.current)
if (commit && inside && geometry && matchesSnapshot(gesture) && gesture.targetSlot !== gesture.sourcePosition) {
onDropRef.current(gesture.sourceIndex, gesture.targetSlot)
}
}
const indicatorTop = (geometry, gesture, slot, listRect) => {
if (slot === gesture.sourcePosition) return clamp(gesture.sourceTop - listRect.top, 0, listRect.height)
const remaining = geometry.filter(unit => unit.position !== gesture.sourcePosition)
let top
if (slot <= 0) top = remaining[0]?.top ?? gesture.sourceTop
else if (slot >= remaining.length) top = remaining.at(-1)?.bottom ?? gesture.sourceBottom
else top = (remaining[slot - 1].bottom + remaining[slot].top) / 2
return clamp(top - listRect.top, 0, listRect.height)
}
const updateDrag = (gesture, x, y, schedule = true) => {
if (gestureRef.current !== gesture || !gesture.active || !matchesSnapshot(gesture)) {
if (gestureRef.current === gesture) finish(gesture, false)
return
}
const geometry = unitGeometry(list, exercisesRef.current)
if (!geometry) { finish(gesture, false); return }
const listRect = list.getBoundingClientRect()
const remaining = geometry.filter(unit => unit.position !== gesture.sourcePosition)
const probeY = clamp(y, listRect.top, listRect.bottom)
const moved = Math.hypot(x - gesture.startX, y - gesture.startY) > ROUTINE_DRAG_SLOP
const slot = moved ? remaining.reduce((count, unit) => count + (probeY > unit.center ? 1 : 0), 0) : gesture.sourcePosition
const rawDelta = y - gesture.grabOffset - gesture.sourceTop
const deltaY = clamp(rawDelta, listRect.top - gesture.sourceTop, listRect.bottom - gesture.sourceBottom)
gesture.lastX = x; gesture.lastY = y; gesture.targetSlot = slot
setDrag({ first: gesture.sourceUnit[0], last: gesture.sourceUnit.at(-1), deltaY, indicatorTop: indicatorTop(geometry, gesture, slot, listRect) })
if (schedule && frame == null) frame = window.requestAnimationFrame(runAutoScroll)
}
function runAutoScroll() {
frame = null
const gesture = gestureRef.current
if (!gesture?.active) return
const step = autoScrollStep(gesture.scrollHost, gesture.lastY)
if (!step) return
if (gesture.scrollHost === window) window.scrollBy(0, step)
else gesture.scrollHost.scrollTop += step
updateDrag(gesture, gesture.lastX, gesture.lastY, false)
if (gestureRef.current === gesture) frame = window.requestAnimationFrame(runAutoScroll)
}
const lift = gesture => {
if (gestureRef.current !== gesture) return
if (!matchesSnapshot(gesture)) { finish(gesture, false); return }
const geometry = unitGeometry(list, exercisesRef.current)
const source = geometry?.find(unit => unit.unit.includes(gesture.sourceIndex))
if (!source) { finish(gesture, false); return }
gesture.active = true; gesture.timer = null
gesture.sourcePosition = source.position; gesture.sourceUnit = source.unit
gesture.sourceTop = source.top; gesture.sourceBottom = source.bottom
gesture.grabOffset = gesture.lastY - source.top; gesture.targetSlot = source.position
gesture.scrollHost = scrollHostFor(list)
gesture.captureTarget = gesture.downTarget
try { gesture.captureTarget.setPointerCapture?.(gesture.pointerId) } catch { /* unsupported */ }
suppressClickRef.current = true
window.clearTimeout(suppressTimerRef.current)
updateDrag(gesture, gesture.lastX, gesture.lastY)
}
const onPointerDown = event => {
// a new touch is intentional — never let the post-drop guard eat its click
suppressClickRef.current = false
window.clearTimeout(suppressTimerRef.current)
const current = gestureRef.current
if (current) {
if (event.pointerId !== current.pointerId) finish(current, false)
return
}
if (event.isPrimary === false || (event.pointerType === 'mouse' && event.button !== 0)) return
const target = event.target
if (!target?.closest || target.closest('button,a,input,textarea,select,[data-nodrag]')) return
const row = target.closest('[data-routine-row]')
if (!row || !list.contains(row)) return
const sourceIndex = Number(row.dataset.exIndex)
if (!Number.isInteger(sourceIndex)) return
const gesture = {
pointerId: event.pointerId, sourceIndex, downTarget: target,
startX: event.clientX, startY: event.clientY, lastX: event.clientX, lastY: event.clientY,
routineIdentity: routineIdentityRef.current,
listIdentity: exercisesRef.current,
snapshot: JSON.stringify(exercisesRef.current), active: false, timer: null,
}
gesture.timer = window.setTimeout(() => lift(gesture), ROUTINE_LONG_PRESS_MS)
gestureRef.current = gesture
}
const onPointerMove = event => {
const gesture = gestureRef.current
if (!gesture || event.pointerId !== gesture.pointerId) return
if (!gesture.active) {
if (Math.hypot(event.clientX - gesture.startX, event.clientY - gesture.startY) > ROUTINE_DRAG_SLOP) {
clearTimer(gesture); gestureRef.current = null
} else { gesture.lastX = event.clientX; gesture.lastY = event.clientY }
return
}
event.preventDefault()
updateDrag(gesture, event.clientX, event.clientY)
}
const onPointerUp = event => {
const gesture = gestureRef.current
if (!gesture || event.pointerId !== gesture.pointerId) return
if (gesture.active) event.preventDefault()
finish(gesture, gesture.active, event.clientX, event.clientY)
}
const onPointerCancel = event => {
const gesture = gestureRef.current
if (gesture && event.pointerId === gesture.pointerId) finish(gesture, false)
}
const onLostCapture = event => {
const gesture = gestureRef.current
if (gesture && event.pointerId === gesture.pointerId) finish(gesture, false)
}
const cancelActive = () => finish(gestureRef.current, false)
const onKeyDown = event => {
if (event.key !== 'Escape' || !gestureRef.current) return
event.preventDefault(); cancelActive()
}
const onVisibility = () => { if (document.visibilityState === 'hidden') cancelActive() }
const onContextMenu = event => { if (gestureRef.current?.active && event.target.closest?.('[data-routine-row]')) event.preventDefault() }
const onDragStart = event => { if (event.target.closest?.('[data-routine-row]')) event.preventDefault() }
// Touch: the rows keep `touch-action: pan-y` so the list still scrolls with a finger, but once
// a long-press has lifted a row the browser must not claim the vertical drag as a pan — it
// would fire pointercancel and scroll instead. preventDefault on a pointer event cannot stop
// that; only a non-passive touchmove listener can, and only while a drag is actually active.
const onTouchMove = event => { if (gestureRef.current?.active) event.preventDefault() }
document.addEventListener('pointerdown', onPointerDown)
document.addEventListener('touchmove', onTouchMove, { passive: false })
document.addEventListener('pointermove', onPointerMove, { passive: false })
document.addEventListener('pointerup', onPointerUp, { passive: false })
document.addEventListener('pointercancel', onPointerCancel)
document.addEventListener('lostpointercapture', onLostCapture)
document.addEventListener('keydown', onKeyDown)
document.addEventListener('visibilitychange', onVisibility)
list.addEventListener('contextmenu', onContextMenu)
list.addEventListener('dragstart', onDragStart)
window.addEventListener('blur', cancelActive)
return () => {
const gesture = gestureRef.current
clearTimer(gesture); clearFrame(); gestureRef.current = null
releaseCapture(gesture)
document.removeEventListener('pointerdown', onPointerDown)
document.removeEventListener('touchmove', onTouchMove)
document.removeEventListener('pointermove', onPointerMove)
document.removeEventListener('pointerup', onPointerUp)
document.removeEventListener('pointercancel', onPointerCancel)
document.removeEventListener('lostpointercapture', onLostCapture)
document.removeEventListener('keydown', onKeyDown)
document.removeEventListener('visibilitychange', onVisibility)
list.removeEventListener('contextmenu', onContextMenu)
list.removeEventListener('dragstart', onDragStart)
window.removeEventListener('blur', cancelActive)
}
}, [hasRows, routineIdentity, exercises])
const onClickCapture = event => {
if (!suppressClickRef.current) return
suppressClickRef.current = false
window.clearTimeout(suppressTimerRef.current)
event.preventDefault(); event.stopPropagation()
}
return { listRef, drag, onClickCapture }
}
export default function RoutineEdit() {
const nav = useNavigate()
const { id } = useParams()
@@ -26,10 +311,21 @@ export default function RoutineEdit() {
// auto-backup on the way out (not per keystroke) covers the whole editing session, deletion
// included: this still unmounts after the delete button navigates away.
useEffect(() => () => useStore.getState().autoBackupNow(), [])
if (!r) return null
const edit = fn => update(s => { fn(s.routines.find(x => x.id === id).ex) })
const move = (i, dir) => edit(ex => { const j = i + dir; if (j < 0 || j >= ex.length) return;[ex[i], ex[j]] = [ex[j], ex[i]]; cleanupSg(ex) })
const reorder = useRoutineReorder(r, r?.ex || [], (sourceIndex, targetSlot) => {
edit(exercises => { reorderRoutineUnit(exercises, sourceIndex, targetSlot) })
})
if (!r) return null
const move = (i, dir) => {
// Guard before update so a stale/boundary activation cannot trigger persistence or cleanup.
if (!moveSupersetUnit(r.ex, i, dir)) return
edit(ex => {
const reordered = moveSupersetUnit(ex, i, dir)
if (!reordered) return
ex.splice(0, ex.length, ...reordered)
cleanupSg(ex)
})
}
const toggleLink = i => edit(ex => {
if (i < 1) return
const cur = ex[i], prev = ex[i - 1]
@@ -39,6 +335,7 @@ export default function RoutineEdit() {
})
const units = supersetUnits(r.ex)
const unitIndex = new Map(units.flatMap((unit, index) => unit.map(i => [i, index])))
const unitFirst = new Set(units.filter(u => u.length > 1).map(u => u[0]))
const inSS = new Set(units.filter(u => u.length > 1).flat())
const profile = activeProfile(S)
@@ -58,9 +355,19 @@ export default function RoutineEdit() {
<SelectRow icon="chartLine" title={t('Progression')} sheetTitle={t('Progression')}
value={r.prog || 'linear'} onChange={v => update(s => { s.routines.find(x => x.id === id).prog = v })}
options={POLICIES_FOR.reps.map(p => ({ value: p, label: t(POLICY_NAME[p]), subtitle: t(POLICY_DESC[p]) }))} />
<Row icon="pause" iconTint="var(--orange)" title={t('Exclude from automatic progression')}
subtitle={t('Use for planned deloads. Workouts stay in history and statistics.')}>
<Switch checked={r.excludeFromProgression === true} onChange={v => update(s => {
const routine = s.routines.find(x => x.id === id)
if (v) routine.excludeFromProgression = true
else delete routine.excludeFromProgression
})} />
</Row>
</div>
<div className="small dim" style={{ margin: '-10px 2px 16px' }}>
{t('Applies to every exercise in this routine that does not set its own rule.')}
{r.excludeFromProgression
? t('The next regular target continues from the last included workout.')
: t('Applies to every exercise in this routine that does not set its own rule.')}
</div>
{missingCount > 0 && <div className="card" style={{ marginBottom: 16, borderColor: 'var(--orange)' }}>
@@ -70,13 +377,17 @@ export default function RoutineEdit() {
</div>
</div>}
{r.ex.length ? <div className="list">{r.ex.map((e, i) => {
{r.ex.length ? <div ref={reorder.listRef} onClickCapture={reorder.onClickCapture}
className={'list routine-list' + (reorder.drag ? ' is-reordering' : '')}>{r.ex.map((e, i) => {
// An unresolvable id is shown rather than skipped — hiding it left an entry you
// could neither see nor delete, but that still turned up in the workout.
const ex = exOr(e.id)
const noEquip = profile && !exAvailable(S, ex)
const linkedPrev = i > 0 && e.sg && r.ex[i - 1].sg === e.sg
return <div key={i}>
const isDragging = reorder.drag && i >= reorder.drag.first && i <= reorder.drag.last
return <div key={i} data-routine-row data-ex-index={i}
className={'routine-drag-row' + (isDragging ? ' is-dragging' : '')}
style={isDragging ? { transform: `translate3d(0, ${reorder.drag.deltaY}px, 0)` } : undefined}>
{unitFirst.has(i) && <div className="ss-label"><Icon name="link" />{t('Superset')}</div>}
<div className={'item' + (inSS.has(i) ? ' in-ss' : '')} onClick={() => {
exConfigSheet(ex, e, cfg => edit(x => { x[i] = { id: x[i].id, sg: x[i].sg, ...cfg } }), () => edit(x => { x.splice(i, 1); cleanupSg(x) }), r)
@@ -88,13 +399,14 @@ export default function RoutineEdit() {
<div style={{ display: 'flex', flexDirection: 'column', gap: 2, flex: 'none', alignItems: 'center' }}>
{i > 0 && <button className={'iconbtn' + (linkedPrev ? ' on-ss' : '')} title={t('Superset with exercise above')} style={{ width: 32, height: 28, borderRadius: 8, fontSize: 15 }} onClick={ev => { ev.stopPropagation(); toggleLink(i) }}><Icon name="link" /></button>}
<div style={{ display: 'flex', gap: 2 }}>
<button className="iconbtn" aria-label="Move up" style={{ width: 28, height: 24, borderRadius: 7, fontSize: 12 }} onClick={ev => { ev.stopPropagation(); move(i, -1) }}><Icon name="chevronUp" /></button>
<button className="iconbtn" aria-label="Move down" style={{ width: 28, height: 24, borderRadius: 7, fontSize: 12 }} onClick={ev => { ev.stopPropagation(); move(i, 1) }}><Icon name="chevronDown" /></button>
<button className="iconbtn" aria-label={t('Move up')} title={t('Move up')} disabled={unitIndex.get(i) === 0} style={{ width: 28, height: 24, borderRadius: 7, fontSize: 12 }} onClick={ev => { ev.stopPropagation(); move(i, -1) }}><Icon name="chevronUp" /></button>
<button className="iconbtn" aria-label={t('Move down')} title={t('Move down')} disabled={unitIndex.get(i) === units.length - 1} style={{ width: 28, height: 24, borderRadius: 7, fontSize: 12 }} onClick={ev => { ev.stopPropagation(); move(i, 1) }}><Icon name="chevronDown" /></button>
</div>
</div>
</div>
</div>
})}</div> : <div className="empty"><div className="ico"><Icon name="dumbbell" /></div>{t('No exercises yet — add your first one.')}</div>}
})}{reorder.drag && <div className="routine-drop-indicator" data-testid="routine-drop-indicator"
aria-hidden="true" style={{ top: `${reorder.drag.indicatorTop}px` }} />}</div> : <div className="empty"><div className="ico"><Icon name="dumbbell" /></div>{t('No exercises yet — add your first one.')}</div>}
{/* Coverage of the routine as planned, so a gap shows up while you're building it
rather than after a month of training around it. */}
@@ -0,0 +1,226 @@
// @vitest-environment happy-dom
import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
import React, { act } from 'react'
import { LANGS } from '../lib/i18n-core.js'
import { createRoot } from 'react-dom/client'
import { MemoryRouter, Route, Routes } from 'react-router-dom'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import RoutineEdit from './RoutineEdit.jsx'
import { DEF, useStore } from '../store/useStore.js'
import { _setLangState } from '../lib/i18n-core.js'
import de from '../locales/de.js'
import { buildPlanBundle, parsePlan } from '../lib/plan-share.js'
const cssSource = readFileSync(resolve(process.cwd(), 'src/index.css'), 'utf8')
const mocks = vi.hoisted(() => ({ exConfigSheet: vi.fn() }))
vi.mock('../lib/api.js', () => ({ api: vi.fn(() => Promise.resolve({})) }))
vi.mock('../sheets.jsx', () => ({
glyphPicker: vi.fn(), exercisePicker: vi.fn(), exConfigSheet: mocks.exConfigSheet, confirmSheet: vi.fn()
}))
vi.mock('../components/Media.jsx', () => ({ Thumb: () => null }))
vi.mock('../components/BodyMap.jsx', () => ({ default: () => null }))
globalThis.IS_REACT_ACT_ENVIRONMENT = true
const clone = value => JSON.parse(JSON.stringify(value))
const custom = id => ({ id, n: id, bp: 'chest', eq: 'body weight', tg: 'chest', custom: true })
const entry = (id, setup, sg) => ({
id, sets: 3, reps: 5, weight: setup, note: `setup-${setup}`,
...(sg ? { sg } : {})
})
let root
let container
function setRoutine(ex) {
const S = clone(DEF)
S.routines = [{ id: 'r1', name: 'Move test', emoji: 'dumbbell', ex }]
S.customEx = ['c1', 'c2', 'c3', 'c4'].map(custom)
useStore.setState({ S, user: null })
}
function renderRoutine() {
container = document.createElement('div')
document.body.appendChild(container)
root = createRoot(container)
act(() => root.render(
<MemoryRouter initialEntries={['/routine/r1']}>
<Routes><Route path="/routine/:id" element={<RoutineEdit />} /></Routes>
</MemoryRouter>
))
}
function itemFor(name) {
return [...container.querySelectorAll('.item')].find(item => item.textContent.includes(name))
}
function moveButton(name, direction) {
return itemFor(name).querySelector(`button[aria-label="${direction}"]`)
}
function pointerActivateArea(button) {
// Model browser hit-testing: pointer-events:none removes the disabled button
// from the target chain, exposing the clickable routine row underneath.
const disabledRule = cssSource.match(/\.iconbtn:disabled\s*\{[^}]*\}/)?.[0] || ''
const target = /pointer-events\s*:\s*none/.test(disabledRule)
? button.closest('.item')
: button
act(() => {
target.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true }))
target.dispatchEvent(new PointerEvent('pointerup', { bubbles: true }))
if (!(target instanceof HTMLButtonElement && target.disabled)) {
target.dispatchEvent(new MouseEvent('click', { bubbles: true }))
}
})
}
beforeEach(() => {
localStorage.clear()
mocks.exConfigSheet.mockClear()
_setLangState('en', null, null, null)
root = null
container = null
})
afterEach(() => {
if (root) act(() => root.unmount())
if (container) container.remove()
_setLangState('en', null, null, null)
})
describe('routine move controls', () => {
it('moves a selected superset member as one contiguous unit and persists complete occurrences', () => {
setRoutine([
entry('c1', 10, 'g'),
entry('c2', 20, 'g'),
entry('c3', 30)
])
renderRoutine()
act(() => moveButton('setup-20', 'Move down').click())
const moved = useStore.getState().S.routines[0].ex
expect(moved).toEqual([
entry('c3', 30),
entry('c1', 10, 'g'),
entry('c2', 20, 'g')
])
expect(JSON.parse(localStorage.getItem('gym_state_v1')).routines[0].ex).toEqual(moved)
})
it('moves the selected duplicate occurrence without aliasing its configuration', () => {
setRoutine([
entry('c1', 10),
entry('c2', 20),
entry('c1', 30)
])
renderRoutine()
act(() => moveButton('setup-30', 'Move up').click())
expect(useStore.getState().S.routines[0].ex).toEqual([
entry('c1', 10),
entry('c1', 30),
entry('c2', 20)
])
})
it('moves a standalone occurrence down with every configuration field intact', () => {
const selected = {
...entry('c1', 10),
mode: 'reps', prog: 'double', repsMin: 4, repsMax: 12,
side: true, warmupSets: 2,
intensifier: { type: 'restpause', pauseSec: 20 }
}
setRoutine([selected, entry('c2', 20), entry('c3', 30)])
renderRoutine()
act(() => moveButton('setup-10', 'Move down').click())
expect(useStore.getState().S.routines[0].ex).toEqual([
entry('c2', 20), selected, entry('c3', 30)
])
})
it('disables unit-boundary directions without cleaning or persisting state', () => {
setRoutine([
entry('c1', 10, 'orphan'),
entry('c2', 20)
])
renderRoutine()
const before = useStore.getState().S
expect(moveButton('c1', 'Move up').disabled).toBe(true)
expect(moveButton('c2', 'Move down').disabled).toBe(true)
act(() => moveButton('c1', 'Move up').click())
expect(useStore.getState().S).toBe(before)
expect(useStore.getState().S.routines[0].ex[0].sg).toBe('orphan')
expect(localStorage.getItem('gym_state_v1')).toBeNull()
})
it('keeps pointer activation in both disabled boundary areas isolated from the routine row', () => {
setRoutine([
entry('c1', 10, 'orphan'),
entry('c2', 20)
])
renderRoutine()
const before = useStore.getState().S
const firstUp = moveButton('c1', 'Move up')
const lastDown = moveButton('c2', 'Move down')
expect(firstUp.disabled).toBe(true)
expect(lastDown.disabled).toBe(true)
pointerActivateArea(firstUp)
pointerActivateArea(lastDown)
expect(mocks.exConfigSheet).not.toHaveBeenCalled()
expect(useStore.getState().S).toBe(before)
expect(useStore.getState().S.routines[0].ex[0].sg).toBe('orphan')
expect(localStorage.getItem('gym_state_v1')).toBeNull()
})
it('uses localized accessible names and titles, retains button focus, and does not open config', () => {
_setLangState('de', de, null, null)
setRoutine([entry('c1', 10), entry('c2', 20)])
renderRoutine()
const button = moveButton('c2', 'Nach oben')
expect(button.title).toBe('Nach oben')
button.focus()
act(() => button.click())
expect(document.activeElement?.tagName).toBe('BUTTON')
expect(mocks.exConfigSheet).not.toHaveBeenCalled()
})
it('retains reordered occurrence order and grouping through plan export and import', () => {
setRoutine([
entry('c1', 10, 'g'),
entry('c2', 20, 'g'),
entry('c3', 30)
])
renderRoutine()
act(() => moveButton('setup-10', 'Move down').click())
const parsed = parsePlan(JSON.stringify(buildPlanBundle(useStore.getState().S, 'Move test')))
expect(parsed.routines[0].ex).toEqual([
entry('c3', 30),
entry('c1', 10, 'g'),
entry('c2', 20, 'g')
])
})
})
describe('routine move-control locale coverage', () => {
const packs = import.meta.glob('../locales/*.js', { eager: true, import: 'default' })
it('defines both accessible names in every non-English locale pack', () => {
expect(Object.keys(packs)).toHaveLength(Object.keys(LANGS).length - 1)
Object.entries(packs).forEach(([path, pack]) => {
expect(pack, `${path} is missing Move up`).toHaveProperty('Move up')
expect(pack, `${path} is missing Move down`).toHaveProperty('Move down')
})
})
})
@@ -0,0 +1,90 @@
// @vitest-environment happy-dom
import React, { act } from 'react'
import { createRoot } from 'react-dom/client'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import Settings from './Settings.jsx'
globalThis.IS_REACT_ACT_ENVIRONMENT = true
const mocks = vi.hoisted(() => {
const state = { S: null }
state.snapshot = () => ({
S: state.S,
user: null,
update: mut => {
const next = structuredClone(state.S)
mut(next)
state.S = next
},
replaceState: vi.fn(), setUser: vi.fn(), pullState: vi.fn(), pushState: vi.fn(),
signOut: vi.fn(), signOutAll: vi.fn(), resetDemo: vi.fn(), disconnectServer: vi.fn(),
})
return state
})
vi.mock('../store/useStore.js', () => {
const useStore = selector => selector ? selector(mocks.snapshot()) : mocks.snapshot()
useStore.getState = mocks.snapshot
return { useStore, DEF: { reminder: { time: '17:30' } }, hasData: () => false }
})
vi.mock('../store/useUI.js', () => {
const snap = () => ({ toast: vi.fn(), openSheet: vi.fn() })
const useUI = selector => selector ? selector(snap()) : snap()
useUI.getState = snap
return { useUI }
})
vi.mock('react-router-dom', () => ({ useNavigate: () => () => {} }))
vi.mock('../lib/api.js', () => ({
api: vi.fn(), webauthnOK: () => false, passkeyLogin: vi.fn(), passkeyRegister: vi.fn(), IS_ANDROID: false,
}))
vi.mock('../lib/push.js', () => ({ pushSupported: () => false, enablePush: vi.fn(), disablePush: vi.fn(), sendTestPush: vi.fn() }))
vi.mock('../lib/wakelock.js', () => ({ wakeLockSupported: () => false }))
vi.mock('../lib/mobile.js', () => ({ MOBILE: false, shareExport: vi.fn(), syncReminder: vi.fn() }))
vi.mock('./MobileOnboarding.jsx', () => ({ ConnectSheet: () => null }))
vi.mock('../sheets.jsx', () => ({
loadStarterPlan: vi.fn(), confirmSheet: vi.fn(), importFromApp: vi.fn(),
importFromHevy: vi.fn(), equipmentProfileSheet: vi.fn(),
}))
// The Settings view reads the build-time version constant at render time.
globalThis.__APP_VERSION__ ??= 'test'
let host, root
beforeEach(() => {
mocks.S = {
unit: 'kg', restSec: 90, restPauseSec: 15, sound: false, effort: 'none',
gifSize: 'full', workouts: [], routines: [], exWeights: {},
}
host = document.createElement('div')
document.body.appendChild(host)
root = createRoot(host)
})
afterEach(() => {
act(() => root.unmount())
host.remove()
})
const mount = () => act(() => root.render(<Settings />))
const segButton = label => [...host.querySelectorAll('.seg button')].find(b => b.textContent === label)
describe('Settings — exercise animations', () => {
it('offers Full / Small / Hidden and writes gifSize to the store', () => {
mount()
expect(segButton('Full')).toBeTruthy()
expect(segButton('Small')).toBeTruthy()
expect(segButton('Hidden')).toBeTruthy()
expect(segButton('Full').getAttribute('aria-pressed')).toBe('true')
act(() => { segButton('Hidden').click() })
expect(mocks.S.gifSize).toBe('off')
mount()
expect(segButton('Hidden').getAttribute('aria-pressed')).toBe('true')
act(() => { segButton('Small').click() })
expect(mocks.S.gifSize).toBe('mini')
})
it('shows a legacy/absent value as Full', () => {
delete mocks.S.gifSize
mount()
expect(segButton('Full').getAttribute('aria-pressed')).toBe('true')
expect(segButton('Hidden').getAttribute('aria-pressed')).toBe('false')
})
})
+24 -2
View File
@@ -2,7 +2,7 @@ import { useEffect, useRef, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useStore, DEF, hasData } from '../store/useStore.js'
import { useUI } from '../store/useUI.js'
import { ACCENTS, todayISO, localTZ } from '../lib/format.js'
import { ACCENTS, todayISO, localTZ, weekStartOf, MONDAY, SUNDAY } from '../lib/format.js'
import { effortOf } from '../lib/history.js'
import { api, webauthnOK, passkeyLogin, passkeyRegister, IS_ANDROID } from '../lib/api.js'
import { pushSupported, enablePush, disablePush, sendTestPush } from '../lib/push.js'
@@ -11,7 +11,7 @@ import { t, LANGS, INSTR_LANGS } from '../lib/i18n.js'
import { DEMO, REPO } from '../lib/demo.js'
import { MOBILE, shareExport, syncReminder } from '../lib/mobile.js'
import { ConnectSheet } from './MobileOnboarding.jsx'
import { loadStarterPlan, confirmSheet, importFromApp, equipmentProfileSheet } from '../sheets.jsx'
import { loadStarterPlan, confirmSheet, importFromApp, importFromHevy, equipmentProfileSheet } from '../sheets.jsx'
import Icon from '../components/Icon.jsx'
import { Section, Row, SelectRow, Switch, Segmented, Button, TextField } from '../components/ui.jsx'
@@ -133,6 +133,13 @@ export default function Settings() {
options={[{ value: 'kg', label: 'kg' }, { value: 'lb', label: 'lb' }]}
value={S.unit} onChange={v => update(s => { s.unit = v })} />
</Row>
{/* Monday or Sunday — the Plan list, the Home strip, the calendar grid and every
"this week" total follow it. Stored as a getDay() index (see lib/format.js). */}
<Row icon="calendar" iconTint="var(--orange)" title={t('Week starts on')}>
<Segmented className="seg-inline"
options={[{ value: MONDAY, label: t('Monday') }, { value: SUNDAY, label: t('Sunday') }]}
value={weekStartOf(S)} onChange={v => update(s => { s.weekStart = v })} />
</Row>
</Section>
{/* ---------- during a workout ---------- */}
@@ -153,9 +160,21 @@ export default function Settings() {
onChange={v => update(s => { s.keepAwake = v })} />
</Row>
)}
{/* 'full'/'mini' is also what the tap-toggle on the workout animation writes; 'off' hides
workout media entirely (library, detail sheet and picker thumbs are unaffected).
Legacy/unknown values read as 'full'. */}
<Row icon="figureRun" iconTint="var(--green)" title={t('Exercise animations')}>
<Segmented className="seg-inline"
options={[{ value: 'full', label: t('Full') }, { value: 'mini', label: t('Small') }, { value: 'off', label: t('Hidden') }]}
value={S.gifSize === 'mini' || S.gifSize === 'off' ? S.gifSize : 'full'}
onChange={v => update(s => { s.gifSize = v })} />
</Row>
<Row icon="bell" iconTint="var(--pink)" title={t('Sounds')}>
<Switch checked={!!S.sound} onChange={v => update(s => { s.sound = v })} />
</Row>
<Row icon="sun" iconTint="var(--yellow)" title={t('Flash screen when timer ends')}>
<Switch checked={!!S.timerFlash} onChange={v => update(s => { s.timerFlash = v })} />
</Row>
{/* Two names for the same judgement, so the column asks in the scale you already think in.
The (i) sits before the control — you read it on the way to the choice, not after it. */}
<Row icon="target" iconTint="var(--purple)" title={t('Effort per set')}>
@@ -211,6 +230,9 @@ export default function Settings() {
<Row icon="shuffle" iconTint="var(--teal)" title={t('Import from another app')}
subtitle={t('FitNotes, Strong, Hevy — or body weight from Apple Health')}
accessory="chevron" onClick={() => importRef.current.click()} />
<Row icon="key" iconTint="var(--teal)" title={t('Import from Hevy')}
subtitle={t('Pull your history with a Hevy Pro API key')}
accessory="chevron" onClick={importFromHevy} />
<Row icon="upload" iconTint="var(--blue)" title={t('Import backup')} accessory="chevron" onClick={() => fileRef.current.click()} />
<Row icon="download" iconTint="var(--blue)" title={t('Export backup (JSON)')} accessory="chevron" onClick={doExport} />
{MOBILE && <Row icon="history" iconTint="var(--blue)" title={t('Auto-backup on changes')}
+45 -10
View File
@@ -1,16 +1,16 @@
import { useEffect, useMemo, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useStore } from '../store/useStore.js'
import { EXIDX } from '../lib/exercises.js'
import { EXIDX, matchExercise } from '../lib/exercises.js'
import { lastBW, streakWeeks, setLabel, modeOf, effortOf, metricModeForEntry, metricRowsForEntry, bestWeightForEntry } from '../lib/history.js'
import { fmtNum, fmtDate, fmtVol, todayISO, weekKey } from '../lib/format.js'
import { fmtNum, fmtDate, fmtVol, todayISO, weekStartOf } from '../lib/format.js'
import { t, exerciseNameFor, getLang } from '../lib/i18n.js'
import { bwSheet, goalSheet, calendarSheet, workoutDetailSheet, WorkoutRow, bwDeltaColor } from '../sheets.jsx'
import LineChart from '../components/LineChart.jsx'
import Heatmap from '../components/Heatmap.jsx'
import Icon from '../components/Icon.jsx'
import BodyMap, { BodyMapLegend } from '../components/BodyMap.jsx'
import { loadOfWorkouts, rankOf, MUSCLE_NAME, musclesOf } from '../lib/muscles.js'
import { loadOfWorkouts, muscleBalanceWindow, rankOf, MUSCLE_NAME, musclesOf } from '../lib/muscles.js'
import { fatigueOf, strengthOf, STRENGTH_FLOOR, LB_TO_KG } from '../lib/recovery.js'
import { strengthExerciseRowsForMuscle } from '../lib/strength-exercises.js'
import { fatigueStateOf } from '../lib/recovery-view.js'
@@ -20,6 +20,7 @@ import {
effortHistogram, isHardSet, HARD_RIR
} from '../lib/effort.js'
import { Button, Segmented, SelectRow } from '../components/ui.jsx'
import { tappable } from '../lib/use-sheet-keyboard.js'
import { isWarmupRow } from '../lib/workout-model.js'
// Which muscles the training in a window actually hit — and, the point of the card,
@@ -122,10 +123,7 @@ function MuscleBalance({ S }) {
return t('Weeks since training: {0}', weeks)
}
const toggleSel = m => setSel(s => (s === m ? null : m))
const inWin = S.workouts.filter(w =>
win === 0 ? true
: win === 7 ? weekKey(w.d) === weekKey(todayISO())
: (w.start || new Date(w.d).getTime()) > now - win * 86400000)
const inWin = muscleBalanceWindow(S.workouts, win, now, todayISO(), weekStartOf(S))
// Counting only the sets taken near failure turns the map from "where did the volume go"
// into "where did the stimulus go" — a muscle can lead on sets and still never be trained
// hard. Offered only when the window holds ratings at all, since with none the hard map
@@ -192,7 +190,7 @@ function MuscleBalance({ S }) {
{sel && <>
<h4 className="sec" style={{ marginTop: 14 }}>{t('Exercises')} · {t(MUSCLE_NAME[sel])}</h4>
{muscleExercises.length ? muscleExercises.map(row => (
<div key={row.id} className="mrow" style={{ minHeight: 48, alignItems: 'stretch', cursor: 'pointer' }} onClick={() => onExercise && onExercise(row.id)}>
<div key={row.id} className="mrow" style={{ minHeight: 48, alignItems: 'stretch', cursor: 'pointer' }} {...tappable(() => onExercise && onExercise(row.id))}>
<span className="nm" style={{ whiteSpace: 'normal', lineHeight: 1.35, display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
<span style={{ display: 'block', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{row.name}
@@ -291,7 +289,38 @@ export default function Stats() {
const workouts = S.workouts
const monthW = workouts.filter(w => String(w.d || '').slice(0, 7) === todayISO().slice(0, 7)).length
const nameOf = id => EXIDX[id] ? exerciseNameFor(EXIDX[id]) : (workouts.flatMap(w => w.entries).find(e => e.id === id)?.n || id)
const entryOf = id => workouts.flatMap(w => w.entries).find(e => e.id === id)
const listOf = value => Array.isArray(value) ? value : value == null || value === '' ? [] : [value]
const firstAvailable = (...values) => {
for (const value of values) {
const list = listOf(value)
if (list.length) return list
}
return []
}
const nameOf = id => {
if (EXIDX[id]) return exerciseNameFor(EXIDX[id])
const entry = entryOf(id)
return entry?.muscleSnapshot?.n || entry?.n || id
}
const matcherOf = id => {
if (EXIDX[id]) return EXIDX[id]
const entry = entryOf(id)
const snapshot = entry?.muscleSnapshot || {}
const primaries = firstAvailable(snapshot.primaries, entry?.primaries)
const secondaries = firstAvailable(
snapshot.sm, snapshot.secondaries, snapshot.muscleGroups,
entry?.sm, entry?.secondaries, entry?.muscleGroups,
)
return {
n: snapshot.n || entry?.n || id,
bp: snapshot.bp || entry?.bp || '',
tg: primaries[0] || snapshot.tg || entry?.tg || '',
sm: secondaries,
eq: snapshot.eq || entry?.eq || '',
desc: snapshot.desc || entry?.desc || '',
}
}
const currentOf = id => {
for (let i = workouts.length - 1; i >= 0; i--) {
const en = workouts[i].entries.find(e => e.id === id)
@@ -428,7 +457,13 @@ export default function Stats() {
{exHist.length ? <>
<div className="sect-b" style={{ marginBottom: 10 }}>
<SelectRow title={t('Exercise')} sheetTitle={t('Exercise progress')} value={curEx} onChange={setExId} stackedValue
options={exHist.map(id => ({ value: id, label: nameOf(id) + (exCurrent[id].mx ? ' ' + '—' + ' ' + fmtNum(exCurrent[id].mx) + ' ' + exCurrent[id].unit : '') }))} />
options={exHist.map(id => ({ value: id, label: nameOf(id) + (exCurrent[id].mx ? ' ' + '—' + ' ' + fmtNum(exCurrent[id].mx) + ' ' + exCurrent[id].unit : '') }))}
search={{
placeholder: t('Search…'),
label: t('Search…'),
emptyLabel: t('No match'),
match: (option, query) => matchExercise(matcherOf(option.value), query),
}} />
</div>
{exOpts.length > 1 && <Segmented className="seg-range" value={onEff ? 'effort' : onE1 ? 'e1rm' : 'top'} onChange={setExMetric} options={exOpts} />}
<div className="chart">
+108 -1
View File
@@ -1,15 +1,21 @@
// @vitest-environment happy-dom
import React, { act } from 'react'
import { createRoot } from 'react-dom/client'
import { Window } from 'happy-dom'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { EXIDX } from '../lib/exercises.js'
import { MUSCLES, levelsOf } from '../lib/muscles.js'
import { FATIGUE_STATES, STRENGTH_FLOOR } from '../lib/recovery.js'
import { fatigueStateOf } from '../lib/recovery-view.js'
import Stats from './Stats.jsx'
import Modals from '../components/Modals.jsx'
import { bindUI } from '../components/ui.jsx'
import { useUI } from '../store/useUI.js'
const DAY = 86400000
const HOUR = 3600000
const BASE_NOW = Date.UTC(2026, 0, 22, 12)
const LEGACY_SNAPSHOT_ID = 'legacy-snapshot-only'
const mocks = vi.hoisted(() => ({
maps: [],
@@ -50,6 +56,8 @@ vi.mock('../components/BodyMap.jsx', () => ({
BodyMapLegend: () => React.createElement('div', { 'data-balance-legend': true }),
}))
bindUI(useUI)
let dom
let root
let container
@@ -105,19 +113,43 @@ function allSubfullWorkout(now = BASE_NOW) {
return workout('all-subfull', now - 15 * DAY, [entry('1254', [set(true)])])
}
function exercisePickerWorkouts(now = BASE_NOW) {
return [
workout('bench', now, [entry('0025', [set(true, { w: 80 })])]),
workout('squat', now - DAY, [entry('0043', [set(true, { w: 60 })])]),
workout('legacy', now - 2 * DAY, [
{
id: LEGACY_SNAPSHOT_ID,
muscleSnapshot: {
n: 'Legacy shoulder press',
bp: 'shoulders',
primaries: ['deltoids'],
secondaries: ['triceps'],
muscleGroups: ['deltoids', 'triceps'],
},
sets: [set(true, { w: 50 })],
},
]),
]
}
function resetFixture(workouts = lifecycleWorkouts()) {
mocks.S.unit = 'kg'
mocks.S.bodyweight = []
mocks.S.workouts = workouts
mocks.maps.length = 0
mocks.mapMounts = 0
useUI.setState({ sheets: [] })
}
function installDom() {
dom = new Window({ url: 'http://localhost/' })
dom.scrollTo = vi.fn()
globalThis.window = dom
globalThis.document = dom.document
Object.defineProperty(globalThis, 'navigator', { configurable: true, value: dom.navigator })
Object.defineProperty(globalThis, 'location', { configurable: true, value: dom.location })
Object.defineProperty(globalThis, 'history', { configurable: true, value: dom.history })
for (const key of ['HTMLElement', 'HTMLIFrameElement', 'Node', 'Element', 'Event', 'MouseEvent']) {
globalThis[key] = dom[key]
}
@@ -129,7 +161,7 @@ function installDom() {
async function mountStats() {
installDom()
await act(async () => { root.render(React.createElement(Stats)) })
await act(async () => { root.render(React.createElement(React.Fragment, null, React.createElement(Stats), React.createElement(Modals))) })
}
async function unmountStats() {
@@ -179,6 +211,7 @@ beforeEach(() => {
afterEach(async () => {
await unmountStats()
useUI.setState({ sheets: [] })
vi.useRealTimers()
vi.restoreAllMocks()
})
@@ -272,3 +305,77 @@ describe('Stats muscle recovery view runtime', () => {
expect(strengthMap.thresholds.at(-1)).toEqual({ at: 1, level: 4 })
})
})
describe('Stats exercise progress picker', () => {
it('filters with the shared exercise matcher and still selects from the mounted sheet', async () => {
resetFixture(exercisePickerWorkouts())
await mountStats()
expect(EXIDX[LEGACY_SNAPSHOT_ID]).toBeUndefined()
const card = [...container.querySelectorAll('.card')].find(el => el.querySelector('h2')?.textContent.trim() === 'Exercise progress')
const selector = [...card.querySelectorAll('button')].find(button => button.querySelector('.lrow-t')?.textContent.trim() === 'Exercise')
await click(selector)
const modal = document.querySelector('#modal-root')
const input = modal.querySelector('input')
expect(input).toBeTruthy()
expect(input.getAttribute('aria-label')).toBe('Search…')
expect(input.getAttribute('placeholder')).toBe('Search…')
expect(modal.querySelector('.picker-search')).toBeTruthy()
const optionButtons = () => [...modal.querySelectorAll('.sect-b button')]
const initialOptionCount = optionButtons().length
expect(initialOptionCount).toBe(3)
expect(modal.textContent).toContain('Legacy shoulder press')
expect(input.compareDocumentPosition(optionButtons()[0]) & globalThis.Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()
const setter = Object.getOwnPropertyDescriptor(input.constructor.prototype, 'value').set
const setSearch = async value => act(async () => {
setter.call(input, value)
input.dispatchEvent(new Event('input', { bubbles: true }))
input.dispatchEvent(new Event('change', { bubbles: true }))
})
// A focused search can leave a newly narrowed result below the visual viewport. The
// correction must advance the sheet's own scroll position, not the page behind it.
const sheet = modal.querySelector('.sheet')
const firstOption = optionButtons()[0]
Object.defineProperties(sheet, {
clientHeight: { configurable: true, value: 400 },
scrollHeight: { configurable: true, value: 1000 },
})
vi.spyOn(sheet, 'getBoundingClientRect').mockReturnValue({ bottom: 600 })
vi.spyOn(firstOption, 'getBoundingClientRect').mockReturnValue({ bottom: 500 })
Object.defineProperty(window, 'visualViewport', { configurable: true, value: { height: 300 } })
input.focus()
expect(sheet.style.getPropertyValue('--picker-visual-height')).toBe('300px')
expect(sheet.style.getPropertyValue('--picker-keyboard-bottom')).toBe(`${Math.max(0, window.innerHeight - 300)}px`)
await setSearch('bench')
await tick(100)
expect(sheet.scrollTop).toBeGreaterThan(0)
await setSearch('no such historical exercise')
expect(modal.textContent).toContain('No match')
expect(optionButtons()).toHaveLength(0)
await click(modal.querySelector('button[aria-label="Clear"]'))
expect(input.value).toBe('')
expect(optionButtons()).toHaveLength(initialOptionCount)
expect(modal.textContent).toContain('Legacy shoulder press')
await setSearch('legacy shoulder press shoulders deltoids triceps')
expect(optionButtons()).toHaveLength(1)
expect(optionButtons()[0].textContent).toContain('Legacy shoulder press')
await click(modal.querySelector('button[aria-label="Clear"]'))
await setSearch('squat full bárbell')
expect(modal.textContent).toContain('barbell full squat')
expect(modal.textContent).not.toContain('barbell bench press')
const matching = [...modal.querySelectorAll('button')].find(button => button.textContent.includes('barbell full squat'))
await click(matching)
expect(useUI.getState().sheets).toHaveLength(0)
expect(card.querySelector('.lrow-v').textContent).toContain('barbell full squat')
})
})
+1 -1
View File
@@ -19,7 +19,7 @@ describe('Stats mixed-entry metric contract', () => {
it('renders one clickable muscle exercise list rather than a duplicate non-clickable copy', () => {
expect((source.match(/muscleExercises\.length \? muscleExercises\.map\(row =>/g) || []).length).toBe(1)
expect(source).toContain('onClick={() => onExercise && onExercise(row.id)}')
expect(source).toContain('{...tappable(() => onExercise && onExercise(row.id))}')
})
it('uses the shared metric mode and row helpers rather than entryMode as a chart gate', () => {
+201 -39
View File
@@ -9,14 +9,20 @@ import { fmtNum, fmtDate, todayISO, exCount, DAYN } from '../lib/format.js'
import { beep, vibrate } from '../lib/sound.js'
import { t, exerciseNameFor } from '../lib/i18n.js'
import { api } from '../lib/api.js'
import { setProgressHighWater, supersetFlowStep, restAfterSet, restOnRecheck } from '../lib/supersetFlow.js'
import { insertionIndexAfterCurrentUnit, nextUnfinishedUnit, setProgressHighWater, supersetFlowStep, restAfterSet, restOnRecheck, restSecFor } from '../lib/supersetFlow.js'
import Media from '../components/Media.jsx'
import { startFlow, exercisePicker, exConfigSheet, exerciseDetailSheet, topWeightSheet, finishWorkout, workoutCompleteSheet, confirmSheet, exerciseNoteSheet, sessionNoteSheet, barWeightSheet } from '../sheets.jsx'
import { startFlow, exercisePicker, exConfigSheet, exerciseDetailSheet, topWeightSheet, finishWorkout, workoutCompleteSheet, confirmSheet, exerciseNoteSheet, sessionNoteSheet, swapActiveWorkoutExercise, barWeightSheet } from '../sheets.jsx'
import Icon from '../components/Icon.jsx'
import { Button, Check, NumberField } from '../components/ui.jsx'
import { nextPrescription, applyPrescription, defaultIncrement } 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 { canMoveActiveWorkoutUnit, moveActiveWorkoutUnit } from '../lib/active-workout-order.js'
const SWIPE_MIN_DISTANCE = 48
const SWIPE_AXIS_RATIO = 1.25
const SWIPE_IGNORED_TARGETS = 'button,input,textarea,select,a,[role="button"],[role="checkbox"],[role="switch"],[role="slider"],[contenteditable="true"],.exmedia,[data-swipe-ignore]'
/* ---------- start chooser (no active workout) ---------- */
function StartChooser() {
@@ -57,7 +63,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 }) {
function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemoveSet, onAddWarmup, onRemoveSetAt, onStartTimed, onPairPrev, onPairNext, onSetRowRef, onProgressionSettings }) {
const S = useStore(s => s.S)
const update = useStore(s => s.update)
const working = useUI(s => s.work)
@@ -107,6 +113,7 @@ function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemov
// What the progression policy decided for this session, and why (issue #17). Computed when
// the session was built so the reason matches the numbers already in the rows.
const plan = entry.plan
const guidance = progressionGuidance(plan)
// A bodyweight set has no weight to type, so the column is not there (issue #32) — one
// stepper instead of two, which is the whole point of the flag. Adding a belt weight in the
// config brings it back, now labelled as the addition it is.
@@ -208,10 +215,11 @@ function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemov
</button>
</div>
})()}
{plan && plan.why && plan.kind !== 'off' && <div className={'progline' + (plan.kind === 'deload' ? ' warn' : '')}>
{guidance && <button type="button" className={'progline' + (plan.kind === 'deload' ? ' warn' : '')}
aria-label={t('Open progression settings')} onClick={onProgressionSettings}>
<Icon name={plan.kind === 'up' ? 'arrowUp' : plan.kind === 'deload' ? 'arrowDown' : 'lightbulb'} />
<span>{t(...plan.why)}</span>
</div>}
<span><strong>{t(guidance.policyLabel)}</strong> · {t(...guidance.why)}</span>
</button>}
<div className="card" style={{ marginTop: 10, marginBottom: 0 }}>
{/* the header carries the same eff3 sizing as the rows, or the labels drift off their columns */}
<div className={'sethead' + (col3 ? ' eff3' : '')}><span className="n-sp" /><span className="w-sp">{col1.hd}</span>{col2 && <span className="r-sp">{col2.hd}</span>}{col3 && <span className="eff-sp">{col3.hd}</span>}{timed && <span className="ck-sp" />}<span className="ck-sp" /></div>
@@ -224,7 +232,7 @@ 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" />}
<div className={'setrow' + (s.done ? ' done' : '') + (col3 ? ' eff3' : '')}>
<div ref={el => onSetRowRef?.(i, el)} className={'setrow' + (s.done ? ' done' : '') + (col3 ? ' eff3' : '')}>
<div className="n">{phaseNum}</div>
{cell(s, i, col1, 'w')}
{col2 && cell(s, i, col2, 'r')}
@@ -279,6 +287,13 @@ export function removeActiveExercise(idx) {
// Clear the work callback before indexes can shift. This also protects a confirmation sheet
// that was opened first and confirmed after a timed hold started.
useUI.getState().stopWork()
// A rest countdown belongs to the exercise whose set started it (timer.forIdx). Removing that
// exercise ends the rest — there is nothing left to rest for. Removing any other exercise
// keeps the countdown and only re-points it, so a pause you are in the middle of survives
// tidying up the list.
const rest = useUI.getState().timer
if (rest && rest.forIdx === idx) useUI.getState().stopRest()
else useUI.getState().shiftRestOwner(idx + 1, -1)
useStore.getState().update(s => {
if (!s.active || !Array.isArray(s.active.entries)) return
if (idx < 0 || idx >= s.active.entries.length) return
@@ -293,16 +308,41 @@ function ActiveWorkout() {
const nav = useNavigate()
const S = useStore(s => s.S)
const update = useStore(s => s.update)
const { startRest, stopRest, 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 = Math.min(A.cur, Math.max(0, A.entries.length - 1))
const cur = Number.isInteger(A.cur)
? Math.min(Math.max(A.cur, 0), Math.max(0, A.entries.length - 1))
: 0
const unit = A.entries.length ? unitOf(units, cur) : []
const unitIdx = units.findIndex(u => u === unit)
const isSuperset = unit.length > 1
// Superset flow: keep the active exercise in view - completing a set scrolls to the
// next exercise in the group, then back up to the first exercise of the next round.
const exRefs = useRef({})
// Superset flow: center the actionable row when completing a set moves to the partner or
// back to the first exercise of the next round. Entry-bound maps keep repeated exercise IDs
// distinct, while each rendered set index identifies the existing row within that entry.
const exRefs = useRef(new Map())
const setRefs = useRef(new Map())
const bindExRef = (entry, el) => {
if (el) exRefs.current.set(entry, el)
else {
exRefs.current.delete(entry)
setRefs.current.delete(entry)
}
}
const bindSetRef = (entry, setIdx, el) => {
let refs = setRefs.current.get(entry)
if (el) {
if (!refs) { refs = new Map(); setRefs.current.set(entry, refs) }
refs.set(setIdx, el)
} else if (refs) {
refs.delete(setIdx)
if (!refs.size) setRefs.current.delete(entry)
}
}
const swipe = useRef(null)
const progressHighWater = useRef(A.entries.map(e => e.sets.filter(s => s.done).length))
// The marks are index-keyed, and removing an exercise shifts every index above it down
// (removeActiveExercise splices). Re-baseline whenever the list length changes, otherwise a
@@ -310,10 +350,22 @@ function ActiveWorkout() {
useEffect(() => {
progressHighWater.current = A.entries.map(e => e.sets.filter(s => s.done).length)
}, [A.entries.length])
useEffect(() => {
const liveEntries = new Set(A.entries)
for (const entry of exRefs.current.keys()) {
if (!liveEntries.has(entry)) exRefs.current.delete(entry)
}
for (const entry of setRefs.current.keys()) {
if (!liveEntries.has(entry)) setRefs.current.delete(entry)
}
})
useEffect(() => {
if (!isSuperset) return
const el = exRefs.current[cur]
if (el && typeof el.scrollIntoView === 'function') el.scrollIntoView({ behavior: 'smooth', block: 'nearest' })
const entry = A.entries[cur]
const firstIncomplete = entry?.sets.findIndex(s => !s.done) ?? -1
const setIdx = firstIncomplete >= 0 ? firstIncomplete : (entry?.sets.length ?? 0) - 1
const el = (setIdx >= 0 && setRefs.current.get(entry)?.get(setIdx)) || exRefs.current.get(entry)
if (el && typeof el.scrollIntoView === 'function') el.scrollIntoView({ behavior: 'smooth', block: 'center' })
}, [cur, isSuperset, A.entries.length])
const total = A.entries.reduce((n, e) => n + e.sets.length, 0)
@@ -352,6 +404,84 @@ function ActiveWorkout() {
})
const onPairPrev = !isSuperset && cur > 0 ? () => pairAt(cur - 1, cur) : null
const onPairNext = !isSuperset && cur < A.entries.length - 1 ? () => pairAt(cur, cur + 1) : null
const moveCurrentUnit = direction => {
const ui = useUI.getState()
const active = useStore.getState().S.active
if (ui.work || !canMoveActiveWorkoutUnit(active, active?.cur, direction)) return
// Invalidate an old timed callback before indexes shift. A running rest is not cancelled:
// it belongs to an exercise (timer.forIdx), and that exercise only changes position.
ui.stopWork()
update(s => {
const moved = moveActiveWorkoutUnit(s.active, s.active?.cur, direction)
if (!moved) return
progressHighWater.current = moved.indices.map(index => progressHighWater.current[index])
const rest = useUI.getState().timer
if (rest && rest.forIdx != null) {
const forIdx = moved.indices.indexOf(rest.forIdx)
if (forIdx >= 0) useUI.setState({ timer: { ...rest, forIdx } })
}
}, true)
}
const navigateUnit = direction => {
const targetFor = active => {
if (!active || !Array.isArray(active.entries) || !Number.isInteger(active.cur)) return null
if (active.cur < 0 || active.cur >= active.entries.length) return null
const freshUnits = supersetUnits(active.entries)
const freshUnitIdx = freshUnits.findIndex(candidate => candidate.includes(active.cur))
return freshUnitIdx < 0 ? null : freshUnits[freshUnitIdx + direction]?.[0] ?? null
}
if (targetFor(useStore.getState().S.active) == null) return
update(s => {
const target = targetFor(s.active)
if (target != null) s.active.cur = target
})
}
const onSwipePointerDown = event => {
if (swipe.current || (event.pointerType && event.pointerType !== 'touch' && event.pointerType !== 'pen')) return
if (event.target.closest?.(SWIPE_IGNORED_TARGETS)) return
swipe.current = { id: event.pointerId, x: event.clientX, y: event.clientY }
event.currentTarget.setPointerCapture?.(event.pointerId)
}
const finishSwipe = (event, navigate) => {
const start = swipe.current
if (!start || start.id !== event.pointerId) return
swipe.current = null
event.currentTarget.releasePointerCapture?.(event.pointerId)
if (!navigate) return
const dx = event.clientX - start.x
const dy = event.clientY - start.y
if (Math.abs(dx) < SWIPE_MIN_DISTANCE || Math.abs(dx) < Math.abs(dy) * SWIPE_AXIS_RATIO) return
navigateUnit(dx < 0 ? 1 : -1)
}
const openProgressionSettings = idx => {
const state = useStore.getState().S
const entry = state.active?.entries?.[idx]
if (!entry) return
const routine = state.routines.find(r => r.id === state.active.routineId)
exConfigSheet(exOr(entry.id), entry.target, cfg => update(s => {
const activeEntry = s.active?.entries?.[idx]
if (!activeEntry) return
const full = { ...cfg, id: activeEntry.id }
const activeRoutine = s.routines.find(r => r.id === s.active.routineId)
const step = 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
const plan = nextPrescription(s, full, activeRoutine)
// The sheet edits sets, reps, weight and warm-ups as well as the rule — so the rows are
// rebuilt from the new config the way the session was, and only what you already logged
// is kept in place (done warm-ups first, then done work sets, then the fresh remainder).
const fresh = applyIntensifierPlan(applyPrescription(buildSets(s, full, { step }), plan, step), full)
const doneWarm = activeEntry.sets.filter(x => x.done && isWarmupRow(x))
const doneWork = activeEntry.sets.filter(x => x.done && !isWarmupRow(x))
const freshWarm = fresh.filter(isWarmupRow)
const freshWork = fresh.filter(x => !isWarmupRow(x))
activeEntry.target = { ...cfg }
activeEntry.plan = plan
activeEntry.sets = [...doneWarm, ...freshWarm.slice(doneWarm.length), ...doneWork, ...freshWork.slice(doneWork.length)]
}), null, routine)
}
// Remove a whole exercise from the session. The confirmation always asks first; in a
// superset it asks WHICH exercise of the group to remove.
@@ -400,7 +530,6 @@ function ActiveWorkout() {
const toggle = (idx, i) => {
const m = modeAt(idx)
const cardioEntry = m === 'cardio'
const isLastUnit = unitIdx >= units.length - 1
let askTop = false, exJustDone = false, workoutDone = false, checked = false
mutEntry(idx, e => {
e.sets[i].done = !e.sets[i].done
@@ -408,7 +537,7 @@ function ActiveWorkout() {
if (e.sets[i].done) {
beep(S.sound, 1040, 0.12); vibrate(30)
const unitDone = unit.every(ui => (ui === idx ? e : A.entries[ui]).sets.every(x => x.done))
if (unitDone && isLastUnit) workoutDone = true // last exercise's last set → done
if (unitDone) workoutDone = !nextUnfinishedUnit(A.entries, supersetUnits(A.entries), idx)
// Only loaded reps training has a "working weight" worth confirming — a bodyweight
// plank has nothing to put in that slider, and neither does a set of push-ups
// (issue #32: the fewest taps that still record what happened).
@@ -432,38 +561,45 @@ function ActiveWorkout() {
const freshUnits = supersetUnits(fresh.entries)
const freshUnit = freshUnits.find(u => u.includes(idx))
const freshUnitIdx = freshUnits.indexOf(freshUnit)
const freshLastUnit = freshUnitIdx >= freshUnits.length - 1
const freshUnitDone = freshUnit?.every(ui => fresh.entries[ui].sets.every(x => x.done))
const nextUnit = freshUnitDone ? nextUnfinishedUnit(fresh.entries, freshUnits, idx) : null
const freshWorkoutDone = freshUnitDone && !nextUnit
const restBeforeWarmup = nextUnit?.some(ui =>
fresh.entries[ui].sets.some(set => isWarmupRow(set) && !set.done),
)
// The rest this set has earned: the exercise's own restSec when it set one, the global
// timer when it did not, and the longest of the group's across a superset (issue #10).
// Resolved once here so every branch below times the same break.
const restSec = restSecFor(fresh.entries, freshUnit || [idx], S.restSec)
// A re-check of finished work must not navigate or reopen a sheet, but it may still owe
// you a rest — see restOnRecheck, and the other half of issue #3.
if (!progress.isNew) {
if (restOnRecheck({ timerRunning: !!useUI.getState().timer, unitDone: freshUnitDone, lastUnit: freshLastUnit })) startRest(S.restSec)
if (!restBeforeWarmup && restOnRecheck({ timerRunning: !!useUI.getState().timer, unitDone: freshUnitDone, lastUnit: freshWorkoutDone })) startRest(restSec, idx)
return
}
// Singleton units are ordinary exercises: they rest between sets and after the closing
// one, and never enter superset navigation. stopRest() first so the rest that belongs
// after this set replaces the one that was running, rather than stacking on it.
// one unless the next unit has an unfinished warm-up, and never enter superset navigation.
// stopRest() first so a rest that belongs after this set replaces the one that was running.
if (freshUnitDone) stopRest()
if (!freshUnit || freshUnit.length <= 1) {
if (restAfterSet({ unitDone: freshUnitDone, lastUnit: freshLastUnit })) startRest(S.restSec)
if (freshUnitDone && !askTop && nextUnit?.length) update(s => { if (s.active) s.active.cur = nextUnit[0] })
if (!restBeforeWarmup && restAfterSet({ unitDone: freshUnitDone, lastUnit: freshWorkoutDone })) startRest(restSec, idx)
return
}
const step = supersetFlowStep(fresh.entries, freshUnit, idx)
if (!step) return
if (step.unitDone) {
if (!freshLastUnit) {
const nextUnit = freshUnits[freshUnitIdx + 1]
if (nextUnit?.length) {
// The top-weight sheet's explicit "Just close" path owns the choice not to advance.
if (!askTop && nextUnit?.length) update(s => { if (s.active) s.active.cur = nextUnit[0] })
startRest(S.restSec)
if (!askTop) update(s => { if (s.active) s.active.cur = nextUnit[0] })
if (!restBeforeWarmup) startRest(restSec, idx)
}
} else {
if (step.nextIdx != null) update(s => { if (s.active) s.active.cur = step.nextIdx })
if (step.roundDone) startRest(S.restSec)
if (step.roundDone) startRest(restSec, idx)
}
}
}
@@ -497,35 +633,47 @@ function ActiveWorkout() {
return <div className="narrow">
<div className="hdr">
<button className="iconbtn" aria-label={t('Discard')} onClick={() => confirmSheet({ title: t('Discard workout?'), message: t('The sets you logged in this session will be lost.'), confirmText: t('Discard'), danger: true, onConfirm: () => { update(s => { s.active = null }); stopRest(); nav('/home') } })}><Icon name="xmark" /></button>
<div style={{ textAlign: 'center' }}><div style={{ fontWeight: 600 }}>{A.name}</div><div className="sub"><Elapsed start={A.start} /> · {t('{0} sets', done + '/' + total)}</div></div>
<button className="iconbtn" aria-label={t('Discard')} onClick={() => confirmSheet({ title: t('Discard workout?'), message: t('The sets you logged in this session will be lost.'), confirmText: t('Discard'), danger: true, onConfirm: () => { update(s => { s.active = null }); stopRest(); stopWork(); nav('/home') } })}><Icon name="xmark" /></button>
<div style={{ textAlign: 'center' }}><div style={{ fontWeight: 600 }}>{A.name}</div><div className="sub">{A.backfill ? fmtDate(A.d, true) : <Elapsed start={A.start} />} · {t('{0} sets', done + '/' + total)}</div></div>
<button className="iconbtn" style={{ color: 'var(--acc)' }} aria-label={t('Finish')} onClick={finishWorkout}><Icon name="check" /></button>
</div>
<div className="wprog"><i style={{ width: (total ? done / total * 100 : 0) + '%' }} /></div>
{A.backfill && <div className="muted small" style={{ marginBottom: 8 }}>{t('Logging a past workout — no rest timers.')}</div>}
{A.entries.length ? <>
<div className="muted small" style={{ marginBottom: 6 }}>{isSuperset ? t('Superset {0} / {1}', unitIdx + 1, units.length) : t('Exercise {0} / {1}', unitIdx + 1, units.length)}</div>
<div className="workout-swipe-surface" data-testid="workout-swipe-surface"
onPointerDown={onSwipePointerDown}
onPointerUp={event => finishSwipe(event, true)}
onPointerCancel={event => finishSwipe(event, false)}
onLostPointerCapture={event => {
if (swipe.current?.id === event.pointerId) swipe.current = null
}}>
{isSuperset ? (
<div className="ss-card">
<div className="ss-hd" style={{ justifyContent: 'space-between' }}>
<span className="row" style={{ gap: 5 }}><Icon name="link" />{t('Superset · do these back-to-back, rest when done')}</span>
<Button size="xs" variant="ghost" icon="link" title={t('Unpair')} onClick={() => unpairAt(cur)}>{t('Unpair')}</Button>
</div>
{unit.map((idx, k) => <div key={idx} ref={el => { exRefs.current[idx] = el }} className="ss-ex" data-exidx={idx}>
{k > 0 && <div className="ss-amp">+</div>}
<ExerciseBlock entryIdx={idx} compact
onToggle={i => toggle(idx, i)} onField={(i, f, v) => setField(idx, i, f, v)} onAddSet={() => addSet(idx)} onRemoveSet={() => removeSet(idx)} onAddWarmup={() => addWarmup(idx)} onRemoveSetAt={i => removeSetAt(idx, i)} onStartTimed={i => startTimed(idx, i)} />
</div>)}
{unit.map((idx, k) => {
const entry = A.entries[idx]
return <div key={idx} ref={el => bindExRef(entry, el)} className="ss-ex" data-exidx={idx}>
{k > 0 && <div className="ss-amp">+</div>}
<ExerciseBlock entryIdx={idx} compact onSetRowRef={(setIdx, el) => bindSetRef(entry, setIdx, el)}
onToggle={i => toggle(idx, i)} onField={(i, f, v) => setField(idx, i, f, v)} onAddSet={() => addSet(idx)} onRemoveSet={() => removeSet(idx)} onAddWarmup={() => addWarmup(idx)} onRemoveSetAt={i => removeSetAt(idx, i)} onStartTimed={i => startTimed(idx, i)} onProgressionSettings={() => openProgressionSettings(idx)} />
</div>
})}
</div>
) : (
<ExerciseBlock entryIdx={cur} onToggle={i => toggle(cur, i)} onField={(i, f, v) => setField(cur, i, f, v)} onAddSet={() => addSet(cur)} onRemoveSet={() => removeSet(cur)} onAddWarmup={() => addWarmup(cur)} onRemoveSetAt={i => removeSetAt(cur, i)} onStartTimed={i => startTimed(cur, i)} onPairPrev={onPairPrev} onPairNext={onPairNext} />
<ExerciseBlock entryIdx={cur} onToggle={i => toggle(cur, i)} onField={(i, f, v) => setField(cur, i, f, v)} onAddSet={() => addSet(cur)} onRemoveSet={() => removeSet(cur)} onAddWarmup={() => addWarmup(cur)} onRemoveSetAt={i => removeSetAt(cur, i)} onStartTimed={i => startTimed(cur, i)} onPairPrev={onPairPrev} onPairNext={onPairNext} onProgressionSettings={() => openProgressionSettings(cur)} />
)}
</div>
</> : <div className="empty"><div className="ico"><Icon name="shuffle" /></div>{t('Freestyle workout — add your first exercise.')}</div>}
<div style={{ height: 12 }} />
<div className="row">
<Button icon="chevronLeft" disabled={unitIdx <= 0} onClick={() => update(s => { s.active.cur = units[unitIdx - 1][0] })}>{t('Prev')}</Button>
<Button trailingIcon="chevronRight" disabled={unitIdx < 0 || unitIdx >= units.length - 1} onClick={() => update(s => { s.active.cur = units[unitIdx + 1][0] })}>{t('Next')}</Button>
<Button icon="chevronLeft" disabled={unitIdx <= 0} onClick={() => navigateUnit(-1)}>{t('Prev')}</Button>
<Button trailingIcon="chevronRight" disabled={unitIdx < 0 || unitIdx >= units.length - 1} onClick={() => navigateUnit(1)}>{t('Next')}</Button>
</div>
<div style={{ height: 10 }} />
<Button onClick={() => exercisePicker(ex => {
@@ -539,11 +687,25 @@ function ActiveWorkout() {
const plan = freestyle ? null : nextPrescription(s, full, s.routines.find(r => r.id === s.active.routineId))
const sets = buildSets(s, full, { step: defaultIncrement(ex.id, s.unit), ...(freestyle ? { preferLast: true } : {}) })
const progressed = freestyle ? sets : applyPrescription(sets, plan, defaultIncrement(ex.id, s.unit))
s.active.entries.push({ id: ex.id, target: { ...cfg }, plan, sets: applyIntensifierPlan(progressed, full) })
s.active.cur = s.active.entries.length - 1
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.cur = insertAt
useUI.getState().shiftRestOwner(insertAt, 1)
}), null, routine, seed)
})} icon="plus">{t('Add exercise')}</Button>
{A.entries.length > 0 && <>
<div style={{ height: 6 }} />
<div className="row">
<Button size="sm" icon="chevronUp" aria-label={t('Move up')}
disabled={!!work || !canMoveActiveWorkoutUnit(A, cur, -1)} onClick={() => moveCurrentUnit(-1)}>{t('Move up')}</Button>
<Button size="sm" trailingIcon="chevronDown" aria-label={t('Move down')}
disabled={!!work || !canMoveActiveWorkoutUnit(A, cur, 1)} onClick={() => moveCurrentUnit(1)}>{t('Move down')}</Button>
</div>
<div style={{ height: 6 }} />
<div style={{ display: 'flex', justifyContent: 'center' }}>
<Button size="sm" icon="shuffle" aria-label={t('Swap exercise')} disabled={!!work}
onClick={() => swapActiveWorkoutExercise(cur)}>{t('Swap exercise')}</Button>
</div>
<div style={{ height: 6 }} />
<div style={{ display: 'flex', justifyContent: 'center' }}>
<Button size="sm" icon="minus" style={{ color: 'var(--red)' }} disabled={!!work} onClick={removeExerciseSheet}>{t('Remove exercise')}</Button>
+123 -2
View File
@@ -6,6 +6,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import Workout, { removeActiveExercise } from './Workout.jsx'
import { DEF, useStore } from '../store/useStore.js'
import { useUI } from '../store/useUI.js'
import { LANGS } from '../lib/i18n-core.js'
vi.mock('../lib/sound.js', () => ({ beep: vi.fn(), vibrate: vi.fn() }))
vi.mock('../lib/api.js', () => ({ api: vi.fn(() => Promise.resolve({})) }))
@@ -21,6 +22,8 @@ const entry = (id, sg) => ({
let root
let container
let sheetRoot
let sheetContainer
function setActive(entries, cur = 0) {
const S = clone(DEF)
@@ -43,6 +46,18 @@ function removeButton() {
return [...container.querySelectorAll('button')].find(button => button.textContent.includes('Remove exercise'))
}
function renderTopSheet() {
if (sheetRoot) act(() => sheetRoot.unmount())
if (sheetContainer) sheetContainer.remove()
const sheet = useUI.getState().sheets.at(-1)
expect(sheet).toBeTruthy()
sheetContainer = document.createElement('div')
document.body.appendChild(sheetContainer)
sheetRoot = createRoot(sheetContainer)
act(() => sheetRoot.render(sheet.render(() => useUI.getState().closeSheet(sheet.id))))
return sheetContainer
}
beforeEach(() => {
vi.useFakeTimers()
localStorage.clear()
@@ -52,9 +67,13 @@ beforeEach(() => {
useStore.setState({ S: clone(DEF), user: null })
root = null
container = null
sheetRoot = null
sheetContainer = null
})
afterEach(() => {
if (sheetRoot) act(() => sheetRoot.unmount())
if (sheetContainer) sheetContainer.remove()
if (root) act(() => root.unmount())
if (container) container.remove()
useUI.getState().stopRest()
@@ -94,6 +113,82 @@ describe('active-session exercise removal', () => {
expect(active.entries[0].sets[0].sec).toBeUndefined()
})
it('cancels a running rest countdown when the exercise it belongs to is removed', () => {
setActive([entry('1001'), entry('1002')], 0)
useUI.getState().startRest(90, 0)
expect(useUI.getState().timer).not.toBeNull()
act(() => { removeActiveExercise(0) })
expect(useUI.getState().timer).toBeNull()
expect(useStore.getState().S.active.entries.map(e => e.id)).toEqual(['1002'])
})
it('keeps a rest countdown that belongs to another exercise, re-pointed at it', () => {
setActive([entry('1001'), entry('1002'), entry('1003')], 1)
useUI.getState().startRest(90, 1)
act(() => { removeActiveExercise(0) })
expect(useUI.getState().timer?.forIdx).toBe(0)
expect(useStore.getState().S.active.entries.map(e => e.id)).toEqual(['1002', '1003'])
act(() => { removeActiveExercise(1) })
expect(useUI.getState().timer?.forIdx).toBe(0)
expect(useStore.getState().S.active.entries.map(e => e.id)).toEqual(['1002'])
act(() => { removeActiveExercise(0) })
expect(useUI.getState().timer).toBeNull()
})
it('leaves a rest countdown without a known owner running', () => {
setActive([entry('1001'), entry('1002')], 0)
useUI.getState().startRest(90)
act(() => { removeActiveExercise(0) })
expect(useUI.getState().timer).not.toBeNull()
})
it('does not mutate before confirmation, leaves state unchanged on Cancel, and removes on Confirm', () => {
renderWorkout([entry('1001'), entry('1002')])
act(() => removeButton().click())
expect(useStore.getState().S.active.entries.map(e => e.id)).toEqual(['1001', '1002'])
let dialog = renderTopSheet()
const cancel = [...dialog.querySelectorAll('button')].find(button => button.textContent === 'Cancel')
act(() => cancel.click())
expect(useStore.getState().S.active.entries.map(e => e.id)).toEqual(['1001', '1002'])
act(() => removeButton().click())
dialog = renderTopSheet()
const confirm = [...dialog.querySelectorAll('button')].find(button => button.textContent === 'Remove')
act(() => confirm.click())
expect(useStore.getState().S.active.entries.map(e => e.id)).toEqual(['1002'])
})
it('uses the selected superset member occurrence rather than its exercise id', () => {
renderWorkout([entry('1001', 'pair'), entry('1001', 'pair'), entry('1002')])
useStore.getState().update(s => {
s.active.entries[0].target.marker = 'keep-first'
s.active.entries[1].target.marker = 'remove-second'
}, false)
act(() => removeButton().click())
const chooser = renderTopSheet()
const choices = [...chooser.querySelectorAll('.item')]
expect(choices).toHaveLength(2)
act(() => choices[1].click())
const dialog = renderTopSheet()
const confirm = [...dialog.querySelectorAll('button')].find(button => button.textContent === 'Remove')
act(() => confirm.click())
const active = useStore.getState().S.active
expect(active.entries.map(e => e.id)).toEqual(['1001', '1002'])
expect(active.entries[0].target.marker).toBe('keep-first')
expect(active.entries[0].sg).toBeUndefined()
})
it('hides the remove control for an empty freestyle session', () => {
renderWorkout([])
expect(removeButton()).toBeUndefined()
@@ -109,9 +204,13 @@ describe('remove-exercise locale coverage', () => {
'Which exercise in this superset do you want to remove?'
]
const packs = import.meta.glob('../locales/*.js', { eager: true, import: 'default' })
// Every non-English language has its own pack (English is the source, so it has none) —
// derived from LANGS rather than hardcoded so adding a language doesn't silently
// understate this test's own coverage.
const nonEnglishLangCount = Object.keys(LANGS).length - 1
it('defines every new prompt in all twelve locale packs', () => {
expect(Object.keys(packs)).toHaveLength(12)
it('defines every new prompt in every non-English locale pack', () => {
expect(Object.keys(packs)).toHaveLength(nonEnglishLangCount)
Object.entries(packs).forEach(([path, pack]) => {
required.forEach(key => expect(pack, `${path} is missing ${key}`).toHaveProperty(key))
})
@@ -143,4 +242,26 @@ describe('remove-exercise edge cases', () => {
expect(A.entries.map(e => e.id)).toEqual(['b', 'c'])
expect(A.entries[A.cur].id).toBe('c')
})
it('persists the shortened active session for reload without changing completed history', () => {
const first = entry('same')
first.target.marker = 'keep-first'
const second = entry('same')
second.target.marker = 'remove-second'
setActive([first, second, entry('other')], 1)
const workouts = [{ id: 'completed', d: '2026-08-10', entries: [{ id: 'same', sets: [{ w: 42, r: 5, done: true }] }] }]
useStore.setState(state => ({ S: { ...state.S, workouts: clone(workouts) } }))
act(() => { removeActiveExercise(1) })
const persisted = JSON.parse(localStorage.getItem('gym_state_v1'))
expect(persisted.workouts).toEqual(workouts)
expect(persisted.active.entries.map(e => e.id)).toEqual(['same', 'other'])
expect(persisted.active.entries[0].target.marker).toBe('keep-first')
expect(persisted.active.cur).toBe(1)
useStore.setState({ S: Object.assign(clone(DEF), persisted), user: null })
expect(useStore.getState().S.active.entries.map(e => e.id)).toEqual(['same', 'other'])
expect(useStore.getState().S.workouts).toEqual(workouts)
})
})
+525 -15
View File
@@ -7,21 +7,40 @@ import Workout from './Workout.jsx'
const mocks = vi.hoisted(() => {
const state = {
S: null,
timer: null,
work: null,
startRest: vi.fn(),
stopRest: vi.fn(),
stopRest: null,
stopWork: null,
confirmSheet: vi.fn(),
topWeightSheet: vi.fn(),
workoutCompleteSheet: vi.fn(),
exercisePicker: vi.fn(),
exConfigSheet: vi.fn(),
toast: vi.fn(),
scrollCalls: [],
swapActiveWorkoutExercise: vi.fn(),
}
state.stopRest = vi.fn(() => { state.timer = null })
state.stopWork = vi.fn(() => { state.work = null })
state.storeSnapshot = () => ({
S: state.S,
user: null,
update: mut => mut(state.S),
update: mut => {
const next = structuredClone(state.S)
mut(next)
state.S = next
},
})
state.uiSnapshot = () => ({
work: null,
timer: state.timer,
work: state.work,
startRest: state.startRest,
stopRest: state.stopRest,
stopWork: state.stopWork,
shiftRestOwner: vi.fn(),
startWork: vi.fn(),
toast: vi.fn(),
toast: state.toast,
})
return state
})
@@ -39,13 +58,14 @@ vi.mock('../store/useUI.js', () => {
vi.mock('react-router-dom', () => ({ useNavigate: () => () => {} }))
vi.mock('../sheets.jsx', () => ({
startFlow: vi.fn(),
exercisePicker: vi.fn(),
exConfigSheet: vi.fn(),
exercisePicker: mocks.exercisePicker,
exConfigSheet: mocks.exConfigSheet,
exerciseDetailSheet: vi.fn(),
topWeightSheet: mocks.topWeightSheet,
finishWorkout: vi.fn(),
workoutCompleteSheet: vi.fn(),
confirmSheet: vi.fn(),
workoutCompleteSheet: mocks.workoutCompleteSheet,
confirmSheet: mocks.confirmSheet,
swapActiveWorkoutExercise: mocks.swapActiveWorkoutExercise,
// Both note sheets belong here even though the tests never open one: Workout.jsx reads
// sessionNoteSheet during render, so a missing export is a render crash, not a no-op.
exerciseNoteSheet: vi.fn(),
@@ -72,11 +92,13 @@ function exercise(id, sets, extra = {}) {
}
}
function workout(entries, cur = 0) {
function workout(entries, cur = 0, overrides = {}) {
const { active: activeOverrides = {}, ...stateOverrides } = overrides
return {
unit: 'kg', restSec: 90, sound: false, effort: 'none', gifSize: 'full',
workouts: [], exWeights: {}, routines: [],
active: { id: 'active', name: 'Test workout', start: Date.now(), cur, entries },
active: { id: 'active', name: 'Test workout', start: Date.now(), cur, entries, ...activeOverrides },
...stateOverrides,
}
}
@@ -87,13 +109,16 @@ function installDom() {
globalThis.document = dom.document
Object.defineProperty(globalThis, 'navigator', { configurable: true, value: dom.navigator })
for (const key of ['HTMLElement', 'Node', 'Element', 'Event', 'Blob']) globalThis[key] = dom[key]
dom.Element.prototype.scrollIntoView = vi.fn(function (options) {
mocks.scrollCalls.push({ node: this, options })
})
globalThis.IS_REACT_ACT_ENVIRONMENT = true
container = document.getElementById('root')
root = createRoot(container)
}
async function mount(entries, cur = 0) {
mocks.S = workout(entries, cur)
async function mount(entries, cur = 0, overrides = {}) {
mocks.S = workout(entries, cur, overrides)
installDom()
await act(async () => { root.render(React.createElement(Workout)) })
}
@@ -112,8 +137,48 @@ async function toggleSet(index) {
await act(async () => { checkbox.dispatchEvent(new dom.Event('click', { bubbles: true })) })
}
async function pressProgression(index = 0) {
const button = container.querySelectorAll('.progline')[index]
expect(button).toBeTruthy()
await act(async () => { button.dispatchEvent(new dom.Event('click', { bubbles: true })) })
return button
}
async function requestDiscard() {
const button = container.querySelector('button[aria-label="Discard"]')
expect(button).toBeTruthy()
await act(async () => { button.dispatchEvent(new dom.Event('click', { bubbles: true })) })
}
async function rerender() {
await act(async () => { root.render(React.createElement(Workout)) })
}
async function addExerciseThroughSheets(ex = { id: 'added-exercise' }, cfg = { mode: 'reps', sets: 1, reps: 5, weight: 0 }) {
const addButton = [...container.querySelectorAll('button')]
.find(button => button.textContent.trim() === 'Add exercise')
expect(addButton).toBeTruthy()
await act(async () => { addButton.dispatchEvent(new dom.Event('click', { bubbles: true })) })
const pickerCall = mocks.exercisePicker.mock.calls.at(-1)
expect(pickerCall?.[0]).toEqual(expect.any(Function))
await act(async () => { pickerCall[0](ex) })
const configCall = mocks.exConfigSheet.mock.calls.at(-1)
expect(configCall?.[2]).toEqual(expect.any(Function))
await act(async () => { configCall[2](cfg) })
}
async function rerenderAt(cur) {
mocks.S.active.cur = cur
await act(async () => { root.render(React.createElement(Workout)) })
}
beforeEach(() => {
vi.clearAllMocks()
mocks.timer = null
mocks.work = null
mocks.scrollCalls.length = 0
})
afterEach(async () => {
@@ -126,7 +191,7 @@ describe('Workout set completion flow', () => {
await toggleSet(0)
expect(mocks.startRest).toHaveBeenCalledOnce()
expect(mocks.startRest).toHaveBeenCalledWith(90)
expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number))
expect(mocks.stopRest).not.toHaveBeenCalled()
await unmount()
@@ -140,6 +205,85 @@ describe('Workout set completion flow', () => {
expect(mocks.startRest).not.toHaveBeenCalled()
})
it.each(['warmup', 'warm-up', 'warm_up'])(
'does not start transition rest before an incomplete %s row in the next ordinary exercise',
async phase => {
await mount([
exercise('current', [false], { asked: true }),
exercise('next', [false, false], {
asked: true,
sets: [
{ w: 30, r: 5, done: false, phase },
{ w: 60, r: 5, done: false },
],
}),
])
await toggleSet(0)
expect(mocks.S.active.cur).toBe(1)
expect(mocks.startRest).not.toHaveBeenCalled()
},
)
it('does not start transition rest when a completed superset advances to an incomplete warm-up', async () => {
await mount([
exercise('superset-a', [true], { sg: 'group', asked: true }),
exercise('superset-b', [false], { sg: 'group', asked: true }),
exercise('next', [false, false], {
asked: true,
sets: [
{ w: 30, r: 5, done: false, phase: 'warmup' },
{ w: 60, r: 5, done: false },
],
}),
], 1)
await toggleSet(1)
expect(mocks.S.active.cur).toBe(2)
expect(mocks.startRest).not.toHaveBeenCalled()
})
it('does not start transition rest before a warm-up while top-weight confirmation owns navigation', async () => {
await mount([
exercise('current-loaded', [false]),
exercise('next', [false, false], {
asked: true,
sets: [
{ w: 30, r: 5, done: false, phase: 'warmup' },
{ w: 60, r: 5, done: false },
],
}),
])
await toggleSet(0)
expect(mocks.topWeightSheet).toHaveBeenCalledWith(0)
expect(mocks.S.active.cur).toBe(0)
expect(mocks.startRest).not.toHaveBeenCalled()
})
it('does not restart transition rest when re-checking a completed unit before an incomplete warm-up', async () => {
await mount([
exercise('current', [true], { asked: true }),
exercise('next', [false, false], {
asked: true,
sets: [
{ w: 30, r: 5, done: false, phase: 'warmup' },
{ w: 60, r: 5, done: false },
],
}),
])
await toggleSet(0)
await rerender()
await toggleSet(0)
expect(mocks.S.active.cur).toBe(0)
expect(mocks.startRest).not.toHaveBeenCalled()
})
it('leaves a completed superset selected while its top-weight sheet owns the advance choice', async () => {
const group = 'superset-1'
await mount([
@@ -151,7 +295,243 @@ describe('Workout set completion flow', () => {
expect(mocks.topWeightSheet).toHaveBeenCalledWith(1)
expect(mocks.S.active.cur).toBe(1)
expect(mocks.startRest).toHaveBeenCalledWith(90)
expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number))
})
it('skips completed intervening units and selects the next unfinished superset as one unit', async () => {
await mount([
exercise('current-hold', [false], { asked: true, target: { mode: 'time', sec: 30, weight: 0 } }),
exercise('already-done', [true], { asked: true }),
exercise('pending-a', [false], { sg: 'pending-group' }),
exercise('pending-b', [false], { sg: 'pending-group' }),
])
await toggleSet(0)
expect(mocks.S.active.cur).toBe(2)
expect(mocks.workoutCompleteSheet).not.toHaveBeenCalled()
expect(mocks.toast).toHaveBeenCalledWith('Hold logged')
expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number))
})
it('wraps to earlier unfinished work instead of showing a false completion prompt', async () => {
await mount([
exercise('pending-earlier', [false], { asked: true }),
exercise('current-hold', [false], { asked: true, target: { mode: 'time', sec: 30, weight: 0 } }),
], 1)
await toggleSet(0)
expect(mocks.S.active.cur).toBe(0)
expect(mocks.workoutCompleteSheet).not.toHaveBeenCalled()
expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number))
})
it('keeps top-weight confirmation in control without declaring completion while work remains', async () => {
await mount([
exercise('current-loaded', [false]),
exercise('pending', [false], { asked: true }),
])
await toggleSet(0)
expect(mocks.topWeightSheet).toHaveBeenCalledWith(0)
expect(mocks.workoutCompleteSheet).not.toHaveBeenCalled()
expect(mocks.S.active.cur).toBe(0)
})
it('shows workout completion only when no unfinished unit remains', async () => {
await mount([
exercise('already-done', [true], { asked: true }),
exercise('final-hold', [false], { asked: true, target: { mode: 'time', sec: 30, weight: 0 } }),
], 1)
await toggleSet(0)
expect(mocks.workoutCompleteSheet).toHaveBeenCalledOnce()
expect(mocks.startRest).not.toHaveBeenCalled()
})
})
describe('Workout add exercise flow', () => {
it.each([
['freestyle', {}],
['planned', {
active: { routineId: 'routine-1' },
routines: [{ id: 'routine-1', ex: [] }],
}],
])('inserts after the current unit and continues to pending work in a %s session', async (_label, overrides) => {
await mount([
exercise('current', [true], { asked: true }),
exercise('pending', [false], { asked: true }),
], 0, overrides)
await addExerciseThroughSheets(
{ id: 'inserted' },
{ mode: 'time', sets: 1, sec: 30, weight: 0 },
)
expect(mocks.S.active.entries.map(entry => entry.id)).toEqual(['current', 'inserted', 'pending'])
expect(mocks.S.active.cur).toBe(1)
await rerender()
await toggleSet(0)
expect(mocks.S.active.entries[1].sets[0].done).toBe(true)
expect(mocks.S.active.cur).toBe(2)
expect(mocks.workoutCompleteSheet).not.toHaveBeenCalled()
})
it('inserts after the complete current superset without splitting the group', async () => {
await mount([
exercise('current-a', [true], { sg: 'current-group', asked: true }),
exercise('current-b', [true], { sg: 'current-group', asked: true }),
exercise('pending', [false], { asked: true }),
])
await addExerciseThroughSheets({ id: 'inserted' })
expect(mocks.S.active.entries.map(entry => entry.id)).toEqual([
'current-a', 'current-b', 'inserted', 'pending',
])
expect(mocks.S.active.entries.slice(0, 2).map(entry => entry.sg)).toEqual([
'current-group', 'current-group',
])
expect(mocks.S.active.cur).toBe(2)
})
})
describe('Workout discard timer lifecycle', () => {
it('preserves active timers while discard is awaiting confirmation', async () => {
const timer = { left: 30, total: 90, endsAt: Date.now() + 30_000 }
const work = { left: 20, total: 45, endsAt: Date.now() + 20_000, label: 'Plank' }
mocks.timer = timer
mocks.work = work
await mount([exercise('timed-plank', [false])])
await requestDiscard()
expect(mocks.confirmSheet).toHaveBeenCalledOnce()
expect(mocks.timer).toBe(timer)
expect(mocks.work).toBe(work)
expect(mocks.stopRest).not.toHaveBeenCalled()
expect(mocks.stopWork).not.toHaveBeenCalled()
expect(mocks.S.active).not.toBeNull()
})
it('clears rest and work timers only after discard is confirmed', async () => {
mocks.timer = { left: 30, total: 90, endsAt: Date.now() + 30_000 }
mocks.work = { left: 20, total: 45, endsAt: Date.now() + 20_000, label: 'Plank' }
await mount([exercise('timed-plank', [false])])
await requestDiscard()
await act(async () => { mocks.confirmSheet.mock.calls[0][0].onConfirm() })
expect(mocks.S.active).toBeNull()
expect(mocks.timer).toBeNull()
expect(mocks.work).toBeNull()
expect(mocks.stopRest).toHaveBeenCalledOnce()
expect(mocks.stopWork).toHaveBeenCalledOnce()
})
})
describe('progression guidance', () => {
it('labels the visible outcome with the policy that calculated it', async () => {
await mount([exercise('plain-bench', [false, false, false], {
plan: {
policy: 'linear',
kind: 'up',
weight: 62.5,
why: ['Every rep last time — {0} {1} more.', 2.5, 'kg'],
},
})])
expect(container.querySelector('.progline')?.textContent)
.toContain('Linear progression · Every rep last time — 2.5 kg more.')
})
it('is a keyboard-accessible button that opens settings for the pressed grouped entry', async () => {
const plan = {
policy: 'linear', kind: 'up', weight: 62.5,
why: ['Every rep last time — {0} {1} more.', 2.5, 'kg'],
}
const first = exercise('plain-bench', [false], { sg: 'group', plan })
const second = exercise('plain-bench', [false], {
sg: 'group', plan, target: { mode: 'reps', reps: 8, weight: 80, bodyweight: false },
})
await mount([first, second])
const firstBefore = JSON.stringify(mocks.S.active.entries[0])
const button = await pressProgression(1)
expect(button.tagName).toBe('BUTTON')
expect(button.getAttribute('type')).toBe('button')
expect(button.getAttribute('aria-label')).toBe('Open progression settings')
expect(mocks.exConfigSheet).toHaveBeenCalledOnce()
expect(mocks.exConfigSheet.mock.calls[0][1]).toBe(second.target)
expect(mocks.exConfigSheet.mock.calls[0][4]).toBe(mocks.S.routines[0])
mocks.exConfigSheet.mock.calls[0][2]({ ...second.target, prog: 'double', repsMin: 6 })
expect(JSON.stringify(mocks.S.active.entries[0])).toBe(firstBefore)
expect(mocks.S.active.entries[1].target.prog).toBe('double')
expect(mocks.S.active.cur).toBe(0)
})
it('leaves the active entry unchanged when progression settings are cancelled', async () => {
const entry = exercise('plain-bench', [true, false], {
plan: {
policy: 'linear', kind: 'up', weight: 62.5,
why: ['Every rep last time — {0} {1} more.', 2.5, 'kg'],
},
})
await mount([entry])
const before = JSON.stringify(mocks.S.active.entries[0])
await pressProgression()
expect(JSON.stringify(mocks.S.active.entries[0])).toBe(before)
})
it('saves the active policy, preserves completed rows, and refreshes guidance immediately', async () => {
const entry = exercise('plain-bench', [true, false], {
plan: {
policy: 'linear', kind: 'up', weight: 62.5,
why: ['Every rep last time — {0} {1} more.', 2.5, 'kg'],
},
})
await mount([entry])
mocks.S.workouts = [{
d: '2026-08-27',
entries: [{
id: entry.id,
target: { sets: 2, reps: 5, weight: 60 },
sets: [{ w: 60, r: 5, done: true }, { w: 60, r: 5, done: true }],
}],
}]
const completed = mocks.S.active.entries[0].sets[0]
await pressProgression()
const save = mocks.exConfigSheet.mock.calls[0][2]
await act(async () => {
save({ ...entry.target, prog: 'double', repsMin: 3 })
root.render(React.createElement(Workout))
})
const saved = mocks.S.active.entries[0]
expect(saved.target.prog).toBe('double')
expect(saved.sets[0]).toEqual(completed)
expect(saved.sets[0]).toEqual({ w: 60, r: 5, done: true })
expect(saved.sets[1]).toEqual({ w: 62.5, r: 3, done: false })
expect(container.querySelector('.progline')?.textContent)
.toContain('Double progression · Top of the rep range in every set — 2.5 kg more, back to 3 reps.')
const persisted = JSON.parse(JSON.stringify(mocks.S))
await unmount()
mocks.S = persisted
installDom()
await act(async () => { root.render(React.createElement(Workout)) })
expect(container.querySelector('.progline')?.textContent)
.toContain('Double progression · Top of the rep range in every set — 2.5 kg more, back to 3 reps.')
})
})
@@ -184,6 +564,136 @@ describe('superset flow survives an exercise being removed mid-session', () => {
// Partner closes the round (each still has a second set), which is what starts the rest.
await toggleSet(2)
expect(mocks.startRest).toHaveBeenCalledWith(90)
expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number))
})
})
describe('superset actionable-set centring', () => {
it('centres the newly active exercise first incomplete set row', async () => {
await mount([
exercise('bench', [true, false], { sg: 'g1' }),
exercise('row', [true, false, false], { sg: 'g1' }),
])
mocks.scrollCalls.length = 0
await rerenderAt(1)
const rows = container.querySelector('[data-exidx="1"]').querySelectorAll('.setrow')
expect(mocks.scrollCalls).toEqual([
{ node: rows[1], options: { behavior: 'smooth', block: 'center' } },
])
})
it('centres the last set row when the newly active exercise is complete', async () => {
await mount([
exercise('bench', [true, false], { sg: 'g1' }),
exercise('row', [true, true], { sg: 'g1' }),
])
mocks.scrollCalls.length = 0
await rerenderAt(1)
const rows = container.querySelector('[data-exidx="1"]').querySelectorAll('.setrow')
expect(mocks.scrollCalls).toEqual([
{ node: rows[1], options: { behavior: 'smooth', block: 'center' } },
])
})
it('centres the exercise wrapper when the newly active exercise has no set row', async () => {
await mount([
exercise('bench', [true, false], { sg: 'g1' }),
exercise('row', [], { sg: 'g1' }),
])
mocks.scrollCalls.length = 0
await rerenderAt(1)
const wrapper = container.querySelector('[data-exidx="1"]')
expect(mocks.scrollCalls).toEqual([
{ node: wrapper, options: { behavior: 'smooth', block: 'center' } },
])
})
it('does not auto-scroll set rows for ordinary exercise navigation', async () => {
await mount([
exercise('bench', [true, false]),
exercise('row', [false, false]),
])
mocks.scrollCalls.length = 0
await rerenderAt(1)
expect(mocks.scrollCalls).toEqual([])
})
})
describe('active workout whole-unit move controls', () => {
const action = label => container.querySelector(`button[aria-label="${label}"]`)
it('shows labelled controls and moves the selected standalone exercise one unit', async () => {
const selected = exercise('duplicate', [false], {
occurrenceId: 'duplicate#2',
target: { mode: 'reps', reps: 7, weight: 82.5, notes: 'Keep this target' },
sets: [{ w: 77.5, r: 6, done: true, rir: 2 }],
})
await mount([
exercise('duplicate', [false], { occurrenceId: 'duplicate#1' }),
exercise('middle', [false]),
selected,
], 2)
expect(action('Move up')?.textContent.trim()).toBe('Move up')
expect(action('Move down')?.textContent.trim()).toBe('Move down')
await act(async () => { action('Move up').dispatchEvent(new dom.Event('click', { bubbles: true })) })
expect(mocks.S.active.entries.map(entry => entry.occurrenceId || entry.id)).toEqual(['duplicate#1', 'duplicate#2', 'middle'])
expect(mocks.S.active.entries[1]).toEqual(selected)
expect(mocks.S.active.entries[1].target).toEqual({ mode: 'reps', reps: 7, weight: 82.5, notes: 'Keep this target' })
expect(mocks.S.active.entries[1].sets).toEqual([{ w: 77.5, r: 6, done: true, rir: 2 }])
expect(mocks.S.active.cur).toBe(1)
expect(mocks.stopWork).toHaveBeenCalledOnce()
expect(mocks.stopRest).not.toHaveBeenCalled()
})
it('moves the selected contiguous group as one unit without changing its metadata', async () => {
const first = exercise('group-a', [false], { sg: 'pair', occurrenceId: 'group-a#1' })
const selected = exercise('group-b', [true], { sg: 'pair', occurrenceId: 'group-b#1' })
const groupMeta = { pair: { kind: 'complex', label: 'Carry pair', cues: 'Stay braced.' } }
await mount([
exercise('before', [false]),
first,
selected,
exercise('after', [false]),
], 2)
mocks.S.active.groupMeta = groupMeta
await act(async () => { action('Move up').dispatchEvent(new dom.Event('click', { bubbles: true })) })
expect(mocks.S.active.entries.map(entry => entry.id)).toEqual(['group-a', 'group-b', 'before', 'after'])
expect(mocks.S.active.entries.slice(0, 2)).toEqual([first, selected])
expect(mocks.S.active.entries.slice(0, 2).map(entry => entry.sg)).toEqual(['pair', 'pair'])
expect(mocks.S.active.groupMeta).toEqual(groupMeta)
expect(mocks.S.active.entries[mocks.S.active.cur]).toEqual(selected)
})
it('disables both moves while a work timer can still write by index', async () => {
mocks.work = { left: 5, total: 5, endsAt: Date.now() + 5000 }
await mount([exercise('first', [false]), exercise('second', [false])], 1)
expect(action('Move up')?.disabled).toBe(true)
expect(action('Move down')?.disabled).toBe(true)
})
})
describe('active exercise swap control', () => {
it('opens the swap flow for the selected duplicate occurrence', async () => {
await mount([exercise('bench', [false]), exercise('bench', [false]), exercise('row', [false])], 1)
const swap = container.querySelector('button[aria-label="Swap exercise"]')
expect(swap).toBeTruthy()
await act(async () => { swap.dispatchEvent(new dom.Event('click', { bubbles: true })) })
expect(mocks.swapActiveWorkoutExercise).toHaveBeenCalledOnce()
expect(mocks.swapActiveWorkoutExercise).toHaveBeenCalledWith(1)
})
})
+120
View File
@@ -0,0 +1,120 @@
// @vitest-environment happy-dom
// The setting is only worth anything if the screens actually follow it: the toggle has to
// write the field, and the Plan list has to draw the week in that order.
import React, { act } from 'react'
import { createRoot } from 'react-dom/client'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import Settings from './Settings.jsx'
import Plan from './Plan.jsx'
globalThis.IS_REACT_ACT_ENVIRONMENT = true
const mocks = vi.hoisted(() => {
const state = { S: null }
state.snapshot = () => ({
S: state.S,
user: null,
update: mut => {
const next = structuredClone(state.S)
mut(next)
state.S = next
},
replaceState: vi.fn(), setUser: vi.fn(), pullState: vi.fn(), pushState: vi.fn(),
signOut: vi.fn(), signOutAll: vi.fn(), resetDemo: vi.fn(), disconnectServer: vi.fn(),
})
return state
})
vi.mock('../store/useStore.js', () => {
const useStore = selector => (selector ? selector(mocks.snapshot()) : mocks.snapshot())
useStore.getState = mocks.snapshot
return { useStore, DEF: { reminder: { time: '17:30' } }, hasData: () => false }
})
vi.mock('../store/useUI.js', () => {
const snap = () => ({ toast: vi.fn(), openSheet: vi.fn() })
const useUI = selector => (selector ? selector(snap()) : snap())
useUI.getState = snap
return { useUI }
})
vi.mock('react-router-dom', () => ({ useNavigate: () => () => {} }))
vi.mock('../lib/api.js', () => ({
api: vi.fn(), webauthnOK: () => false, passkeyLogin: vi.fn(), passkeyRegister: vi.fn(), IS_ANDROID: false,
}))
vi.mock('../lib/push.js', () => ({ pushSupported: () => false, enablePush: vi.fn(), disablePush: vi.fn(), sendTestPush: vi.fn() }))
vi.mock('../lib/wakelock.js', () => ({ wakeLockSupported: () => false }))
vi.mock('../lib/mobile.js', () => ({ MOBILE: false, shareExport: vi.fn(), syncReminder: vi.fn() }))
vi.mock('./MobileOnboarding.jsx', () => ({ ConnectSheet: () => null }))
vi.mock('../sheets.jsx', () => ({
loadStarterPlan: vi.fn(), confirmSheet: vi.fn(), importFromApp: vi.fn(),
importFromHevy: vi.fn(), equipmentProfileSheet: vi.fn(),
dayAssignSheet: vi.fn(), planToolsSheet: vi.fn(),
}))
globalThis.__APP_VERSION__ ??= 'test'
let host, root
beforeEach(() => {
mocks.S = {
unit: 'kg', restSec: 90, restPauseSec: 15, sound: false, effort: 'none',
gifSize: 'full', workouts: [], routines: [], exWeights: {}, week: {}, dayPlan: {},
}
host = document.createElement('div')
document.body.appendChild(host)
root = createRoot(host)
})
afterEach(() => {
act(() => root.unmount())
host.remove()
})
const segButton = label => [...host.querySelectorAll('.seg button')].find(b => b.textContent === label)
const dayRows = () => [...host.querySelectorAll('.item .tt')].map(e => e.textContent)
describe('Settings — week starts on', () => {
const mount = () => act(() => root.render(<Settings />))
it('offers Monday and Sunday and writes the getDay() index', () => {
mount()
expect(segButton('Monday').getAttribute('aria-pressed')).toBe('true')
act(() => { segButton('Sunday').click() })
expect(mocks.S.weekStart).toBe(0)
mount()
expect(segButton('Sunday').getAttribute('aria-pressed')).toBe('true')
act(() => { segButton('Monday').click() })
expect(mocks.S.weekStart).toBe(1)
})
it('shows a profile written before the setting existed as Monday', () => {
delete mocks.S.weekStart
mount()
expect(segButton('Monday').getAttribute('aria-pressed')).toBe('true')
expect(segButton('Sunday').getAttribute('aria-pressed')).toBe('false')
})
})
describe('Plan — the week schedule follows the setting', () => {
const mount = () => act(() => root.render(<Plan />))
it('runs Monday to Sunday by default', () => {
mount()
expect(dayRows().slice(0, 7)).toEqual(
['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'])
})
it('runs Sunday to Saturday for a Sunday profile', () => {
mocks.S.weekStart = 0
mount()
expect(dayRows().slice(0, 7)).toEqual(
['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'])
})
it('keeps a routine attached to its day, not to its position in the list', () => {
mocks.S.routines = [{ id: 'r1', name: 'Push', emoji: null, ex: [] }]
mocks.S.week = { 0: 'r1' } // Sunday
mocks.S.weekStart = 0
mount()
const rows = [...host.querySelectorAll('.item')]
expect(rows[0].querySelector('.tt').textContent).toBe('Sunday')
expect(rows[0].textContent).toContain('Push')
expect(rows[1].textContent).not.toContain('Push')
})
})