feat(workout): add configurable list view for active workouts

This commit is contained in:
Daniel Patrón Gómez committed 2026-09-04 10:09:30 +02:00
1 parent d6f0db9b4b
commit e278051fae
20 files changed
+332 -11

No files matched your search

+8
View File
@@ -144,6 +144,14 @@ export default function Settings() {
{/* ---------- during a workout ---------- */}
<Section title={t('During a workout')} footer={wakeOK ? t('The screen stays on while a workout is running, so you don’t have to unlock your phone between sets.') : null}>
{/* One exercise at a time (cards with Prev/Next) or the whole session stacked as a
scrollable list. Legacy/unknown values read as cards. */}
<Row icon="list" iconTint="var(--blue)" title={t('Workout view')}>
<Segmented className="seg-inline"
options={[{ value: 'cards', label: t('Cards') }, { value: 'list', label: t('List') }]}
value={S.workoutView === 'list' ? 'list' : 'cards'}
onChange={v => update(s => { s.workoutView = v })} />
</Row>
<SelectRow icon="timer" iconTint="var(--orange)" title={t('Rest timer')}
value={S.restSec} onChange={v => update(s => { s.restSec = v })}
options={[{ value: 0, label: t('Off') }, ...[60, 90, 120, 150, 180].map(v => ({ value: v, label: v + 's' }))]} />
@@ -0,0 +1,89 @@
// @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 — workout view', () => {
it('offers Cards / List and writes workoutView to the store', () => {
mount()
expect(segButton('Cards')).toBeTruthy()
expect(segButton('List')).toBeTruthy()
expect(segButton('Cards').getAttribute('aria-pressed')).toBe('true')
act(() => { segButton('List').click() })
expect(mocks.S.workoutView).toBe('list')
mount()
expect(segButton('List').getAttribute('aria-pressed')).toBe('true')
act(() => { segButton('Cards').click() })
expect(mocks.S.workoutView).toBe('cards')
})
it('shows a legacy/absent value as Cards', () => {
delete mocks.S.workoutView
mount()
expect(segButton('Cards').getAttribute('aria-pressed')).toBe('true')
expect(segButton('List').getAttribute('aria-pressed')).toBe('false')
})
})
+67 -9
View File
@@ -320,6 +320,12 @@ function ActiveWorkout() {
const unit = A.entries.length ? unitOf(units, cur) : []
const unitIdx = units.findIndex(u => u === unit)
const isSuperset = unit.length > 1
// Cards show one unit at a time with Prev/Next + swipe; list stacks every unit so the
// whole session is visible and scrollable (Settings → During a workout → Workout view).
// Every set handler below is already entry-index parameterised, so list mode only changes
// what is rendered — completion, rest, top-weight and auto-advance share one path.
// Unknown/absent values read as cards, keeping every pre-existing profile as it was.
const listMode = S.workoutView === 'list'
// 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.
@@ -360,13 +366,13 @@ function ActiveWorkout() {
}
})
useEffect(() => {
if (!isSuperset) return
if (!isSuperset || listMode) return
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])
}, [cur, isSuperset, listMode, A.entries.length])
const total = A.entries.reduce((n, e) => n + e.sets.length, 0)
const done = setsDoneActive(A)
@@ -423,6 +429,17 @@ function ActiveWorkout() {
}, true)
}
// One prop object per entry so the card and list layouts share the exact same wiring.
const blockProps = idx => ({
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),
})
const navigateUnit = direction => {
const targetFor = active => {
if (!active || !Array.isArray(active.entries) || !Number.isInteger(active.cur)) return null
@@ -437,6 +454,10 @@ function ActiveWorkout() {
if (target != null) s.active.cur = target
})
}
// List mode shows every unit at once, so the "current" exercise is chosen by tapping
// "Set current" on its header instead of Prev/Next. The bottom Move/Swap/Remove actions
// keep operating on it, and completing sets still advances it on its own.
const focusUnit = firstIdx => update(s => { if (s.active) s.active.cur = firstIdx })
const onSwipePointerDown = event => {
if (swipe.current || (event.pointerType && event.pointerType !== 'touch' && event.pointerType !== 'pen')) return
if (event.target.closest?.(SWIPE_IGNORED_TARGETS)) return
@@ -640,7 +661,43 @@ function ActiveWorkout() {
<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 ? <>
{A.entries.length ? (listMode ? (
<div className="workout-list" data-testid="workout-list">
{units.map((u, ui) => {
const multi = u.length > 1
const isCur = u.includes(cur)
return <section key={u.join('-')} className={'wl-unit' + (isCur ? ' cur' : '')} data-exidx={u[0]}>
<div className="wl-hd">
<span className="muted small">{multi ? t('Superset {0} / {1}', ui + 1, units.length) : t('Exercise {0} / {1}', ui + 1, units.length)}</span>
{isCur
? <span className="tag acc">{t('Current')}</span>
: <button className="chip" onClick={() => focusUnit(u[0])}>{t('Set current')}</button>}
</div>
{multi ? (
<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(u[0])}>{t('Unpair')}</Button>
</div>
{u.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)}
{...blockProps(idx)} />
</div>
})}
</div>
) : (
<ExerciseBlock entryIdx={u[0]}
onPairPrev={u[0] > 0 ? () => pairAt(u[0] - 1, u[0]) : null}
onPairNext={u[0] < A.entries.length - 1 ? () => pairAt(u[0], u[0] + 1) : null}
{...blockProps(u[0])} />
)}
</section>
})}
</div>
) : <>
<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}
@@ -660,22 +717,23 @@ function ActiveWorkout() {
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)} />
{...blockProps(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} onProgressionSettings={() => openProgressionSettings(cur)} />
<ExerciseBlock entryIdx={cur} onPairPrev={onPairPrev} onPairNext={onPairNext} {...blockProps(cur)} />
)}
</div>
</> : <div className="empty"><div className="ico"><Icon name="shuffle" /></div>{t('Freestyle workout — add your first exercise.')}</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">
{!listMode && <div className="row">
<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 }} />
</div>}
{!listMode && <div style={{ height: 10 }} />}
{listMode && A.entries.length > 0 && <div className="muted small" style={{ marginBottom: 6 }}>{t('Move, swap and remove below act on the exercise marked {0}.', t('Current'))}</div>}
<Button onClick={() => exercisePicker(ex => {
const routine = S.routines.find(r => r.id === A.routineId)
const freestyle = !A.routineId
+72
View File
@@ -697,3 +697,75 @@ describe('active exercise swap control', () => {
expect(mocks.swapActiveWorkoutExercise).toHaveBeenCalledWith(1)
})
})
describe('workout list view', () => {
const units = () => [...container.querySelectorAll('.wl-unit')]
const focusButton = unit => [...unit.querySelectorAll('button')].find(b => b.textContent.trim() === 'Set current')
it('stacks every exercise, labels each unit, and hides card navigation', async () => {
await mount([exercise('plain-bench', [false, false]), exercise('plain-row', [false])], 0, { workoutView: 'list' })
expect(container.querySelector('[data-testid="workout-list"]')).toBeTruthy()
expect(container.querySelector('[data-testid="workout-swipe-surface"]')).toBeNull()
expect(units().length).toBe(2)
// Every set in the session is visible at once: 2 + 1 checkboxes, not just the current one.
expect(container.querySelectorAll('[role="checkbox"]').length).toBe(3)
expect(units().map(u => u.querySelector('.wl-hd .muted')?.textContent)).toEqual([
'Exercise 1 / 2', 'Exercise 2 / 2',
])
expect(units()[0].textContent).toContain('Current')
expect(focusButton(units()[1])).toBeTruthy()
const navButtons = [...container.querySelectorAll('button')]
.filter(b => b.textContent.trim() === 'Prev' || b.textContent.trim() === 'Next')
expect(navButtons.length).toBe(0)
})
it('marks the current unit and moves the mark with Set current', async () => {
await mount([exercise('plain-bench', [false]), exercise('plain-row', [false])], 0, { workoutView: 'list' })
await act(async () => { focusButton(units()[1]).dispatchEvent(new dom.Event('click', { bubbles: true })) })
expect(mocks.S.active.cur).toBe(1)
await rerender()
expect(units()[0].textContent).not.toContain('Current')
expect(units()[1].textContent).toContain('Current')
expect(focusButton(units()[0])).toBeTruthy()
})
it('completing a set in list mode advances the current exercise like cards do', async () => {
await mount([
exercise('plain-bench', [false], { asked: true }),
exercise('plain-row', [false], { asked: true }),
], 0, { workoutView: 'list' })
await toggleSet(0)
expect(mocks.S.active.entries[0].sets[0].done).toBe(true)
expect(mocks.S.active.cur).toBe(1)
expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number))
})
it('renders a superset as one grouped unit with its own unpair control', async () => {
await mount([
exercise('bench', [false], { sg: 'g1', asked: true }),
exercise('row', [false], { sg: 'g1', asked: true }),
exercise('squat', [false], { asked: true }),
], 0, { workoutView: 'list' })
expect(units().length).toBe(2)
expect(units()[0].querySelector('.ss-card')).toBeTruthy()
expect(units()[1].querySelector('.ss-card')).toBeNull()
expect(units().map(u => u.querySelector('.wl-hd .muted')?.textContent)).toEqual([
'Superset 1 / 2', 'Exercise 2 / 2',
])
})
it('defaults to cards when the setting is absent (pre-existing profiles)', async () => {
await mount([exercise('plain-bench', [false]), exercise('plain-row', [false])])
expect(container.querySelector('[data-testid="workout-list"]')).toBeNull()
expect(container.querySelector('[data-testid="workout-swipe-surface"]')).toBeTruthy()
// Only the current exercise's sets are on screen.
expect(container.querySelectorAll('[role="checkbox"]').length).toBe(1)
})
})