Standalone mobile app: Capacitor shells for iOS and Android

A second flavor of openGym (VITE_MOBILE=1) that runs entirely on the
phone: no account, no server, no sync. State is mirrored into a file in
the app's private storage (survives WebView storage eviction), the
workout-day reminder is a native local notification scheduled on planned
weekdays, and backups export through the OS share sheet. Exercise media
loads from the same CDN as the demo build. npm run build:mobile, then
Android Studio / Xcode — see docs/MOBILE.md. NOTICE.md gains an AGPL §7
app-store exception.
This commit is contained in:
Duarte Santos committed 2026-07-23 15:14:36 +02:00
1 parent 389315625c
commit ee2be743b0
92 files changed
+3117 -29

No files matched your search

+68
View File
@@ -0,0 +1,68 @@
// Mobile build (VITE_MOBILE=1) — the standalone app-store version (Capacitor native shell).
//
// There is no backend: nothing to sign in to, everything lives on the phone. Unlike guest
// mode in a browser, this is the user's only copy of their training log, so it can't depend
// on WebView localStorage alone (iOS evicts that under storage pressure). Every persist()
// therefore also lands in a JSON file in the app's private data directory, and boot()
// restores from it. The workout reminder uses native local notifications scheduled per
// planned weekday — no server involved, unlike Web Push in the self-hosted version.
//
// Like the demo build, MOBILE is replaced at build time, so all of this folds away in
// web bundles; the Capacitor plugins are only ever imported behind it.
import { t } from './i18n.js'
export const MOBILE = import.meta.env.VITE_MOBILE === '1'
const FILE = 'opengym-state.json'
export async function nativeLoad() {
try {
const { Filesystem, Directory, Encoding } = await import('@capacitor/filesystem')
const r = await Filesystem.readFile({ path: FILE, directory: Directory.Data, encoding: Encoding.UTF8 })
return JSON.parse(r.data)
} catch (e) { return null } // first launch, or unreadable — localStorage copy takes over
}
export async function nativeSave(state) {
try {
const { Filesystem, Directory, Encoding } = await import('@capacitor/filesystem')
await Filesystem.writeFile({ path: FILE, directory: Directory.Data, data: JSON.stringify(state), encoding: Encoding.UTF8 })
} catch (e) { /* keep the localStorage copy */ }
}
// (Re)schedule the workout-day reminder: one repeating notification per weekday that has a
// routine in the weekly plan. Cheap enough to run after any state change — the plan or the
// reminder time may just have been edited. `interactive` gates the OS permission prompt to
// the Settings toggle; a background resync never pops a dialog.
export async function syncReminder(S, interactive = false) {
try {
const { LocalNotifications } = await import('@capacitor/local-notifications')
await LocalNotifications.cancel({ notifications: [0, 1, 2, 3, 4, 5, 6].map(d => ({ id: 100 + d })) }).catch(() => {})
const r = S.reminder
if (!r?.on) return true
let perm = await LocalNotifications.checkPermissions()
if (perm.display !== 'granted' && interactive) perm = await LocalNotifications.requestPermissions()
if (perm.display !== 'granted') return false
const [hour, minute] = (r.time || '08:00').split(':').map(Number)
const notifications = Object.entries(S.week || {})
.filter(([, rid]) => rid && (S.routines || []).some(x => x.id === rid))
.map(([day, rid]) => ({
id: 100 + Number(day),
title: t('Workout day'),
body: t('{0} is on the plan today — let’s go!', S.routines.find(x => x.id === rid).name),
// Capacitor weekdays are 1 (Sunday) … 7 (Saturday); S.week uses getDay() 0…6.
schedule: { on: { weekday: Number(day) + 1, hour, minute }, allowWhileIdle: true },
}))
if (notifications.length) await LocalNotifications.schedule({ notifications })
return true
} catch (e) { return false }
}
// WKWebView can't do blob-URL downloads, so the backup goes out through the OS share sheet
// (Files, AirDrop, mail, …) from a temp file instead.
export async function shareExport(json, filename) {
const { Filesystem, Directory, Encoding } = await import('@capacitor/filesystem')
const { Share } = await import('@capacitor/share')
const w = await Filesystem.writeFile({ path: filename, directory: Directory.Cache, data: json, encoding: Encoding.UTF8 })
await Share.share({ title: filename, url: w.uri })
}
+8 -1
View File
@@ -417,5 +417,12 @@ export default {
'Could not read that file': 'Datei konnte nicht gelesen werden',
'That file is empty': 'Diese Datei ist leer',
'That file\'s columns aren\'t recognised — see the docs for supported apps.': 'Die Spalten dieser Datei sind unbekannt — unterstützte Apps stehen in der Doku.',
'Nothing to import from that file': 'Aus dieser Datei gibt es nichts zu importieren'
'Nothing to import from that file': 'Aus dieser Datei gibt es nichts zu importieren',
// --- mobile build ---
'Your data': 'Deine Daten',
'All data stays on this phone': 'Alle Daten bleiben auf diesem Handy',
'No account, no cloud — back it up anytime with Export below.': 'Kein Konto, keine Cloud — sichere sie jederzeit über den Export unten.',
'Reminds you at this time on days that have a routine planned.': 'Erinnert dich zu dieser Zeit an Tagen, für die eine Routine geplant ist.',
'Workout day': 'Trainingstag',
'{0} is on the plan today — let’s go!': '{0} steht heute auf dem Plan — los geht’s!'
}
+8 -1
View File
@@ -399,5 +399,12 @@ export default {
'Could not read that file': 'No se pudo leer ese archivo',
'That file is empty': 'Ese archivo está vacío',
'That file\'s columns aren\'t recognised — see the docs for supported apps.': 'No se reconocen las columnas del archivo — consulta la documentación.',
'Nothing to import from that file': 'No hay nada que importar de ese archivo'
'Nothing to import from that file': 'No hay nada que importar de ese archivo',
// --- mobile build ---
'Your data': 'Tus datos',
'All data stays on this phone': 'Todos los datos se quedan en este teléfono',
'No account, no cloud — back it up anytime with Export below.': 'Sin cuenta ni nube — haz una copia cuando quieras con Exportar, más abajo.',
'Reminds you at this time on days that have a routine planned.': 'Te avisa a esta hora los días que tienen una rutina planificada.',
'Workout day': 'Día de entrenamiento',
'{0} is on the plan today — let’s go!': '¡Hoy toca {0} — vamos!'
}
+8 -1
View File
@@ -399,5 +399,12 @@ export default {
'Could not read that file': 'Impossible de lire ce fichier',
'That file is empty': 'Ce fichier est vide',
'That file\'s columns aren\'t recognised — see the docs for supported apps.': 'Colonnes non reconnues — voir la documentation pour les apps prises en charge.',
'Nothing to import from that file': 'Rien à importer depuis ce fichier'
'Nothing to import from that file': 'Rien à importer depuis ce fichier',
// --- mobile build ---
'Your data': 'Vos données',
'All data stays on this phone': 'Toutes les données restent sur ce téléphone',
'No account, no cloud — back it up anytime with Export below.': 'Pas de compte, pas de cloud — sauvegardez-les à tout moment via Exporter ci-dessous.',
'Reminds you at this time on days that have a routine planned.': 'Vous rappelle à cette heure les jours où une routine est planifiée.',
'Workout day': 'Jour d’entraînement',
'{0} is on the plan today — let’s go!': '{0} est au programme aujourd’hui — allez !'
}
+8 -1
View File
@@ -399,5 +399,12 @@ export default {
'Could not read that file': 'वह फ़ाइल पढ़ी नहीं जा सकी',
'That file is empty': 'वह फ़ाइल खाली है',
'That file\'s columns aren\'t recognised — see the docs for supported apps.': 'फ़ाइल के कॉलम पहचाने नहीं गए — समर्थित ऐप्स के लिए दस्तावेज़ देखें।',
'Nothing to import from that file': 'उस फ़ाइल से आयात करने को कुछ नहीं'
'Nothing to import from that file': 'उस फ़ाइल से आयात करने को कुछ नहीं',
// --- mobile build ---
'Your data': 'आपका डेटा',
'All data stays on this phone': 'सारा डेटा इसी फ़ोन पर रहता है',
'No account, no cloud — back it up anytime with Export below.': 'न खाता, न क्लाउड — नीचे एक्सपोर्ट से कभी भी बैकअप लें।',
'Reminds you at this time on days that have a routine planned.': 'जिन दिनों रूटीन प्लान है, उस समय याद दिलाता है।',
'Workout day': 'वर्कआउट का दिन',
'{0} is on the plan today — let’s go!': 'आज प्लान में {0} है — चलो शुरू करें!'
}
+8 -1
View File
@@ -399,5 +399,12 @@ export default {
'Could not read that file': 'Impossibile leggere il file',
'That file is empty': 'Il file è vuoto',
'That file\'s columns aren\'t recognised — see the docs for supported apps.': 'Colonne non riconosciute — vedi la documentazione per le app supportate.',
'Nothing to import from that file': 'Niente da importare da questo file'
'Nothing to import from that file': 'Niente da importare da questo file',
// --- mobile build ---
'Your data': 'I tuoi dati',
'All data stays on this phone': 'Tutti i dati restano su questo telefono',
'No account, no cloud — back it up anytime with Export below.': 'Niente account, niente cloud — fai un backup quando vuoi con Esporta qui sotto.',
'Reminds you at this time on days that have a routine planned.': 'Ti avvisa a quest’ora nei giorni con una routine pianificata.',
'Workout day': 'Giorno di allenamento',
'{0} is on the plan today — let’s go!': 'Oggi è in programma {0} — forza!'
}
+8 -1
View File
@@ -399,5 +399,12 @@ export default {
'Could not read that file': '파일을 읽을 수 없습니다',
'That file is empty': '파일이 비어 있습니다',
'That file\'s columns aren\'t recognised — see the docs for supported apps.': '열을 인식할 수 없습니다 — 지원 앱은 문서를 참고하세요.',
'Nothing to import from that file': '이 파일에서 가져올 내용이 없습니다'
'Nothing to import from that file': '이 파일에서 가져올 내용이 없습니다',
// --- mobile build ---
'Your data': '내 데이터',
'All data stays on this phone': '모든 데이터는 이 휴대폰에만 저장됩니다',
'No account, no cloud — back it up anytime with Export below.': '계정도 클라우드도 없음 — 아래 내보내기로 언제든 백업하세요.',
'Reminds you at this time on days that have a routine planned.': '루틴이 계획된 날 이 시간에 알려 드립니다.',
'Workout day': '운동하는 날',
'{0} is on the plan today — let’s go!': '오늘은 {0} 하는 날이에요 — 화이팅!'
}
+8 -1
View File
@@ -399,5 +399,12 @@ export default {
'Could not read that file': 'Nie udało się odczytać pliku',
'That file is empty': 'Ten plik jest pusty',
'That file\'s columns aren\'t recognised — see the docs for supported apps.': 'Nie rozpoznano kolumn — obsługiwane aplikacje znajdziesz w dokumentacji.',
'Nothing to import from that file': 'Brak danych do importu z tego pliku'
'Nothing to import from that file': 'Brak danych do importu z tego pliku',
// --- mobile build ---
'Your data': 'Twoje dane',
'All data stays on this phone': 'Wszystkie dane zostają na tym telefonie',
'No account, no cloud — back it up anytime with Export below.': 'Bez konta i chmury — w każdej chwili zrób kopię przez Eksport poniżej.',
'Reminds you at this time on days that have a routine planned.': 'Przypomina o tej godzinie w dni z zaplanowaną rutyną.',
'Workout day': 'Dzień treningu',
'{0} is on the plan today — let’s go!': 'Dziś w planie: {0} — do dzieła!'
}
+8 -1
View File
@@ -399,5 +399,12 @@ export default {
'Could not read that file': 'Não foi possível ler o ficheiro',
'That file is empty': 'Esse ficheiro está vazio',
'That file\'s columns aren\'t recognised — see the docs for supported apps.': 'Colunas não reconhecidas — vê a documentação para apps suportadas.',
'Nothing to import from that file': 'Nada para importar desse ficheiro'
'Nothing to import from that file': 'Nada para importar desse ficheiro',
// --- mobile build ---
'Your data': 'Os teus dados',
'All data stays on this phone': 'Todos os dados ficam neste telemóvel',
'No account, no cloud — back it up anytime with Export below.': 'Sem conta, sem nuvem — faz uma cópia quando quiseres com Exportar, abaixo.',
'Reminds you at this time on days that have a routine planned.': 'Lembra-te a esta hora nos dias com uma rotina planeada.',
'Workout day': 'Dia de treino',
'{0} is on the plan today — let’s go!': 'Hoje tens {0} no plano — vamos!'
}
+8 -1
View File
@@ -399,5 +399,12 @@ export default {
'Could not read that file': 'Не удалось прочитать файл',
'That file is empty': 'Файл пуст',
'That file\'s columns aren\'t recognised — see the docs for supported apps.': 'Колонки не распознаны — список поддерживаемых приложений в документации.',
'Nothing to import from that file': 'В этом файле нечего импортировать'
'Nothing to import from that file': 'В этом файле нечего импортировать',
// --- mobile build ---
'Your data': 'Ваши данные',
'All data stays on this phone': 'Все данные остаются на этом телефоне',
'No account, no cloud — back it up anytime with Export below.': 'Без аккаунта и облака — в любой момент сделайте резервную копию через «Экспорт» ниже.',
'Reminds you at this time on days that have a routine planned.': 'Напоминает в это время в дни с запланированной программой.',
'Workout day': 'День тренировки',
'{0} is on the plan today — let’s go!': 'Сегодня по плану {0} — вперёд!'
}
+8 -1
View File
@@ -399,5 +399,12 @@ export default {
'Could not read that file': 'Dosya okunamadı',
'That file is empty': 'Bu dosya boş',
'That file\'s columns aren\'t recognised — see the docs for supported apps.': 'Sütunlar tanınmadı — desteklenen uygulamalar için belgelere bak.',
'Nothing to import from that file': 'Bu dosyada içe aktarılacak bir şey yok'
'Nothing to import from that file': 'Bu dosyada içe aktarılacak bir şey yok',
// --- mobile build ---
'Your data': 'Verileriniz',
'All data stays on this phone': 'Tüm veriler bu telefonda kalır',
'No account, no cloud — back it up anytime with Export below.': 'Hesap yok, bulut yok — aşağıdaki Dışa aktar ile istediğiniz zaman yedekleyin.',
'Reminds you at this time on days that have a routine planned.': 'Rutin planlanmış günlerde bu saatte hatırlatır.',
'Workout day': 'Antrenman günü',
'{0} is on the plan today — let’s go!': 'Bugün planda {0} var — hadi!'
}
+8 -1
View File
@@ -399,5 +399,12 @@ export default {
'Could not read that file': '无法读取该文件',
'That file is empty': '该文件是空的',
'That file\'s columns aren\'t recognised — see the docs for supported apps.': '无法识别该文件的列 — 支持的应用请见文档。',
'Nothing to import from that file': '该文件中没有可导入的内容'
'Nothing to import from that file': '该文件中没有可导入的内容',
// --- mobile build ---
'Your data': '你的数据',
'All data stays on this phone': '所有数据都保存在这部手机上',
'No account, no cloud — back it up anytime with Export below.': '无需账号、无需云端——随时可用下方的导出功能备份。',
'Reminds you at this time on days that have a routine planned.': '在安排了训练计划的日子,此时间提醒你。',
'Workout day': '训练日',
'{0} is on the plan today — let’s go!': '今天的计划是{0}——加油!'
}
+3 -1
View File
@@ -1,12 +1,14 @@
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import App from './App.jsx'
import { MOBILE } from './lib/mobile.js'
import './index.css'
createRoot(document.getElementById('root')).render(
<StrictMode><App /></StrictMode>
)
if ('serviceWorker' in navigator && location.protocol === 'https:') {
// Not in the mobile build: the native shell already serves everything from disk.
if (!MOBILE && 'serviceWorker' in navigator && location.protocol === 'https:') {
navigator.serviceWorker.register('sw.js').catch(() => {})
}
+35 -2
View File
@@ -3,6 +3,7 @@ import { api } from '../lib/api.js'
import { localTZ } from '../lib/format.js'
import { registerCustom } from '../lib/exercises.js'
import { DEMO, DEMO_SEEDED } from '../lib/demo.js'
import { MOBILE, nativeLoad, nativeSave, syncReminder } from '../lib/mobile.js'
const KEY = 'gym_state_v1'
export const DEF = {
@@ -26,12 +27,21 @@ const hasData = st => !!((st.workouts || []).length || (st.routines || []).lengt
export const useStore = create((set, get) => {
let pushTm = null
let saveTm = null
// Mobile build: mirror the state into a file in the app's data directory (survives WebView
// storage eviction) and keep the native reminder schedule in step with the weekly plan.
const nativePersist = () => {
clearTimeout(saveTm)
saveTm = setTimeout(() => { saveTm = null; nativeSave(get().S); syncReminder(get().S) }, 800)
}
const persist = (S, push = true) => {
S._ts = Date.now()
registerCustom(S.customEx)
localStorage.setItem(KEY, JSON.stringify(S))
set({ S })
if (MOBILE) nativePersist()
if (push && get().user) {
clearTimeout(pushTm)
pushTm = setTimeout(() => get().pushState(), 1500)
@@ -39,9 +49,17 @@ export const useStore = create((set, get) => {
}
// A setting changed right before switching away/closing the tab must not get lost mid-debounce
// (e.g. setting the reminder time then immediately backgrounding to test it).
// (e.g. setting the reminder time then immediately backgrounding to test it). On mobile the
// same applies to the file mirror — backgrounding is often the last thing before the OS
// kills the app.
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'hidden' && pushTm) {
if (document.visibilityState !== 'hidden') return
if (MOBILE && saveTm) {
clearTimeout(saveTm)
saveTm = null
nativeSave(get().S)
}
if (pushTm) {
clearTimeout(pushTm)
pushTm = null
get().pushState()
@@ -109,6 +127,21 @@ export const useStore = create((set, get) => {
// Boot: ask the server who we are, then pull.
async boot() {
// Mobile build: no backend either — restore from the file mirror (the durable copy;
// localStorage may have been evicted since the last run) and go straight in.
if (MOBILE) {
const saved = await nativeLoad()
const S = get().S
if (saved && (!hasData(S) || (saved._ts || 0) >= (S._ts || 0))) {
persist(Object.assign(clone(DEF), saved), false)
} else if (hasData(S)) {
nativeSave(S) // first run after an update from a file-less version: seed the mirror
}
get().setGuest(true)
syncReminder(get().S)
set({ ready: true })
return
}
// Demo build (GitHub Pages): no backend at all — seed once, stay in guest mode.
if (DEMO) {
if (!localStorage.getItem(DEMO_SEEDED)) {
+58 -11
View File
@@ -7,6 +7,7 @@ import { webauthnOK, passkeyLogin, passkeyRegister, IS_ANDROID } from '../lib/ap
import { pushSupported, enablePush, disablePush, sendTestPush } from '../lib/push.js'
import { t, LANGS, INSTR_LANGS } from '../lib/i18n.js'
import { DEMO, REPO } from '../lib/demo.js'
import { MOBILE, shareExport, syncReminder } from '../lib/mobile.js'
import { loadStarterPlan, confirmSheet, importFromApp } from '../sheets.jsx'
import Icon from '../components/Icon.jsx'
import { Section, Row, SelectRow, Switch, Segmented, Button, TextField } from '../components/ui.jsx'
@@ -20,9 +21,16 @@ export default function Settings() {
const fileRef = useRef(null)
const importRef = useRef(null)
const doExport = () => {
const blob = new Blob([JSON.stringify(S, null, 2)], { type: 'application/json' })
const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = 'opengym-backup-' + todayISO() + '.json'; a.click(); URL.revokeObjectURL(a.href)
const doExport = async () => {
const json = JSON.stringify(S, null, 2)
const name = 'opengym-backup-' + todayISO() + '.json'
// WKWebView can't download blob URLs — the native build hands the file to the share sheet.
if (MOBILE) {
try { await shareExport(json, name); toast(t('Backup exported')) } catch (e) { /* share sheet dismissed */ }
return
}
const blob = new Blob([json], { type: 'application/json' })
const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = name; a.click(); URL.revokeObjectURL(a.href)
toast(t('Backup exported'))
}
const doImport = ev => {
@@ -49,9 +57,13 @@ export default function Settings() {
<div style={{ flex: 1, marginLeft: 10 }}><h1>{t('Settings')}</h1></div>
</div>
{/* ---------- account (demo builds have nothing to sign in to) ---------- */}
<Section title={DEMO ? t('Demo') : t('Account')}>
{DEMO ? <>
{/* ---------- account (demo and mobile builds have nothing to sign in to) ---------- */}
<Section title={MOBILE ? t('Your data') : DEMO ? t('Demo') : t('Account')}>
{MOBILE ? <>
<Row icon="lock" iconTint="var(--acc)" title={t('All data stays on this phone')} subtitle={t('No account, no cloud — back it up anytime with Export below.')} />
<Row icon="rocket" iconTint="var(--indigo)" title={t('Self-host openGym')} subtitle={t('Passkey sign-in, sync across your devices, your own data.')} accessory="chevron"
onClick={() => window.open(REPO, '_blank', 'noopener')} />
</> : DEMO ? <>
<Row icon="sparkles" iconTint="var(--acc)" title={t('You’re in the demo')} subtitle={t('Example data, stored only in this browser — change anything you like.')} />
<Row icon="reset" iconTint="var(--blue)" title={t('Reset demo data')} accessory="chevron"
onClick={() => confirmSheet({ title: t('Reset demo data?'), message: t('Puts the example plan, workouts and weigh-ins back the way they started.'), confirmText: t('Reset'), onConfirm: () => { resetDemo(); nav('/home'); toast(t('Demo data reset')) } })} />
@@ -68,10 +80,10 @@ export default function Settings() {
<Row icon="lock" iconTint="var(--grey)" title={t('Passkeys not supported in this browser.')} />
)}
</Section>
{!user && !DEMO && <p className="sect-f" style={{ marginTop: -18, marginBottom: 22 }}>{t('Guest mode — data lives only in this browser.')}</p>}
{!user && !DEMO && !MOBILE && <p className="sect-f" style={{ marginTop: -18, marginBottom: 22 }}>{t('Guest mode — data lives only in this browser.')}</p>}
{/* ---------- appearance ---------- */}
<Section title={t('Appearance')} footer={DEMO ? undefined : t('synced with your profile')}>
<Section title={t('Appearance')} footer={DEMO || MOBILE ? undefined : t('synced with your profile')}>
<SelectRow
icon="globe" iconTint="var(--blue)" title={t('Language')}
value={S.lang || 'en'} onChange={v => update(s => { s.lang = v })}
@@ -123,7 +135,7 @@ export default function Settings() {
</Row>
</Section>
{user && <NotificationsCard S={S} update={update} toast={toast} />}
{(user || MOBILE) && <NotificationsCard S={S} update={update} toast={toast} />}
{/* ---------- data ---------- */}
<Section title={t('Data')}>
@@ -140,11 +152,12 @@ export default function Settings() {
<input ref={importRef} type="file" accept=".csv,.xml,text/csv,text/xml" style={{ display: 'none' }}
onChange={ev => { const f = ev.target.files[0]; if (f) importFromApp(f); ev.target.value = '' }} />
<Section title={t('Tip')}>
{/* "Add to Home screen" makes no sense inside the native app */}
{!MOBILE && <Section title={t('Tip')}>
<Row icon="lightbulb" iconTint="var(--yellow)"
title={IS_ANDROID ? t('In Chrome: ⋮ menu → Add to Home screen') : t('In Safari: Share → Add to Home Screen')}
subtitle={t('to install openGym as a full-screen app.') + ' ' + (user ? t('Your data syncs with your profile — sign in anywhere to see it.') : t('Guest data stays on this device — export a backup now and then!'))} />
</Section>
</Section>}
<div className="dim small" style={{ textAlign: 'center', marginTop: 4, lineHeight: 1.6 }}>
openGym · {t('free & open source (AGPL v3)')}<br />
@@ -154,6 +167,40 @@ export default function Settings() {
}
function NotificationsCard({ S, update, toast }) {
if (MOBILE) return <MobileReminderCard S={S} update={update} toast={toast} />
return <PushCard S={S} update={update} toast={toast} />
}
// Mobile build: the reminder is a native local notification scheduled on planned weekdays —
// no push server involved. The schedule itself is (re)synced by the store on every persist;
// this card only owns the OS permission prompt when the switch turns on.
function MobileReminderCard({ S, update, toast }) {
const setReminder = patch => update(s => { s.reminder = { ...(s.reminder || DEF.reminder), ...patch, tz: localTZ() } })
const toggle = async () => {
const on = !S.reminder?.on
if (on) {
const ok = await syncReminder({ ...S, reminder: { ...(S.reminder || DEF.reminder), on: true } }, true)
if (!ok) { toast(t('Could not change notification settings')); return }
}
setReminder({ on })
}
return (
<Section title={t('Notifications')}
footer={S.reminder?.on ? t('Reminds you at this time on days that have a routine planned.') : null}>
<Row icon="calendar" iconTint="var(--orange)" title={t('Workout day reminder')}>
<Switch checked={!!S.reminder?.on} onChange={toggle} />
</Row>
{S.reminder?.on && (
<Row icon="clock" iconTint="var(--purple)" title={t('Reminder time')}>
<input type="time" className="timef" value={S.reminder?.time || DEF.reminder.time}
onChange={e => setReminder({ time: e.target.value })} />
</Row>
)}
</Section>
)
}
function PushCard({ S, update, toast }) {
const [on, setOn] = useState(false)
const [busy, setBusy] = useState(false)
const supported = pushSupported()