Skip to content

Open-source gym & body-weight tracker, now in the App Store (iPhone + Apple Watch) and as an Android APK. Plan routines, log workouts, see which muscles are trained, import from Strong/Hevy/FitNotes. Self-host it or use it on the phone alone.

feat(workout): swipe between active units

Space_Hermes85ecf3563e13
diff --git a/frontend/src/index.css b/frontend/src/index.css
index a34845995..333f537f8 100644
--- a/frontend/src/index.css
+++ b/frontend/src/index.css
@@ -930,6 +930,7 @@ h4.sec{
border-radius:var(--r-lg);padding:14px;
background:var(--surface);box-shadow:inset 0 0 0 1.5px var(--acc-line);
}
+.workout-swipe-surface{touch-action:pan-y}
/* A superset nests a card inside the page's own gutter, so its inset is paid twice. On a
narrow phone that left the weight and reps steppers too tight to show a three-digit
number — reported as "the reps textbox becomes too small when superset on mobile". The
diff --git a/frontend/src/views/Workout.jsx b/frontend/src/views/Workout.jsx
index d0a627977..393c659a2 100644
--- a/frontend/src/views/Workout.jsx
+++ b/frontend/src/views/Workout.jsx
@@ -17,6 +17,10 @@ import { nextPrescription, applyPrescription, defaultIncrement } from '../lib/pr
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'
+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() {
const nav = useNavigate()
@@ -278,13 +282,16 @@ function ActiveWorkout() {
const { startRest, stopRest, work } = useUI()
const A = S.active
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({})
+ 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
@@ -335,6 +342,38 @@ 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 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)
+ }
+
// Remove a whole exercise from the session. The confirmation always asks first; in a
// superset it asks WHICH exercise of the group to remove.
const removeExercise = removeActiveExercise
@@ -487,6 +526,13 @@ function ActiveWorkout() {
{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' }}>
@@ -502,12 +548,13 @@ function ActiveWorkout() {
) : (
<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} />
)}
+ </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 => {
diff --git a/frontend/src/views/Workout.test.jsx b/frontend/src/views/Workout.test.jsx
index 0564b8a68..8e4f56852 100644
--- a/frontend/src/views/Workout.test.jsx
+++ b/frontend/src/views/Workout.test.jsx
@@ -7,21 +7,33 @@ import Workout from './Workout.jsx'
const mocks = vi.hoisted(() => {
const state = {
S: null,
+ cloneOnUpdate: false,
startRest: vi.fn(),
stopRest: vi.fn(),
+ startWork: vi.fn(),
+ toast: vi.fn(),
+ timer: null,
topWeightSheet: vi.fn(),
}
+ state.update = vi.fn(mut => {
+ if (state.cloneOnUpdate) {
+ const next = structuredClone(state.S)
+ mut(next)
+ state.S = next
+ } else mut(state.S)
+ })
state.storeSnapshot = () => ({
S: state.S,
user: null,
- update: mut => mut(state.S),
+ update: state.update,
})
state.uiSnapshot = () => ({
work: null,
+ timer: state.timer,
startRest: state.startRest,
stopRest: state.stopRest,
- startWork: vi.fn(),
- toast: vi.fn(),
+ startWork: state.startWork,
+ toast: state.toast,
})
return state
})
@@ -51,7 +63,10 @@ vi.mock('../sheets.jsx', () => ({
exerciseNoteSheet: vi.fn(),
sessionNoteSheet: vi.fn(),
}))
-vi.mock('../components/Media.jsx', () => ({ default: () => null }))
+vi.mock('../components/Media.jsx', () => ({
+ default: () => React.createElement('div', { className: 'exmedia' },
+ React.createElement('button', { 'aria-label': 'Minimize media' }, 'Media')),
+}))
// api.js reads navigator.userAgent at module scope. This file installs its own DOM inside the
// tests rather than declaring a vitest environment, so it must not depend on an ambient one.
vi.mock('../lib/api.js', () => ({
@@ -98,6 +113,12 @@ async function mount(entries, cur = 0) {
await act(async () => { root.render(React.createElement(Workout)) })
}
+async function mountState(state) {
+ mocks.S = state
+ installDom()
+ await act(async () => { root.render(React.createElement(Workout)) })
+}
+
async function unmount() {
if (!root) return
await act(async () => { root.unmount() })
@@ -112,14 +133,253 @@ async function toggleSet(index) {
await act(async () => { checkbox.dispatchEvent(new dom.Event('click', { bubbles: true })) })
}
+function pointerEvent(type, { x, y, pointerId = 1, pointerType = '' }) {
+ const event = new dom.Event(type, { bubbles: true, cancelable: true })
+ Object.defineProperties(event, {
+ clientX: { value: x },
+ clientY: { value: y },
+ pointerId: { value: pointerId },
+ pointerType: { value: pointerType },
+ })
+ return event
+}
+
+async function swipe(target, from, to, pointerType = '') {
+ await act(async () => {
+ target.dispatchEvent(pointerEvent('pointerdown', { x: from[0], y: from[1], pointerType }))
+ target.dispatchEvent(pointerEvent('pointerup', { x: to[0], y: to[1], pointerType }))
+ })
+}
+
beforeEach(() => {
vi.clearAllMocks()
+ mocks.cloneOnUpdate = false
+ mocks.timer = null
})
afterEach(async () => {
await unmount()
})
+describe('Workout swipe navigation', () => {
+ it('moves left from one exercise to the next unit exactly once', async () => {
+ await mount([exercise('first', [false]), exercise('second', [false])])
+ const surface = container.querySelector('[data-testid="workout-swipe-surface"]')
+
+ expect(surface).toBeTruthy()
+ await swipe(surface, [160, 200], [90, 202])
+
+ expect(mocks.S.active.cur).toBe(1)
+ })
+
+ it('navigates through the production-shaped cloned update boundary', async () => {
+ mocks.cloneOnUpdate = true
+ await mount([exercise('first', [false]), exercise('second', [false])])
+
+ await swipe(container.querySelector('[data-testid="workout-swipe-surface"]'), [160, 200], [90, 202])
+
+ expect(mocks.S.active.cur).toBe(1)
+ })
+
+ it('moves right to the previous unit without wrapping at either boundary', async () => {
+ await mount([exercise('first', [false]), exercise('second', [false])], 1)
+ const surface = container.querySelector('[data-testid="workout-swipe-surface"]')
+
+ await swipe(surface, [90, 200], [160, 202])
+ expect(mocks.S.active.cur).toBe(0)
+ mocks.update.mockClear()
+ await swipe(surface, [90, 200], [160, 202])
+ expect(mocks.S.active.cur).toBe(0)
+ expect(mocks.update).not.toHaveBeenCalled()
+
+ mocks.S.active.cur = 1
+ await swipe(surface, [160, 200], [90, 202])
+ expect(mocks.S.active.cur).toBe(1)
+ expect(mocks.update).not.toHaveBeenCalled()
+ })
+
+ it.each([
+ ['vertical', [160, 200], [150, 280], ''],
+ ['short', [160, 200], [120, 200], ''],
+ ['diagonal', [160, 200], [80, 270], ''],
+ ['mouse', [160, 200], [90, 202], 'mouse'],
+ ])('ignores a %s pointer sequence', async (_label, from, to, pointerType) => {
+ await mount([exercise('first', [false]), exercise('second', [false])])
+ const surface = container.querySelector('[data-testid="workout-swipe-surface"]')
+ const down = pointerEvent('pointerdown', { x: from[0], y: from[1], pointerType })
+ const up = pointerEvent('pointerup', { x: to[0], y: to[1], pointerType })
+
+ await act(async () => {
+ surface.dispatchEvent(down)
+ surface.dispatchEvent(up)
+ })
+
+ expect(mocks.S.active.cur).toBe(0)
+ expect(mocks.update).not.toHaveBeenCalled()
+ expect(down.defaultPrevented).toBe(false)
+ expect(up.defaultPrevented).toBe(false)
+ })
+
+ it('cleans up a cancelled pointer without navigating on its later release', async () => {
+ await mount([exercise('first', [false]), exercise('second', [false])])
+ const surface = container.querySelector('[data-testid="workout-swipe-surface"]')
+
+ await act(async () => {
+ surface.dispatchEvent(pointerEvent('pointerdown', { x: 160, y: 200 }))
+ surface.dispatchEvent(pointerEvent('pointercancel', { x: 120, y: 200 }))
+ surface.dispatchEvent(pointerEvent('pointerup', { x: 80, y: 200 }))
+ })
+
+ expect(mocks.S.active.cur).toBe(0)
+ expect(mocks.update).not.toHaveBeenCalled()
+ })
+
+ it('cleans up when the active pointer capture is lost', async () => {
+ await mount([exercise('first', [false]), exercise('second', [false])])
+ const surface = container.querySelector('[data-testid="workout-swipe-surface"]')
+
+ await act(async () => {
+ surface.dispatchEvent(pointerEvent('pointerdown', { x: 160, y: 200 }))
+ surface.dispatchEvent(pointerEvent('lostpointercapture', { x: 120, y: 200 }))
+ surface.dispatchEvent(pointerEvent('pointerup', { x: 80, y: 200 }))
+ })
+
+ expect(mocks.S.active.cur).toBe(0)
+ expect(mocks.update).not.toHaveBeenCalled()
+ })
+
+ it('crosses a whole contiguous superset in both directions', async () => {
+ const entries = [
+ exercise('first', [false]),
+ exercise('group-a', [false], { sg: 'g' }),
+ exercise('group-b', [false], { sg: 'g' }),
+ exercise('last', [false]),
+ ]
+ await mount(entries, 1)
+ const surface = container.querySelector('[data-testid="workout-swipe-surface"]')
+
+ await swipe(surface, [160, 200], [90, 202])
+ expect(mocks.S.active.cur).toBe(3)
+ mocks.S.active.cur = 3
+ await swipe(surface, [90, 200], [160, 202])
+ expect(mocks.S.active.cur).toBe(1)
+ })
+
+ it('keeps duplicate exercise occurrences and their sets unchanged', async () => {
+ const entries = [exercise('bench', [false]), exercise('row', [false]), exercise('bench', [true])]
+ const references = [...entries]
+ await mount(entries, 2)
+ const surface = container.querySelector('[data-testid="workout-swipe-surface"]')
+
+ await swipe(surface, [90, 200], [160, 202])
+
+ expect(mocks.S.active.cur).toBe(1)
+ expect(mocks.S.active.entries).toEqual(references)
+ expect(mocks.S.active.entries[0]).toBe(references[0])
+ expect(mocks.S.active.entries[2]).toBe(references[2])
+ })
+
+ it('leaves interactive controls and media in charge of their own gestures', async () => {
+ await mount([exercise('first', [false]), exercise('second', [false])])
+ const surface = container.querySelector('[data-testid="workout-swipe-surface"]')
+ const targets = [
+ surface.querySelector('[role="checkbox"]'),
+ surface.querySelector('input'),
+ surface.querySelector('button[aria-label="Note"]'),
+ surface.querySelector('.exmedia'),
+ surface.querySelector('.exmedia button'),
+ ]
+ expect(targets.every(Boolean)).toBe(true)
+
+ for (const target of targets) await swipe(target, [160, 200], [80, 202], 'touch')
+
+ expect(mocks.S.active.cur).toBe(0)
+ expect(mocks.update).not.toHaveBeenCalled()
+ })
+
+ it('changes only the cursor while leaving running timer state and callbacks untouched', async () => {
+ mocks.timer = { left: 42, running: true }
+ const entries = [exercise('first', [false]), exercise('second', [false])]
+ await mount(entries)
+ const before = structuredClone(mocks.S)
+
+ await swipe(container.querySelector('[data-testid="workout-swipe-surface"]'), [160, 200], [90, 202], 'pen')
+
+ expect(mocks.S).toEqual({ ...before, active: { ...before.active, cur: 1 } })
+ expect(mocks.S.active.entries[0]).toBe(entries[0])
+ expect(mocks.timer).toEqual({ left: 42, running: true })
+ expect(mocks.startRest).not.toHaveBeenCalled()
+ expect(mocks.stopRest).not.toHaveBeenCalled()
+ expect(mocks.startWork).not.toHaveBeenCalled()
+ expect(mocks.topWeightSheet).not.toHaveBeenCalled()
+ expect(mocks.update).toHaveBeenCalledOnce()
+ })
+
+ it('keeps semantic Prev and Next buttons as the non-gesture path', async () => {
+ await mount([exercise('first', [false]), exercise('second', [false])])
+ const buttons = [...container.querySelectorAll('button')]
+ const prev = buttons.find(button => button.textContent.trim() === 'Prev')
+ const next = buttons.find(button => button.textContent.trim() === 'Next')
+ const surface = container.querySelector('[data-testid="workout-swipe-surface"]')
+
+ expect(prev.disabled).toBe(true)
+ expect(next.disabled).toBe(false)
+ expect(surface.getAttribute('role')).toBeNull()
+ expect(surface.getAttribute('tabindex')).toBeNull()
+ await act(async () => { next.dispatchEvent(new dom.Event('click', { bubbles: true })) })
+ expect(mocks.S.active.cur).toBe(1)
+ })
+
+ it('uses fresh cursor state at release time', async () => {
+ await mount([exercise('first', [false]), exercise('second', [false]), exercise('third', [false])])
+ const surface = container.querySelector('[data-testid="workout-swipe-surface"]')
+
+ await act(async () => {
+ surface.dispatchEvent(pointerEvent('pointerdown', { x: 160, y: 200 }))
+ mocks.S.active.cur = 1
+ surface.dispatchEvent(pointerEvent('pointerup', { x: 90, y: 202 }))
+ })
+
+ expect(mocks.S.active.cur).toBe(2)
+ })
+
+ it('accepts the exact distance and axis-dominance thresholds', async () => {
+ await mount([exercise('first', [false]), exercise('second', [false]), exercise('third', [false])])
+ const surface = container.querySelector('[data-testid="workout-swipe-surface"]')
+
+ await swipe(surface, [100, 100], [52, 100])
+ expect(mocks.S.active.cur).toBe(1)
+ await swipe(surface, [100, 100], [50, 140])
+
+ expect(mocks.S.active.cur).toBe(2)
+ })
+
+ it('renders safely with no active workout or with an empty active workout', async () => {
+ const missing = workout([])
+ missing.active = null
+ missing.week = {}
+ missing.dayPlan = {}
+ await mountState(missing)
+ expect(container.querySelector('[data-testid="workout-swipe-surface"]')).toBeNull()
+ expect(mocks.update).not.toHaveBeenCalled()
+
+ await unmount()
+ await mount([])
+ expect(container.querySelector('[data-testid="workout-swipe-surface"]')).toBeNull()
+ expect(mocks.update).not.toHaveBeenCalled()
+ })
+
+ it('fails closed for an invalid negative cursor', async () => {
+ await mount([exercise('first', [false]), exercise('second', [false])], -1)
+ const surface = container.querySelector('[data-testid="workout-swipe-surface"]')
+
+ await swipe(surface, [160, 200], [90, 202])
+
+ expect(mocks.S.active.cur).toBe(-1)
+ expect(mocks.update).not.toHaveBeenCalled()
+ })
+})
+
describe('Workout set completion flow', () => {
it('starts rest after a non-final ordinary set, but stops rest without restarting it on the final set', async () => {
await mount([exercise('plain-bench', [false, false, false])])