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
feat: collapse completed workout exercises without scroll jumps
helgehelge1238fb96d5ef5a9
diff --git a/frontend/src/components/Modals.jsx b/frontend/src/components/Modals.jsxindex 397ccc4ab..ae8465d0e 100644--- a/frontend/src/components/Modals.jsx+++ b/frontend/src/components/Modals.jsx@@ -174,13 +174,23 @@ export default function Modals() {const b = document.body.styleb.position = 'fixed'; b.top = -y + 'px'; b.left = '0'; b.right = '0'; b.width = '100%'return () => {+ // A workout layout change can move the anchor while this sheet is open.+ const restoreY = -(parseFloat(b.top) || 0)b.position = b.top = b.left = b.right = b.width = ''- window.scrollTo(0, y)+ window.scrollTo(0, restoreY)// If the sheet closed with the keyboard still up (tap "+" in the picker, then finish),// 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.- window.setTimeout(() => { if (document.body.style.position !== 'fixed') window.scrollTo(0, y) }, 350)+ const cancelRestore = () => {+ window.clearTimeout(restoreTimer)+ window.removeEventListener('workout-scroll-anchor', cancelRestore)+ }+ const restoreTimer = window.setTimeout(() => {+ window.removeEventListener('workout-scroll-anchor', cancelRestore)+ if (document.body.style.position !== 'fixed') window.scrollTo(0, restoreY)+ }, 350)+ window.addEventListener('workout-scroll-anchor', cancelRestore, { once: true })}}, [sheets.length > 0])diff --git a/frontend/src/components/Modals.test.jsx b/frontend/src/components/Modals.test.jsxindex 09038a7bf..e16985a41 100644--- a/frontend/src/components/Modals.test.jsx+++ b/frontend/src/components/Modals.test.jsx@@ -162,6 +162,28 @@ describe('Modals sheet history accounting', () => {})})+describe('Modals scroll restoration', () => {+ it('uses the body offset corrected by a workout layout change', async () => {+ await setSheets([sheet('layout')])+ document.body.style.top = '-240px'+ await setSheets([])+ expect(window.scrollTo).toHaveBeenLastCalledWith(0, 240)+ })++ it('does not undo a newer workout scroll anchor with its delayed keyboard restore', async () => {+ vi.useFakeTimers()+ try {+ await setSheets([sheet('layout')])+ document.body.style.top = '-800px'+ await setSheets([])+ window.scrollTo.mockClear()+ window.dispatchEvent(new dom.Event('workout-scroll-anchor'))+ await act(async () => { vi.advanceTimersByTime(350) })+ expect(window.scrollTo).not.toHaveBeenCalled()+ } finally { vi.useRealTimers() }+ })+})+describe('Modals mouse dragging', () => {it('leaves range sliders opted out of sheet dragging', async () => {await setSheets([sheet('slider', {diff --git a/frontend/src/components/WorkoutScrollAnchor.jsx b/frontend/src/components/WorkoutScrollAnchor.jsxnew file mode 100644index 000000000..76276687b--- /dev/null+++ b/frontend/src/components/WorkoutScrollAnchor.jsx@@ -0,0 +1,58 @@+import { Component, createRef } from 'react'++// A layout-effect cleanup is too late to measure the old DOM. React's snapshot lifecycle+// brackets the collapse itself, including changes made while the Layout sheet locks the body.+export default class WorkoutScrollAnchor extends Component {+ root = createRef()+ leadingSpace = null++ getSnapshotBeforeUpdate(prev) {+ if (prev.collapsed === this.props.collapsed) return null+ const root = this.root.current+ const top = Math.max(0, root.querySelector('.whdr')?.getBoundingClientRect().bottom || 0)+ const collapsing = new Set(this.props.collapsed.split(',').filter(k => !prev.collapsed.split(',').includes(k)))+ const visible = [...root.querySelectorAll('.wl-unit')].filter(el => {+ const rect = el.getBoundingClientRect()+ return rect.bottom > top && rect.top < window.innerHeight+ })+ // If the content at the top is itself disappearing, hold the next surviving tile in+ // place instead. A summary already collapsed is a perfectly good anchor too.+ const anchor = visible.find(el => !collapsing.has(el.dataset.unitKey)) || visible[0]+ return anchor ? { anchor, top: anchor.getBoundingClientRect().top } : null+ }++ componentDidUpdate(prev, state, snapshot) {+ if (!snapshot) return+ const root = this.root.current+ if (this.leadingSpace) this.leadingSpace.style.marginTop = ''+ this.leadingSpace = null+ if (!snapshot.anchor.isConnected) { root.style.paddingBottom = ''; return }+ const body = document.body+ const locked = body.style.position === 'fixed'+ const delta = snapshot.anchor.getBoundingClientRect().top - snapshot.top+ const y = locked ? -(parseFloat(body.style.top) || 0) : window.scrollY+ const target = Math.max(0, y + delta)+ // At the page start we cannot scroll to a negative offset. Keep the minimum gap+ // before the surviving tile instead; a later expansion reclaims it.+ if (y + delta < 0) {+ snapshot.anchor.style.marginTop = `${-(y + delta)}px`+ this.leadingSpace = snapshot.anchor+ }+ // Collapsing near the page end can clamp scrollY before we restore it. Keep only the+ // trailing space needed to hold this viewport; a later expansion can reclaim it.+ const oldSpace = parseFloat(root.style.paddingBottom) || 0+ const height = Math.max(body.scrollHeight, document.documentElement.scrollHeight) - oldSpace+ const space = Math.max(0, target + window.innerHeight - height)+ root.style.paddingBottom = space ? `${space}px` : ''+ if (locked) body.style.top = `${-target}px`+ else if (delta || oldSpace !== space) {+ // Cancel a sheet's delayed keyboard correction before it can undo this newer anchor.+ window.dispatchEvent(new Event('workout-scroll-anchor'))+ window.scrollTo({ top: target, left: window.scrollX, behavior: 'instant' })+ }+ }++ render() {+ return <div ref={this.root} className="narrow" style={{ overflowAnchor: this.props.enabled ? 'none' : undefined }}>{this.props.children}</div>+ }+}diff --git a/frontend/src/components/WorkoutScrollAnchor.test.jsx b/frontend/src/components/WorkoutScrollAnchor.test.jsxnew file mode 100644index 000000000..3afba9d54--- /dev/null+++ b/frontend/src/components/WorkoutScrollAnchor.test.jsx@@ -0,0 +1,117 @@+import React, { act } from 'react'+import { createRoot } from 'react-dom/client'+import { parseHTML } from 'linkedom'+import { afterEach, beforeEach, expect, it, vi } from 'vitest'+import WorkoutScrollAnchor from './WorkoutScrollAnchor.jsx'++let root, container, dom, scrollY, pageHeight+const height = () => pageHeight + (parseFloat(container.firstChild?.style.paddingBottom) || 0)+const tileTop = key => container.querySelector(`[data-unit-key="${key}"]`).getBoundingClientRect().top++beforeEach(() => {+ dom = parseHTML('<html><body><div id="root"></div></body></html>').window+ globalThis.window = dom+ globalThis.document = dom.document+ for (const key of ['HTMLElement', 'Node', 'Element', 'Event']) globalThis[key] = dom[key]+ globalThis.IS_REACT_ACT_ENVIRONMENT = true+ scrollY = 800; pageHeight = 2400+ dom.innerHeight = 600; dom.scrollX = 0+ Object.defineProperty(dom, 'scrollY', { configurable: true, get: () => Math.min(scrollY, Math.max(0, height() - 600)) })+ Object.defineProperty(document.body, 'scrollHeight', { configurable: true, get: height })+ Object.defineProperty(document.documentElement, 'scrollHeight', { configurable: true, get: height })+ dom.scrollTo = vi.fn(({ top }) => { scrollY = top })+ dom.Element.prototype.getBoundingClientRect = function () {+ if (this.className === 'whdr') return { top: 0, bottom: 80 }+ const offset = document.body.style.position === 'fixed' ? parseFloat(document.body.style.top) : -window.scrollY+ const top = Number(this.dataset.top || 0) + offset + (parseFloat(this.style.marginTop) || 0)+ return { top, bottom: top + Number(this.dataset.height || 0) }+ }+ container = document.getElementById('root')+ root = createRoot(container)+})++afterEach(async () => { await act(async () => { root.unmount() }) })++async function render(collapsed, tiles, nextHeight = pageHeight) {+ // Changing height during commit models the browser clamping scrollY when the page shrinks.+ const committed = el => { if (el) pageHeight = nextHeight }+ await act(async () => {+ root.render(<WorkoutScrollAnchor collapsed={collapsed}>+ <div className="whdr" />+ <div className="workout-list" ref={committed}>+ {tiles.map(([key, top, height]) => <section className="wl-unit" key={key} data-unit-key={key} data-top={top} data-height={height} />)}+ </div>+ </WorkoutScrollAnchor>)+ })+}++it('keeps the visible tile at the same pixel when a completed tile above it collapses', async () => {+ await render('', [['0', 100, 700], ['1', 800, 650]])+ const top = tileTop('1')+ await render('0', [['0', 100, 200], ['1', 300, 650]])+ expect(tileTop('1')).toBe(top)+ expect(window.scrollTo).toHaveBeenLastCalledWith({ top: 300, left: 0, behavior: 'instant' })+})++it('keeps a partly visible next tile still when the topmost tile itself is collapsing', async () => {+ scrollY = 600+ await render('', [['0', 100, 700], ['1', 800, 650]])+ const top = tileTop('1')+ await render('0', [['0', 100, 200], ['1', 300, 650]])+ expect(tileTop('1')).toBe(top)+})++it('reserves only enough space to avoid a page-end clamp, then reclaims it on expansion', async () => {+ await render('', [['0', 100, 700], ['1', 800, 400]], 1400)+ const top = tileTop('1')+ await render('0', [['0', 100, 100], ['1', 200, 400]], 700)+ expect(tileTop('1')).toBe(top)+ expect(container.firstChild.style.paddingBottom).toBe('100px')+ await render('', [['0', 100, 700], ['1', 800, 400]], 1400)+ expect(tileTop('1')).toBe(top)+ expect(container.firstChild.style.paddingBottom).toBe('')+})++it('holds the next tile at the page start when shrinking would require a negative scroll offset', async () => {+ scrollY = 400+ await render('', [['0', 100, 700], ['1', 800, 650]])+ const top = tileTop('1')+ await render('0', [['0', 100, 100], ['1', 200, 650]])+ expect(tileTop('1')).toBe(top)+ expect(window.scrollY).toBe(0)+ expect(container.querySelector('[data-unit-key="1"]').style.marginTop).toBe('200px')+ const firstTop = tileTop('0')+ await render('', [['0', 100, 700], ['1', 800, 650]])+ expect(tileTop('0')).toBe(firstTop)+ expect(container.querySelector('[data-unit-key="1"]').style.marginTop).toBe('')+})++it('updates the locked body offset while the Layout sheet is open', async () => {+ document.body.style.position = 'fixed'; document.body.style.top = '-800px'+ await render('', [['0', 100, 700], ['1', 800, 650]])+ const top = tileTop('1')+ await render('0', [['0', 100, 200], ['1', 300, 650]])+ expect(tileTop('1')).toBe(top)+ expect(document.body.style.top).toBe('-300px')+ expect(window.scrollTo).not.toHaveBeenCalled()+})++it('does not scroll when a collapse below the viewport leaves its top unchanged', async () => {+ await render('', [['0', 100, 700], ['1', 800, 650], ['2', 1500, 700]])+ await render('2', [['0', 100, 700], ['1', 800, 650], ['2', 1500, 100]])+ expect(window.scrollTo).not.toHaveBeenCalled()+})++it('ignores unrelated updates and mounting a restored collapsed session', async () => {+ await render('0', [['0', 100, 100], ['1', 200, 1000]])+ await render('0', [['0', 100, 100], ['1', 200, 1000]])+ expect(window.scrollTo).not.toHaveBeenCalled()+})++it('cancels an older sheet correction when restoring the workout anchor', async () => {+ const cancel = vi.fn()+ window.addEventListener('workout-scroll-anchor', cancel)+ await render('', [['0', 100, 700], ['1', 800, 650]])+ await render('0', [['0', 100, 200], ['1', 300, 650]])+ expect(cancel).toHaveBeenCalledOnce()+})diff --git a/frontend/src/index.css b/frontend/src/index.cssindex 12a1643b4..81f82cc8a 100644--- a/frontend/src/index.css+++ b/frontend/src/index.css@@ -1151,6 +1151,7 @@ body.chips-dragging *{cursor:inherit}}.wl-unit.cur{box-shadow:inset 0 0 0 1.5px var(--acc-line)}.wl-hd{display:flex;align-items:center;justify-content:space-between;gap:8px;margin-bottom:10px}+.wl-summary{display:grid;gap:8px;padding-bottom:10px}@media (max-width:400px){.wl-unit{padding:10px 8px 2px}}diff --git a/frontend/src/lib/pt-br-locale.test.js b/frontend/src/lib/pt-br-locale.test.jsindex f692c6095..b0dfc831b 100644--- a/frontend/src/lib/pt-br-locale.test.js+++ b/frontend/src/lib/pt-br-locale.test.js@@ -27,7 +27,7 @@ describe('Brazilian Portuguese locale', () => {.sort(byCodeUnit)const fingerprint = createHash('sha256').update(JSON.stringify(inherited)).digest('hex')- expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(644)+ expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(646)expect(inherited).toHaveLength(647)// If this fails, review the changed keys and wording before accepting a new hash. From// frontend/: node scripts/pt-br-inheritance-fingerprint.mjs --listdiff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.jsindex fad9cba71..90525e83b 100644--- a/frontend/src/locales/de.js+++ b/frontend/src/locales/de.js@@ -1256,4 +1256,6 @@ export default {'already added': 'schon drin','no exercises': 'keine Übungen','Pick equipment': 'Gerät wählen',+ 'Collapse completed exercises': 'Fertige Übungen einklappen',+ 'Keep the current exercise open': 'Die aktuelle Übung bleibt geöffnet',}diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.jsindex 68e2144a4..674c5121b 100644--- a/frontend/src/locales/es.js+++ b/frontend/src/locales/es.js@@ -1236,4 +1236,6 @@ export default {'already added': 'ya añadido','no exercises': 'sin ejercicios','Pick equipment': 'Elegir equipamiento',+ 'Collapse completed exercises': 'Contraer ejercicios completados',+ 'Keep the current exercise open': 'Mantener abierto el ejercicio actual',}diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.jsindex ff4b17cfd..32ae29937 100644--- a/frontend/src/locales/fr.js+++ b/frontend/src/locales/fr.js@@ -1236,4 +1236,6 @@ export default {'already added': 'déjà ajouté','no exercises': 'aucun exercice','Pick equipment': 'Choisir l’équipement',+ 'Collapse completed exercises': 'Replier les exercices terminés',+ 'Keep the current exercise open': 'Garder l’exercice actuel ouvert',}diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.jsindex da466b3f2..4e9ee1cad 100644--- a/frontend/src/locales/hi.js+++ b/frontend/src/locales/hi.js@@ -1236,4 +1236,6 @@ export default {'already added': 'पहले से जोड़ा हुआ','no exercises': 'कोई व्यायाम नहीं','Pick equipment': 'उपकरण चुनें',+ 'Collapse completed exercises': 'पूरे हुए व्यायाम समेटें',+ 'Keep the current exercise open': 'वर्तमान व्यायाम खुला रखें',}diff --git a/frontend/src/locales/hu.js b/frontend/src/locales/hu.jsindex f99fa4ff9..159d8dcb1 100644--- a/frontend/src/locales/hu.js+++ b/frontend/src/locales/hu.js@@ -1239,4 +1239,6 @@ export default {'already added': 'már hozzáadva','no exercises': 'nincs gyakorlat','Pick equipment': 'Eszköz kiválasztása',+ 'Collapse completed exercises': 'Befejezett gyakorlatok összecsukása',+ 'Keep the current exercise open': 'Az aktuális gyakorlat maradjon nyitva',}diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.jsindex 3c8c8415f..00728df26 100644--- a/frontend/src/locales/it.js+++ b/frontend/src/locales/it.js@@ -1236,4 +1236,6 @@ export default {'already added': 'già aggiunto','no exercises': 'nessun esercizio','Pick equipment': 'Scegli l’attrezzatura',+ 'Collapse completed exercises': 'Comprimi gli esercizi completati',+ 'Keep the current exercise open': 'Mantieni aperto l’esercizio corrente',}diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.jsindex 48ea492ff..98074049f 100644--- a/frontend/src/locales/ko.js+++ b/frontend/src/locales/ko.js@@ -1236,4 +1236,6 @@ export default {'already added': '이미 추가됨','no exercises': '운동 없음','Pick equipment': '기구 선택',+ 'Collapse completed exercises': '완료한 운동 접기',+ 'Keep the current exercise open': '현재 운동은 펼쳐 두기',}diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.jsindex 213baab72..6863a36dd 100644--- a/frontend/src/locales/pl.js+++ b/frontend/src/locales/pl.js@@ -1236,4 +1236,6 @@ export default {'already added': 'już dodano','no exercises': 'brak ćwiczeń','Pick equipment': 'Wybierz sprzęt',+ 'Collapse completed exercises': 'Zwijaj ukończone ćwiczenia',+ 'Keep the current exercise open': 'Bieżące ćwiczenie pozostaje rozwinięte',}diff --git a/frontend/src/locales/pt-BR.js b/frontend/src/locales/pt-BR.jsindex 324b0f2ae..c3648064c 100644--- a/frontend/src/locales/pt-BR.js+++ b/frontend/src/locales/pt-BR.js@@ -671,6 +671,8 @@ export const PT_BR_OVERRIDES = {'Download & Install': 'Baixar e instalar','Starting download…': 'Iniciando download…','Downloading update…': 'Baixando atualização…',+ 'Collapse completed exercises': 'Recolher exercícios concluídos',+ 'Keep the current exercise open': 'Manter o exercício atual aberto',}export default { ...pt, ...PT_BR_OVERRIDES }diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.jsindex ea44d465c..e5cd63e9e 100644--- a/frontend/src/locales/pt.js+++ b/frontend/src/locales/pt.js@@ -1236,4 +1236,6 @@ export default {'already added': 'já adicionado','no exercises': 'sem exercícios','Pick equipment': 'Escolher equipamento',+ 'Collapse completed exercises': 'Recolher exercícios concluídos',+ 'Keep the current exercise open': 'Manter o exercício atual aberto',}diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.jsindex 46ce8efb2..6c793adef 100644--- a/frontend/src/locales/ru.js+++ b/frontend/src/locales/ru.js@@ -1236,4 +1236,6 @@ export default {'already added': 'уже добавлено','no exercises': 'нет упражнений','Pick equipment': 'Выбрать оборудование',+ 'Collapse completed exercises': 'Сворачивать завершённые упражнения',+ 'Keep the current exercise open': 'Оставлять текущее упражнение открытым',}diff --git a/frontend/src/locales/th.js b/frontend/src/locales/th.jsindex f2b372dbd..fbcd0c036 100644--- a/frontend/src/locales/th.js+++ b/frontend/src/locales/th.js@@ -1247,4 +1247,6 @@ export default {'already added': 'เพิ่มแล้ว','no exercises': 'ไม่มีท่าออกกำลังกาย','Pick equipment': 'เลือกอุปกรณ์',+ 'Collapse completed exercises': 'ย่อท่าฝึกที่เสร็จแล้ว',+ 'Keep the current exercise open': 'เปิดท่าฝึกปัจจุบันไว้',}diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.jsindex 95720d15e..c96e2a9c9 100644--- a/frontend/src/locales/tr.js+++ b/frontend/src/locales/tr.js@@ -1236,4 +1236,6 @@ export default {'already added': 'zaten ekli','no exercises': 'egzersiz yok','Pick equipment': 'Ekipman seç',+ 'Collapse completed exercises': 'Tamamlanan egzersizleri daralt',+ 'Keep the current exercise open': 'Geçerli egzersizi açık tut',}diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.jsindex f45110eec..0df7ebe60 100644--- a/frontend/src/locales/zh.js+++ b/frontend/src/locales/zh.js@@ -1236,4 +1236,6 @@ export default {'already added': '已添加','no exercises': '没有动作','Pick equipment': '选择器械',+ 'Collapse completed exercises': '折叠已完成的动作',+ 'Keep the current exercise open': '保持当前动作展开',}diff --git a/frontend/src/views/Workout.jsx b/frontend/src/views/Workout.jsxindex 8e772d080..db50c455b 100644--- a/frontend/src/views/Workout.jsx+++ b/frontend/src/views/Workout.jsx@@ -12,6 +12,7 @@ import { t, exerciseNameFor } from '../lib/i18n.js'import { api } from '../lib/api.js'import { insertionIndexAfterCurrentUnit, nextUnfinishedUnit, setProgressHighWater, supersetFlowStep, restAfterSet, restOnRecheck, restSecFor, warmupRestSecFor } from '../lib/supersetFlow.js'import Media from '../components/Media.jsx'+import WorkoutScrollAnchor from '../components/WorkoutScrollAnchor.jsx'import { startFlow, exercisePicker, exConfigSheet, exerciseDetailSheet, finishWorkout, workoutCompleteSheet, confirmSheet, exerciseNoteSheet, sessionNoteSheet, swapActiveWorkoutExercise, barWeightSheet, menuSheet, effortPickerSheet, exerciseHistorySheet, addRoutineToSessionSheet } from '../sheets.jsx'import { effortColor } from '../lib/effort.js'import Icon from '../components/Icon.jsx'@@ -530,6 +531,11 @@ function ActiveWorkout() {const workoutView = A.workoutView || S.workoutViewconst listMode = workoutView === 'list' || workoutView === 'compact'const dense = workoutView === 'compact'+ // Keep the current superset together until the user moves on, including its finished+ // members. Empty exercises and partially completed warm-ups/left-right sets stay open.+ const collapsed = new Set(listMode && A.collapseCompleted ? units.filter(u =>+ !u.includes(cur) && u.every(idx => A.entries[idx].sets.length > 0 && A.entries[idx].sets.every(s => s.done)),+ ).map(u => u.join('-')) : [])const wc = workoutControls(S)// 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@@ -695,6 +701,9 @@ function ActiveWorkout() {{ icon: 'clipboard', label: t('Cards'), on: workoutView === 'cards', onClick: () => setWorkoutView('cards') },{ icon: 'list', label: t('List'), on: workoutView === 'list', onClick: () => setWorkoutView('list') },{ icon: 'minimize', label: t('Compact'), on: workoutView === 'compact', onClick: () => setWorkoutView('compact') },+ listMode && { icon: 'minimize', label: t('Collapse completed exercises'),+ sub: t('Keep the current exercise open'), on: !!A.collapseCompleted,+ onClick: () => update(s => { if (s.active) s.active.collapseCompleted = !s.active.collapseCompleted }) },],})// The header ⋮: bring another routine into the session, then the layout switch nested a@@ -928,7 +937,7 @@ function ActiveWorkout() {}}, [])- return <div className="narrow">+ return <WorkoutScrollAnchor enabled={listMode && A.collapseCompleted} collapsed={[...collapsed].join(',')}>{/* In list mode the whole session scrolls under the header, so the header (name, clock,set counter, discard/finish, progress) stays pinned — the one thing you want in viewwhile you are somewhere in the middle of a long stack. Cards mode never scrolls far. */}@@ -950,14 +959,22 @@ function ActiveWorkout() {{units.map((u, ui) => {const multi = u.length > 1const isCur = u.includes(cur)- return <section key={u.join('-')} className={'wl-unit' + (isCur ? ' cur' : '')} data-exidx={u[0]}>+ const isCollapsed = collapsed.has(u.join('-'))+ return <section key={u.join('-')} className={'wl-unit' + (isCur ? ' cur' : '')} data-exidx={u[0]} data-unit-key={u.join('-')}><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>}+ : <button className="chip" aria-expanded={!isCollapsed} aria-controls={'workout-unit-' + u.join('-')}+ onClick={() => focusUnit(u[0])}>{t('Set current')}</button>}</div>- {multi ? (+ <div id={'workout-unit-' + u.join('-')}>+ {isCollapsed ? <div className="wl-summary">+ {u.map(idx => <div key={idx} className="row between" style={{ gap: 8 }}>+ <span style={{ fontWeight: 600, textTransform: 'capitalize' }}>{exerciseNameFor(exOr(A.entries[idx].id))}</span>+ <span className="tag acc nocap"><Icon name="check" />{t('{0} sets', A.entries[idx].sets.length)}</span>+ </div>)}+ </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>@@ -978,6 +995,7 @@ function ActiveWorkout() {onPairNext={u[0] < A.entries.length - 1 ? () => pairAt(u[0], u[0] + 1) : null}{...blockProps(u[0])} />)}+ </div></section>})}</div>@@ -1086,7 +1104,7 @@ function ActiveWorkout() {</button>})()}<div className="workout-end-spacer" />- </div>+ </WorkoutScrollAnchor>}export default function Workout() {diff --git a/frontend/src/views/Workout.test.jsx b/frontend/src/views/Workout.test.jsxindex 5409de4d7..3a2ab442f 100644--- a/frontend/src/views/Workout.test.jsx+++ b/frontend/src/views/Workout.test.jsx@@ -1191,7 +1191,7 @@ describe('workout view header menu', () => {expect(item(menu, 'Layout').sub).toBe('List')const layout = await openLayout(menu)- expect(layout.items.filter(Boolean).map(it => it.label)).toEqual(['Cards', 'List', 'Compact'])+ expect(layout.items.filter(Boolean).map(it => it.label)).toEqual(['Cards', 'List', 'Compact', 'Collapse completed exercises'])expect(item(layout, 'List').on).toBe(true)expect(item(layout, 'Cards').on).toBe(false)})@@ -1205,6 +1205,89 @@ describe('workout view header menu', () => {expect(mocks.S.active.workoutView).toBe('compact')expect(mocks.S.workoutView).toBe('cards')})++ it('toggles completed exercises for the running list session and can show them again', async () => {+ await mount([exercise('bench', [true]), exercise('row', [false])], 1, { active: { workoutView: 'list' } })+ let layout = await openLayout(await openMenu())+ expect(item(layout, 'Collapse completed exercises').on).toBe(false)+ await act(async () => { item(layout, 'Collapse completed exercises').onClick() })+ await rerender()+ expect(container.querySelectorAll('.wl-summary').length).toBe(1)+ expect(mocks.S.collapseCompleted).toBeUndefined()+ layout = await openLayout(await openMenu())+ expect(item(layout, 'Collapse completed exercises').on).toBe(true)+ await act(async () => { item(layout, 'Collapse completed exercises').onClick() })+ await rerender()+ expect(container.querySelector('.wl-summary')).toBeNull()+ expect(container.querySelectorAll('[role="checkbox"]').length).toBe(2)+ })++ it('only offers collapsing in layouts that show more than the current exercise', async () => {+ await mount([exercise('bench', [true])], 0, { active: { workoutView: 'cards' } })+ expect(item(await openLayout(await openMenu()), 'Collapse completed exercises')).toBeUndefined()+ })+})++describe('collapsing completed workout exercises', () => {+ const units = () => [...container.querySelectorAll('.wl-unit')]+ const setCurrent = async index => {+ const button = [...units()[index].querySelectorAll('button')].find(b => b.textContent.trim() === 'Set current')+ await act(async () => { button.dispatchEvent(new dom.Event('click', { bubbles: true })) })+ await rerender()+ }++ it.each(['list', 'compact'])('keeps the finished current exercise open in %s, then collapses it when moving on', async workoutView => {+ await mount([exercise('bench', [true, false]), exercise('row', [false])], 0,+ { active: { workoutView, collapseCompleted: true } })+ await toggleSet(1)+ await rerender()+ expect(units()[0].querySelector('.wl-summary')).toBeNull()+ const loggedSets = structuredClone(mocks.S.active.entries[0].sets)+ await setCurrent(1)+ expect(units()[0].querySelector('.wl-summary')).toBeTruthy()+ expect(units()[0].querySelector('.setrow')).toBeNull()+ expect(units()[0].querySelector('.exmedia')).toBeNull()+ expect(units()[0].querySelector('[aria-expanded="false"]')).toBeTruthy()+ expect(units()[1].querySelector('.setrow')).toBeTruthy()+ expect(mocks.S.active.entries[0].sets).toEqual(loggedSets)+ await setCurrent(0)+ expect(units()[0].querySelectorAll('.setrow').length).toBe(2)+ await toggleSet(0)+ await setCurrent(1)+ expect(units()[0].querySelector('.wl-summary')).toBeNull()+ })++ it('leaves completed exercises expanded unless the option is enabled', async () => {+ await mount([exercise('bench', [true]), exercise('row', [false])], 1, { workoutView: 'list' })+ expect(container.querySelector('.wl-summary')).toBeNull()+ })++ it('keeps an unfinished warm-up, one unfinished side and an empty exercise expanded', async () => {+ await mount([+ exercise('warmup', [false, true], { sets: [{ w: 20, r: 5, phase: 'warmup', done: false }, { w: 60, r: 5, done: true }] }),+ exercise('side', [false], { target: { mode: 'reps', side: true }, sets: [{ done: false, sides: { L: { done: true }, R: { done: false } } }] }),+ exercise('empty', []), exercise('current', [false]),+ ], 3, { active: { workoutView: 'list', collapseCompleted: true } })+ expect(container.querySelector('.wl-summary')).toBeNull()+ })++ it('collapses a superset only after all members are done and the group is no longer current', async () => {+ await mount([exercise('bench', [true], { sg: 'pair' }), exercise('row', [false], { sg: 'pair' }), exercise('squat', [false])], 2,+ { active: { workoutView: 'list', collapseCompleted: true } })+ expect(units()[0].querySelector('.wl-summary')).toBeNull()+ await toggleSet(1)+ await rerender()+ expect(units()[0].querySelectorAll('.wl-summary .tag').length).toBe(2)+ await setCurrent(0)+ expect(units()[0].querySelectorAll('[role="checkbox"]').length).toBe(2)+ })++ it('treats duplicate exercise occurrences separately when restoring a running session', async () => {+ await mount([exercise('bench', [true]), exercise('bench', [false]), exercise('row', [false])], 2,+ { active: { workoutView: 'compact', collapseCompleted: true } })+ expect(units()[0].querySelector('.wl-summary')).toBeTruthy()+ expect(units()[1].querySelector('.wl-summary')).toBeNull()+ })})describe('workout controls: the more menu and the set menu', () => {