Keep the screen awake while a workout is running

Locking and unlocking the phone between every set was the worst part of logging on
one. Settings -> During a workout -> Keep screen awake, on by default; the lock is
held only while S.active exists, so it follows the workout rather than the route and
lets go when you finish.

The browser drops the lock whenever the document stops being visible, which is what
happens the moment you glance at a message, so wakelock.js keeps its own 'wanted'
intent and re-acquires on every visibilitychange. It also releases a sentinel that
arrives after a release landed mid-request, and swallows the rejection iOS gives in
Low Power Mode. Where the API is missing the row shows disabled instead of offering
a switch that does nothing.

Settings is regrouped by what each thing affects while the row needed a home:
General (language, units), During a workout (rest timer, keep awake, sounds, effort),
Notifications, Appearance, Data. Nothing removed, no setting changed meaning.
This commit is contained in:
Duarte Santos committed 2026-07-31 15:35:18 +02:00
1 parent 42d3659615
commit 248da53dca
16 files changed
+258 -43

No files matched your search

+3
View File
@@ -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 (
+57
View File
@@ -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])
}
+109
View File
@@ -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
})
})
+4 -1
View File
@@ -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',
+4 -1
View File
@@ -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',
+4 -1
View File
@@ -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',
+4 -1
View File
@@ -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': 'ध्वनियाँ',
+4 -1
View File
@@ -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',
+4 -1
View File
@@ -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': '소리',
+4 -1
View File
@@ -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',
+4 -1
View File
@@ -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',
+4 -1
View File
@@ -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': 'Звуки',
+4 -1
View File
@@ -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',
+4 -1
View File
@@ -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': '声音',
+1 -1
View File
@@ -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',
+44 -31
View File
@@ -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() {
</Section>
{!user && !DEMO && !MOBILE && <p className="sect-f" style={{ marginTop: -18, marginBottom: 22 }}>{t('Guest mode — data lives only in this browser.')}</p>}
{/* ---------- appearance ---------- */}
<Section title={t('Appearance')} footer={DEMO || MOBILE ? undefined : t('synced with your profile')}>
{/* ---------- general ---------- */}
<Section title={t('General')} footer={t('Note: switching units only changes the label — logged numbers are not converted.')}>
<SelectRow
icon="globe" iconTint="var(--blue)" title={t('Language')}
value={S.lang || 'en'} onChange={v => update(s => { s.lang = v })}
@@ -93,6 +95,42 @@ export default function Settings() {
subtitle: INSTR_LANGS.includes(k) ? null : t("Exercise instructions aren't available in this language yet — they stay in English."),
}))}
/>
<Row icon="scale" iconTint="var(--teal)" title={t('Weight unit')}>
<Segmented className="seg-inline"
options={[{ value: 'kg', label: 'kg' }, { value: 'lb', label: 'lb' }]}
value={S.unit} onChange={v => update(s => { s.unit = v })} />
</Row>
</Section>
{/* ---------- during a workout ---------- */}
<Section title={t('During a workout')} footer={wakeOK ? t('The screen stays on while a workout is running, so you don’t have to unlock your phone between sets.') : null}>
<SelectRow icon="timer" iconTint="var(--orange)" title={t('Rest timer')}
value={S.restSec} onChange={v => update(s => { s.restSec = v })}
options={[60, 90, 120, 150, 180].map(v => ({ value: v, label: v + 's' }))} />
{(wakeOK || !MOBILE) && (
<Row icon="sun" iconTint="var(--yellow)" title={t('Keep screen awake')}
subtitle={wakeOK ? null : t('Not supported in this browser.')}>
<Switch checked={wakeOK && S.keepAwake !== false} disabled={!wakeOK}
onChange={v => update(s => { s.keepAwake = v })} />
</Row>
)}
<Row icon="bell" iconTint="var(--pink)" title={t('Sounds')}>
<Switch checked={!!S.sound} onChange={v => update(s => { s.sound = v })} />
</Row>
{/* Two names for the same judgement, so the column asks in the scale you already think in.
The (i) sits before the control — you read it on the way to the choice, not after it. */}
<Row icon="target" iconTint="var(--purple)" title={t('Effort per set')}>
<button className="helpbtn" aria-label={t('What are RIR and RPE?')} onClick={effortHelpSheet}><Icon name="info" /></button>
<Segmented className="seg-inline"
options={[{ value: 'none', label: t('Off') }, { value: 'rir', label: t('RIR') }, { value: 'rpe', label: t('RPE') }]}
value={effortOf(S)} onChange={v => update(s => { s.effort = v; delete s.showRir })} />
</Row>
</Section>
{(user || MOBILE) && <NotificationsCard S={S} update={update} toast={toast} />}
{/* ---------- appearance ---------- */}
<Section title={t('Appearance')} footer={DEMO || MOBILE ? undefined : t('synced with your profile')}>
<Row icon="moon" iconTint="var(--indigo)" title={t('Theme')}>
<Segmented
className="seg-inline"
@@ -121,39 +159,14 @@ export default function Settings() {
</div>
</Section>
{/* ---------- units & timer ---------- */}
<Section title={t('Units & timer')} footer={t('Note: switching units only changes the label — logged numbers are not converted.')}>
<Row icon="scale" iconTint="var(--teal)" title={t('Weight unit')}>
<Segmented className="seg-inline"
options={[{ value: 'kg', label: 'kg' }, { value: 'lb', label: 'lb' }]}
value={S.unit} onChange={v => update(s => { s.unit = v })} />
</Row>
<SelectRow icon="timer" iconTint="var(--orange)" title={t('Rest timer')}
value={S.restSec} onChange={v => update(s => { s.restSec = v })}
options={[60, 90, 120, 150, 180].map(v => ({ value: v, label: v + 's' }))} />
<Row icon="bell" iconTint="var(--pink)" title={t('Sounds')}>
<Switch checked={!!S.sound} onChange={v => update(s => { s.sound = v })} />
</Row>
{/* Two names for the same judgement, so the column asks in the scale you already think in.
The (i) sits before the control — you read it on the way to the choice, not after it. */}
<Row icon="target" iconTint="var(--purple)" title={t('Effort per set')}>
<button className="helpbtn" aria-label={t('What are RIR and RPE?')} onClick={effortHelpSheet}><Icon name="info" /></button>
<Segmented className="seg-inline"
options={[{ value: 'none', label: t('Off') }, { value: 'rir', label: t('RIR') }, { value: 'rpe', label: t('RPE') }]}
value={effortOf(S)} onChange={v => update(s => { s.effort = v; delete s.showRir })} />
</Row>
</Section>
{(user || MOBILE) && <NotificationsCard S={S} update={update} toast={toast} />}
{/* ---------- data ---------- */}
{/* ---------- data: fill it, bring things over, back it up, wipe it ---------- */}
<Section title={t('Data')}>
<Row icon="download" iconTint="var(--blue)" title={t('Export backup (JSON)')} accessory="chevron" onClick={doExport} />
<Row icon="upload" iconTint="var(--blue)" title={t('Import backup')} accessory="chevron" onClick={() => fileRef.current.click()} />
<Row icon="sparkles" iconTint="var(--acc)" title={t('Load starter plan (PPL)')} accessory="chevron" onClick={loadStarterPlan} />
<Row icon="shuffle" iconTint="var(--teal)" title={t('Import from another app')}
subtitle={t('FitNotes, Strong, Hevy — or body weight from Apple Health')}
accessory="chevron" onClick={() => importRef.current.click()} />
<Row icon="sparkles" iconTint="var(--acc)" title={t('Load starter plan (PPL)')} accessory="chevron" onClick={loadStarterPlan} />
<Row icon="upload" iconTint="var(--blue)" title={t('Import backup')} accessory="chevron" onClick={() => fileRef.current.click()} />
<Row icon="download" iconTint="var(--blue)" title={t('Export backup (JSON)')} accessory="chevron" onClick={doExport} />
<Row icon="trash" iconTint="var(--red)" title={t('Reset everything')} danger onClick={() => confirmSheet({ title: t('Reset everything?'), message: t('Deletes your plan, workouts and body weight on this device. This cannot be undone.'), confirmText: t('Delete everything'), danger: true, onConfirm: () => { replaceState(JSON.parse(JSON.stringify(DEF)), true); nav('/home'); toast(t('All data reset')) } })} />
</Section>
<input ref={fileRef} type="file" accept=".json,application/json" style={{ display: 'none' }} onChange={doImport} />