diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx index 48cba0c..e7c8c52 100644 --- a/frontend/src/App.jsx +++ b/frontend/src/App.jsx @@ -6,6 +6,7 @@ import { bindUI } from './components/ui.jsx' import { ACCENTS } from './lib/format.js' import { setLang, useLang } from './lib/i18n.js' import { setNav } from './lib/nav.js' +import { useWakeLock } from './lib/wakelock.js' import { startFlow } from './sheets.jsx' import Icon from './components/Icon.jsx' import TabBar from './components/TabBar.jsx' @@ -46,6 +47,8 @@ function Shell() { useEffect(() => { document.documentElement.lang = S.lang || 'en' }, [langV, S.lang]) // every tab/route change starts at the top of the page useEffect(() => { window.scrollTo(0, 0) }, [loc.pathname]) + // bound to the workout, not to the route — checking Stats mid-session keeps the screen on + useWakeLock(!!S.active && S.keepAwake !== false) const authed = user || isGuest if (!ready && !authed) return ( diff --git a/frontend/src/lib/wakelock.js b/frontend/src/lib/wakelock.js new file mode 100644 index 0000000..7578f30 --- /dev/null +++ b/frontend/src/lib/wakelock.js @@ -0,0 +1,57 @@ +// Screen Wake Lock — keeps the display on while a workout is running, so nobody has to +// unlock their phone between sets. +// +// The browser drops the lock on its own whenever the document stops being visible (tab +// switch, app backgrounded, screen locked by hand). A one-shot request therefore works +// exactly once and then silently dies, which is why `wanted` is kept as our own intent +// and the lock is re-acquired on every visibilitychange for as long as it holds. +import { useEffect } from 'react' + +export const wakeLockSupported = () => 'wakeLock' in navigator + +let sentinel = null // the live WakeLockSentinel, null when we hold nothing +let wanted = false // do we currently want the screen to stay on? +let pending = false // a request() is in flight — don't stack a second one + +async function acquire() { + if (!wanted || sentinel || pending || !wakeLockSupported()) return + if (document.visibilityState !== 'visible') return // request() rejects on a hidden document + pending = true + try { + const s = await navigator.wakeLock.request('screen') + if (!wanted) { s.release().catch(() => {}); return } // released while we were awaiting + sentinel = s + s.addEventListener('release', () => { if (sentinel === s) sentinel = null }) + } catch (e) { + // iOS refuses in Low Power Mode, and some browsers refuse on low battery. Nothing to + // do about it and nothing the user could act on — stay quiet and try again next time + // the document becomes visible. + sentinel = null + } finally { pending = false } +} + +const onVisible = () => { if (document.visibilityState === 'visible') acquire() } + +export function requestWakeLock() { + if (wanted) return + wanted = true + document.addEventListener('visibilitychange', onVisible) + acquire() +} + +export function releaseWakeLock() { + wanted = false + document.removeEventListener('visibilitychange', onVisible) + const s = sentinel + sentinel = null + if (s) s.release().catch(() => {}) +} + +// Holds the lock for as long as `enabled` stays true. +export function useWakeLock(enabled) { + useEffect(() => { + if (!enabled) return + requestWakeLock() + return releaseWakeLock + }, [enabled]) +} diff --git a/frontend/src/lib/wakelock.test.js b/frontend/src/lib/wakelock.test.js new file mode 100644 index 0000000..a15b142 --- /dev/null +++ b/frontend/src/lib/wakelock.test.js @@ -0,0 +1,109 @@ +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest' + +// The whole point of the module is surviving what the browser does on its own: it drops the +// lock every time the document goes hidden. So the fake browser here has to do that too, +// otherwise the tests pass against a one-shot implementation that dies on the first tab switch. +let requests, released, live, listeners, reject + +function fakeBrowser() { + requests = 0; released = 0; live = null; reject = false + listeners = new Set() + globalThis.document = { + visibilityState: 'visible', + addEventListener: (type, fn) => { if (type === 'visibilitychange') listeners.add(fn) }, + removeEventListener: (type, fn) => { if (type === 'visibilitychange') listeners.delete(fn) }, + } + globalThis.navigator = { + wakeLock: { + request: async () => { + requests++ + if (reject) throw new Error('NotAllowedError') // iOS Low Power Mode + const subs = new Set() + const s = { addEventListener: (_, fn) => subs.add(fn), release: async () => { if (live === s) live = null; released++; subs.forEach(fn => fn()) } } + live = s + return s + }, + }, + } +} +const fire = () => listeners.forEach(fn => fn()) +const settle = () => new Promise(r => setTimeout(r, 0)) +const background = async () => { globalThis.document.visibilityState = 'hidden'; if (live) await live.release(); fire(); await settle() } +const foreground = async () => { globalThis.document.visibilityState = 'visible'; fire(); await settle() } + +let requestWakeLock, releaseWakeLock, wakeLockSupported + +beforeEach(async () => { + fakeBrowser() + vi.resetModules() // the module holds process-wide state; each test gets a fresh one + ;({ requestWakeLock, releaseWakeLock, wakeLockSupported } = await import('./wakelock.js')) +}) +afterEach(() => { delete globalThis.document; delete globalThis.navigator }) + +describe('wakeLockSupported', () => { + it('is false when the browser has no wakeLock at all', () => { + globalThis.navigator = {} + expect(wakeLockSupported()).toBe(false) + }) + it('is true when it does', () => { + expect(wakeLockSupported()).toBe(true) + }) +}) + +describe('requestWakeLock', () => { + it('takes a lock', async () => { + requestWakeLock(); await settle() + expect(requests).toBe(1) + expect(live).not.toBeNull() + }) + + it('does not stack a second lock while one is held', async () => { + requestWakeLock(); await settle() + requestWakeLock(); await settle() + expect(requests).toBe(1) + }) + + it('does not request one on a hidden document', async () => { + globalThis.document.visibilityState = 'hidden' + requestWakeLock(); await settle() + expect(requests).toBe(0) + }) + + it('re-acquires after the browser drops it on backgrounding', async () => { + requestWakeLock(); await settle() + await background() + expect(live).toBeNull() + await foreground() + expect(requests).toBe(2) + expect(live).not.toBeNull() + }) + + it('survives a rejection and retries when the document comes back', async () => { + reject = true + requestWakeLock(); await settle() + expect(live).toBeNull() + reject = false + await foreground() + expect(live).not.toBeNull() + }) +}) + +describe('releaseWakeLock', () => { + it('releases the held lock and stops re-acquiring', async () => { + requestWakeLock(); await settle() + releaseWakeLock(); await settle() + expect(released).toBe(1) + expect(live).toBeNull() + await background(); await foreground() + expect(requests).toBe(1) + }) + + it('does not leak a lock when it lands while a request is in flight', async () => { + requestWakeLock() // no await — the request is still pending + releaseWakeLock() + await settle() + expect(live).toBeNull() // the arriving sentinel was released immediately + await foreground() + expect(requests).toBe(1) // and we did not start wanting it again + }) +}) diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.js index 8801aeb..21c106c 100644 --- a/frontend/src/locales/de.js +++ b/frontend/src/locales/de.js @@ -256,7 +256,10 @@ export default { 'Dark': 'Dunkel', 'Light': 'Hell', 'Accent color': 'Akzentfarbe', - 'Units & timer': 'Einheiten & Timer', + 'General': 'Allgemein', + 'During a workout': 'Während des Trainings', + 'Keep screen awake': 'Bildschirm anlassen', + 'The screen stays on while a workout is running, so you don’t have to unlock your phone between sets.': 'Der Bildschirm bleibt an, solange ein Workout läuft — so musst du zwischen den Sätzen nicht entsperren.', 'Weight unit': 'Gewichtseinheit', 'Rest timer': 'Pausen-Timer', 'Sounds': 'Töne', diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js index c515af3..4b2e707 100644 --- a/frontend/src/locales/es.js +++ b/frontend/src/locales/es.js @@ -242,7 +242,10 @@ export default { 'Dark': 'Oscuro', 'Light': 'Claro', 'Accent color': 'Color de acento', - 'Units & timer': 'Unidades y temporizador', + 'General': 'General', + 'During a workout': 'Durante el entrenamiento', + 'Keep screen awake': 'Mantener la pantalla encendida', + 'The screen stays on while a workout is running, so you don’t have to unlock your phone between sets.': 'La pantalla se mantiene encendida mientras hay un entrenamiento en curso, así no tienes que desbloquear el móvil entre series.', 'Weight unit': 'Unidad de peso', 'Rest timer': 'Temporizador de descanso', 'Sounds': 'Sonidos', diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.js index 7f1e076..12fed6b 100644 --- a/frontend/src/locales/fr.js +++ b/frontend/src/locales/fr.js @@ -242,7 +242,10 @@ export default { 'Dark': 'Sombre', 'Light': 'Clair', 'Accent color': "Couleur d'accent", - 'Units & timer': 'Unités et minuteur', + 'General': 'Général', + 'During a workout': 'Pendant la séance', + 'Keep screen awake': 'Garder l’écran allumé', + 'The screen stays on while a workout is running, so you don’t have to unlock your phone between sets.': 'L’écran reste allumé tant qu’une séance est en cours, pas besoin de déverrouiller ton téléphone entre les séries.', 'Weight unit': 'Unité de poids', 'Rest timer': 'Minuteur de repos', 'Sounds': 'Sons', diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.js index 4e77dea..8f4db4f 100644 --- a/frontend/src/locales/hi.js +++ b/frontend/src/locales/hi.js @@ -242,7 +242,10 @@ export default { 'Dark': 'डार्क', 'Light': 'लाइट', 'Accent color': 'एक्सेंट रंग', - 'Units & timer': 'इकाइयाँ और टाइमर', + 'General': 'सामान्य', + 'During a workout': 'वर्कआउट के दौरान', + 'Keep screen awake': 'स्क्रीन चालू रखें', + 'The screen stays on while a workout is running, so you don’t have to unlock your phone between sets.': 'वर्कआउट चलने के दौरान स्क्रीन चालू रहती है, ताकि सेट के बीच फ़ोन अनलॉक न करना पड़े।', 'Weight unit': 'वज़न की इकाई', 'Rest timer': 'आराम टाइमर', 'Sounds': 'ध्वनियाँ', diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.js index 12834d2..e06f6c7 100644 --- a/frontend/src/locales/it.js +++ b/frontend/src/locales/it.js @@ -242,7 +242,10 @@ export default { 'Dark': 'Scuro', 'Light': 'Chiaro', 'Accent color': 'Colore accento', - 'Units & timer': 'Unità e timer', + 'General': 'Generale', + 'During a workout': 'Durante l’allenamento', + 'Keep screen awake': 'Mantieni lo schermo acceso', + 'The screen stays on while a workout is running, so you don’t have to unlock your phone between sets.': 'Lo schermo resta acceso mentre un allenamento è in corso, così non devi sbloccare il telefono tra una serie e l’altra.', 'Weight unit': 'Unità di peso', 'Rest timer': 'Timer di riposo', 'Sounds': 'Suoni', diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.js index 78dac2b..7e83dfa 100644 --- a/frontend/src/locales/ko.js +++ b/frontend/src/locales/ko.js @@ -242,7 +242,10 @@ export default { 'Dark': '다크', 'Light': '라이트', 'Accent color': '강조 색상', - 'Units & timer': '단위와 타이머', + 'General': '일반', + 'During a workout': '운동 중', + 'Keep screen awake': '화면 켜두기', + 'The screen stays on while a workout is running, so you don’t have to unlock your phone between sets.': '운동이 진행되는 동안 화면이 켜져 있어 세트 사이에 잠금을 해제할 필요가 없습니다.', 'Weight unit': '무게 단위', 'Rest timer': '휴식 타이머', 'Sounds': '소리', diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.js index e0acc37..6441b6a 100644 --- a/frontend/src/locales/pl.js +++ b/frontend/src/locales/pl.js @@ -242,7 +242,10 @@ export default { 'Dark': 'Ciemny', 'Light': 'Jasny', 'Accent color': 'Kolor akcentu', - 'Units & timer': 'Jednostki i minutnik', + 'General': 'Ogólne', + 'During a workout': 'Podczas treningu', + 'Keep screen awake': 'Nie wygaszaj ekranu', + 'The screen stays on while a workout is running, so you don’t have to unlock your phone between sets.': 'Ekran pozostaje włączony w trakcie treningu, więc nie musisz odblokowywać telefonu między seriami.', 'Weight unit': 'Jednostka wagi', 'Rest timer': 'Minutnik przerwy', 'Sounds': 'Dźwięki', diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.js index 124442f..529d7df 100644 --- a/frontend/src/locales/pt.js +++ b/frontend/src/locales/pt.js @@ -242,7 +242,10 @@ export default { 'Dark': 'Escuro', 'Light': 'Claro', 'Accent color': 'Cor de destaque', - 'Units & timer': 'Unidades e temporizador', + 'General': 'Geral', + 'During a workout': 'Durante o treino', + 'Keep screen awake': 'Manter o ecrã ligado', + 'The screen stays on while a workout is running, so you don’t have to unlock your phone between sets.': 'O ecrã fica ligado enquanto há um treino a decorrer, para não teres de desbloquear o telemóvel entre séries.', 'Weight unit': 'Unidade de peso', 'Rest timer': 'Temporizador de descanso', 'Sounds': 'Sons', diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.js index c0d4ee3..a610e15 100644 --- a/frontend/src/locales/ru.js +++ b/frontend/src/locales/ru.js @@ -242,7 +242,10 @@ export default { 'Dark': 'Тёмная', 'Light': 'Светлая', 'Accent color': 'Акцентный цвет', - 'Units & timer': 'Единицы и таймер', + 'General': 'Основное', + 'During a workout': 'Во время тренировки', + 'Keep screen awake': 'Не гасить экран', + 'The screen stays on while a workout is running, so you don’t have to unlock your phone between sets.': 'Экран не гаснет, пока идёт тренировка, — не нужно разблокировать телефон между подходами.', 'Weight unit': 'Единица веса', 'Rest timer': 'Таймер отдыха', 'Sounds': 'Звуки', diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.js index 13b7677..ee991c7 100644 --- a/frontend/src/locales/tr.js +++ b/frontend/src/locales/tr.js @@ -242,7 +242,10 @@ export default { 'Dark': 'Koyu', 'Light': 'Açık', 'Accent color': 'Vurgu rengi', - 'Units & timer': 'Birimler ve sayaç', + 'General': 'Genel', + 'During a workout': 'Antrenman sırasında', + 'Keep screen awake': 'Ekranı açık tut', + 'The screen stays on while a workout is running, so you don’t have to unlock your phone between sets.': 'Antrenman sürerken ekran açık kalır, böylece setler arasında telefonunu açmak zorunda kalmazsın.', 'Weight unit': 'Ağırlık birimi', 'Rest timer': 'Dinlenme sayacı', 'Sounds': 'Sesler', diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.js index a3e2d8c..20d6b89 100644 --- a/frontend/src/locales/zh.js +++ b/frontend/src/locales/zh.js @@ -242,7 +242,10 @@ export default { 'Dark': '深色', 'Light': '浅色', 'Accent color': '强调色', - 'Units & timer': '单位与计时', + 'General': '通用', + 'During a workout': '训练期间', + 'Keep screen awake': '保持屏幕常亮', + 'The screen stays on while a workout is running, so you don’t have to unlock your phone between sets.': '训练进行时屏幕保持常亮,组间无需再解锁手机。', 'Weight unit': '重量单位', 'Rest timer': '休息计时', 'Sounds': '声音', diff --git a/frontend/src/store/useStore.js b/frontend/src/store/useStore.js index 232b880..641961d 100644 --- a/frontend/src/store/useStore.js +++ b/frontend/src/store/useStore.js @@ -7,7 +7,7 @@ import { MOBILE, nativeLoad, nativeSave, syncReminder } from '../lib/mobile.js' const KEY = 'gym_state_v1' export const DEF = { - unit: 'kg', restSec: 90, sound: true, lang: 'en', + unit: 'kg', restSec: 90, sound: true, keepAwake: true, lang: 'en', theme: 'dark', accent: 'lime', body: 'male', targetW: null, bodyweight: [], routines: [], week: {}, dayPlan: {}, exWeights: {}, workouts: [], active: null, customEx: [], gifSize: 'full', diff --git a/frontend/src/views/Settings.jsx b/frontend/src/views/Settings.jsx index d191764..7e30f6f 100644 --- a/frontend/src/views/Settings.jsx +++ b/frontend/src/views/Settings.jsx @@ -6,6 +6,7 @@ import { ACCENTS, todayISO, localTZ } from '../lib/format.js' import { effortOf } from '../lib/history.js' import { webauthnOK, passkeyLogin, passkeyRegister, IS_ANDROID } from '../lib/api.js' import { pushSupported, enablePush, disablePush, sendTestPush } from '../lib/push.js' +import { wakeLockSupported } from '../lib/wakelock.js' import { t, LANGS, INSTR_LANGS } from '../lib/i18n.js' import { DEMO, REPO } from '../lib/demo.js' import { MOBILE, shareExport, syncReminder } from '../lib/mobile.js' @@ -21,6 +22,7 @@ export default function Settings() { const toast = useUI(s => s.toast) const fileRef = useRef(null) const importRef = useRef(null) + const wakeOK = wakeLockSupported() const doExport = async () => { const json = JSON.stringify(S, null, 2) @@ -83,8 +85,8 @@ export default function Settings() { {!user && !DEMO && !MOBILE &&
{t('Guest mode — data lives only in this browser.')}
} - {/* ---------- appearance ---------- */} -