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 42c1854..f692c60 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(642) + expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(644) expect(inherited).toHaveLength(647) // If this fails, review the changed keys and wording before accepting a new hash. From // frontend/: node scripts/pt-br-inheritance-fingerprint.mjs --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 8c159df..fad9cba 100644 --- a/frontend/src/locales/de.js +++ b/frontend/src/locales/de.js @@ -339,6 +339,8 @@ export default { 'Weigh in before workouts': 'Vor dem Training wiegen', 'Asks for your body weight when a workout starts. Off starts the session straight away.': 'Fragt beim Start eines Trainings nach deinem Körpergewicht. Aus startet die Einheit direkt.', 'No entries yet — log your weight to start the curve.': 'Noch keine Einträge — trag dein Gewicht ein, um die Kurve zu starten.', + '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 916ce4c..68e2144 100644 --- a/frontend/src/locales/es.js +++ b/frontend/src/locales/es.js @@ -324,6 +324,8 @@ export default { 'Weigh in before workouts': 'Pesarse antes de entrenar', 'Asks for your body weight when a workout starts. Off starts the session straight away.': 'Pide tu peso corporal al empezar un entrenamiento. Desactivado, la sesión empieza directamente.', 'No entries yet — log your weight to start the curve.': 'Sin registros aún — apunta tu peso para empezar la curva.', + '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 c9443b4..ff4b17c 100644 --- a/frontend/src/locales/fr.js +++ b/frontend/src/locales/fr.js @@ -324,6 +324,8 @@ export default { 'Weigh in before workouts': 'Se peser avant la séance', 'Asks for your body weight when a workout starts. Off starts the session straight away.': 'Demande ton poids au début d’une séance. Désactivé, la séance démarre directement.', 'No entries yet — log your weight to start the curve.': 'Aucune entrée — note ton poids pour démarrer la courbe.', + '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 2dd2d05..da466b3 100644 --- a/frontend/src/locales/hi.js +++ b/frontend/src/locales/hi.js @@ -324,6 +324,8 @@ export default { 'Weigh in before workouts': 'वर्कआउट से पहले वज़न दर्ज करना', 'Asks for your body weight when a workout starts. Off starts the session straight away.': 'वर्कआउट शुरू होते समय आपका वज़न पूछता है। बंद होने पर सेशन सीधे शुरू होता है।', 'No entries yet — log your weight to start the curve.': 'अभी कोई एंट्री नहीं — ग्राफ़ शुरू करने के लिए वज़न दर्ज करें।', + '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 54b3138..f99fa4f 100644 --- a/frontend/src/locales/hu.js +++ b/frontend/src/locales/hu.js @@ -748,6 +748,8 @@ export default { 'Weigh in before workouts': 'Súlymérés edzés előtt', 'Asks for your body weight when a workout starts. Off starts the session straight away.': 'Edzés indításakor rákérdez a testsúlyodra. Kikapcsolva az edzés azonnal indul.', 'No entries yet — log your weight to start the curve.': 'Még nincs bejegyzés — rögzítsd a súlyodat a görbe elindításához.', + '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 ffe810a..3c8c841 100644 --- a/frontend/src/locales/it.js +++ b/frontend/src/locales/it.js @@ -324,6 +324,8 @@ export default { 'Weigh in before workouts': 'Pesarsi prima dell’allenamento', 'Asks for your body weight when a workout starts. Off starts the session straight away.': 'Chiede il tuo peso all’avvio di un allenamento. Disattivato, la sessione parte subito.', 'No entries yet — log your weight to start the curve.': 'Nessun dato — registra il tuo peso per iniziare la curva.', + '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 1a32294..48ea492 100644 --- a/frontend/src/locales/ko.js +++ b/frontend/src/locales/ko.js @@ -324,6 +324,8 @@ export default { 'Weigh in before workouts': '운동 전 체중 기록', 'Asks for your body weight when a workout starts. Off starts the session straight away.': '운동을 시작할 때 체중을 물어봅니다. 끄면 세션이 바로 시작됩니다.', 'No entries yet — log your weight to start the curve.': '아직 기록이 없어요 — 체중을 기록해 그래프를 시작하세요.', + '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 5ab74e1..213baab 100644 --- a/frontend/src/locales/pl.js +++ b/frontend/src/locales/pl.js @@ -324,6 +324,8 @@ export default { 'Weigh in before workouts': 'Ważenie przed treningiem', 'Asks for your body weight when a workout starts. Off starts the session straight away.': 'Pyta o Twoją masę ciała przy rozpoczęciu treningu. Wyłączone — sesja zaczyna się od razu.', 'No entries yet — log your weight to start the curve.': 'Brak wpisów — zapisz wagę, aby zacząć krzywą.', + '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 9f01fc1..324b0f2 100644 --- a/frontend/src/locales/pt-BR.js +++ b/frontend/src/locales/pt-BR.js @@ -118,6 +118,8 @@ export const PT_BR_OVERRIDES = { 'Weigh in before workouts': 'Pesar antes do treino', 'Asks for your body weight when a workout starts. Off starts the session straight away.': 'Pede seu peso ao iniciar um treino. Desligado, a sessão começa na hora.', 'No entries yet — log your weight to start the curve.': 'Ainda não há registros — informe seu peso para começar a curva.', + '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 531d991..ea44d46 100644 --- a/frontend/src/locales/pt.js +++ b/frontend/src/locales/pt.js @@ -324,6 +324,8 @@ export default { 'Weigh in before workouts': 'Pesar antes do treino', 'Asks for your body weight when a workout starts. Off starts the session straight away.': 'Pede o teu peso ao iniciar um treino. Desligado, a sessão começa de imediato.', 'No entries yet — log your weight to start the curve.': 'Ainda sem registos — regista o teu peso para começar a curva.', + '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 1101b26..46ce8ef 100644 --- a/frontend/src/locales/ru.js +++ b/frontend/src/locales/ru.js @@ -324,6 +324,8 @@ export default { 'Weigh in before workouts': 'Взвешивание перед тренировкой', 'Asks for your body weight when a workout starts. Off starts the session straight away.': 'Спрашивает ваш вес при начале тренировки. Выключено — сессия начинается сразу.', 'No entries yet — log your weight to start the curve.': 'Записей пока нет — внеси вес, чтобы начать кривую.', + '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 1bfabe3..f2b372d 100644 --- a/frontend/src/locales/th.js +++ b/frontend/src/locales/th.js @@ -756,6 +756,8 @@ export default { 'Weigh in before workouts': 'ชั่งน้ำหนักก่อนออกกำลังกาย', 'Asks for your body weight when a workout starts. Off starts the session straight away.': 'ถามน้ำหนักตัวเมื่อเริ่มออกกำลังกาย ถ้าปิด เซสชันจะเริ่มทันที', 'No entries yet — log your weight to start the curve.': 'ยังไม่มีข้อมูล — บันทึกน้ำหนักเพื่อเริ่มกราฟ', + '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 f3c09a5..95720d1 100644 --- a/frontend/src/locales/tr.js +++ b/frontend/src/locales/tr.js @@ -324,6 +324,8 @@ export default { 'Weigh in before workouts': 'Antrenman öncesi tartılma', 'Asks for your body weight when a workout starts. Off starts the session straight away.': 'Antrenman başlarken kilonu sorar. Kapalıyken seans hemen başlar.', 'No entries yet — log your weight to start the curve.': 'Henüz kayıt yok — eğriyi başlatmak için kilonu gir.', + '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 eed9cea..f45110e 100644 --- a/frontend/src/locales/zh.js +++ b/frontend/src/locales/zh.js @@ -324,6 +324,8 @@ export default { 'Weigh in before workouts': '训练前称重', 'Asks for your body weight when a workout starts. Off starts the session straight away.': '开始训练时询问体重。关闭后直接进入训练。', 'No entries yet — log your weight to start the curve.': '还没有记录——记录体重以开始曲线。', + '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 8125241..79451df 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 1705f43..1682ba1 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' @@ -307,8 +308,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 2fe5384..8e772d0 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, warmupRestSecFor } from '../lib/supersetFlow.js' @@ -806,6 +806,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 4e0b853..ce50584 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, DERIVED_LOCALES } 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