From 6e44e2f793e8f473e49ee5287f93c36771bb4a61 Mon Sep 17 00:00:00 2001 From: Boris Kurktchiev Date: Sat, 12 Sep 2026 16:13:17 -0400 Subject: [PATCH] =?UTF-8?q?fix(sound):=20iOS=20timer=20sounds=20=E2=80=94?= =?UTF-8?q?=20resume=20before=20every=20tone,=20unlock=20from=20the=20tap,?= =?UTF-8?q?=20and=20a=20"play=20on=20silent"=20setting=20(#152)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Three things iOS needs that a desktop browser does not, all in lib/sound.js: 1. The ring/silent switch mutes Web Audio: a page whose only audio is Web Audio gets the Ambient category, which obeys the switch. The way out is the 'playback' audio-session type (iOS 17+), which is exclusive — it pauses whatever else is playing and WebKit never tells that app it may resume — so it is a setting, off by default: Settings → Sounds → "Play sounds when the phone is on silent" (S.soundOnSilent, applied page-wide by App.jsx). Offered only where it means something: a WebKit with navigator.audioSession on a device with a switch. 2. Locking the screen or switching apps leaves a suspended context suspended, and a suspended context makes no sound: every tone resumes the context first. The context sleeps again a second after the last tone so it does not keep the phone's audio session busy. 3. A context created outside a tap starts suspended and no timer tick can start it: unlock() runs from the taps that lead to a timer (turning Sounds on, starting a hold). Split out of #165 at the maintainer's request; the per-kind rest-over sounds and the timer-bar work stay there. Tests: lib/sound.test.js (fake AudioContext + audioSession), views/Settings.sound.test.jsx. --- frontend/src/App.jsx | 4 + frontend/src/lib/pt-br-locale.test.js | 2 +- frontend/src/lib/sound.js | 81 ++++++++- frontend/src/lib/sound.test.js | 198 +++++++++++++++++++++ frontend/src/locales/de.js | 2 + frontend/src/locales/es.js | 2 + frontend/src/locales/fr.js | 2 + frontend/src/locales/hi.js | 2 + frontend/src/locales/hu.js | 2 + frontend/src/locales/it.js | 2 + frontend/src/locales/ko.js | 2 + frontend/src/locales/pl.js | 2 + frontend/src/locales/pt-BR.js | 2 + frontend/src/locales/pt.js | 2 + frontend/src/locales/ru.js | 2 + frontend/src/locales/th.js | 2 + frontend/src/locales/tr.js | 2 + frontend/src/locales/zh.js | 2 + frontend/src/store/useStore.js | 2 +- frontend/src/views/Settings.jsx | 14 +- frontend/src/views/Settings.sound.test.jsx | 132 ++++++++++++++ frontend/src/views/Workout.jsx | 5 +- frontend/src/views/Workout.remove.test.jsx | 2 +- 23 files changed, 459 insertions(+), 9 deletions(-) create mode 100644 frontend/src/lib/sound.test.js create mode 100644 frontend/src/views/Settings.sound.test.jsx diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx index c1f84f8..6d21984 100644 --- a/frontend/src/App.jsx +++ b/frontend/src/App.jsx @@ -5,6 +5,7 @@ import { useUI } from './store/useUI.js' import { bindUI } from './components/ui.jsx' import { ACCENTS } from './lib/format.js' import { setLang, useLang } from './lib/i18n.js' +import { setPlayOnSilent } from './lib/sound.js' import { setNav } from './lib/nav.js' import { initBackButton } from './lib/back.js' import { useWakeLock } from './lib/wakelock.js' @@ -61,6 +62,9 @@ function Shell() { const loc = useLocation() const navType = useNavigationType() const { S, user, ready } = useStore() + // iOS: whether timer sounds get past the ring/silent switch (Settings → Sounds). Page-level, + // so it is applied here on load and on change rather than at each beep. + useEffect(() => { setPlayOnSilent(!!S.soundOnSilent) }, [S.soundOnSilent]) const isGuest = useStore(s => s.isGuest()) const needsMobileOnboarding = useStore(s => s.needsMobileOnboarding) const langV = useLang() // re-renders the whole shell when the language (pack) changes diff --git a/frontend/src/lib/pt-br-locale.test.js b/frontend/src/lib/pt-br-locale.test.js index 544cf42..5d153e2 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(639) + expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(641) expect(inherited).toHaveLength(643) // If this fails, review the changed keys and wording before accepting a new hash. From // frontend/: node scripts/pt-br-inheritance-fingerprint.mjs --list diff --git a/frontend/src/lib/sound.js b/frontend/src/lib/sound.js index c9e6fe7..6f7ceef 100644 --- a/frontend/src/lib/sound.js +++ b/frontend/src/lib/sound.js @@ -1,17 +1,90 @@ // WebAudio beeps + haptics (ported from the vanilla app). `enabled` gates sound. +// +// iOS needs three things a desktop browser does not (#152, "flash but no beep"): +// 1. The ring/silent switch mutes Web Audio. WebKit gives a page whose only audio is Web Audio +// the Ambient category, and Ambient obeys the switch — at a gym the phone is usually on +// silent, so the timer was mute exactly where it mattered. The only way out is the +// 'playback' audio-session type (iOS 17+), which is exclusive: it pauses whatever else the +// phone is playing, and WebKit never tells that app it may resume. Hence a setting +// (setPlayOnSilent), off by default, rather than something done for everyone. +// 2. Locking the screen or switching apps moves a running context to 'interrupted'. WebKit +// only brings it back by itself if it was running when the interruption began; a context +// that was suspended comes back suspended, and a suspended context makes no sound. So every +// tone resumes the context first — allowed without a tap once the context has started +// inside one. +// 3. A context created outside a tap starts 'suspended' and no timer tick can start it. +// unlock() runs from the taps that lead to a timer (set check, hold start, turning Sounds +// on) so the context has started before any tick needs it. +// +// The context is suspended again a second after the last tone: an idle context otherwise keeps +// rendering silence for the rest of the page, and under 'playback' keeps the phone's audio +// session busy. (Suspending does NOT hand the phone back to a paused music app — see 1.) let audioCtx = null +let idleTm = null +let idleAt = 0 + +const ctxFor = () => { + if (!audioCtx || audioCtx.state === 'closed') audioCtx = new (window.AudioContext || window.webkitAudioContext)() + return audioCtx +} + +const wake = () => { + const ctx = ctxFor() + if (ctx.state !== 'running') { const p = ctx.resume(); if (p && p.catch) p.catch(() => {}) } + return ctx +} + +// Suspend once every scheduled tone is over. A burst schedules several tones in one go; the +// latest end wins, and a tone scheduled while the timer is pending pushes it out. +const sleepAfter = endSec => { + const at = Date.now() + endSec * 1000 + 1000 + if (at <= idleAt && idleTm) return + idleAt = at + clearTimeout(idleTm) + idleTm = setTimeout(() => { + idleTm = null + try { if (audioCtx && audioCtx.state === 'running') { const p = audioCtx.suspend(); if (p && p.catch) p.catch(() => {}) } } catch (e) { /* */ } + }, at - Date.now()) +} + export function beep(enabled, freq, dur, when) { if (!enabled) return try { - audioCtx = audioCtx || new (window.AudioContext || window.webkitAudioContext)() - const o = audioCtx.createOscillator(), g = audioCtx.createGain() - o.connect(g); g.connect(audioCtx.destination) + const ctx = wake() + const o = ctx.createOscillator(), g = ctx.createGain() + o.connect(g); g.connect(ctx.destination) o.frequency.value = freq || 880; o.type = 'sine' - const t0 = audioCtx.currentTime + (when || 0) + const t0 = ctx.currentTime + (when || 0) g.gain.setValueAtTime(0.001, t0) g.gain.exponentialRampToValueAtTime(0.35, t0 + 0.02) g.gain.exponentialRampToValueAtTime(0.001, t0 + (dur || 0.18)) o.start(t0); o.stop(t0 + (dur || 0.18) + 0.05) + sleepAfter((when || 0) + (dur || 0.18) + 0.05) } catch (e) { /* */ } } + +// Call from inside a tap. Gets the context created and running while the browser still counts +// this as a user gesture; it goes back to sleep on its own. Nothing audible. +export function unlock(enabled) { + if (!enabled) return + try { wake(); sleepAfter(0) } catch (e) { /* */ } +} + +// Settings → "Play sounds when the phone is on silent". Offered only where it means something: +// a WebKit with the audio-session API (iOS 17+) on a device that has a ring/silent switch or its +// Control Centre equivalent — iPhone, or an iPad (which reports itself as a Mac with a touch +// screen). macOS Safari has the API but no switch, and other browsers have neither. +// 'playback' ignores the switch; 'auto' is the browser's own choice (Ambient for a page like +// this one). Applied by App.jsx whenever the setting is loaded or changed. +export const playOnSilentSupported = () => { + if (typeof navigator === 'undefined' || !navigator.audioSession) return false + const ua = navigator.userAgent || '' + return /iPhone|iPad|iPod/.test(ua) || (/Macintosh/.test(ua) && navigator.maxTouchPoints > 1) +} +export function setPlayOnSilent(on) { + if (!playOnSilentSupported()) return + try { navigator.audioSession.type = on ? 'playback' : 'auto' } catch (e) { /* */ } +} + + export function vibrate(p) { try { navigator.vibrate && navigator.vibrate(p) } catch (e) { /* */ } } diff --git a/frontend/src/lib/sound.test.js b/frontend/src/lib/sound.test.js new file mode 100644 index 0000000..c19f714 --- /dev/null +++ b/frontend/src/lib/sound.test.js @@ -0,0 +1,198 @@ +// @vitest-environment happy-dom +// lib/sound.js keeps one AudioContext per page; each test gets a fresh module so that state +// does not leak. The fake context records what the real one would be asked to do. +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +class FakeCtx { + constructor() { + this.state = 'suspended' // what every browser hands back outside a user gesture + this.currentTime = 0 + this.destination = {} + this.tones = [] + this.resumes = 0 + this.suspends = 0 + FakeCtx.instances.push(this) + } + resume() { this.resumes++; this.state = 'running'; return Promise.resolve() } + suspend() { this.suspends++; this.state = 'suspended'; return Promise.resolve() } + createGain() { return { connect() {}, gain: { setValueAtTime() {}, exponentialRampToValueAtTime() {} } } } + createOscillator() { + const ctx = this + const o = { frequency: { value: 0 }, type: '', connect() {}, start(at) { ctx.tones.push({ freq: o.frequency.value, at }) }, stop() {} } + return o + } +} +FakeCtx.instances = [] + +let sound +let session +const ctx = () => FakeCtx.instances[0] +const IPHONE = 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148' +const MAC = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Safari/605.1.15' +const setDevice = (userAgent, maxTouchPoints = 0) => { + Object.defineProperty(navigator, 'userAgent', { value: userAgent, configurable: true }) + Object.defineProperty(navigator, 'maxTouchPoints', { value: maxTouchPoints, configurable: true }) +} + +beforeEach(async () => { + vi.useFakeTimers() + FakeCtx.instances = [] + window.AudioContext = FakeCtx + session = { type: 'auto' } + Object.defineProperty(navigator, 'audioSession', { value: session, configurable: true, writable: true }) + setDevice(IPHONE) + vi.resetModules() + sound = await import('./sound.js') +}) +afterEach(() => { vi.useRealTimers() }) + +describe('sounds off', () => { + it('creates no audio context and leaves the audio session alone', () => { + sound.beep(false, 880, 0.15) + sound.unlock(false) + expect(FakeCtx.instances).toHaveLength(0) + expect(session.type).toBe('auto') + }) +}) + +describe('iOS: silent switch and interruptions (#152)', () => { + it('the first tone gets the context running and leaves the audio session type alone', () => { + sound.beep(true, 880, 0.15) + expect(ctx().resumes).toBe(1) + expect(ctx().state).toBe('running') + expect(ctx().tones).toEqual([{ freq: 880, at: 0 }]) + expect(session.type).toBe('auto') // the silent-switch override is the setting's job + }) + + it('resumes a context that a lock or app switch left suspended before scheduling the tone', () => { + sound.beep(true, 880, 0.15) + ctx().state = 'interrupted' // what iOS does on screen lock / app switch + sound.beep(true, 660, 0.1) + expect(ctx().resumes).toBe(2) + expect(ctx().state).toBe('running') + expect(ctx().tones).toHaveLength(2) + }) + + // A real context reports 'suspended' until its resume() settles, so a burst can issue one + // resume() per tone in a browser — harmless. What this pins is the guard itself. + it('skips resume when the context already reports running', () => { + sound.beep(true, 880, 0.15) + sound.beep(true, 880, 0.15, 0.25) + expect(ctx().resumes).toBe(1) + }) + + it('replaces a context the browser has closed', () => { + sound.beep(true, 880, 0.15) + ctx().state = 'closed' + sound.beep(true, 880, 0.15) + expect(FakeCtx.instances).toHaveLength(2) + expect(FakeCtx.instances[1].tones).toHaveLength(1) + }) + + it('works in a browser without navigator.audioSession', () => { + Object.defineProperty(navigator, 'audioSession', { value: undefined, configurable: true, writable: true }) + sound.beep(true, 880, 0.15) + expect(ctx().tones).toHaveLength(1) + }) +}) + +describe('the context sleeps between beeps', () => { + it('suspends about a second after the last tone of a burst has ended', () => { + sound.beep(true, 880, 0.25, 0); sound.beep(true, 1320, 0.5, 0.35) // last tone ends at 0.35 + 0.5 + 0.05 = 0.9s + vi.advanceTimersByTime(1500) + expect(ctx().state).toBe('running') + vi.advanceTimersByTime(500) + expect(ctx().state).toBe('suspended') + expect(ctx().suspends).toBe(1) + }) + + it('a later tone pushes the sleep out instead of cutting itself short', () => { + sound.beep(true, 660, 0.1) // 3 + vi.advanceTimersByTime(1000) + sound.beep(true, 660, 0.1) // 2 + vi.advanceTimersByTime(1000) + sound.beep(true, 660, 0.1) // 1 + vi.advanceTimersByTime(1000) + sound.beep(true, 880, 0.15, 0); sound.beep(true, 880, 0.15, 0.25) // 0: last tone ends at 0.25 + 0.15 + 0.05 = 0.45s + expect(ctx().suspends).toBe(0) + vi.advanceTimersByTime(1400) + expect(ctx().state).toBe('running') + vi.advanceTimersByTime(100) + expect(ctx().state).toBe('suspended') + expect(ctx().suspends).toBe(1) + }) + + it('a short tone scheduled during a longer one does not shorten the longer one\'s sleep', () => { + sound.beep(true, 880, 0.5) // ends 0.55s → sleep at 1.55s + sound.beep(true, 660, 0.1) // ends 0.15s → must not pull the sleep to 1.15s + vi.advanceTimersByTime(1200) + expect(ctx().state).toBe('running') + vi.advanceTimersByTime(400) + expect(ctx().state).toBe('suspended') + }) +}) + +describe('unlock from a tap', () => { + it('gets the context created and running, without a tone', () => { + sound.unlock(true) + expect(FakeCtx.instances).toHaveLength(1) + expect(ctx().state).toBe('running') + expect(ctx().tones).toHaveLength(0) + }) + + it('lets the context sleep again on its own', () => { + sound.unlock(true) + vi.advanceTimersByTime(1000) + expect(ctx().state).toBe('suspended') + }) + + it('a tick after the tap finds a context it can resume rather than one it must create', () => { + sound.unlock(true) + vi.advanceTimersByTime(1000) + sound.beep(true, 660, 0.1) + expect(FakeCtx.instances).toHaveLength(1) + expect(ctx().state).toBe('running') + }) +}) + +describe('play on silent (Settings switch, WebKit only)', () => { + it('is offered on an iPhone with the audio-session API', () => { + expect(sound.playOnSilentSupported()).toBe(true) + }) + + it('is offered on an iPad, which calls itself a Mac with a touch screen', () => { + setDevice(MAC, 5) + expect(sound.playOnSilentSupported()).toBe(true) + }) + + it('is not offered on macOS Safari: it has the API but no ring/silent switch', () => { + setDevice(MAC, 0) + expect(sound.playOnSilentSupported()).toBe(false) + }) + + it('is not offered where navigator.audioSession does not exist', () => { + Object.defineProperty(navigator, 'audioSession', { value: undefined, configurable: true, writable: true }) + expect(sound.playOnSilentSupported()).toBe(false) + }) + + it("on: the page's audio session becomes 'playback', which ignores the ring/silent switch", () => { + sound.setPlayOnSilent(true) + expect(session.type).toBe('playback') + }) + + it("off: hands the choice back to the browser ('auto')", () => { + sound.setPlayOnSilent(true) + sound.setPlayOnSilent(false) + expect(session.type).toBe('auto') + }) + + it('is a no-op in a browser without navigator.audioSession', () => { + Object.defineProperty(navigator, 'audioSession', { value: undefined, configurable: true, writable: true }) + expect(() => sound.setPlayOnSilent(true)).not.toThrow() + }) + + it('survives a browser that rejects the type', () => { + Object.defineProperty(navigator, 'audioSession', { value: Object.freeze({ type: 'auto' }), configurable: true, writable: true }) + expect(() => sound.setPlayOnSilent(true)).not.toThrow() + }) +}) diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.js index f72b606..9661c2d 100644 --- a/frontend/src/locales/de.js +++ b/frontend/src/locales/de.js @@ -336,6 +336,8 @@ export default { 'Rest timer': 'Pausen-Timer', 'Sounds': 'Töne', 'Flash screen when timer ends': 'Bildschirm bei Timer-Ende blinken lassen', + 'Play sounds when the phone is on silent': 'Töne auch bei stummgeschaltetem Telefon abspielen', + 'Music playing on this phone stops during a workout and does not resume by itself.': 'Musik, die auf diesem Telefon läuft, stoppt während eines Trainings und setzt nicht von selbst wieder ein.', 'Data': 'Daten', 'Export backup (JSON)': 'Backup exportieren (JSON)', 'Import backup': 'Backup importieren', diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js index 8295e0a..3fd6772 100644 --- a/frontend/src/locales/es.js +++ b/frontend/src/locales/es.js @@ -321,6 +321,8 @@ export default { 'Rest timer': 'Temporizador de descanso', 'Sounds': 'Sonidos', 'Flash screen when timer ends': 'Hacer parpadear la pantalla al finalizar el temporizador', + 'Play sounds when the phone is on silent': 'Reproducir sonidos con el teléfono en silencio', + 'Music playing on this phone stops during a workout and does not resume by itself.': 'La música que suena en este teléfono se detiene durante un entrenamiento y no se reanuda por sí sola.', 'Data': 'Datos', 'Export backup (JSON)': 'Exportar copia (JSON)', 'Import backup': 'Importar copia', diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.js index 7804355..0c1347f 100644 --- a/frontend/src/locales/fr.js +++ b/frontend/src/locales/fr.js @@ -321,6 +321,8 @@ export default { 'Rest timer': 'Minuteur de repos', 'Sounds': 'Sons', 'Flash screen when timer ends': 'Faire clignoter l’écran à la fin du minuteur', + 'Play sounds when the phone is on silent': 'Jouer les sons même si le téléphone est en mode silencieux', + 'Music playing on this phone stops during a workout and does not resume by itself.': 'La musique en cours de lecture sur ce téléphone s’arrête pendant une séance et ne reprend pas toute seule.', 'Data': 'Données', 'Export backup (JSON)': 'Exporter une sauvegarde (JSON)', 'Import backup': 'Importer une sauvegarde', diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.js index 17e88d1..1f1c8f2 100644 --- a/frontend/src/locales/hi.js +++ b/frontend/src/locales/hi.js @@ -321,6 +321,8 @@ export default { 'Rest timer': 'आराम टाइमर', 'Sounds': 'ध्वनियाँ', 'Flash screen when timer ends': 'टाइमर खत्म होने पर स्क्रीन फ्लैश करें', + 'Play sounds when the phone is on silent': 'फ़ोन साइलेंट पर हो तब भी आवाज़ें बजाएँ', + 'Music playing on this phone stops during a workout and does not resume by itself.': 'इस फ़ोन पर चल रहा संगीत वर्कआउट के दौरान रुक जाता है और अपने आप फिर से शुरू नहीं होता।', 'Data': 'डेटा', 'Export backup (JSON)': 'बैकअप निर्यात करें (JSON)', 'Import backup': 'बैकअप आयात करें', diff --git a/frontend/src/locales/hu.js b/frontend/src/locales/hu.js index f72e542..7b53d15 100644 --- a/frontend/src/locales/hu.js +++ b/frontend/src/locales/hu.js @@ -745,6 +745,8 @@ export default { 'Logged sets stay with the original exercise. The replacement will be inserted afterward.': 'A naplózott sorozatok az eredeti gyakorlatnál maradnak. A csere utána kerül beszúrásra.', 'Rest after each set of this exercise. Leave at 0 to use your default rest timer.': 'Pihenő a gyakorlat minden sorozata után. Hagyd 0-n az alapértelmezett pihenőidőzítőhöz.', 'Flash screen when timer ends': 'Képernyő villogása, ha lejár az időzítő', + 'Play sounds when the phone is on silent': 'Hangok lejátszása akkor is, ha a telefon némítva van', + 'Music playing on this phone stops during a workout and does not resume by itself.': 'A telefonon szóló zene edzés közben leáll, és nem indul újra magától.', 'Import from Hevy': 'Importálás a Hevyből', 'Pull your history with a Hevy Pro API key': 'Előzmények letöltése Hevy Pro API-kulccsal', 'Pull your history with a Hevy Pro API key. The key is only used for this import and is not saved.': 'Előzmények letöltése Hevy Pro API-kulccsal. A kulcs csak ehhez az importhoz kell, nem mentjük el.', diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.js index 71057e8..5b3c368 100644 --- a/frontend/src/locales/it.js +++ b/frontend/src/locales/it.js @@ -321,6 +321,8 @@ export default { 'Rest timer': 'Timer di riposo', 'Sounds': 'Suoni', 'Flash screen when timer ends': 'Fai lampeggiare lo schermo alla fine del timer', + 'Play sounds when the phone is on silent': 'Riproduci i suoni anche con il telefono in silenzioso', + 'Music playing on this phone stops during a workout and does not resume by itself.': 'La musica in riproduzione su questo telefono si ferma durante un allenamento e non riprende da sola.', 'Data': 'Dati', 'Export backup (JSON)': 'Esporta backup (JSON)', 'Import backup': 'Importa backup', diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.js index 470861e..b3c18fa 100644 --- a/frontend/src/locales/ko.js +++ b/frontend/src/locales/ko.js @@ -321,6 +321,8 @@ export default { 'Rest timer': '휴식 타이머', 'Sounds': '소리', 'Flash screen when timer ends': '타이머 종료 시 화면 깜박임', + 'Play sounds when the phone is on silent': '무음 모드에서도 소리 재생', + 'Music playing on this phone stops during a workout and does not resume by itself.': '운동 중에는 이 휴대폰에서 재생 중인 음악이 멈추며, 자동으로 다시 재생되지 않습니다.', 'Data': '데이터', 'Export backup (JSON)': '백업 내보내기 (JSON)', 'Import backup': '백업 가져오기', diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.js index e4ebafd..f6cc720 100644 --- a/frontend/src/locales/pl.js +++ b/frontend/src/locales/pl.js @@ -321,6 +321,8 @@ export default { 'Rest timer': 'Minutnik przerwy', 'Sounds': 'Dźwięki', 'Flash screen when timer ends': 'Migaj ekranem po zakończeniu minutnika', + 'Play sounds when the phone is on silent': 'Odtwarzaj dźwięki także przy wyciszonym telefonie', + 'Music playing on this phone stops during a workout and does not resume by itself.': 'Muzyka odtwarzana na tym telefonie zatrzymuje się podczas treningu i nie wznawia się sama.', 'Data': 'Dane', 'Export backup (JSON)': 'Eksportuj kopię (JSON)', 'Import backup': 'Importuj kopię', diff --git a/frontend/src/locales/pt-BR.js b/frontend/src/locales/pt-BR.js index fb03200..541b865 100644 --- a/frontend/src/locales/pt-BR.js +++ b/frontend/src/locales/pt-BR.js @@ -115,6 +115,8 @@ export const PT_BR_OVERRIDES = { 'synced with your profile': 'sincronizado com seu perfil', 'The screen stays on while a workout is running, so you don’t have to unlock your phone between sets.': 'A tela permanece ligada durante o treino, para você não precisar desbloquear o celular entre as séries.', 'Flash screen when timer ends': 'Piscar a tela quando o temporizador terminar', + 'Play sounds when the phone is on silent': 'Tocar sons com o celular no silencioso', + 'Music playing on this phone stops during a workout and does not resume by itself.': 'A música que estiver tocando neste celular para durante o treino e não volta sozinha.', 'Export backup (JSON)': 'Exportar backup (JSON)', 'Import backup': 'Importar backup', 'Reset everything?': 'Redefinir tudo?', diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.js index 82354bb..88285eb 100644 --- a/frontend/src/locales/pt.js +++ b/frontend/src/locales/pt.js @@ -321,6 +321,8 @@ export default { 'Rest timer': 'Temporizador de descanso', 'Sounds': 'Sons', 'Flash screen when timer ends': 'Piscar o ecrã quando o temporizador terminar', + 'Play sounds when the phone is on silent': 'Reproduzir sons com o telemóvel em silêncio', + 'Music playing on this phone stops during a workout and does not resume by itself.': 'A música a tocar neste telemóvel para durante um treino e não retoma sozinha.', 'Data': 'Dados', 'Export backup (JSON)': 'Exportar cópia (JSON)', 'Import backup': 'Importar cópia', diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.js index b442937..20244af 100644 --- a/frontend/src/locales/ru.js +++ b/frontend/src/locales/ru.js @@ -321,6 +321,8 @@ export default { 'Rest timer': 'Таймер отдыха', 'Sounds': 'Звуки', 'Flash screen when timer ends': 'Мигать экраном по окончании таймера', + 'Play sounds when the phone is on silent': 'Воспроизводить звуки при беззвучном режиме', + 'Music playing on this phone stops during a workout and does not resume by itself.': 'Музыка, играющая на этом телефоне, останавливается во время тренировки и сама не возобновляется.', 'Data': 'Данные', 'Export backup (JSON)': 'Экспорт резервной копии (JSON)', 'Import backup': 'Импорт резервной копии', diff --git a/frontend/src/locales/th.js b/frontend/src/locales/th.js index 0419836..96f7a2a 100644 --- a/frontend/src/locales/th.js +++ b/frontend/src/locales/th.js @@ -753,6 +753,8 @@ export default { 'Logged sets stay with the original exercise. The replacement will be inserted afterward.': 'เซ็ตที่บันทึกแล้วจะอยู่กับท่าเดิม ท่าใหม่จะถูกแทรกไว้ถัดไป', 'Rest after each set of this exercise. Leave at 0 to use your default rest timer.': 'พักหลังแต่ละเซ็ตของท่านี้ ปล่อยไว้ที่ 0 เพื่อใช้ตัวจับเวลาพักค่าเริ่มต้น', 'Flash screen when timer ends': 'กะพริบหน้าจอเมื่อหมดเวลา', + 'Play sounds when the phone is on silent': 'เล่นเสียงแม้โทรศัพท์อยู่ในโหมดเงียบ', + 'Music playing on this phone stops during a workout and does not resume by itself.': 'เพลงที่เล่นอยู่บนโทรศัพท์นี้จะหยุดระหว่างการออกกำลังกาย และจะไม่เล่นต่อเอง', 'Import from Hevy': 'นำเข้าจาก Hevy', 'Pull your history with a Hevy Pro API key': 'ดึงประวัติด้วยคีย์ API ของ Hevy Pro', 'Pull your history with a Hevy Pro API key. The key is only used for this import and is not saved.': 'ดึงประวัติด้วยคีย์ API ของ Hevy Pro คีย์ใช้สำหรับการนำเข้าครั้งนี้เท่านั้นและจะไม่ถูกบันทึก', diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.js index bdb5211..7f72d8a 100644 --- a/frontend/src/locales/tr.js +++ b/frontend/src/locales/tr.js @@ -321,6 +321,8 @@ export default { 'Rest timer': 'Dinlenme sayacı', 'Sounds': 'Sesler', 'Flash screen when timer ends': 'Zamanlayıcı bitince ekranı yanıp söndür', + 'Play sounds when the phone is on silent': 'Telefon sessizdeyken de sesleri çal', + 'Music playing on this phone stops during a workout and does not resume by itself.': 'Bu telefonda çalan müzik antrenman sırasında durur ve kendiliğinden devam etmez.', 'Data': 'Veriler', 'Export backup (JSON)': 'Yedeği dışa aktar (JSON)', 'Import backup': 'Yedeği içe aktar', diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.js index d2cc00a..1295ae8 100644 --- a/frontend/src/locales/zh.js +++ b/frontend/src/locales/zh.js @@ -321,6 +321,8 @@ export default { 'Rest timer': '休息计时', 'Sounds': '声音', 'Flash screen when timer ends': '计时结束时闪烁屏幕', + 'Play sounds when the phone is on silent': '手机静音时也播放提示音', + 'Music playing on this phone stops during a workout and does not resume by itself.': '锻炼期间,这部手机正在播放的音乐会停止,且不会自动恢复。', 'Data': '数据', 'Export backup (JSON)': '导出备份(JSON)', 'Import backup': '导入备份', diff --git a/frontend/src/store/useStore.js b/frontend/src/store/useStore.js index 18e6cc3..4fcea75 100644 --- a/frontend/src/store/useStore.js +++ b/frontend/src/store/useStore.js @@ -21,7 +21,7 @@ const SYNC_KEY = 'gym_sync' const CHECK_MIN_MS = 3000 // rev checks closer together than this are the same event (focus + visibility) const POLL_MS = 30000 // while the app is open and signed in, ask the server for its revision this often export const DEF = { - unit: 'kg', restSec: 90, restPauseSec: 15, sound: true, timerFlash: false, keepAwake: true, lang: 'en', + unit: 'kg', restSec: 90, restPauseSec: 15, sound: true, soundOnSilent: false, timerFlash: false, 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 3b931a4..ce9cf10 100644 --- a/frontend/src/views/Settings.jsx +++ b/frontend/src/views/Settings.jsx @@ -6,6 +6,7 @@ import { convertStateUnit } from '../lib/units.js' import { useUI } from '../store/useUI.js' import { ACCENTS, todayISO, localTZ, weekStartOf, MONDAY, SUNDAY } from '../lib/format.js' import { effortOf } from '../lib/history.js' +import { unlock, playOnSilentSupported } from '../lib/sound.js' import { api, webauthnOK, passkeyLogin, passkeyRegister, IS_ANDROID } from '../lib/api.js' import { pushSupported, enablePush, disablePush, sendTestPush, syncPushSubscription } from '../lib/push.js' import { wakeLockSupported } from '../lib/wakelock.js' @@ -301,8 +302,19 @@ export default function Settings() { onChange={v => update(s => { s.gifSize = v })} /> - update(s => { s.sound = v })} /> + {/* Turning Sounds on is a tap: unlock the audio context now so a timer that ends before + the next set check can already sound (iOS, #152). */} + { if (v) unlock(true); update(s => { s.sound = v }) }} /> + {/* iOS only (WebKit's audio-session API, iOS 17+): with it off the ring/silent switch mutes + the timer. On, the phone treats the timer like a music player — exclusive, and the + music app is not told it may resume — so it is a choice, off by default (lib/sound.js). */} + {S.sound && playOnSilentSupported() && ( + + update(s => { s.soundOnSilent = v })} /> + + )} update(s => { s.timerFlash = v })} /> diff --git a/frontend/src/views/Settings.sound.test.jsx b/frontend/src/views/Settings.sound.test.jsx new file mode 100644 index 0000000..10feccb --- /dev/null +++ b/frontend/src/views/Settings.sound.test.jsx @@ -0,0 +1,132 @@ +// @vitest-environment happy-dom +import React, { act } from 'react' +import { createRoot } from 'react-dom/client' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import Settings from './Settings.jsx' +import { unlock } from '../lib/sound.js' + +globalThis.IS_REACT_ACT_ENVIRONMENT = true + +const mocks = vi.hoisted(() => { + const state = { S: null } + state.snapshot = () => ({ + S: state.S, + user: null, + update: mut => { + const next = structuredClone(state.S) + mut(next) + state.S = next + }, + replaceState: vi.fn(), setUser: vi.fn(), pullState: vi.fn(), pushState: vi.fn(), + signOut: vi.fn(), signOutAll: vi.fn(), resetDemo: vi.fn(), disconnectServer: vi.fn(), + }) + return state +}) +vi.mock('../store/useStore.js', () => { + const useStore = selector => selector ? selector(mocks.snapshot()) : mocks.snapshot() + useStore.getState = mocks.snapshot + return { useStore, DEF: { reminder: { time: '17:30' } }, hasData: () => false } +}) +vi.mock('../store/useUI.js', () => { + const snap = () => ({ toast: vi.fn(), openSheet: vi.fn() }) + const useUI = selector => selector ? selector(snap()) : snap() + useUI.getState = snap + return { useUI } +}) +vi.mock('react-router-dom', () => ({ useNavigate: () => () => {} })) +vi.mock('../lib/api.js', () => ({ + api: vi.fn(), webauthnOK: () => false, passkeyLogin: vi.fn(), passkeyRegister: vi.fn(), IS_ANDROID: false, +})) +vi.mock('../lib/push.js', () => ({ pushSupported: () => false, enablePush: vi.fn(), disablePush: vi.fn(), sendTestPush: vi.fn() })) +vi.mock('../lib/wakelock.js', () => ({ wakeLockSupported: () => false })) +vi.mock('../lib/mobile.js', () => ({ MOBILE: false, isAndroid: () => Promise.resolve(false), shareExport: vi.fn(), syncReminder: vi.fn() })) +vi.mock('./MobileOnboarding.jsx', () => ({ ConnectSheet: () => null })) +vi.mock('../sheets.jsx', () => ({ + starterPlanSheet: vi.fn(), confirmSheet: vi.fn(), importFromApp: vi.fn(), + importFromHevy: vi.fn(), equipmentProfileSheet: vi.fn(), +})) +// The real module decides "supported" from navigator.audioSession, which each test sets up; +// unlock is spied on so the Sounds switch can be checked for its tap-time side effect. +vi.mock('../lib/sound.js', async importOriginal => { + const real = await importOriginal() + return { ...real, unlock: vi.fn() } +}) + +globalThis.__APP_VERSION__ ??= 'test' + +let host, root +const setAudioSession = value => Object.defineProperty(navigator, 'audioSession', { value, configurable: true, writable: true }) +beforeEach(() => { + mocks.S = { + unit: 'kg', restSec: 90, restPauseSec: 15, sound: true, soundOnSilent: false, effort: 'none', + gifSize: 'full', workouts: [], routines: [], exWeights: {}, + } + setAudioSession({ type: 'auto' }) + Object.defineProperty(navigator, 'userAgent', { value: 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148', configurable: true }) + unlock.mockClear() + host = document.createElement('div') + document.body.appendChild(host) + root = createRoot(host) +}) +afterEach(() => { + act(() => root.unmount()) + host.remove() + setAudioSession(undefined) +}) + +const mount = () => act(() => root.render()) +const rowTitled = title => [...host.querySelectorAll('.lrow')].find(r => r.querySelector('.lrow-t')?.textContent === title) +const switchIn = row => row.querySelector('[role="switch"]') || row.querySelector('input[type="checkbox"]') || row.querySelector('button') + +describe('Settings — play sounds when the phone is on silent', () => { + it('is offered on a browser with an audio session (iOS), under Sounds, with the music trade-off spelled out', () => { + mount() + const row = rowTitled('Play sounds when the phone is on silent') + expect(row).toBeTruthy() + expect(row.querySelector('.lrow-s').textContent).toBe('Music playing on this phone stops during a workout and does not resume by itself.') + const rows = [...host.querySelectorAll('.lrow')] + expect(rows.indexOf(row)).toBe(rows.indexOf(rowTitled('Sounds')) + 1) + }) + + it('is not offered where the browser has no audio session API', () => { + setAudioSession(undefined) + mount() + expect(rowTitled('Play sounds when the phone is on silent')).toBeUndefined() + }) + + it('is not offered on macOS Safari, which has the API but no ring/silent switch', () => { + Object.defineProperty(navigator, 'userAgent', { value: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Safari/605.1.15', configurable: true }) + Object.defineProperty(navigator, 'maxTouchPoints', { value: 0, configurable: true }) + mount() + expect(rowTitled('Play sounds when the phone is on silent')).toBeUndefined() + }) + + it('is not offered while Sounds is off', () => { + mocks.S.sound = false + mount() + expect(rowTitled('Play sounds when the phone is on silent')).toBeUndefined() + }) + + it('writes soundOnSilent to the store', () => { + mount() + const sw = switchIn(rowTitled('Play sounds when the phone is on silent')) + expect(sw).toBeTruthy() + act(() => { sw.click() }) + expect(mocks.S.soundOnSilent).toBe(true) + }) +}) + +describe('Settings — Sounds switch unlocks audio from the tap', () => { + it('turning Sounds on unlocks; turning it off does not', () => { + mocks.S.sound = false + mount() + act(() => { switchIn(rowTitled('Sounds')).click() }) + expect(mocks.S.sound).toBe(true) + expect(unlock).toHaveBeenCalledWith(true) + unlock.mockClear() + mount() + act(() => { switchIn(rowTitled('Sounds')).click() }) + expect(mocks.S.sound).toBe(false) + expect(unlock).not.toHaveBeenCalled() + }) +}) diff --git a/frontend/src/views/Workout.jsx b/frontend/src/views/Workout.jsx index 3e8c870..fbb0c1f 100644 --- a/frontend/src/views/Workout.jsx +++ b/frontend/src/views/Workout.jsx @@ -7,7 +7,7 @@ import { exOr } from '../lib/exercises.js' import { usesBar, barWeightFor, plateSplit } from '../lib/bar.js' import { effectiveRoutines, effectiveRoutineIds, lastEntryFor, bestWeightFor, bestWeightForEntry, buildSets, freestyleConfig, defaultConfig, setsDoneActive, setUnitsTotal, supersetUnits, unitOf, setLabel, modeOf, isBw, isPerSide, repStep, EFFORT, effortOf, stepEffort, capEffort, cascadeWeight, insertWarmupRow, removeRowAt, pairAdjacent, unpairSuperset, cleanupSg, applyIntensifierPlan, pinnedNoteFor, exNoteFor } from '../lib/history.js' import { fmtNum, capWords, fmtDate, todayISO, exCount, DAYN } from '../lib/format.js' -import { beep, vibrate } from '../lib/sound.js' +import { beep, vibrate, unlock } from '../lib/sound.js' import { t, exerciseNameFor } from '../lib/i18n.js' import { api } from '../lib/api.js' import { insertionIndexAfterCurrentUnit, nextUnfinishedUnit, setProgressHighWater, supersetFlowStep, restAfterSet, restOnRecheck, restSecFor } from '../lib/supersetFlow.js' @@ -802,6 +802,9 @@ function ActiveWorkout() { // behave exactly as they do for a reps set. const startTimed = (idx, i) => { const e = A.entries[idx] + // This tap may be the only one before the hold's countdown beeps (a timed first exercise): + // get the audio context running while it still counts as a gesture (iOS, #152). + unlock(S.sound) useUI.getState().startWork(e.sets[i].sec || 45, exerciseNameFor(exOr(e.id)), elapsed => { mutEntry(idx, en => { en.sets[i].sec = elapsed }) if (!useStore.getState().S.active.entries[idx].sets[i].done) toggle(idx, i) diff --git a/frontend/src/views/Workout.remove.test.jsx b/frontend/src/views/Workout.remove.test.jsx index aa6666e..ea0097d 100644 --- a/frontend/src/views/Workout.remove.test.jsx +++ b/frontend/src/views/Workout.remove.test.jsx @@ -8,7 +8,7 @@ import { DEF, useStore } from '../store/useStore.js' import { useUI } from '../store/useUI.js' import { LANGS } from '../lib/i18n-core.js' -vi.mock('../lib/sound.js', () => ({ beep: vi.fn(), vibrate: vi.fn() })) +vi.mock('../lib/sound.js', () => ({ beep: vi.fn(), vibrate: vi.fn(), unlock: vi.fn() })) vi.mock('../lib/api.js', () => ({ api: vi.fn(() => Promise.resolve({})) })) globalThis.IS_REACT_ACT_ENVIRONMENT = true