Skip to content

Open-source gym & body-weight tracker, now in the App Store (iPhone + Apple Watch) and as an Android APK. Plan routines, log workouts, see which muscles are trained, import from Strong/Hevy/FitNotes. Self-host it or use it on the phone alone.

Settings search: offers only rows the page shows, and finds the ones it missed

Duarte Santos892668565c90
diff --git a/frontend/src/index.css b/frontend/src/index.css
index 5747a8bf5..a74f7ceba 100644
--- a/frontend/src/index.css
+++ b/frontend/src/index.css
@@ -1896,7 +1896,7 @@ body.no-tabbar.resting #toast{bottom:calc(100px + var(--sab))}
.sp-version{text-align:center;margin-top:4px;line-height:1.6}
.lrow.dis .lrow-i,.lrow.dis .lrow-t,.lrow.dis .sw{opacity:.45}
/* a row a search result jumped to: a short accent wash that fades out */
-.lrow.sp-flash{animation:spflash 1.8s ease}
+.lrow.sp-flash,.btn.sp-flash{animation:spflash 1.8s ease}
@keyframes spflash{0%,45%{background:var(--acc-soft)}100%{background:transparent}}
.sp-empty{color:var(--label-2);text-align:center;padding:28px 12px;line-height:1.4}
diff --git a/frontend/src/locales/ar.js b/frontend/src/locales/ar.js
index bbf22ed40..b1c52eb38 100644
--- a/frontend/src/locales/ar.js
+++ b/frontend/src/locales/ar.js
@@ -1931,4 +1931,5 @@ export default {
'Order and supersets': 'الترتيب والمجموعات المتتالية',
'Sets, reps, rest, progression': 'المجموعات، التكرارات، الراحة، التقدم',
'This workout': 'هذا التمرين',
+ 'Turn on push notifications first.': 'فعّل الإشعارات الفورية أولًا.',
}
diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.js
index bc354f7b3..f90db2143 100644
--- a/frontend/src/locales/de.js
+++ b/frontend/src/locales/de.js
@@ -1898,4 +1898,5 @@ export default {
'Order and supersets': 'Reihenfolge und Supersätze',
'Sets, reps, rest, progression': 'Sätze, Wdh., Pause, Progression',
'This workout': 'Dieses Training',
+ 'Turn on push notifications first.': 'Schalte zuerst die Push-Benachrichtigungen ein.',
}
diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js
index 2cf092ff0..6a75fda9b 100644
--- a/frontend/src/locales/es.js
+++ b/frontend/src/locales/es.js
@@ -1878,4 +1878,5 @@ export default {
'Order and supersets': 'Orden y superseries',
'Sets, reps, rest, progression': 'Series, reps, descanso, progresión',
'This workout': 'Este entrenamiento',
+ 'Turn on push notifications first.': 'Activa primero las notificaciones push.',
}
diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.js
index 7b4720efe..c4a27fbe6 100644
--- a/frontend/src/locales/fr.js
+++ b/frontend/src/locales/fr.js
@@ -1878,4 +1878,5 @@ export default {
'Order and supersets': 'Ordre et supersets',
'Sets, reps, rest, progression': 'Séries, reps, repos, progression',
'This workout': 'Cette séance',
+ 'Turn on push notifications first.': 'Active d’abord les notifications push.',
}
diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.js
index 8f4992a56..5e8c4e824 100644
--- a/frontend/src/locales/hi.js
+++ b/frontend/src/locales/hi.js
@@ -1878,4 +1878,5 @@ export default {
'Order and supersets': 'क्रम और सुपरसेट',
'Sets, reps, rest, progression': 'सेट, रेप्स, आराम, प्रगति',
'This workout': 'यह वर्कआउट',
+ 'Turn on push notifications first.': 'पहले पुश सूचनाएँ चालू करें।',
}
diff --git a/frontend/src/locales/hu.js b/frontend/src/locales/hu.js
index 67bd4b16c..bfd264737 100644
--- a/frontend/src/locales/hu.js
+++ b/frontend/src/locales/hu.js
@@ -1881,4 +1881,5 @@ export default {
'Order and supersets': 'Sorrend és szupersorozatok',
'Sets, reps, rest, progression': 'Sorozatok, ismétlések, pihenő, progresszió',
'This workout': 'Ez az edzés',
+ 'Turn on push notifications first.': 'Előbb kapcsold be a push-értesítéseket.',
}
diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.js
index 1527045b7..1e4efca03 100644
--- a/frontend/src/locales/it.js
+++ b/frontend/src/locales/it.js
@@ -1878,4 +1878,5 @@ export default {
'Order and supersets': 'Ordine e superset',
'Sets, reps, rest, progression': 'Serie, rip., recupero, progressione',
'This workout': 'Questo allenamento',
+ 'Turn on push notifications first.': 'Attiva prima le notifiche push.',
}
diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.js
index 5938cfc1d..c04c4862d 100644
--- a/frontend/src/locales/ko.js
+++ b/frontend/src/locales/ko.js
@@ -1878,4 +1878,5 @@ export default {
'Order and supersets': '순서와 슈퍼세트',
'Sets, reps, rest, progression': '세트, 반복, 휴식, 진행',
'This workout': '이번 운동',
+ 'Turn on push notifications first.': '먼저 푸시 알림을 켜세요.',
}
diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.js
index 82bdd8034..4ce362634 100644
--- a/frontend/src/locales/pl.js
+++ b/frontend/src/locales/pl.js
@@ -1878,4 +1878,5 @@ export default {
'Order and supersets': 'Kolejność i superserie',
'Sets, reps, rest, progression': 'Serie, powt., przerwa, progresja',
'This workout': 'Ten trening',
+ 'Turn on push notifications first.': 'Najpierw włącz powiadomienia push.',
}
diff --git a/frontend/src/locales/pt-BR.js b/frontend/src/locales/pt-BR.js
index 2ab6540cd..dd954da31 100644
--- a/frontend/src/locales/pt-BR.js
+++ b/frontend/src/locales/pt-BR.js
@@ -1164,6 +1164,7 @@ export const PT_BR_OVERRIDES = {
'Enter the code your other device shows under Settings → Account → Add another device. This device then gets a passkey of its own.': 'Digite o código que seu outro dispositivo mostra em Configurações → Conta → Adicionar outro dispositivo. Este dispositivo passa a ter uma chave de acesso própria.',
'Open Settings → Account → “Pair the mobile app” on the openGym site you’re already signed into, then enter its address and the code shown there.': 'No site openGym em que você já está conectado, abra Configurações → Conta → “Parear o aplicativo”, depois digite o endereço e o código mostrado lá.',
'Open Settings → Account → “Pair the mobile app” on your openGym site in a browser and enter the new code shown there. What this phone kept is merged into your account.': 'No seu site openGym em um navegador, abra Configurações → Conta → “Parear o aplicativo” e digite o novo código mostrado lá. O que este celular manteve é incorporado à sua conta.',
+ 'Turn on push notifications first.': 'Ative primeiro as notificações push.',
}
export default { ...pt, ...PT_BR_OVERRIDES }
diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.js
index ad540651d..6a96d7cd1 100644
--- a/frontend/src/locales/pt.js
+++ b/frontend/src/locales/pt.js
@@ -1878,4 +1878,5 @@ export default {
'Order and supersets': 'Ordem e supersets',
'Sets, reps, rest, progression': 'Séries, reps, descanso, progressão',
'This workout': 'Este treino',
+ 'Turn on push notifications first.': 'Ativa primeiro as notificações push.',
}
diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.js
index ed4bd77a6..4bf85ebb0 100644
--- a/frontend/src/locales/ru.js
+++ b/frontend/src/locales/ru.js
@@ -1882,4 +1882,5 @@ export default {
'Order and supersets': 'Порядок и суперсеты',
'Sets, reps, rest, progression': 'Подходы, повторы, отдых, прогрессия',
'This workout': 'Эта тренировка',
+ 'Turn on push notifications first.': 'Сначала включи push-уведомления.',
}
diff --git a/frontend/src/locales/th.js b/frontend/src/locales/th.js
index 34d02b984..189c0d046 100644
--- a/frontend/src/locales/th.js
+++ b/frontend/src/locales/th.js
@@ -1889,4 +1889,5 @@ export default {
'Order and supersets': 'ลำดับและซูเปอร์เซ็ต',
'Sets, reps, rest, progression': 'เซ็ต ครั้ง เวลาพัก การเพิ่มน้ำหนัก',
'This workout': 'การออกกำลังกายครั้งนี้',
+ 'Turn on push notifications first.': 'เปิดการแจ้งเตือนแบบพุชก่อน',
}
diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.js
index 4db92300b..174fb4819 100644
--- a/frontend/src/locales/tr.js
+++ b/frontend/src/locales/tr.js
@@ -1878,4 +1878,5 @@ export default {
'Order and supersets': 'Sıra ve süper setler',
'Sets, reps, rest, progression': 'Setler, tekrarlar, dinlenme, ilerleme',
'This workout': 'Bu antrenman',
+ 'Turn on push notifications first.': 'Önce anlık bildirimleri aç.',
}
diff --git a/frontend/src/locales/uk.js b/frontend/src/locales/uk.js
index 4fe89a6a1..24d20ede9 100644
--- a/frontend/src/locales/uk.js
+++ b/frontend/src/locales/uk.js
@@ -1875,4 +1875,5 @@ export default {
'Order and supersets': 'Порядок і суперсети',
'Sets, reps, rest, progression': 'Підходи, повтори, відпочинок, прогресія',
'This workout': 'Це тренування',
+ 'Turn on push notifications first.': 'Спершу увімкни push-сповіщення.',
}
diff --git a/frontend/src/locales/zh-TW.js b/frontend/src/locales/zh-TW.js
index 5feb5da76..abb238d94 100644
--- a/frontend/src/locales/zh-TW.js
+++ b/frontend/src/locales/zh-TW.js
@@ -1871,4 +1871,5 @@ export default {
'Order and supersets': '順序與超級組',
'Sets, reps, rest, progression': '組數、次數、休息、漸進',
'This workout': '本次訓練',
+ 'Turn on push notifications first.': '請先開啟推播通知。',
}
diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.js
index dd21cbed3..a52d565ab 100644
--- a/frontend/src/locales/zh.js
+++ b/frontend/src/locales/zh.js
@@ -1878,4 +1878,5 @@ export default {
'Order and supersets': '顺序与超级组',
'Sets, reps, rest, progression': '组数、次数、休息、渐进',
'This workout': '本次训练',
+ 'Turn on push notifications first.': '请先打开推送通知。',
}
diff --git a/frontend/src/views/Settings.jsx b/frontend/src/views/Settings.jsx
index 8638fe490..762b6e438 100644
--- a/frontend/src/views/Settings.jsx
+++ b/frontend/src/views/Settings.jsx
@@ -58,7 +58,7 @@ export function SettingsRoute() {
const ctx = { user: useStore(s => s.user), mobile: MOBILE }
if (page && (!PAGES[page] || !pageVisible(PAGES[page].parent || page, ctx))) return <Navigate to="/settings" replace />
if (page === 'coach') return <Navigate to="/coach/setup" replace />
- return <Settings key={page || 'root'} page={page || null} find={loc.state?.find || null} />
+ return <Settings key={page || 'root'} page={page || null} find={loc.state?.find || null} via={loc.state?.via || null} />
}
// "Mon" / "Sun" in the app's language, for the Plan & schedule row's preview.
@@ -71,7 +71,7 @@ const standalone = () => {
try { return !!(window.matchMedia?.('(display-mode: standalone)').matches || window.navigator.standalone === true) } catch { return false }
}
-export default function Settings({ page = null, find = null }) {
+export default function Settings({ page = null, find = null, via = null }) {
const nav = useNavigate()
const S = useStore(s => s.S)
const user = useStore(s => s.user)
@@ -159,16 +159,36 @@ export default function Settings({ page = null, find = null }) {
isAndroid().then(ok => { setAndroid(ok); if (ok && page === 'about') checkForUpdate().then(setUpdateInfo).catch(() => {}) })
}, [page])
- // A search hit: scroll its row into view and flash it once.
+ // A search hit: scroll its row (or button) into view and flash it once. A row that shows only
+ // once the page has heard back from the server (web push, the passkey list) is waited for a
+ // moment; still missing, the hit's `via` row, if it names one, is flashed instead, with a word
+ // on why.
useEffect(() => {
if (!find || !body.current) return
- const label = t(find)
- const row = [...body.current.querySelectorAll('.lrow')].find(r => r.querySelector('.lrow-t')?.textContent === label)
- if (!row) return
- row.classList.add('sp-flash')
- if (typeof row.scrollIntoView === 'function') row.scrollIntoView({ block: 'center' })
- const tm = setTimeout(() => row.classList.remove('sp-flash'), 1900)
- return () => clearTimeout(tm)
+ const el = body.current
+ const named = label => [...el.querySelectorAll('.lrow')].find(r => r.querySelector('.lrow-t')?.textContent === label)
+ || [...el.querySelectorAll('.btn')].find(b => b.textContent.trim() === label)
+ let tm = null
+ const flash = row => {
+ row.classList.add('sp-flash')
+ if (typeof row.scrollIntoView === 'function') row.scrollIntoView({ block: 'center' })
+ tm = setTimeout(() => row.classList.remove('sp-flash'), 1900)
+ }
+ const row = named(t(find))
+ if (row) { flash(row); return () => clearTimeout(tm) }
+ let done = false
+ const mo = typeof MutationObserver === 'function' ? new MutationObserver(() => {
+ const r = named(t(find))
+ if (r && !done) { done = true; mo.disconnect(); clearTimeout(wait); flash(r) }
+ }) : null
+ mo?.observe(el, { childList: true, subtree: true })
+ const wait = setTimeout(() => {
+ if (done) return
+ done = true; mo?.disconnect()
+ const r = via && named(t(via))
+ if (r) { flash(r); toast(t('Turn on push notifications first.')) }
+ }, 1500)
+ return () => { done = true; mo?.disconnect(); clearTimeout(wait); clearTimeout(tm) }
}, [find])
// The same check, on demand: the automatic one is silent when it finds nothing or cannot
@@ -364,6 +384,8 @@ export default function Settings({ page = null, find = null }) {
user, mobile: MOBILE, android, demo: DEMO, wakeOK, hasMedia, pwOn, webauthn: webauthnOK(),
sound: !!S.sound, playOnSilent: playOnSilentSupported(), canVibrate, vibrate: S.vibrate !== false,
profiles: (S.equipProfiles || []).length > 0, nameLang: EXERCISE_NAME_LANGS.includes(baseLang(lang)),
+ pushOK: !MOBILE && pushSupported(), reminderOn: !!S.reminder?.on, nudge: !!S.reminder?.nudge,
+ autoBackup: !!S.autoBackup, synced: !!sync, installTip: !MOBILE && !standalone(), androidWeb: IS_ANDROID,
}
const mode = scheduleModeOf(S)
const layout = ['list', 'compact'].includes(S.workoutView) ? S.workoutView : 'cards'
@@ -838,7 +860,7 @@ export default function Settings({ page = null, find = null }) {
return <SettingsRoot ctx={ctx} preview={preview} open={open} user={user} sync={sync}
home={() => nav('/home')} go={(hit) => {
if (hit.page === 'coach') { nav('/coach/setup'); return }
- nav('/settings/' + hit.page, hit.isPage ? undefined : { state: { find: hit.title } })
+ nav('/settings/' + hit.page, hit.isPage ? undefined : { state: hit.via ? { find: hit.title, via: hit.via } : { find: hit.title } })
}} />
}
diff --git a/frontend/src/views/settings-pages.js b/frontend/src/views/settings-pages.js
index b2cf6b4ef..56152b483 100644
--- a/frontend/src/views/settings-pages.js
+++ b/frontend/src/views/settings-pages.js
@@ -39,8 +39,13 @@ export function pageVisible(page, ctx) {
// One entry per row. `kw` is extra words people search for (English; the translated title and
// page name are searched too). `when` repeats the row's own visibility rule, so a search never
-// offers a row the page would not show.
+// offers a row the page would not show. The one rule a search cannot know in advance is whether
+// this browser's push subscription is on (the server is asked when the page opens): those rows
+// name `via`, the row the hit flashes instead when they turn out not to be there.
const signedInWeb = c => !!c.user && !c.mobile && !c.demo
+// The reminder rows: the phone's own notifications, or web push where the browser has it.
+const remind = c => !!c.mobile || !!c.pushOK
+const PUSH = 'Push notifications'
export const SEARCH = [
// Workout
{ page: 'workout', title: 'Rest timer', icon: 'timer', tint: 'var(--orange)', kw: 'rest pause break seconds minutes timer countdown' },
@@ -67,9 +72,12 @@ export const SEARCH = [
{ page: 'alerts', title: 'Vibrate on silent too', icon: 'vibrate', tint: 'var(--indigo)', kw: 'alarm silent vibrate android', when: c => c.mobile && c.android && c.canVibrate && c.vibrate },
{ page: 'alerts', title: 'Flash the screen', icon: 'sun', tint: 'var(--yellow)', kw: 'flash light blink screen' },
// Reminders
- { page: 'reminders', title: 'Push notifications', icon: 'bell', tint: 'var(--red)', kw: 'push notification alerts', when: c => !c.mobile && c.user },
- { page: 'reminders', title: 'Workout day reminder', icon: 'calendar', tint: 'var(--orange)', kw: 'reminder notification remind' },
- { page: 'reminders', title: 'Nudge me when I skip a planned workout', icon: 'bell', tint: 'var(--red)', kw: 'nudge skip missed motivation' },
+ { page: 'reminders', title: PUSH, icon: 'bell', tint: 'var(--red)', kw: 'push notification alerts', when: c => !c.mobile && !!c.user && c.pushOK },
+ { page: 'reminders', title: 'Workout day reminder', icon: 'calendar', tint: 'var(--orange)', kw: 'reminder notification remind', when: remind, via: PUSH },
+ { page: 'reminders', title: 'Reminder time', icon: 'clock', tint: 'var(--purple)', kw: 'reminder time clock hour when', when: c => remind(c) && c.reminderOn, via: PUSH },
+ { page: 'reminders', title: 'Nudge me when I skip a planned workout', icon: 'bell', tint: 'var(--red)', kw: 'nudge skip missed motivation', when: c => remind(c) && c.reminderOn, via: PUSH },
+ { page: 'reminders', title: 'Nudge tone', icon: 'chat', tint: 'var(--blue)', kw: 'nudge tone friendly guilt drill sergeant', when: c => remind(c) && c.reminderOn && c.nudge, via: PUSH },
+ { page: 'reminders', title: 'Send test notification', icon: 'bell', tint: 'var(--red)', kw: 'test push notification try', when: c => !c.mobile && c.pushOK, via: PUSH },
// Plan & schedule
{ page: 'plan', title: 'How you train', icon: 'repeat', tint: 'var(--orange)', kw: 'scheduling schedule rotation fixed week split' },
{ page: 'plan', title: 'Week starts on', icon: 'calendar', tint: 'var(--orange)', kw: 'monday sunday first day week' },
@@ -97,6 +105,7 @@ export const SEARCH = [
{ page: 'data', title: 'Export backup (JSON)', icon: 'share', tint: 'var(--blue)', kw: 'export backup json download save' },
{ page: 'data', title: 'Export with photos & videos (.zip)', icon: 'share', tint: 'var(--blue)', kw: 'zip media export backup', when: c => c.hasMedia },
{ page: 'data', title: 'Auto-backup on changes', icon: 'folder', tint: 'var(--blue)', kw: 'auto backup automatic', when: c => c.mobile },
+ { page: 'data', title: 'Backup folder', icon: 'folder', tint: 'var(--blue)', kw: 'auto backup folder location directory', when: c => c.mobile && c.android && c.autoBackup },
{ page: 'data', title: 'Import backup', icon: 'download', tint: 'var(--teal)', kw: 'import restore backup json zip' },
{ page: 'data', title: 'Import from another app', icon: 'download', tint: 'var(--teal)', kw: 'strong hevy fitnotes apple health csv import' },
{ page: 'data', title: 'Import from Hevy', icon: 'key', tint: 'var(--teal)', kw: 'hevy api import' },
@@ -106,7 +115,10 @@ export const SEARCH = [
{ page: 'about', title: 'Check for updates', icon: 'download', tint: 'var(--green)', kw: 'update apk android version', when: c => c.mobile && c.android },
{ page: 'about', title: 'Get the Android app', icon: 'download', tint: 'var(--green)', kw: 'apk android download app', when: c => !c.mobile },
{ page: 'about', title: 'Version', icon: 'info', tint: 'var(--grey)', kw: 'version about licence license source code open source' },
+ { page: 'about', title: 'In Chrome: ⋮ menu → Add to Home screen', icon: 'share', tint: 'var(--blue)', kw: 'install app home screen tip pwa', when: c => c.installTip && c.androidWeb },
+ { page: 'about', title: 'In Safari: Share → Add to Home Screen', icon: 'share', tint: 'var(--blue)', kw: 'install app home screen tip pwa', when: c => c.installTip && !c.androidWeb },
// Account
+ { page: 'account', title: 'Sync now', icon: 'reset', tint: 'var(--acc)', kw: 'server sync upload refresh status connection', when: c => !!c.user && !c.demo && c.synced },
{ page: 'account', title: 'Passkeys', icon: 'fingerprint', tint: 'var(--acc)', kw: 'passkey security login', when: signedInWeb },
{ page: 'account', title: 'Add another device', icon: 'qr', tint: 'var(--blue)', kw: 'device link code phone computer', when: signedInWeb },
{ page: 'account', title: 'Pair the mobile app', icon: 'qr', tint: 'var(--blue)', kw: 'pair phone app android iphone', when: signedInWeb },
diff --git a/frontend/src/views/settings-pages.test.jsx b/frontend/src/views/settings-pages.test.jsx
index 5aa249489..d0c2d7fd9 100644
--- a/frontend/src/views/settings-pages.test.jsx
+++ b/frontend/src/views/settings-pages.test.jsx
@@ -9,9 +9,9 @@ import { PAGES, PAGE_IDS, ROOT_GROUPS, SEARCH, pageVisible, searchSettings, page
globalThis.IS_REACT_ACT_ENVIRONMENT = true
const mocks = vi.hoisted(() => {
- const state = { S: null, user: null, MOBILE: false, sheets: [], navs: [] }
+ const state = { S: null, user: null, sync: null, MOBILE: false, push: false, sheets: [], navs: [], toast: null }
state.snapshot = () => ({
- S: state.S, user: state.user, coachLocal: null, sync: null, config: null,
+ S: state.S, user: state.user, coachLocal: null, sync: state.sync, config: 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(), setUnit: vi.fn(),
resetEverything: vi.fn(), resetDemo: vi.fn(), importBackup: vi.fn(), importConflict: vi.fn(),
@@ -24,14 +24,14 @@ vi.mock('../store/useStore.js', () => {
return { useStore, DEF: { reminder: { time: '17:30' } }, hasData: () => false }
})
vi.mock('../store/useUI.js', () => {
- const snap = () => ({ toast: vi.fn(), openSheet: render => { mocks.sheets.push(render); return { close: vi.fn() } } })
+ const snap = () => ({ toast: mocks.toast, openSheet: render => { mocks.sheets.push(render); return { close: vi.fn() } } })
const useUI = selector => selector ? selector(snap()) : snap()
useUI.getState = snap
return { useUI }
})
vi.mock('react-router-dom', () => ({ useNavigate: () => (...a) => mocks.navs.push(a) }))
-vi.mock('../lib/api.js', () => ({ api: vi.fn(() => Promise.resolve({})), 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(), syncPushSubscription: vi.fn() }))
+vi.mock('../lib/api.js', () => ({ api: vi.fn(path => Promise.resolve(path === '/api/account/passkeys' ? { passkeys: [] } : {})), webauthnOK: () => false, passkeyLogin: vi.fn(), passkeyRegister: vi.fn(), IS_ANDROID: false }))
+vi.mock('../lib/push.js', () => ({ pushSupported: () => mocks.push, enablePush: vi.fn(), disablePush: vi.fn(), sendTestPush: vi.fn(), syncPushSubscription: vi.fn(() => Promise.resolve(mocks.pushOn)) }))
vi.mock('../lib/wakelock.js', () => ({ wakeLockSupported: () => true }))
vi.mock('../lib/mobile.js', () => ({ get MOBILE() { return mocks.MOBILE }, isAndroid: () => Promise.resolve(false), shareExport: vi.fn(), shareExportBlob: vi.fn(), syncReminder: vi.fn() }))
vi.mock('./MobileOnboarding.jsx', () => ({ ConnectSheet: () => null }))
@@ -52,7 +52,11 @@ beforeEach(() => {
reminder: { on: false, time: '17:30' },
}
mocks.user = null
+ mocks.sync = null
mocks.MOBILE = false
+ mocks.push = false
+ mocks.pushOn = false
+ mocks.toast = vi.fn()
mocks.sheets = []
mocks.navs = []
Object.defineProperty(navigator, 'vibrate', { value: () => true, configurable: true, writable: true })
@@ -66,7 +70,7 @@ afterEach(() => {
delete navigator.vibrate
})
-const mount = (page = null, find = null) => act(() => root.render(<Settings page={page} find={find} />))
+const mount = (page = null, find = null, via = null) => act(() => root.render(<Settings page={page} find={find} via={via} />))
const rowTitled = title => [...host.querySelectorAll('.lrow')].find(r => r.querySelector('.lrow-t')?.textContent === title)
const titles = () => [...host.querySelectorAll('.lrow .lrow-t')].map(e => e.textContent)
@@ -74,6 +78,7 @@ const titles = () => [...host.querySelectorAll('.lrow .lrow-t')].map(e => e.text
const guestWeb = {
user: null, mobile: false, android: false, demo: false, wakeOK: true, hasMedia: false, pwOn: false, webauthn: false,
sound: true, playOnSilent: false, canVibrate: true, vibrate: true, profiles: true, nameLang: false,
+ pushOK: false, reminderOn: false, nudge: false, autoBackup: false, synced: false, installTip: true, androidWeb: false,
}
describe('the root', () => {
@@ -142,6 +147,74 @@ describe('the root', () => {
})
})
+// Each search hit is a row on its page, on the device and profile it was offered for. The ctx is
+// the one Settings builds (views/Settings.jsx) for the same mocks; push-dependent web rows are
+// the exception the page settles on open (`via`), tested on their own below.
+describe('the search lands on a row', () => {
+ const scenarios = {
+ 'guest in a browser': () => {},
+ 'signed in, browser without push': () => { mocks.user = { id: 'u1', name: 'Dana' }; mocks.sync = { status: 'ok', server: 'https://gym.example' } },
+ 'phone, reminder off': () => { mocks.MOBILE = true },
+ 'phone, reminder and nudge on': () => { mocks.MOBILE = true; mocks.S.reminder = { on: true, time: '17:30', nudge: true }; mocks.S.autoBackup = true },
+ 'phone paired with a server': () => { mocks.MOBILE = true; mocks.user = { id: 'u1', name: 'Dana' }; mocks.sync = { status: 'ok', server: 'https://gym.example' } },
+ }
+ const ctxNow = () => ({
+ ...guestWeb, user: mocks.user, mobile: mocks.MOBILE, pushOK: !mocks.MOBILE && mocks.push,
+ reminderOn: !!mocks.S.reminder?.on, nudge: !!mocks.S.reminder?.nudge, autoBackup: !!mocks.S.autoBackup,
+ synced: !!mocks.sync, installTip: !mocks.MOBILE, hasMedia: false, wakeOK: true,
+ })
+ for (const [name, setUp] of Object.entries(scenarios)) it(name, async () => {
+ setUp()
+ const ctx = ctxNow()
+ const byPage = {}
+ for (const e of SEARCH) if (pageVisible(PAGES[e.page].parent || e.page, ctx) && (!e.when || e.when(ctx))) (byPage[e.page] ||= []).push(e.title)
+ for (const [page, want] of Object.entries(byPage)) {
+ if (page === 'coach') continue
+ mount(page)
+ await act(async () => {}) // the passkey list, asked of the server on open
+ const have = [...titles(), ...[...host.querySelectorAll('.btn')].map(b => b.textContent.trim())]
+ for (const title of want) expect(have, `${page}: ${title}`).toContain(title)
+ }
+ })
+
+ it('finds the rows that used to be missing', () => {
+ const tr = s => s
+ const web = { ...guestWeb, user: { id: 'u' }, synced: true, pushOK: true, reminderOn: true, nudge: true }
+ expect(searchSettings('reminder time', web, tr).map(h => h.title)).toEqual(['Reminder time'])
+ expect(searchSettings('tone', web, tr).map(h => h.title)).toContain('Nudge tone')
+ expect(searchSettings('test notification', web, tr).map(h => h.title)).toEqual(['Send test notification'])
+ expect(searchSettings('server', web, tr).map(h => h.title)).toContain('Sync now')
+ expect(searchSettings('sync', web, tr).map(h => h.title)).toContain('Sync now')
+ expect(searchSettings('home screen', web, tr).map(h => h.title)).toEqual(['In Safari: Share → Add to Home Screen'])
+ expect(searchSettings('install', { ...web, androidWeb: true }, tr).map(h => h.title)).toEqual(['In Chrome: ⋮ menu → Add to Home screen'])
+ expect(searchSettings('backup folder', { ...guestWeb, mobile: true, android: true, autoBackup: true }, tr).map(h => h.title)).toEqual(['Backup folder'])
+ expect(searchSettings('backup folder', { ...guestWeb, mobile: true, android: true }, tr)).toEqual([])
+ })
+
+ it('a web reminder row waits for push to answer, and flashes Push notifications when it stays off', async () => {
+ vi.useFakeTimers()
+ try {
+ mocks.user = { id: 'u1', name: 'Dana' }
+ mocks.push = true
+ mocks.S.reminder = { on: true, time: '17:30' }
+ mount('reminders', 'Nudge me when I skip a planned workout', 'Push notifications')
+ await act(async () => { await vi.advanceTimersByTimeAsync(1600) })
+ expect(rowTitled('Push notifications').classList.contains('sp-flash')).toBe(true)
+ expect(mocks.toast).toHaveBeenCalledWith('Turn on push notifications first.')
+
+ // push on: the row appears once the server answers, and that row is the one flashed
+ mocks.pushOn = true
+ mocks.toast.mockClear()
+ act(() => root.render(null))
+ mount('reminders', 'Nudge me when I skip a planned workout', 'Push notifications')
+ await act(async () => { await vi.advanceTimersByTimeAsync(50) })
+ expect(rowTitled('Nudge me when I skip a planned workout').classList.contains('sp-flash')).toBe(true)
+ await act(async () => { await vi.advanceTimersByTimeAsync(1600) })
+ expect(mocks.toast).not.toHaveBeenCalled()
+ } finally { vi.useRealTimers() }
+ })
+})
+
describe('the search query', () => {
const type = v => act(() => {
const input = host.querySelector('.sp-search input')
@@ -276,7 +349,10 @@ describe('searchSettings', () => {
expect(pageTrail('advanced', tr)).toBe('Workout › Fine-tuning')
expect(searchSettings('overtime', guestWeb, tr)[0].trail).toBe('Workout › Fine-tuning')
expect(searchSettings('nudge', guestWeb, tr)).toEqual([]) // no Reminders for a web guest
- expect(searchSettings('nudge', { ...guestWeb, user: { id: 'u' } }, tr).map(h => h.title)).toEqual(['Nudge me when I skip a planned workout'])
+ expect(searchSettings('nudge', { ...guestWeb, user: { id: 'u' } }, tr)).toEqual([]) // no push in this browser
+ expect(searchSettings('nudge', { ...guestWeb, user: { id: 'u' }, pushOK: true }, tr)).toEqual([]) // the reminder is off
+ expect(searchSettings('nudge', { ...guestWeb, user: { id: 'u' }, pushOK: true, reminderOn: true }, tr).map(h => h.title)).toEqual(['Nudge me when I skip a planned workout'])
+ expect(searchSettings('nudge', { ...guestWeb, mobile: true, reminderOn: true }, tr).map(h => h.title)).toEqual(['Nudge me when I skip a planned workout'])
expect(searchSettings('coach', guestWeb, tr)).toEqual([])
expect(searchSettings('coach', { ...guestWeb, mobile: true }, tr)[0].page).toBe('coach')
expect(searchSettings('vibrate silent', { ...guestWeb, mobile: true, android: true }, tr).map(h => h.title)).toEqual(['Vibrate on silent too'])