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): rating a superset set scrolls to the partner, like a tick
Boris 'B' Kurktchiev5a6a63ac29fa
diff --git a/frontend/src/components/Modals.jsx b/frontend/src/components/Modals.jsxindex 3ca3ae07e..e4c876b78 100644--- a/frontend/src/components/Modals.jsx+++ b/frontend/src/components/Modals.jsx@@ -2,6 +2,48 @@ import { useEffect, useLayoutEffect, useRef } from 'react'import { useUI } from '../store/useUI.js'import { keyboardOpen } from '../lib/viewport-guard.js'+// Putting the page back after a sheet closes takes up to three goes (see the un-pin below): now,+// next frame, and once the keyboard's dismiss animation is over. Anything else that wants to+// scroll in that same commit is overwritten. Rating a set closes the effort picker AND ticks the+// set in one tap, and the superset card's "bring the partner's row into view" was undone about+// 3 ms after it was asked for, every time. afterScrollRestore runs fn once the sequence is done,+// or straight away when none is running, and returns a canceller for the caller's effect cleanup.+//+// It does not get a timer of its own. Two ~350 ms timers armed a few milliseconds apart run in+// whichever order the browser likes, and on a phone the re-assert can come second and undo the+// scroll. So the last re-assert runs these itself, in its own timer callback, right after its own+// scrollTo: there is no ordering left to get wrong.+const RESTORE_MS = 350+let restoreUntil = 0+// Real closes, counted, so the last re-assert can tell whether it belongs to the latest one. That,+// not the clock, ends the sequence: with Date.now() coarsened or jittered (privacy.resistFingerprinting+// rounds it to 100 ms) a deadline read in that callback can still look a few ms away, and a waiter+// would then sit in the queue with nothing left to run it.+let closes = 0+let waiting = []+export function afterScrollRestore(fn) {+ if (!(restoreUntil - Date.now() > 0)) { fn(); return () => {} }+ waiting.push(fn)+ return () => { waiting = waiting.filter(x => x !== fn) }+}+// Whether that sequence is still running, for a scroll that would rather not happen at all than+// come after it: the superset card's scroll when the marker did not move (views/Workout.jsx) used+// to be undone by the restore on the spot, and skipping it keeps that exactly.+export const scrollRestorePending = () => restoreUntil - Date.now() > 0+// Called by the last re-assert of close number `close`, once it has had its say. Two reasons to+// leave the queue alone and let a later re-assert take it: a second sheet closed inside this window+// (its own last re-assert drains it), or the page is pinned again behind a newly opened sheet,+// where a scroll would be meaningless; that sheet's own un-pin comes with a fresh sequence.+const drainScrollRestore = close => {+ if (!close || close !== closes || document.body.style.position === 'fixed') return+ restoreUntil = 0+ const queue = waiting+ waiting = []+ for (const fn of queue) {+ try { fn() } catch (e) { /* one caller must not keep the others waiting */ }+ }+}+// One bottom sheet (or centered dialog) with swipe-to-dismiss.function Sheet({ sheet }) {const { closeSheet } = useUI()@@ -184,6 +226,13 @@ export default function Modals() {b.position = 'fixed'; b.top = -y + 'px'; b.left = '0'; b.right = '0'; b.width = '100%'return () => {b.position = b.top = b.left = b.right = b.width = ''+ // Tell anything that scrolls for its own reasons how long this will go on (afterScrollRestore),+ // but only when a sheet really did close. React StrictMode runs this cleanup immediately after+ // the effect when Modals mounts with a sheet already up, and arming the window there would make+ // anything waiting on the restore wait RESTORE_MS for a page nobody is putting back: late in+ // dev, on time in production. In production this cleanup runs on the close path alone.+ const close = useUI.getState().sheets.length ? 0 : ++closes+ if (close) restoreUntil = Date.now() + RESTORE_MSwindow.scrollTo(0, y)// iOS scrolls asynchronously; a restore issued in the same task as the un-pin can be applied// a frame late or against the still-short layout. Say it once more on the next frame.@@ -192,13 +241,21 @@ export default function Modals() {// iOS scrolls the page again while the keyboard dismisses — after the line above ran.// Ask once more when that animation is over. The window-level guard in// lib/viewport-guard.js covers the keyboard closing while a sheet stays open.- // Only with the keyboard up, though: without one there is nothing to undo, and a late- // restore would overwrite a scroll the page behind made on purpose because the sheet- // closed — the workout list going to the current exercise after ⋯ → Layout → List- // (issue #224). At this point the sheet's field is already out of the DOM but the- // keyboard has not started to go, so the visual viewport still tells the truth.- if (!keyboardOpen()) return- window.setTimeout(() => { if (document.body.style.position !== 'fixed') window.scrollTo(0, y) }, 350)+ // This last one also hands the page over to anything that has been waiting for the sequence+ // to finish (afterScrollRestore), in this same callback, right after its own scrollTo, so a+ // scroll of someone else's cannot be undone by a re-assert still to come.+ //+ // The re-assert itself is for the keyboard case only: without one there is nothing to undo,+ // and a late restore would overwrite a scroll the page behind made on purpose because the+ // sheet closed — the workout list going to the current exercise after ⋯ → Layout → List+ // (issue #224). At this point the sheet's field is already out of the DOM but the keyboard+ // has not started to go, so the visual viewport still tells the truth. The timer is armed+ // either way, because the hand-over is the only thing that drains the queue.+ const hadKeyboard = keyboardOpen()+ window.setTimeout(() => {+ if (hadKeyboard && document.body.style.position !== 'fixed') window.scrollTo(0, y)+ drainScrollRestore(close)+ }, RESTORE_MS)}}, [sheets.length > 0])diff --git a/frontend/src/components/Modals.test.jsx b/frontend/src/components/Modals.test.jsxindex c6466ad92..211a7fce2 100644--- a/frontend/src/components/Modals.test.jsx+++ b/frontend/src/components/Modals.test.jsx@@ -2,7 +2,7 @@ import React, { act } from 'react'import { createRoot } from 'react-dom/client'import { parseHTML } from 'linkedom'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import Modals from './Modals.jsx'+import Modals, { afterScrollRestore, scrollRestorePending } from './Modals.jsx'const mocks = vi.hoisted(() => {const listeners = new Set()@@ -353,4 +353,145 @@ describe('pinning the page behind a sheet', () => {expect(dom.scrollTo).toHaveBeenCalledTimes(3) // and after the keyboard's dismiss animationvi.useRealTimers()})++ // Rating a set closes the effort picker AND ticks it in one tap, so the superset card's own+ // "bring the partner's row into view" is asked for in the same commit as the restore, and the+ // re-assert overwrote it a few ms later, every time. Anything scrolling for its own reasons+ // waits for the restores, and then has the last word.+ it('hands a scroll of its own over the moment the restores are done, and not a frame before', async () => {+ vi.useFakeTimers()+ dom.innerHeight = 800+ dom.visualViewport = { height: 800 } // no keyboard: a menu sheet+ Object.defineProperty(dom, 'scrollY', { configurable: true, value: 974 })+ const rafs = []+ dom.requestAnimationFrame = fn => { rafs.push(fn); return rafs.length }+ await setSheets([sheet('effort-picker')])+ await setSheets([]) // the pick closes it and ticks the set+ expect(scrollRestorePending()).toBe(true)++ // The order is the whole point, so record it rather than counting: the handed-over scroll must+ // come STRICTLY after the last restore. Equal-time is a fail; on a phone that is a coin toss.+ const order = []+ dom.scrollTo.mockImplementation(() => order.push('scrollTo'))+ afterScrollRestore(() => order.push('handed over'))+ expect(order).toEqual([]) // not while the page is being put back+ rafs.forEach(fn => fn())+ expect(order).toEqual(['scrollTo']) // the next-frame re-assert, alone+ vi.advanceTimersByTime(400)+ expect(order).toEqual(['scrollTo', 'handed over']) // no keyboard, so no late re-assert+ expect(order.indexOf('handed over')).toBeGreaterThan(order.lastIndexOf('scrollTo'))+ expect(scrollRestorePending()).toBe(false)+ vi.advanceTimersByTime(1000)+ expect(order.at(-1)).toBe('handed over') // and nothing undoes it afterwards+ vi.useRealTimers()+ })++ it('hands over after the late re-assert when the sheet closed with the keyboard up', async () => {+ vi.useFakeTimers()+ dom.innerHeight = 800+ dom.visualViewport = { height: 460 }+ Object.defineProperty(dom, 'scrollY', { configurable: true, value: 974 })+ const rafs = []+ dom.requestAnimationFrame = fn => { rafs.push(fn); return rafs.length }+ await setSheets([sheet('effort-picker')])+ await setSheets([])+ const order = []+ dom.scrollTo.mockImplementation(() => order.push('scrollTo'))+ afterScrollRestore(() => order.push('handed over'))+ rafs.forEach(fn => fn())+ vi.advanceTimersByTime(400)+ expect(order).toEqual(['scrollTo', 'scrollTo', 'handed over'])+ vi.useRealTimers()+ })++ it('waits for a second sheet that closes inside the first one\'s window', async () => {+ vi.useFakeTimers()+ Object.defineProperty(dom, 'scrollY', { configurable: true, value: 974 })+ let rafs = []+ dom.requestAnimationFrame = fn => { rafs.push(fn); return rafs.length }+ await setSheets([sheet('one')])+ await setSheets([])+ const order = []+ dom.scrollTo.mockImplementation(() => order.push('scrollTo'))+ afterScrollRestore(() => order.push('handed over'))+ vi.advanceTimersByTime(200)+ await setSheets([sheet('two')]) // and another one closes+ await setSheets([])+ rafs.forEach(fn => fn()); rafs = []+ vi.advanceTimersByTime(160) // past the FIRST deadline+ expect(order).not.toContain('handed over') // the sequence moved; so does the queue+ vi.advanceTimersByTime(200) // past the second one+ expect(order.at(-1)).toBe('handed over')+ expect(order.indexOf('handed over')).toBeGreaterThan(order.lastIndexOf('scrollTo'))+ vi.advanceTimersByTime(1000)+ expect(order.filter(x => x === 'handed over')).toHaveLength(1)+ vi.useRealTimers()+ })++ // A clock that reads coarse (privacy.resistFingerprinting rounds Date.now to 100 ms) can make+ // the last re-assert look early against the deadline. The hand-over happens there all the same,+ // and nothing asked for after it is left waiting for a close that is over.+ it('hands over on the last re-assert even when the clock reads behind the deadline', async () => {+ vi.useFakeTimers()+ dom.innerHeight = 800+ dom.visualViewport = { height: 800 }+ Object.defineProperty(dom, 'scrollY', { configurable: true, value: 974 })+ dom.requestAnimationFrame = () => 0+ await setSheets([sheet('effort-picker')])+ await setSheets([])+ const ran = vi.fn()+ afterScrollRestore(ran)+ vi.setSystemTime(Date.now() - 100) // the clock now reads 100 ms behind+ vi.advanceTimersByTime(360)+ expect(ran).toHaveBeenCalledTimes(1)+ expect(scrollRestorePending()).toBe(false)+ const later = vi.fn()+ afterScrollRestore(later)+ expect(later).toHaveBeenCalledTimes(1)+ vi.useRealTimers()+ })++ it('runs a scroll of its own straight away when no sheet is closing', async () => {+ vi.useFakeTimers()+ vi.advanceTimersByTime(1000) // whatever closed earlier is long done+ expect(scrollRestorePending()).toBe(false)+ const ran = vi.fn()+ afterScrollRestore(ran)+ expect(ran).toHaveBeenCalledTimes(1) // the plain checkbox tick's path+ vi.useRealTimers()+ })+})++// The scroll-restore window says "the page is being put back, wait your turn". It belongs to the+// close path alone. StrictMode (dev) runs the pin/un-pin layout effect twice when Modals mounts+// with a sheet already open, and the cleanup in between looked exactly like a close, so anything+// waiting on the restore (the superset card's scroll, views/Workout.jsx) sat out 350 ms for a+// page nobody was putting back. In dev only.+describe('the restore window under StrictMode', () => {+ it('is not armed by a sheet opening, and still is by one closing', async () => {+ vi.useFakeTimers()+ vi.advanceTimersByTime(1000) // whatever ran earlier is long done+ await act(async () => { root.unmount() })+ root = createRoot(container)+ const rafs = []+ dom.requestAnimationFrame = fn => { rafs.push(fn); return rafs.length }++ // Mounting with a sheet already up is the path StrictMode double-invokes: effect, cleanup,+ // effect, all in the one commit, with the sheet open throughout.+ mocks.state.sheets = [sheet('already-open')]+ await act(async () => { root.render(React.createElement(React.StrictMode, null, React.createElement(Modals))) })+ expect(document.body.style.position).toBe('fixed') // the page is pinned, not restoring++ const onOpen = vi.fn()+ afterScrollRestore(onOpen)+ expect(onOpen).toHaveBeenCalledTimes(1) // so a scroll of its own runs now++ await setSheets([])+ const onClose = vi.fn()+ afterScrollRestore(onClose)+ expect(onClose).not.toHaveBeenCalled() // and a real close still holds it+ vi.advanceTimersByTime(400)+ expect(onClose).toHaveBeenCalledTimes(1)+ vi.useRealTimers()+ })})diff --git a/frontend/src/views/Workout.jsx b/frontend/src/views/Workout.jsxindex 39340a4ed..8b93d000c 100644--- a/frontend/src/views/Workout.jsx+++ b/frontend/src/views/Workout.jsx@@ -16,6 +16,7 @@ import { api, beacon } from '../lib/api.js'import { insertionIndexAfterCurrentUnit, nextUnfinishedUnit, setProgressHighWater, supersetFlowStep, restAfterSet, restOnRecheck, restSecFor, warmupRestSecFor } from '../lib/supersetFlow.js'import Media from '../components/Media.jsx'import { startFlow, exercisePicker, exConfigSheet, exerciseDetailSheet, finishWorkout, exitWorkoutEdit, workoutCompleteSheet, confirmSheet, exerciseNoteSheet, sessionNoteSheet, renameWorkoutSheet, swapActiveWorkoutExercise, barWeightSheet, menuSheet, effortPickerSheet, exerciseHistorySheet, addRoutineToSessionSheet } from '../sheets.jsx'+import { afterScrollRestore, scrollRestorePending } from '../components/Modals.jsx'import { effortColor } from '../lib/effort.js'import Icon from '../components/Icon.jsx'import { Button, Check, NumberField } from '../components/ui.jsx'@@ -648,6 +649,35 @@ export function removeActiveExercise(idx) {}, true)}+// Whether a set row sits wholly between the fixed bars at the top and at the bottom: the status bar+// and the connection bar above, the tab bar and the rest or hold bar below. The Cards header+// scrolls with the page, so it takes nothing off the top, and a row is short enough to be all in+// or all out.+const rowOnScreen = el => {+ if (typeof window === 'undefined' || typeof el.getBoundingClientRect !== 'function') return false+ const r = el.getBoundingClientRect()+ let bottom = window.innerHeight+ for (const id of ['timer', 'tabbar']) {+ const bar = document.getElementById(id)+ const top = bar && typeof bar.getBoundingClientRect === 'function' ? bar.getBoundingClientRect().top : null+ if (top != null && top < bottom) bottom = top+ }+ return r.bottom <= bottom && r.top >= coveredTop()+}+// How much of the top of the screen the fixed bars cover. The installed app draws the page under+// the translucent status bar (viewport-fit=cover), and the connection bar (SyncBanner) sits below+// it while there is no server to reach. index.css keeps the two as --sat and --conn, but --sat is+// a max() of env() and --native-sat, and a custom property's computed value is the expression as+// text ("max(0px,47px)"), not a length. So it is measured off an element that is that tall.+const coveredTop = () => {+ const probe = document.createElement('div')+ probe.style.cssText = 'position:fixed;top:0;left:0;width:0;height:calc(var(--sat) + var(--conn));visibility:hidden;pointer-events:none'+ document.body.appendChild(probe)+ const inset = probe.offsetHeight || 0+ probe.remove()+ return inset+}+function ActiveWorkout() {const nav = useNavigate()const S = useStore(s => s.S)@@ -715,13 +745,49 @@ function ActiveWorkout() {if (!liveEntries.has(entry)) setRefs.current.delete(entry)}})+ // What this render shows, for a scroll that may run after it (below): the store clones the+ // whole state on every write and the ref maps above are keyed by entry object, so an entry+ // kept from an earlier render can be a key nothing is under any more.+ const shown = useRef(null)+ shown.current = { entries: A.entries, cur }+ // The marker's index when the effect below last ran. The effect also runs on mount, when two+ // exercises are paired, on List → Cards and when a unit is moved up or down. Each of those used+ // to ask for the same scroll, and a sheet closing in the same tap (the weigh-in sheet a session+ // starts through, the exercise ⋯ menu, the Layout menu) undid it on the spot. Once the scroll+ // waits for that restore they would land, and a session started through the weigh-in sheet+ // would open with its header off screen. So a run the marker did not cause scrolls only a row+ // that is off screen, and never while a sheet is still putting the page back. Coming back to+ // the session with the row below the fold still brings it back, as it always did.+ const lastCur = useRef(null)useEffect(() => {+ // Judged by index alone. A unit moved up or down carries the marker's index with it, and+ // moveUnitAt records the new index here itself before this runs, so that reads as no move;+ // a superset of two rows of the same exercise still reads the tick from one to the other as+ // a move.+ const was = lastCur.current+ lastCur.current = cur+ const moved = was != null && was !== curif (!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' })+ // A run the marker did not cause, with a sheet closing in the same tap, never scrolled: the+ // restore undid it. Keep that by not asking at all. Asking after the restore and then judging+ // the row would centre a first row that a tall first block (a note, "Last time", the+ // progression line) pushes partly under the tab bar, and scroll the header away.+ if (!moved && scrollRestorePending()) return+ // Rating the set (RIR or RPE, one picker) closes the sheet and ticks the set in one tap, and+ // the sheet's un-pin puts the page back where it stood, now and once more a frame later+ // (components/Modals.jsx). A scroll asked for in this same commit was undone a few ms later,+ // every time, and the partner's row stayed below the fold. With no sheet closing in the last+ // third of a second, afterScrollRestore runs this at once, as the tick always did.+ return afterScrollRestore(() => {+ const { entries, cur: at } = shown.current+ const entry = entries[at]+ 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') return+ if (!moved && rowOnScreen(el)) return+ el.scrollIntoView({ behavior: 'smooth', block: 'center' })+ })}, [cur, isSuperset, listMode, A.entries.length])// The list opens at the exercise you are on, not at the top of the session (issue #224): you// switch to it mid-workout to look at what comes before and after. Only on the way in — once@@ -820,6 +886,8 @@ function ActiveWorkout() {update(s => {const moved = 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.curprogressHighWater.current = moved.indices.map(index => progressHighWater.current[index])const rest = useUI.getState().timerif (rest && rest.forIdx != null) {diff --git a/frontend/src/views/Workout.sheet-scroll.test.jsx b/frontend/src/views/Workout.sheet-scroll.test.jsxnew file mode 100644index 000000000..5dc417a1a--- /dev/null+++ b/frontend/src/views/Workout.sheet-scroll.test.jsx@@ -0,0 +1,131 @@+// @vitest-environment happy-dom+// The real pieces together: the real Workout view, the real Modals with its scroll restore, the+// real useUI and the real effort picker. Rating a set in a superset closes the picker AND ticks+// the set in one tap, so the sheet's restore and the card's "bring the partner's row into view"+// are asked for in the same commit. Each half is tested alone elsewhere with the other mocked;+// only both together show the order they land in, and the order is the bug.+import React, { act } from 'react'+import { createRoot } from 'react-dom/client'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import Workout from './Workout.jsx'+import Modals from '../components/Modals.jsx'+import { useUI } from '../store/useUI.js'+import { DEF, useStore } from '../store/useStore.js'++vi.mock('../lib/sound.js', async importOriginal => ({+ ...(await importOriginal()), beep: vi.fn(), chime: vi.fn(), unlock: vi.fn(), vibrate: vi.fn(),+}))+vi.mock('../lib/api.js', () => ({+ api: vi.fn(() => Promise.resolve({})), IS_APPLE: false, IS_ANDROID: false, BIO: 'biometrics',+}))+vi.mock('react-router-dom', () => ({ useNavigate: () => () => {} }))+vi.mock('../components/Media.jsx', () => ({ default: () => null }))++globalThis.IS_REACT_ACT_ENVIRONMENT = true++let host, root, originalS, scrolls, rafs++const row = () => ({ w: 60, r: 5, done: false })+const entry = (id, sg) => ({ id, sg, target: { mode: 'reps', sets: 2, reps: 5, weight: 60, bodyweight: false }, sets: [row(), row()] })++// The restore window is module state in Modals.jsx, kept as a time. Each test's fake clock starts+// a minute past the previous one's, so a sheet an earlier test closed is long done.+let clock = Date.now()++beforeEach(() => {+ vi.useFakeTimers({ now: clock += 60_000 })+ originalS = useStore.getState().S+ scrolls = []+ rafs = []++ window.scrollTo = vi.fn(() => scrolls.push('scrollTo'))+ window.requestAnimationFrame = fn => { rafs.push(fn); return rafs.length }+ window.cancelAnimationFrame = () => {}+ Element.prototype.scrollIntoView = vi.fn(function () { scrolls.push(this) })++ const S = JSON.parse(JSON.stringify(DEF))+ S.workoutView = 'cards'+ S.effort = 'rir'+ S.restSec = 90+ S.sound = false+ // Bench and squat as one superset card, then a row press on its own.+ S.active = {+ id: 'a', name: 'Test', start: Date.now(), cur: 0,+ entries: [entry('0025', 'g'), entry('0043', 'g'), entry('0001')],+ }+ useStore.setState({ S, user: null })+ useUI.setState({ sheets: [], timer: null, work: null, toastMsg: '' })++ host = document.createElement('div')+ document.body.appendChild(host)+ root = createRoot(host)+})++afterEach(() => {+ act(() => root.unmount())+ host.remove()+ useUI.getState().stopRest()+ useUI.getState().stopWork()+ useUI.setState({ sheets: [] })+ useStore.setState({ S: originalS })+ document.body.style.position = ''+ vi.useRealTimers()+})++const mount = async () => {+ await act(async () => { root.render(<><Workout /><Modals /></>) })+}+const click = async el => {+ expect(el).toBeTruthy()+ await act(async () => { el.dispatchEvent(new window.Event('click', { bubbles: true })) })+}+const runFrames = async () => {+ const queued = rafs+ rafs = []+ await act(async () => { queued.forEach(fn => fn()) })+}++describe('rating a superset set closes a sheet and moves the marker in one tap', () => {+ it('scrolls to the partner row after the sheet has finished putting the page back', async () => {+ await mount()+ const partnerRow = () => host.querySelectorAll('.setrow')[2]++ // The RIR cell of the first set of the first exercise.+ await click(host.querySelector('.setrow .effcell.is-empty'))+ expect(useUI.getState().sheets.length).toBe(1)+ expect(document.body.style.position).toBe('fixed') // the page is pinned behind the sheet+ await runFrames()+ scrolls.length = 0++ // Pick a level: the sheet closes, the set is ticked and the marker moves to the partner.+ await click(document.querySelector('.effpick .item.menu-item'))+ expect(useUI.getState().sheets.length).toBe(0)+ expect(useStore.getState().S.active.entries[0].sets[0].done).toBe(true)+ expect(useStore.getState().S.active.cur).toBe(1)+ expect(scrolls).toEqual(['scrollTo']) // the un-pin's restore, nothing else yet++ await runFrames()+ expect(scrolls).toEqual(['scrollTo', 'scrollTo']) // the next-frame re-assert++ await act(async () => { vi.advanceTimersByTime(349) })+ expect(scrolls).toEqual(['scrollTo', 'scrollTo']) // still nothing of the card's+ await act(async () => { vi.advanceTimersByTime(3) })++ // The card's scroll comes STRICTLY after the last restore, onto the partner's row.+ expect(scrolls).toEqual(['scrollTo', 'scrollTo', partnerRow()])++ // And nothing undoes it afterwards.+ await runFrames()+ await act(async () => { vi.advanceTimersByTime(1000) })+ expect(scrolls.filter(s => s === 'scrollTo')).toHaveLength(2)+ expect(scrolls.at(-1)).toBe(partnerRow())+ })++ it('a plain tick still scrolls to the partner row at once', async () => {+ await mount()+ scrolls.length = 0+ await click(host.querySelector('[role="checkbox"]'))+ expect(useStore.getState().S.active.cur).toBe(1)+ expect(scrolls).toEqual([host.querySelectorAll('.setrow')[2]])+ })+})diff --git a/frontend/src/views/Workout.superset-scroll.test.jsx b/frontend/src/views/Workout.superset-scroll.test.jsxnew file mode 100644index 000000000..60359284c--- /dev/null+++ b/frontend/src/views/Workout.superset-scroll.test.jsx@@ -0,0 +1,308 @@+import React, { act } from 'react'+import { createRoot } from 'react-dom/client'+import { parseHTML } from 'linkedom'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import Workout from './Workout.jsx'+import { effortPickerSheet } from '../sheets.jsx'++// In the Cards layout a superset is one card, and a tick that moves the marker to the partner+// centres the partner's next set row. Rating the set instead (RIR or RPE, one picker) closes the+// picker and ticks the set in the same tap, and the sheet's un-pin puts the page back where it+// stood, now and a frame later (components/Modals.jsx): a scroll asked for in that same commit+// was undone a few ms later, every time, and the partner's row stayed below the fold. So the+// card's scroll waits for the restore (afterScrollRestore), and reads the row when the wait is+// over: the store clones the whole state on every write and the row refs are keyed by entry.+const mocks = vi.hoisted(() => {+ const state = {+ S: null, timer: null, work: null,+ startRest: vi.fn(), startWork: vi.fn(), toast: vi.fn(), menuSheet: vi.fn(),+ stopRest: null, stopWork: null,+ afterScrollRestore: vi.fn(fn => { fn(); return () => {} }),+ scrollRestorePending: vi.fn(() => false),+ }+ state.stopRest = vi.fn(() => { state.timer = null })+ state.stopWork = vi.fn(() => { state.work = null })+ state.storeSnapshot = () => ({+ S: state.S,+ user: null,+ update: mut => { const next = structuredClone(state.S); mut(next); state.S = next },+ })+ state.uiSnapshot = () => ({+ timer: state.timer, work: state.work,+ startRest: state.startRest, stopRest: state.stopRest, stopWork: state.stopWork,+ shiftRestOwner: vi.fn(), startWork: state.startWork, toast: state.toast,+ })+ return state+})++vi.mock('../store/useStore.js', () => {+ const useStore = selector => selector(mocks.storeSnapshot())+ useStore.getState = mocks.storeSnapshot+ return { useStore }+})+vi.mock('../store/useUI.js', () => {+ const useUI = selector => selector ? selector(mocks.uiSnapshot()) : mocks.uiSnapshot()+ useUI.getState = mocks.uiSnapshot+ return { useUI }+})+vi.mock('react-router-dom', () => ({ useNavigate: () => () => {} }))+vi.mock('../sheets.jsx', () => ({+ startFlow: vi.fn(), exercisePicker: vi.fn(), exConfigSheet: vi.fn(), exerciseDetailSheet: vi.fn(),+ finishWorkout: vi.fn(), exitWorkoutEdit: vi.fn(), workoutCompleteSheet: vi.fn(), confirmSheet: vi.fn(),+ swapActiveWorkoutExercise: vi.fn(), menuSheet: mocks.menuSheet, barWeightSheet: vi.fn(),+ exerciseNoteSheet: vi.fn(), sessionNoteSheet: vi.fn(), renameWorkoutSheet: vi.fn(),+ effortPickerSheet: vi.fn(), exerciseHistorySheet: vi.fn(), addRoutineToSessionSheet: vi.fn(),+}))+vi.mock('../components/Media.jsx', () => ({ default: () => null }))+vi.mock('../components/Modals.jsx', () => ({ afterScrollRestore: mocks.afterScrollRestore, scrollRestorePending: mocks.scrollRestorePending }))+vi.mock('../lib/api.js', () => ({+ api: vi.fn(() => Promise.resolve({})), IS_APPLE: false, IS_ANDROID: false, BIO: 'biometrics',+}))++let dom, root, container++// The ids are real library ones so the card has names to show.+const lifted = (id, sg) => ({+ id, sg,+ target: { mode: 'reps', sets: 3, reps: 8, weight: 60, restSec: 60 },+ sets: Array.from({ length: 3 }, () => ({ r: 8, w: 60, done: false })),+})++function installDom() {+ const parsed = parseHTML('<!doctype html><html><body><div id="root"></div></body></html>')+ dom = parsed.window+ globalThis.window = dom+ 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()+ dom.requestAnimationFrame = () => 0+ dom.cancelAnimationFrame = () => {}+ globalThis.IS_REACT_ACT_ENVIRONMENT = true+ container = document.getElementById('root')+ root = createRoot(container)+}++async function mount(entries, cur = 0, active = {}, prep = null) {+ mocks.S = {+ 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 },+ }+ installDom()+ prep?.() // anything the first render must already find on the DOM: the screen's geometry+ await act(async () => { root.render(React.createElement(Workout)) })+}++async function press(button) {+ expect(button).toBeTruthy()+ await act(async () => { button.dispatchEvent(new dom.Event('click', { bubbles: true })) })+}++// The mocked store is a plain snapshot with nothing subscribed to it, so a change reaches the+// DOM only on the next render. Tests that read the screen ask for one.+const rerender = () => act(async () => { root.render(React.createElement(Workout)) })++beforeEach(() => {+ mocks.timer = null; mocks.work = null+ // The default runs a queued scroll at once; a test that defers one must not leak that into the next.+ mocks.afterScrollRestore.mockReset(); mocks.afterScrollRestore.mockImplementation(fn => { fn(); return () => {} })+ mocks.scrollRestorePending.mockReset(); mocks.scrollRestorePending.mockImplementation(() => false)+ mocks.startRest.mockClear(); mocks.startWork.mockClear()+ mocks.stopRest.mockClear(); mocks.stopWork.mockClear(); mocks.menuSheet.mockClear()+ effortPickerSheet.mockClear()+})+afterEach(async () => {+ if (root) await act(async () => { root.unmount() })+ root = null; container = null; dom = null+})++describe('the superset card after a rating', () => {+ const superset = () => [lifted('0025', 'g'), lifted('0043', 'g'), lifted('0001', 'h')]+ const partnerFirstRow = () => container.querySelectorAll('.setrow')[3]+ // scrollIntoView's `this` is the row it was asked to bring in.+ const watchScrolls = () => { const seen = []; dom.Element.prototype.scrollIntoView = vi.fn(function () { seen.push(this) }); return seen }+ // Where every row stands on a 659 px screen (linkedom lays nothing out): 400 is in view, 889 is+ // below the fold.+ const rowsAt = top => { dom.innerHeight = 659; dom.Element.prototype.getBoundingClientRect = () => ({ top, bottom: top + 44, left: 0, right: 390, width: 390, height: 44 }) }+ // The height the bars at the top (--sat, --conn) measure at. linkedom lays nothing out, so the+ // element Workout.jsx sizes by them reports what the test says.+ const topBars = px => {+ Object.defineProperty(dom.HTMLElement.prototype, 'offsetHeight', {+ configurable: true, get() { return this.style?.height === 'calc(var(--sat) + var(--conn))' ? px : 0 },+ })+ }++ it.each(['rir', 'rpe'])('%s: the scroll waits for the sheet to hand the page back, then lands on the partner row', async kind => {+ await mount(superset(), 0)+ mocks.S = { ...mocks.S, effort: kind }; await rerender()+ const seen = watchScrolls()+ await press(container.querySelector('.setrow:not(.done) .effcell.is-empty'))+ const [pickedKind, , pick] = effortPickerSheet.mock.calls.at(-1)+ expect(pickedKind).toBe(kind)+ // The picker closes in this same commit: Modals.jsx hands the page back later.+ const queued = []+ mocks.afterScrollRestore.mockImplementationOnce(fn => { queued.push(fn); return () => {} })+ const rating = kind === 'rpe' ? 8 : 2+ await act(async () => { pick(rating) })+ await rerender()+ expect(mocks.S.active.entries[0].sets[0].done).toBe(true)+ expect(mocks.S.active.entries[0].sets[0][kind]).toBe(rating)+ expect(mocks.S.active.cur).toBe(1)+ expect(queued).toHaveLength(1)+ expect(seen).toHaveLength(0)+ // Another write lands before the wait is over. Every write clones the whole state, so the+ // entry the asking render had is under no row ref any more.+ mocks.storeSnapshot().update(s => { s.active.entries[2].sets[0].w = 62.5 }); await rerender()+ await act(async () => { queued[0]() })+ expect(seen).toEqual([partnerFirstRow()])+ })++ it('a plain tick scrolls at once, as it did', async () => {+ await mount(superset(), 0)+ const seen = watchScrolls()+ await press(container.querySelector('[role="checkbox"]'))+ await rerender()+ expect(mocks.S.active.cur).toBe(1)+ expect(seen).toEqual([partnerFirstRow()])+ })++ it('unpairing during the wait cancels the queued scroll', async () => {+ await mount(superset(), 0)+ mocks.S = { ...mocks.S, effort: 'rir' }; await rerender()+ const seen = watchScrolls()+ await press(container.querySelector('.setrow:not(.done) .effcell.is-empty'))+ const [, , pick] = effortPickerSheet.mock.calls.at(-1)+ const cancel = vi.fn(); const queued = []+ mocks.afterScrollRestore.mockImplementationOnce(fn => { queued.push(fn); return cancel })+ await act(async () => { pick(2) })+ await rerender()+ expect(queued).toHaveLength(1)+ // The queued callback never re-checks the pairing: the effect's cleanup is what stops it.+ mocks.storeSnapshot().update(s => { delete s.active.entries[0].sg; delete s.active.entries[1].sg }); await rerender()+ expect(cancel).toHaveBeenCalledTimes(1)+ expect(seen).toEqual([])+ })++ // The effect also runs on mount, on pairing and on a layout switch. Each used to ask for the+ // same scroll, undone by the sheet those pass through (weigh-in, exercise ⋯, Layout). With the+ // wait in place they would land, and a session would open with its header off screen.+ it('does not scroll on mount when the row is on screen', async () => {+ await mount(superset(), 0, {}, () => rowsAt(400))+ expect(dom.Element.prototype.scrollIntoView).not.toHaveBeenCalled()+ })+ // Coming back to the session, or a fresh open, with the row below the fold.+ it('brings a row below the fold back on mount, as it always did', async () => {+ await mount(superset(), 1, {}, () => rowsAt(889))+ const scroll = dom.Element.prototype.scrollIntoView+ expect(scroll).toHaveBeenCalledTimes(1)+ expect(scroll.mock.contexts[0]).toBe(partnerFirstRow())+ })+ it('does not scroll when two exercises are paired', async () => {+ await mount([lifted('0025'), lifted('0043'), lifted('0001')], 0)+ rowsAt(400); const seen = watchScrolls()+ mocks.storeSnapshot().update(s => { s.active.entries[0].sg = 'g'; s.active.entries[1].sg = 'g' }); await rerender()+ expect(container.querySelectorAll('.setrow')).toHaveLength(6)+ expect(seen).toEqual([])+ })+ it('does not scroll on List → Cards', async () => {+ await mount(superset(), 0, { workoutView: 'list' })+ rowsAt(400); const seen = watchScrolls()+ mocks.storeSnapshot().update(s => { s.active.workoutView = 'cards' }); await rerender()+ expect(seen).toEqual([])+ // …and a marker move after the switch still does, on-screen row or not.+ await press(container.querySelector('[role="checkbox"]'))+ await rerender()+ expect(mocks.S.active.cur).toBe(1)+ expect(seen).toEqual([partnerFirstRow()])+ })+ // The marker moved while the List was up, where this scroll never runs; the switch back to+ // Cards is not that move. The marker's position is remembered on every run, early return or not.+ it('a marker moved in the List does not scroll once Cards comes back', async () => {+ await mount(superset(), 0, {}, () => rowsAt(400))+ const seen = watchScrolls()+ mocks.storeSnapshot().update(s => { s.active.workoutView = 'list' }); await rerender()+ await press(container.querySelector('[role="checkbox"]'))+ await rerender()+ expect(mocks.S.active.cur).toBe(1)+ mocks.storeSnapshot().update(s => { s.active.workoutView = 'cards' }); await rerender()+ expect(seen).toEqual([])+ })+ // A session started through the weigh-in sheet, its first block tall enough to push the first+ // row partly under the tab bar: off screen by the rule above, but the sheet's restore is still+ // running, and a scroll the marker did not cause never fought that, so it is not asked for.+ it('does not scroll on mount while a sheet\'s restore is pending, off-screen row or not', async () => {+ mocks.scrollRestorePending.mockImplementation(() => true)+ await mount(superset(), 0, {}, () => rowsAt(630))+ expect(dom.Element.prototype.scrollIntoView).not.toHaveBeenCalled()+ expect(mocks.afterScrollRestore).not.toHaveBeenCalled()+ // …while the marker moving inside that same window still asks, through the wait.+ const seen = watchScrolls()+ await press(container.querySelector('[role="checkbox"]'))+ await rerender()+ expect(mocks.S.active.cur).toBe(1)+ expect(seen).toEqual([partnerFirstRow()])+ })+ // Exercise ⋯ → Move up: the unit changes place and the marker's index follows it. Not a move,+ // so an on-screen row stays where it is.+ it('moving the marker\'s unit up or down does not scroll', async () => {+ await mount([lifted('0001'), lifted('0025', 'g'), lifted('0043', 'g')], 1, {}, () => rowsAt(400))+ const seen = watchScrolls()+ // Through the exercise's own ⋯ menu, as a thumb does it: the move records the marker's new+ // index itself, which is what tells it apart from a real move.+ await press(container.querySelector('button[aria-label="More"]'))+ const items = mocks.menuSheet.mock.calls.at(-1)[0].items.filter(Boolean)+ await act(async () => { items.find(i => i.label === 'Move up').onClick() })+ await rerender()+ expect(mocks.S.active.entries[0].id).toBe('0025')+ expect(mocks.S.active.cur).toBe(0)+ expect(seen).toEqual([])+ // …while the tick that moves the marker to the partner still centres its row.+ await press(container.querySelector('[role="checkbox"]'))+ await rerender()+ expect(mocks.S.active.cur).toBe(1)+ expect(seen).toEqual([container.querySelectorAll('.setrow')[3]])+ })+ // Two rows of the same exercise in one superset: the tick from one to the other is a move all+ // the same (judged by index), so rating the first still centres the second, through the wait,+ // with the picker's restore pending.+ it('rating a set in a same-exercise superset still centres the partner row', async () => {+ await mount([lifted('0025', 'g'), lifted('0025', 'g'), lifted('0001')], 0, {}, () => rowsAt(400))+ mocks.S = { ...mocks.S, effort: 'rir' }; await rerender()+ const seen = watchScrolls()+ await press(container.querySelector('.setrow:not(.done) .effcell.is-empty'))+ const [, , pick] = effortPickerSheet.mock.calls.at(-1)+ mocks.scrollRestorePending.mockImplementation(() => true)+ const queued = []+ mocks.afterScrollRestore.mockImplementationOnce(fn => { queued.push(fn); return () => {} })+ await act(async () => { pick(2) })+ await rerender()+ expect(mocks.S.active.cur).toBe(1)+ expect(queued).toHaveLength(1)+ await act(async () => { queued[0]() })+ expect(seen).toEqual([partnerFirstRow()])+ })+ // The installed app runs under the translucent status bar, and the connection bar sits below it+ // while there is no server: a row up there is not on screen.+ it('a row under the bars at the top counts as off screen', async () => {+ await mount(superset(), 1, {}, () => { rowsAt(30); topBars(59) })+ const scroll = dom.Element.prototype.scrollIntoView+ expect(scroll).toHaveBeenCalledTimes(1)+ expect(scroll.mock.contexts[0]).toBe(partnerFirstRow())+ // The element it measured with is gone again.+ expect([...document.body.children].some(el => el.style?.height === 'calc(var(--sat) + var(--conn))')).toBe(false)+ })+ it('the same row is on screen where nothing covers the top', async () => {+ await mount(superset(), 1, {}, () => { rowsAt(30); topBars(0) })+ expect(dom.Element.prototype.scrollIntoView).not.toHaveBeenCalled()+ })+ // The rest and tab bars are fixed over the page: a row under either is not on screen.+ it('a row under the rest bar counts as off screen', async () => {+ await mount(superset(), 0, { workoutView: 'list' })+ rowsAt(400); const seen = watchScrolls()+ const bar = document.createElement('div'); bar.id = 'timer'; document.body.appendChild(bar)+ dom.Element.prototype.getBoundingClientRect = function () { return this.id === 'timer' ? { top: 380, bottom: 659 } : { top: 400, bottom: 444 } }+ mocks.storeSnapshot().update(s => { s.active.workoutView = 'cards' }); await rerender()+ expect(seen).toEqual([container.querySelectorAll('.setrow')[0]])+ })+})