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.
JavaScript apple-watchbodyweightdockerfitnessfitness-trackergymhealthiosmcpnodejspasskeysprogressive-web-applicationspwareactself-hostedself-hostingvitewebauthnweightliftingworkout-tracker
fix(workout): Move up/down on a superset member reorders it inside the superset
Boris 'B' Kurktchiev2aee8cfbae62
diff --git a/frontend/src/lib/active-workout-order.js b/frontend/src/lib/active-workout-order.jsindex 57a00895e..a77437535 100644--- a/frontend/src/lib/active-workout-order.js+++ b/frontend/src/lib/active-workout-order.js@@ -29,3 +29,53 @@ export function moveActiveWorkoutUnit(active, index, direction) {active.cur = active.entries.indexOf(selected)return { indices }}++// The exercise ⋯ menu's Move up/down. Moving a hanging leg raise away from the pull-ups next to+// it used to move the whole superset past the main lift. A member of a superset moves inside it:+// it swaps places with the member next to it and keeps its sg, so the superset stays one block+// under the same id (its layout choice and groupMeta are keyed by that id). At the superset's+// first or last member there is nobody to swap with, and the move takes the whole superset past+// its neighbouring block, as moveActiveWorkoutUnit always has. The routine editor's arrows+// (moveRoutineEntry, #377) take a member at the edge out of its superset instead; during a+// workout that would change a superset whose round is under way, so here the edge keeps the+// whole-superset move. A lone exercise moves exactly as before.+//+// The round-robin through a superset is positional (supersetFlowStep): the members before the+// marker have done the round in progress, the marker's member and those after it still owe it.+// So the marker keeps its position through a swap and points at whichever member now sits there.+// A swap may not carry a member across it, because the one moved behind the marker would be+// skipped this round and the one moved in front of it would run twice. A swap with both members+// on one side of the marker is safe, and so is any swap while the marker is outside the superset.+function memberSwapTarget(active, index, direction) {+ if (!active || !Array.isArray(active.entries) || (direction !== -1 && direction !== 1)) return null+ const unit = supersetUnits(active.entries).find(members => members.includes(index))+ if (!unit || unit.length < 2) return null+ const target = index + direction+ return unit.includes(target) ? { unit, target } : null+}++function crossesMarker(active, unit, index, target) {+ const cur = active.cur+ if (!unit.includes(cur)) return false+ return Math.min(index, target) < cur && Math.max(index, target) >= cur+}++export function canMoveActiveWorkoutEntry(active, index, direction) {+ const swap = memberSwapTarget(active, index, direction)+ if (swap) return !crossesMarker(active, swap.unit, index, swap.target)+ return canMoveActiveWorkoutUnit(active, index, direction)+}++// Returns the same { indices } permutation as moveActiveWorkoutUnit (new position -> old index),+// so the caller remaps per-entry state the same way; null when the move is refused.+export function moveActiveWorkoutEntry(active, index, direction) {+ const swap = memberSwapTarget(active, index, direction)+ if (!swap) return moveActiveWorkoutUnit(active, index, direction)+ if (crossesMarker(active, swap.unit, index, swap.target)) return null+ const indices = active.entries.map((_, i) => i)+ indices[index] = swap.target+ indices[swap.target] = index+ const reorderedEntries = indices.map(entryIndex => active.entries[entryIndex])+ active.entries.splice(0, active.entries.length, ...reorderedEntries)+ return { indices }+}diff --git a/frontend/src/lib/active-workout-order.test.js b/frontend/src/lib/active-workout-order.test.jsindex dff7657da..8e7f8e483 100644--- a/frontend/src/lib/active-workout-order.test.js+++ b/frontend/src/lib/active-workout-order.test.js@@ -1,5 +1,7 @@import { describe, expect, it } from 'vitest'-import { canMoveActiveWorkoutUnit, moveActiveWorkoutUnit } from './active-workout-order.js'+import { canMoveActiveWorkoutUnit, moveActiveWorkoutUnit, canMoveActiveWorkoutEntry, moveActiveWorkoutEntry } from './active-workout-order.js'+import { supersetFlowStep } from './supersetFlow.js'+import { supersetUnits } from './history.js'import { LANGS, DERIVED_LOCALES } from './i18n-core.js'import { PT_BR_OVERRIDES } from '../locales/pt-BR.js'@@ -66,6 +68,110 @@ describe('active workout whole-unit order', () => {})})+// Move down on a hanging leg raise, to get it away from the pull-ups next to it, moved the whole+// superset instead and left the order inside it as it was (#377, there in the routine editor).+describe('active workout member move (the exercise ⋯ menu)', () => {+ const circuit = () => {+ const ids = ['split-squat', 'pull-up', 'hanging-leg-raise', 'plank', 'triceps', 'carry']+ return [entry('incline-bench'), ...ids.map(id => entry(id, { sg: 'sg-m3' })), entry('cool-down')]+ }+ const ids = active => active.entries.map(item => item.id)++ it('swaps a member with its neighbour inside the superset and keeps the superset whole', () => {+ const active = { cur: 0, entries: circuit(), groupMeta: { 'sg-m3': { label: 'Circuit' } } }+ expect(canMoveActiveWorkoutEntry(active, 3, 1)).toBe(true)+ expect(moveActiveWorkoutEntry(active, 3, 1)?.indices).toEqual([0, 1, 2, 4, 3, 5, 6, 7])+ expect(ids(active)).toEqual(['incline-bench', 'split-squat', 'pull-up', 'plank', 'hanging-leg-raise', 'triceps', 'carry', 'cool-down'])+ expect(active.entries.slice(1, 7).every(item => item.sg === 'sg-m3')).toBe(true)+ expect(active.cur).toBe(0)+ moveActiveWorkoutEntry(active, 4, -1)+ expect(ids(active).slice(2, 5)).toEqual(['pull-up', 'hanging-leg-raise', 'plank'])+ })++ // The round-robin is positional: the members before the marker have done the round, the+ // marker's member and those after it owe it. The marker keeps its position, so after the+ // pull-ups the leg raise moved down puts the plank on the marker, next.+ it('the marker keeps its position: the member swapped onto it is the one that comes next', () => {+ const active = { cur: 3, entries: circuit() }+ expect(moveActiveWorkoutEntry(active, 3, 1)?.indices).toEqual([0, 1, 2, 4, 3, 5, 6, 7])+ expect(active.cur).toBe(3)+ expect(active.entries[active.cur].id).toBe('plank')+ // two members both behind the marker (done this round) swap freely too+ const behind = { cur: 5, entries: circuit() }+ expect(moveActiveWorkoutEntry(behind, 1, 1)).not.toBeNull()+ expect(ids(behind).slice(1, 3)).toEqual(['pull-up', 'split-squat'])+ expect(behind.cur).toBe(5)+ })++ // The whole point of the two rules above, run through the real round-robin: after the split+ // squat and the pull-up, the leg raise moves down, and the round still gives every member+ // exactly one set before its rest.+ it('a swap allowed mid-round leaves the round-robin giving every member one set per round', () => {+ const sets = done => done.map(value => ({ w: 0, r: 5, done: value }))+ const ids = ['split-squat', 'pull-up', 'hanging-leg-raise', 'plank', 'triceps', 'carry']+ const entries = [entry('incline-bench', { sets: sets([true]) }),+ ...ids.map((id, i) => entry(id, { sg: 'sg-m3', sets: sets([i < 2, false, false, false]) }))]+ const active = { cur: 3, entries }+ expect(moveActiveWorkoutEntry(active, 3, 1)).not.toBeNull()+ const order = []+ for (let guard = 0; guard < 10; guard++) {+ const e = active.entries[active.cur]+ e.sets[e.sets.findIndex(set => !set.done)].done = true+ order.push(e.id)+ const unit = supersetUnits(active.entries).find(members => members.includes(active.cur))+ const step = supersetFlowStep(active.entries, unit, active.cur)+ active.cur = step.nextIdx+ if (step.roundDone) break+ }+ expect(order).toEqual(['plank', 'hanging-leg-raise', 'triceps', 'carry'])+ expect(active.entries.slice(1).map(e => e.sets.filter(set => set.done).length)).toEqual([1, 1, 1, 1, 1, 1])+ expect(active.entries[active.cur].id).toBe('split-squat')+ })++ it('refuses a swap across the marker mid-round, which would skip one member and repeat the other', () => {+ const active = { cur: 3, entries: circuit() }+ const before = ids(active)+ expect(canMoveActiveWorkoutEntry(active, 3, -1)).toBe(false)+ expect(canMoveActiveWorkoutEntry(active, 2, 1)).toBe(false)+ expect(moveActiveWorkoutEntry(active, 3, -1)).toBeNull()+ expect(moveActiveWorkoutEntry(active, 2, 1)).toBeNull()+ expect(ids(active)).toEqual(before)+ expect(active.cur).toBe(3)+ // at the top of a round nobody is behind the marker, so the first member may move down+ const top = { cur: 1, entries: circuit() }+ expect(canMoveActiveWorkoutEntry(top, 1, 1)).toBe(true)+ moveActiveWorkoutEntry(top, 1, 1)+ expect(top.entries[top.cur].id).toBe('pull-up')+ })++ it('at the superset edge moves the whole superset, as the unit move always has', () => {+ const up = { cur: 1, entries: circuit() }+ expect(moveActiveWorkoutEntry(up, 1, -1)?.indices).toEqual([1, 2, 3, 4, 5, 6, 0, 7])+ expect(ids(up)[6]).toBe('incline-bench')++ const down = { cur: 6, entries: circuit() }+ expect(moveActiveWorkoutEntry(down, 6, 1)?.indices).toEqual([0, 7, 1, 2, 3, 4, 5, 6])+ expect(ids(down)[1]).toBe('cool-down')+ })++ it('a lone exercise moves exactly as before, and the ends still refuse', () => {+ const solo = { cur: 0, entries: circuit() }+ expect(moveActiveWorkoutEntry(solo, 0, 1)?.indices).toEqual([1, 2, 3, 4, 5, 6, 0, 7])+ const ends = { cur: 0, entries: [entry('first'), entry('last')] }+ expect(canMoveActiveWorkoutEntry(ends, 0, -1)).toBe(false)+ expect(canMoveActiveWorkoutEntry(ends, 1, 1)).toBe(false)+ expect(moveActiveWorkoutEntry(ends, 0, -1)).toBeNull()+ expect(moveActiveWorkoutEntry(ends, 0, 0)).toBeNull()+ expect(ids(ends)).toEqual(['first', 'last'])+ })++ it('two adjacent supersets stay apart: an edge member never swaps into the next superset', () => {+ const active = { cur: 0, entries: [entry('a1', { sg: 'a' }), entry('a2', { sg: 'a' }), entry('b1', { sg: 'b' }), entry('b2', { sg: 'b' })] }+ expect(moveActiveWorkoutEntry(active, 1, 1)?.indices).toEqual([2, 3, 0, 1])+ expect(active.entries.map(item => `${item.id}:${item.sg}`)).toEqual(['b1:b', 'b2:b', 'a1:a', 'a2:a'])+ })+})+describe('active workout move locale coverage', () => {const packs = import.meta.glob('../locales/*.js', { eager: true, import: 'default' })// English is the source language and has no pack. Derived locales (de-CH) have none either:diff --git a/frontend/src/views/Workout.jsx b/frontend/src/views/Workout.jsxindex 39a96e3d8..63b1dd00e 100644--- a/frontend/src/views/Workout.jsx+++ b/frontend/src/views/Workout.jsx@@ -37,7 +37,7 @@ import { glyphOf } from '../lib/glyphs.js'import { markAllSetsDone, sessionHistory } from '../lib/backfill.js'import { bestSetFor } from '../lib/exercise-history.js'import { isWarmupRow, isDropSet, isRestPauseSet, dropsOf, clustersOf, addDrop, addCluster, removeDropAt, removeClusterAt, setDropAt, setClusterAt, nextDropWeight, nextBurstReps, isSideSet, makeSideSet, setSideField, toggleSide, addSideDrop, removeSideDropAt, setSideDropAt, addSideCluster, removeSideClusterAt, setSideClusterAt, WEIGHT_ORIGIN_MANUAL } from '../lib/workout-model.js'-import { canMoveActiveWorkoutUnit, moveActiveWorkoutUnit } from '../lib/active-workout-order.js'+import { canMoveActiveWorkoutUnit, moveActiveWorkoutUnit, canMoveActiveWorkoutEntry, moveActiveWorkoutEntry } from '../lib/active-workout-order.js'import { nextOpenSet, workoutKeyAction } from '../lib/workout-keys.js'import { MUSCLE_NAME } from '../lib/muscles.js'@@ -1127,15 +1127,19 @@ function ActiveWorkout() {})const onPairPrev = !isSuperset && cur > 0 ? () => pairAt(cur - 1, cur) : nullconst onPairNext = !isSuperset && cur < A.entries.length - 1 ? () => pairAt(cur, cur + 1) : null- const moveUnitAt = (at, direction) => {+ // `member`: the exercise ⋯ menu's move, which reorders a superset member inside its superset+ // (lib/active-workout-order.js moveActiveWorkoutEntry). The buttons below the exercise move the+ // whole unit. Both return the same index permutation, so everything below remaps the same way.+ const moveUnitAt = (at, direction, member = false) => {const ui = useUI.getState()const active = useStore.getState().S.active- if (ui.work || !canMoveActiveWorkoutUnit(active, at, direction)) return+ const canMove = member ? canMoveActiveWorkoutEntry : canMoveActiveWorkoutUnit+ if (ui.work || !canMove(active, at, 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, at, direction)+ const moved = (member ? moveActiveWorkoutEntry : moveActiveWorkoutUnit)(s.active, at, direction)if (!moved) return// The marker follows its unit: the superset card's scroll must not read that as a move.lastCur.current = s.active.cur@@ -1209,10 +1213,10 @@ function ActiveWorkout() {const blockProps = idx => ({editing,onSwap: () => swapActiveWorkoutExercise(idx),- onMoveUp: () => moveUnitAt(idx, -1),- onMoveDown: () => moveUnitAt(idx, 1),- canMoveUp: canMoveActiveWorkoutUnit(A, idx, -1),- canMoveDown: canMoveActiveWorkoutUnit(A, idx, 1),+ onMoveUp: () => moveUnitAt(idx, -1, true),+ onMoveDown: () => moveUnitAt(idx, 1, true),+ canMoveUp: canMoveActiveWorkoutEntry(A, idx, -1),+ canMoveDown: canMoveActiveWorkoutEntry(A, idx, 1),onRemoveExercise: () => confirmRemoveExercise(idx),busy: !!work,onToggle: i => toggle(idx, i),diff --git a/frontend/src/views/Workout.test.jsx b/frontend/src/views/Workout.test.jsxindex 5e8e6384b..37726620c 100644--- a/frontend/src/views/Workout.test.jsx+++ b/frontend/src/views/Workout.test.jsx@@ -69,6 +69,12 @@ vi.mock('../store/useStore.js', () => {vi.mock('../store/useUI.js', () => {const useUI = selector => selector ? selector(mocks.uiSnapshot()) : mocks.uiSnapshot()useUI.getState = mocks.uiSnapshot+ // A move hands the running rest to its exercise's new index (Workout.jsx moveUnitAt).+ useUI.setState = patch => {+ const next = typeof patch === 'function' ? patch(mocks.uiSnapshot()) : patch+ if ('timer' in next) mocks.timer = next.timer+ if ('work' in next) mocks.work = next.work+ }return { useUI }})vi.mock('react-router-dom', () => ({ useNavigate: () => mocks.nav }))@@ -1764,6 +1770,91 @@ describe('workout controls: the more menu and the set menu', () => {expect(mocks.confirmSheet).toHaveBeenCalled()})+ // Move down on a superset member's More menu moved the whole superset and left the member next+ // to the same partner (#377 reports it in the routine editor). It now swaps inside the superset.+ it('moves a superset member inside its superset from that member\'s More menu', async () => {+ await mount([+ exercise('bench', [true]),+ exercise('pull-up', [false], { sg: 'm' }),+ exercise('leg-raise', [false], { sg: 'm' }),+ exercise('plank', [false], { sg: 'm' }),+ ], 1)+ const more = container.querySelector('.ss-ex[data-exidx="2"] button[aria-label="More"]')+ expect(more).toBeTruthy()+ await act(async () => { more.dispatchEvent(new dom.Event('click', { bubbles: true })) })+ expect(item('Move up').disabled).toBe(false)+ expect(item('Move down').disabled).toBe(false)+ await act(async () => { item('Move down').onClick() })++ expect(mocks.S.active.entries.map(entry => entry.id)).toEqual(['bench', 'pull-up', 'plank', 'leg-raise'])+ expect(mocks.S.active.entries.slice(1).map(entry => entry.sg)).toEqual(['m', 'm', 'm'])+ expect(mocks.S.active.entries[mocks.S.active.cur].id).toBe('pull-up')+ })++ // A move reorders the entries, and two things the screen keeps by index have to follow their+ // exercise: the running rest (timer.forIdx) and how many sets of each exercise have already+ // counted as progress (the mark a tick is compared against to tell new work from a re-check).+ const openMore = async exIdx => {+ const more = container.querySelector(`.ss-ex[data-exidx="${exIdx}"] button[aria-label="More"]`)+ || container.querySelector('button[aria-label="More"]')+ await act(async () => { more.dispatchEvent(new dom.Event('click', { bubbles: true })) })+ }+ const restFor = forIdx => ({ left: 60, total: 60, endsAt: Date.now() + 60_000, forIdx, kind: 'set' })++ it('a member swap during a rest hands the rest to the moved exercise\'s new place', async () => {+ await mount([+ exercise('bench', [true]),+ exercise('pull-up', [true, false], { sg: 'm' }),+ exercise('leg-raise', [true, false], { sg: 'm' }),+ exercise('plank', [false, false], { sg: 'm' }),+ ], 1)+ mocks.timer = restFor(2)+ await openMore(2)+ await act(async () => { item('Move down').onClick() })++ expect(mocks.S.active.entries.map(entry => entry.id)).toEqual(['bench', 'pull-up', 'plank', 'leg-raise'])+ expect(mocks.timer.forIdx).toBe(3)+ expect(mocks.S.active.entries[mocks.timer.forIdx].id).toBe('leg-raise')+ expect(mocks.timer.endsAt).toBeGreaterThan(Date.now())+ expect(mocks.stopRest).not.toHaveBeenCalled()+ })++ it('a whole-superset move during a rest hands the rest to the resting exercise\'s new place', async () => {+ await mount([+ exercise('bench', [true, false]),+ exercise('pull-up', [false], { sg: 'm' }),+ exercise('leg-raise', [false], { sg: 'm' }),+ ], 1)+ mocks.timer = restFor(0)+ await openMore(1)+ await act(async () => { item('Move up').onClick() })++ expect(mocks.S.active.entries.map(entry => entry.id)).toEqual(['pull-up', 'leg-raise', 'bench'])+ expect(mocks.timer.forIdx).toBe(2)+ expect(mocks.S.active.entries[mocks.timer.forIdx].id).toBe('bench')+ })++ it('a member swap keeps each exercise\'s counted sets with it, so its next tick still counts', async () => {+ // pull-up has two sets counted, leg-raise none. After the swap, the leg raise's first tick+ // is new work and moves on through the superset; read against the pull-up's two it would be+ // taken for a re-check and go nowhere.+ await mount([+ exercise('bench', [true]),+ exercise('pull-up', [true, true, false], { sg: 'm' }),+ exercise('leg-raise', [false, false, false], { sg: 'm' }),+ exercise('plank', [false, false, false], { sg: 'm' }),+ ], 1)+ await openMore(1)+ await act(async () => { item('Move down').onClick() })+ expect(mocks.S.active.entries.map(entry => entry.id)).toEqual(['bench', 'leg-raise', 'pull-up', 'plank'])+ expect(mocks.S.active.cur).toBe(1)++ const tick = container.querySelector('.ss-ex[data-exidx="1"] [role="checkbox"]')+ await act(async () => { tick.dispatchEvent(new dom.Event('click', { bubbles: true })) })+ expect(mocks.S.active.entries[1].sets.filter(set => set.done)).toHaveLength(1)+ expect(mocks.S.active.cur).toBe(2)+ })+it('opens the exercise history sheet from the More menu, for the tapped exercise', async () => {// the screen shows one exercise at a time, so "the tapped exercise" is the current oneawait mount([exercise('plain-bench', [false]), exercise('plain-row', [false])], 1)