fix(sound): iOS timer sounds — resume before every tone, unlock from the tap, and a "play on silent" setting (#152)
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.
This commit is contained in:
1 parent
14c454f5c1
commit
6e44e2f793
23 files changed
+459
-9
No files matched your search
@@ -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 })} />
|
||||
</Row>
|
||||
<Row icon="bell" iconTint="var(--pink)" title={t('Sounds')}>
|
||||
<Switch checked={!!S.sound} onChange={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). */}
|
||||
<Switch checked={!!S.sound} onChange={v => { if (v) unlock(true); update(s => { s.sound = v }) }} />
|
||||
</Row>
|
||||
{/* 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() && (
|
||||
<Row icon="bell" iconTint="var(--orange)" title={t('Play sounds when the phone is on silent')}
|
||||
subtitle={t('Music playing on this phone stops during a workout and does not resume by itself.')}>
|
||||
<Switch checked={!!S.soundOnSilent} onChange={v => update(s => { s.soundOnSilent = v })} />
|
||||
</Row>
|
||||
)}
|
||||
<Row icon="sun" iconTint="var(--yellow)" title={t('Flash screen when timer ends')}>
|
||||
<Switch checked={!!S.timerFlash} onChange={v => update(s => { s.timerFlash = v })} />
|
||||
</Row>
|
||||
|
||||
@@ -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(<Settings />))
|
||||
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()
|
||||
})
|
||||
})
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in new issue
Block a user