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
Workout: the rest timer can be paused and resumed; paused time does not count and its alert is booked again for the new end (#193)
Duarte Santos8583922bdac0
diff --git a/frontend/src/components/RestTimer.jsx b/frontend/src/components/RestTimer.jsxindex 75fd09154..d218311e7 100644--- a/frontend/src/components/RestTimer.jsx+++ b/frontend/src/components/RestTimer.jsx@@ -12,7 +12,7 @@ const clock = sec => Math.floor(sec / 60) + ':' + String(sec % 60).padStart(2, 'export default function RestTimer() {const timer = useUI(s => s.timer)const work = useUI(s => s.work)- const { addRest, stopRest, finishWorkEarly, stopWork } = useUI()+ const { addRest, stopRest, pauseRest, resumeRest, finishWorkEarly, stopWork } = useUI()const on = work || timer// The bar is fixed above the tab bar and floats over whatever is beneath it — during a// rest that was the next set's row. Extra bottom padding lets the page scroll clear.@@ -38,8 +38,10 @@ export default function RestTimer() {// with about 30px and stops saying anything. So the rest variant stacks: clock and bar// read at a glance, controls get their own row. −15 and +15 sit together in number-line// order; Skip is pushed to the far edge, away from the button you tap to buy more time.+ // Pause sits between them as an icon (#193): it holds the time, it neither adds nor ends it.+ // A rest that is over has nothing left to hold, so Ready offers no pause.return (- <div id="timer" className="rest">+ <div id="timer" className={'rest' + (timer.paused ? ' paused' : '')}><div className="head"><div className="t" role={timer.ready ? 'status' : undefined}>{timer.ready ? t('Ready') : clock(timer.left)}</div><div className="bar"><i style={{ width: pct + '%' }} /></div>@@ -47,6 +49,9 @@ export default function RestTimer() {<div className="acts"><Button size="sm" icon="minus" onClick={() => addRest(-15)}>15s</Button><Button size="sm" icon="plus" onClick={() => addRest(15)}>15s</Button>+ {!timer.ready && <Button size="sm" className="pause" icon={timer.paused ? 'play' : 'pause'}+ aria-label={t(timer.paused ? 'Resume' : 'Pause')} aria-pressed={!!timer.paused}+ onClick={timer.paused ? resumeRest : pauseRest} />}<Button size="sm" variant="primary" className="skip" onClick={stopRest}>{t(timer.ready ? 'Dismiss' : 'Skip')}</Button></div></div>diff --git a/frontend/src/components/RestTimer.ready.test.jsx b/frontend/src/components/RestTimer.ready.test.jsxindex 5e45f9a6f..240c04ed4 100644--- a/frontend/src/components/RestTimer.ready.test.jsx+++ b/frontend/src/components/RestTimer.ready.test.jsx@@ -61,3 +61,41 @@ describe('RestTimer Ready and overtime display', () => {expect(host.querySelector('#timer .bar i').style.width).toBe('0%')})})++// Pause sits between +15 and Skip (#193): it holds the rest where it is and says so, and the+// same button carries on from there. A rest that is over has nothing left to hold.+describe('RestTimer pause and resume', () => {+ const pause = () => host.querySelector('#timer .pause')++ it('pauses the countdown, shows it held, and resumes from the same second', () => {+ act(() => useUI.getState().startRest(90, 0))+ mount()+ act(() => vi.advanceTimersByTime(10000))+ expect(host.querySelector('#timer .t').textContent).toBe('1:20')+ expect(pause().getAttribute('aria-label')).toBe('Pause')++ act(() => pause().click())+ expect(host.querySelector('#timer').classList.contains('paused')).toBe(true)+ expect(pause().getAttribute('aria-label')).toBe('Resume')+ expect(pause().getAttribute('aria-pressed')).toBe('true')+ act(() => vi.advanceTimersByTime(60000))+ expect(host.querySelector('#timer .t').textContent).toBe('1:20')++ act(() => pause().click())+ expect(host.querySelector('#timer').classList.contains('paused')).toBe(false)+ act(() => vi.advanceTimersByTime(20000))+ expect(host.querySelector('#timer .t').textContent).toBe('1:00')+ })++ it('offers no pause once the rest is Ready, and none on the timed hold', () => {+ act(() => useUI.getState().startRest(1))+ mount()+ act(() => vi.advanceTimersByTime(1000))+ expect(host.querySelector('#timer .t').textContent).toBe('Ready')+ expect(pause()).toBeNull()++ act(() => useUI.getState().startWork(30, 'Hold', vi.fn()))+ expect(host.querySelector('#timer.working')).not.toBeNull()+ expect(pause()).toBeNull()+ })+})diff --git a/frontend/src/index.css b/frontend/src/index.cssindex 7477ef83c..63d439b4c 100644--- a/frontend/src/index.css+++ b/frontend/src/index.css@@ -1071,6 +1071,8 @@ body.chips-dragging *{cursor:inherit}#timer.rest .acts{display:flex;align-items:center;gap:8px}#timer.rest .acts .btn{padding-top:11px;padding-bottom:11px} /* sweaty hands, mid-set */#timer.rest .acts .skip{margin-left:auto;min-width:84px}+/* A paused rest reads as held: the clock and the bar step back until it runs again. */+#timer.rest.paused .t,#timer.rest.paused .bar{opacity:.5}/* work timer (issue #16): the same bar doing the opposite job — outlined and tinted so aglance tells "you are holding this" apart from "you are recovering". */#timer.working{border:var(--hair) solid var(--acc)}diff --git a/frontend/src/lib/pt-br-locale.test.js b/frontend/src/lib/pt-br-locale.test.jsindex 8d6bc61de..a350fee03 100644--- a/frontend/src/lib/pt-br-locale.test.js+++ b/frontend/src/lib/pt-br-locale.test.js@@ -41,7 +41,7 @@ describe('Brazilian Portuguese locale', () => {// has to be taught is a number nobody reads. What the numbers stood for is asserted above.// If the hash fails, review the changed keys and wording before accepting a new one. From// frontend/: node scripts/pt-br-inheritance-fingerprint.mjs --list- expect(fingerprint, 'pt-PT inheritance changed; review the inherited pt-BR wording').toBe('234dd9b792d0e74555054650c8cd29b0318590fd89b8aedf3812e79985253f3c')+ expect(fingerprint, 'pt-PT inheritance changed; review the inherited pt-BR wording').toBe('17fcd34a5d5c3194e16f4a44b94a6915d35550d4b0f82e650f73f4baf4515fc9')})test('does not leak European Portuguese UI terms', () => {diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.jsindex 41b806746..e17676080 100644--- a/frontend/src/locales/de.js+++ b/frontend/src/locales/de.js@@ -1334,6 +1334,7 @@ export default {'Save as routine?': 'Als Routine speichern?','Save as routine': 'Als Routine speichern','Create an independent routine from these exercise targets. Your workout history is kept.': 'Eine unabhängige Routine aus diesen Trainingszielen erstellen. Dein Trainingsverlauf bleibt erhalten.',+ 'Pause': 'Pausieren','Keep timing after target': 'Nach dem Ziel weiterzählen','Timed sets continue up to 15 extra minutes. Tap Done to log the actual duration.': 'Zeitbasierte Sätze laufen bis zu 15 zusätzliche Minuten weiter. Tippe auf „Fertig“, um die tatsächliche Dauer zu speichern.','Edit workout': 'Training bearbeiten',diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.jsindex 1a272f02a..425cd0a84 100644--- a/frontend/src/locales/es.js+++ b/frontend/src/locales/es.js@@ -1314,6 +1314,7 @@ export default {'Save as routine?': '¿Guardar como rutina?','Save as routine': 'Guardar como rutina','Create an independent routine from these exercise targets. Your workout history is kept.': 'Crea una rutina independiente a partir de estos objetivos. Tu historial de entrenamientos se conserva.',+ 'Pause': 'Pausar','Keep timing after target': 'Seguir contando después del objetivo','Timed sets continue up to 15 extra minutes. Tap Done to log the actual duration.': 'Las series cronometradas continúan hasta 15 minutos extra. Toca «Listo» para registrar la duración real.','Edit workout': 'Editar entrenamiento',diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.jsindex aa3cd6d3f..1ea45c6c5 100644--- a/frontend/src/locales/fr.js+++ b/frontend/src/locales/fr.js@@ -1314,6 +1314,7 @@ export default {'Save as routine?': 'Enregistrer comme routine ?','Save as routine': 'Enregistrer comme routine','Create an independent routine from these exercise targets. Your workout history is kept.': 'Créer une routine indépendante à partir de ces objectifs. Votre historique reste conservé.',+ 'Pause': 'Mettre en pause','Keep timing after target': 'Continuer après l’objectif','Timed sets continue up to 15 extra minutes. Tap Done to log the actual duration.': 'Les séries chronométrées continuent jusqu’à 15 minutes supplémentaires. Touchez « Terminé » pour enregistrer la durée réelle.','Edit workout': 'Modifier l’entraînement',diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.jsindex 3d165917c..024cf8cb0 100644--- a/frontend/src/locales/hi.js+++ b/frontend/src/locales/hi.js@@ -1314,6 +1314,7 @@ export default {'Save as routine?': 'रूटीन के रूप में सहेजें?','Save as routine': 'रूटीन के रूप में सहेजें','Create an independent routine from these exercise targets. Your workout history is kept.': 'इन व्यायाम लक्ष्यों से एक स्वतंत्र रूटीन बनाएँ। आपका वर्कआउट इतिहास सुरक्षित रहेगा।',+ 'Pause': 'रोकें','Keep timing after target': 'लक्ष्य के बाद भी समय जारी रखें','Timed sets continue up to 15 extra minutes. Tap Done to log the actual duration.': 'समयबद्ध सेट 15 अतिरिक्त मिनट तक जारी रहेंगे। वास्तविक अवधि दर्ज करने के लिए “पूरा” दबाएँ।','Edit workout': 'वर्कआउट संपादित करें',diff --git a/frontend/src/locales/hu.js b/frontend/src/locales/hu.jsindex 7eb703d37..4fbd2ccda 100644--- a/frontend/src/locales/hu.js+++ b/frontend/src/locales/hu.js@@ -1317,6 +1317,7 @@ export default {'Save as routine?': 'Mentés rutinként?','Save as routine': 'Mentés rutinként','Create an independent routine from these exercise targets. Your workout history is kept.': 'Független rutin létrehozása ezekből a célokból. Az edzéstörténeted megmarad.',+ 'Pause': 'Szüneteltetés','Keep timing after target': 'Időzítés folytatása a cél után','Timed sets continue up to 15 extra minutes. Tap Done to log the actual duration.': 'Az időzített sorozatok legfeljebb 15 extra percig folytatódnak. A tényleges idő rögzítéséhez koppints a Kész gombra.','Edit workout': 'Edzés szerkesztése',diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.jsindex 9536b374c..90afe6ee1 100644--- a/frontend/src/locales/it.js+++ b/frontend/src/locales/it.js@@ -1314,6 +1314,7 @@ export default {'Save as routine?': 'Salvare come routine?','Save as routine': 'Salva come routine','Create an independent routine from these exercise targets. Your workout history is kept.': 'Crea una routine indipendente da questi obiettivi. La cronologia degli allenamenti resta invariata.',+ 'Pause': 'Metti in pausa','Keep timing after target': 'Continua a cronometrare dopo l’obiettivo','Timed sets continue up to 15 extra minutes. Tap Done to log the actual duration.': 'Le serie a tempo continuano fino a 15 minuti extra. Tocca Fine per registrare la durata effettiva.','Edit workout': 'Modifica allenamento',diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.jsindex d0aadd3bd..412a445c3 100644--- a/frontend/src/locales/ko.js+++ b/frontend/src/locales/ko.js@@ -1314,6 +1314,7 @@ export default {'Save as routine?': '루틴으로 저장할까요?','Save as routine': '루틴으로 저장','Create an independent routine from these exercise targets. Your workout history is kept.': '이 운동 목표로 독립 루틴을 만듭니다. 운동 기록은 그대로 유지됩니다.',+ 'Pause': '일시정지','Keep timing after target': '목표 시간 후에도 계속 측정','Timed sets continue up to 15 extra minutes. Tap Done to log the actual duration.': '시간 제한 세트는 최대 15분 추가로 계속됩니다. 실제 시간을 기록하려면 완료를 누르세요.','Edit workout': '운동 편집',diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.jsindex 01f464aa6..0dafa85ce 100644--- a/frontend/src/locales/pl.js+++ b/frontend/src/locales/pl.js@@ -1314,6 +1314,7 @@ export default {'Save as routine?': 'Zapisać jako rutynę?','Save as routine': 'Zapisz jako rutynę','Create an independent routine from these exercise targets. Your workout history is kept.': 'Utwórz niezależną rutynę z tych celów ćwiczeń. Historia treningów pozostanie bez zmian.',+ 'Pause': 'Wstrzymaj','Keep timing after target': 'Kontynuuj pomiar po czasie docelowym','Timed sets continue up to 15 extra minutes. Tap Done to log the actual duration.': 'Serie na czas trwają do 15 dodatkowych minut. Stuknij Gotowe, aby zapisać rzeczywisty czas.','Edit workout': 'Edytuj trening',diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.jsindex cbfef679f..0407a71ab 100644--- a/frontend/src/locales/pt.js+++ b/frontend/src/locales/pt.js@@ -1314,6 +1314,7 @@ export default {'Save as routine?': 'Guardar como rotina?','Save as routine': 'Guardar como rotina','Create an independent routine from these exercise targets. Your workout history is kept.': 'Criar uma rotina independente a partir destes objetivos. O teu histórico de treinos é mantido.',+ 'Pause': 'Pausar','Keep timing after target': 'Continuar a contar após o objetivo','Timed sets continue up to 15 extra minutes. Tap Done to log the actual duration.': 'As séries cronometradas continuam até mais 15 minutos. Toca em Concluído para registar a duração real.','Edit workout': 'Editar treino',diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.jsindex 19f388af1..5e9d7fe04 100644--- a/frontend/src/locales/ru.js+++ b/frontend/src/locales/ru.js@@ -1314,6 +1314,7 @@ export default {'Save as routine?': 'Сохранить как тренировку?','Save as routine': 'Сохранить как тренировку','Create an independent routine from these exercise targets. Your workout history is kept.': 'Создать отдельную тренировку из этих целей. История тренировок сохранится.',+ 'Pause': 'Пауза','Keep timing after target': 'Продолжать отсчёт после цели','Timed sets continue up to 15 extra minutes. Tap Done to log the actual duration.': 'Подходы на время продолжаются ещё до 15 минут. Нажмите «Готово», чтобы записать фактическую длительность.','Edit workout': 'Редактировать тренировку',diff --git a/frontend/src/locales/th.js b/frontend/src/locales/th.jsindex 4facdfd61..7c51281ba 100644--- a/frontend/src/locales/th.js+++ b/frontend/src/locales/th.js@@ -1325,6 +1325,7 @@ export default {'Save as routine?': 'บันทึกเป็นรูทีนไหม','Save as routine': 'บันทึกเป็นรูทีน','Create an independent routine from these exercise targets. Your workout history is kept.': 'สร้างรูทีนอิสระจากเป้าหมายเหล่านี้ ประวัติการออกกำลังกายของคุณจะยังคงอยู่',+ 'Pause': 'หยุดชั่วคราว','Keep timing after target': 'จับเวลาต่อหลังถึงเป้าหมาย','Timed sets continue up to 15 extra minutes. Tap Done to log the actual duration.': 'เซ็ตแบบจับเวลาจะทำต่อได้อีกสูงสุด 15 นาที แตะ “เสร็จแล้ว” เพื่อบันทึกระยะเวลาจริง','Edit workout': 'แก้ไขการออกกำลังกาย',diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.jsindex 9e474aa79..c57da5a87 100644--- a/frontend/src/locales/tr.js+++ b/frontend/src/locales/tr.js@@ -1314,6 +1314,7 @@ export default {'Save as routine?': 'Rutin olarak kaydedilsin mi?','Save as routine': 'Rutin olarak kaydet','Create an independent routine from these exercise targets. Your workout history is kept.': 'Bu egzersiz hedeflerinden bağımsız bir rutin oluştur. Antrenman geçmişin korunur.',+ 'Pause': 'Duraklat','Keep timing after target': 'Hedeften sonra zamanlamayı sürdür','Timed sets continue up to 15 extra minutes. Tap Done to log the actual duration.': 'Süreli setler en fazla 15 dakika daha devam eder. Gerçek süreyi kaydetmek için Bitti’ye dokunun.','Edit workout': 'Antrenmanı düzenle',diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.jsindex e0713dd31..75caab9c5 100644--- a/frontend/src/locales/zh.js+++ b/frontend/src/locales/zh.js@@ -1314,6 +1314,7 @@ export default {'Save as routine?': '要保存为训练计划吗?','Save as routine': '保存为训练计划','Create an independent routine from these exercise targets. Your workout history is kept.': '根据这些训练目标创建独立训练计划。你的训练记录会保留。',+ 'Pause': '暂停','Keep timing after target': '达到目标后继续计时','Timed sets continue up to 15 extra minutes. Tap Done to log the actual duration.': '计时组最多继续 15 分钟。点击“完成”记录实际时长。','Edit workout': '编辑训练',diff --git a/frontend/src/store/useUI.js b/frontend/src/store/useUI.jsindex a9cb0f46a..1e1e17965 100644--- a/frontend/src/store/useUI.js+++ b/frontend/src/store/useUI.js@@ -60,11 +60,50 @@ let workTick = nulllet workDone = nullconst MAX_WORK_OVERTIME_SEC = 15 * 60+const stopRestTicking = () => {+ if (timerInt) clearInterval(timerInt); timerInt = null+ if (timerTick) document.removeEventListener('visibilitychange', timerTick); timerTick = null+}+// The rest countdown's tick, from a start or from a resume: the same endsAt-based count either+// way, so a paused rest carries on exactly as a started one runs.+const runRest = (set, get) => {+ stopRestTicking()+ timerTick = () => {+ const tm = get().timer+ if (!tm || tm.ready || tm.paused) return+ const left = Math.max(0, Math.round((tm.endsAt - Date.now()) / 1000))+ const seenLive = !document.hidden && pageHiddenAt === null+ if (!document.hidden) pageHiddenAt = null+ if (left === tm.left) return+ const snd = useStore.getState().S.sound+ if (left <= 0) {+ if (seenLive) {+ beep(snd, 880, 0.15); beep(snd, 880, 0.15, 0.25); beep(snd, 1320, 0.4, 0.5)+ vibrate([200, 100, 200]); get().flashTimer()+ }+ // The toast stays even when the rest ran out while the app was hidden: a guest, or anyone+ // without push permission, gets no notification, and a countdown that silently vanishes+ // on reopen reads like a bug. Only the loud parts (beep, vibration, flash) are gated.+ get().toast(t('Rest over — next set!'))+ maybeRestNotification()+ cancelPushRestTimer()+ stopRestTicking()+ set({ timer: { ...tm, left: 0, ready: true } })+ return+ }+ if (left <= 3) beep(snd, 660, 0.1)+ set({ timer: { ...tm, left } })+ }+ timerInt = setInterval(timerTick, 1000)+ document.addEventListener('visibilitychange', timerTick)+}+export const useUI = create((set, get) => ({sheets: [], // { id, render:(close)=>JSX, kind:'sheet'|'center', locked }toastMsg: '',- timer: null, // rest countdown between sets — { left, total, endsAt, forIdx, ready? }+ timer: null, // rest countdown between sets — { left, total, endsAt, forIdx, ready?, paused? }// forIdx: index of the active entry whose set started the rest (undefined when unknown)+ // paused: held at `left`; `endsAt` means nothing until resumeRest sets it againwork: null, // work countdown DURING a timed set (issue #16) — { left, total, endsAt, label, overtime? }timerFlashId: 0, // changing the id retriggers the theme-blink visual alert@@ -110,35 +149,32 @@ export const useUI = create((set, get) => ({const endsAt = Date.now() + sec * 1000set({ timer: { left: sec, total: sec, endsAt, forIdx } })pushRestTimer(sec)- timerTick = () => {- const tm = get().timer- if (!tm || tm.ready) return- const left = Math.max(0, Math.round((tm.endsAt - Date.now()) / 1000))- const seenLive = !document.hidden && pageHiddenAt === null- if (!document.hidden) pageHiddenAt = null- if (left === tm.left) return- const snd = useStore.getState().S.sound- if (left <= 0) {- if (seenLive) {- beep(snd, 880, 0.15); beep(snd, 880, 0.15, 0.25); beep(snd, 1320, 0.4, 0.5)- vibrate([200, 100, 200]); get().flashTimer()- }- // The toast stays even when the rest ran out while the app was hidden: a guest, or anyone- // without push permission, gets no notification, and a countdown that silently vanishes- // on reopen reads like a bug. Only the loud parts (beep, vibration, flash) are gated.- get().toast(t('Rest over — next set!'))- maybeRestNotification()- cancelPushRestTimer()- if (timerInt) clearInterval(timerInt); timerInt = null- if (timerTick) document.removeEventListener('visibilitychange', timerTick); timerTick = null- set({ timer: { ...tm, left: 0, ready: true } })- return- }- if (left <= 3) beep(snd, 660, 0.1)- set({ timer: { ...tm, left } })- }- timerInt = setInterval(timerTick, 1000)- document.addEventListener('visibilitychange', timerTick)+ runRest(set, get)+ },+ // Holding the rest where it is — a longer break than planned, a machine to wait for, a phone+ // call (#193). Paused time does not count: the countdown stops, and so does everything that+ // would announce its end — the server's push and the alert this tab shows are cancelled, not+ // left to fire at the old time. The timed hold is a different timer and is not touched.+ pauseRest() {+ const tm = get().timer+ if (!tm || tm.ready || tm.paused) return+ stopRestTicking()+ cancelPushRestTimer()+ const left = Math.max(1, Math.round((tm.endsAt - Date.now()) / 1000))+ set({ timer: { ...tm, left, paused: true } })+ },+ // Carrying on from where the pause held it: the end moves out by however long the pause was,+ // and the push that announces it is booked again for the new time.+ resumeRest() {+ const tm = get().timer+ if (!tm?.paused) return+ const { paused, ...rest } = tm+ // As in startRest: the page may have been hidden and shown while paused, and that is no+ // catch-up of a countdown that was not running.+ pageHiddenAt = document.hidden ? Date.now() : null+ set({ timer: { ...rest, endsAt: Date.now() + tm.left * 1000 } })+ pushRestTimer(tm.left)+ runRest(set, get)},addRest(sec) {const tm = get().timer@@ -148,6 +184,8 @@ export const useUI = create((set, get) => ({// taking off more than is left means "I'm ready now" — same as skipping, and it keeps a// negative duration out of both the progress bar and the server-side push scheduleif (left <= 0) { get().stopRest(); return }+ // Paused, there is no end to move and nothing booked on the server: the time is simply held.+ if (tm.paused) { set({ timer: { ...tm, left, total: tm.total + sec } }); return }set({ timer: { ...tm, left, total: tm.total + sec, endsAt: tm.endsAt + sec * 1000 } })pushRestTimer(left)},@@ -159,8 +197,7 @@ export const useUI = create((set, get) => ({set({ timer: { ...tm, forIdx: tm.forIdx + delta } })},stopRest() {- if (timerInt) clearInterval(timerInt); timerInt = null- if (timerTick) document.removeEventListener('visibilitychange', timerTick); timerTick = null+ stopRestTicking()if (get().timer) cancelPushRestTimer()set({ timer: null })},diff --git a/frontend/src/store/useUI.pause.test.js b/frontend/src/store/useUI.pause.test.jsnew file mode 100644index 000000000..d3ed72bf7--- /dev/null+++ b/frontend/src/store/useUI.pause.test.js@@ -0,0 +1,115 @@+// @vitest-environment happy-dom+// Pausing the rest between sets (#193): paused time does not count, nothing announces the end at+// the old time, and resuming books the push again for the new one. The timed hold is its own timer.+import { describe, expect, it, beforeEach, afterEach, vi } from 'vitest'++vi.mock('../lib/api.js', () => ({ api: vi.fn(() => Promise.resolve({ ok: true })) }))+const { beep } = vi.hoisted(() => ({ beep: vi.fn() }))+vi.mock('../lib/sound.js', () => ({ beep, vibrate: vi.fn() }))++import { api } from '../lib/api.js'+import { useUI } from './useUI.js'+import { useStore } from './useStore.js'++const posts = path => api.mock.calls.filter(([p]) => p === path).map(([, o]) => JSON.parse(o.body))++describe('pausing the rest timer', () => {+ let original+ beforeEach(() => {+ vi.useFakeTimers()+ original = { S: useStore.getState().S, user: useStore.getState().user }+ useStore.setState({ S: { ...original.S, sound: true, timerFlash: true }, user: { id: 'u1' } })+ useUI.setState({ timer: null, work: null, timerFlashId: 0, toastMsg: '' })+ api.mockClear()+ beep.mockClear()+ })+ afterEach(() => {+ useUI.getState().stopRest()+ useUI.getState().stopWork()+ useStore.setState(original)+ vi.useRealTimers()+ })++ it('holds the time left while paused and runs it out after resuming', () => {+ useUI.getState().startRest(90, 1)+ vi.advanceTimersByTime(30000)+ useUI.getState().pauseRest()+ expect(useUI.getState().timer).toMatchObject({ left: 60, total: 90, paused: true, forIdx: 1 })++ vi.advanceTimersByTime(10 * 60000) // a phone call+ expect(useUI.getState().timer).toMatchObject({ left: 60, paused: true })+ expect(useUI.getState().timer.ready).toBeUndefined()+ expect(beep).not.toHaveBeenCalled()+ expect(useUI.getState().toastMsg).toBe('')++ useUI.getState().resumeRest()+ expect(useUI.getState().timer.paused).toBeUndefined()+ vi.advanceTimersByTime(59000)+ expect(useUI.getState().timer).toMatchObject({ left: 1 })+ vi.advanceTimersByTime(1000)+ expect(useUI.getState().timer).toMatchObject({ left: 0, ready: true, forIdx: 1 })+ expect(useUI.getState().timerFlashId).toBe(1) // ended on screen: the usual alert+ })++ it('cancels the push booked for the old end and books it again on resume', () => {+ useUI.getState().startRest(90)+ expect(posts('/api/push/rest-timer').map(b => b.seconds)).toEqual([90])+ vi.advanceTimersByTime(20000)+ useUI.getState().pauseRest()+ expect(posts('/api/push/rest-timer/cancel')).toHaveLength(1)+ vi.advanceTimersByTime(60000)+ useUI.getState().resumeRest()+ expect(posts('/api/push/rest-timer').map(b => b.seconds)).toEqual([90, 70])+ })++ it('adds and takes off time while paused without booking anything', () => {+ useUI.getState().startRest(60)+ useUI.getState().pauseRest()+ api.mockClear()+ useUI.getState().addRest(15)+ expect(useUI.getState().timer).toMatchObject({ left: 75, total: 75, paused: true })+ expect(api).not.toHaveBeenCalled()+ useUI.getState().addRest(-90)+ expect(useUI.getState().timer).toBeNull()+ })++ it('has nothing to pause once the rest is over, and nothing to resume while it runs', () => {+ useUI.getState().startRest(1)+ vi.advanceTimersByTime(1000)+ useUI.getState().pauseRest()+ expect(useUI.getState().timer).toMatchObject({ ready: true })+ expect(useUI.getState().timer.paused).toBeUndefined()++ useUI.getState().startRest(30)+ const running = useUI.getState().timer+ useUI.getState().resumeRest()+ expect(useUI.getState().timer).toBe(running)+ })++ it('a set finished while paused starts its own rest, running', () => {+ useUI.getState().startRest(90, 0)+ useUI.getState().pauseRest()+ useUI.getState().startRest(60, 2)+ expect(useUI.getState().timer).toMatchObject({ left: 60, forIdx: 2 })+ expect(useUI.getState().timer.paused).toBeUndefined()+ vi.advanceTimersByTime(10000)+ expect(useUI.getState().timer.left).toBe(50)+ })++ it('leaves the timed hold alone: pausing is the rest\'s alone, and a hold still ends a paused rest', () => {+ const done = vi.fn()+ useUI.getState().startWork(45, 'Plank', done)+ useUI.getState().pauseRest()+ vi.advanceTimersByTime(5000)+ expect(useUI.getState().work).toMatchObject({ left: 40 })+ expect(useUI.getState().work.paused).toBeUndefined()+ useUI.getState().stopWork()++ useUI.getState().startRest(90)+ useUI.getState().pauseRest()+ useUI.getState().startWork(30, 'Plank', done)+ expect(useUI.getState().timer).toBeNull()+ vi.advanceTimersByTime(30000)+ expect(done).toHaveBeenCalledExactlyOnceWith(30)+ })+})diff --git a/frontend/src/views/Workout.jsx b/frontend/src/views/Workout.jsxindex 07fbf898f..967f2306c 100644--- a/frontend/src/views/Workout.jsx+++ b/frontend/src/views/Workout.jsx@@ -988,7 +988,8 @@ function ActiveWorkout() {// A re-check of finished work must not navigate or reopen a sheet, but it may still owe// you a rest — see restOnRecheck, and the other half of issue #3. A rest that already ran- // out and only shows Ready is not running: it has nothing left to time.+ // out and only shows Ready is not running: it has nothing left to time. A paused one is+ // still the rest you are in, held on purpose, and a re-check leaves it as it is.if (!progress.isNew) {const rest = useUI.getState().timerif (!restBeforeWarmup && restOnRecheck({ timerRunning: !!(rest && !rest.ready), unitDone: freshUnitDone, lastUnit: freshWorkoutDone })) startRest(restAfter, idx)