From 50194442b6c5ef5f68f29f3d0a60b49a36f1bb41 Mon Sep 17 00:00:00 2001 From: Josevi Date: Mon, 24 Aug 2026 20:54:28 +0200 Subject: [PATCH] mobile: opcion de auto-backup local al terminar entreno o editar rutina En el build movil (Capacitor) los datos solo viven en el dispositivo, sin backend. Ademas del export/import manual ya existente, se agrega un toggle en Settings que escribe una copia fechada en la carpeta Documents (visible en Files/gestor de archivos) tras terminar un entrenamiento o salir del editor de rutinas, para que una app de sincronizacion externa (o una copia manual) siempre tenga algo reciente que llevarse. --- frontend/src/lib/mobile.js | 18 ++++++++++++++++++ frontend/src/locales/es.js | 2 ++ frontend/src/sheets.jsx | 1 + frontend/src/store/useStore.js | 12 ++++++++++-- frontend/src/views/RoutineEdit.jsx | 4 ++++ frontend/src/views/Settings.jsx | 4 ++++ 6 files changed, 39 insertions(+), 2 deletions(-) diff --git a/frontend/src/lib/mobile.js b/frontend/src/lib/mobile.js index a337abb..439b155 100644 --- a/frontend/src/lib/mobile.js +++ b/frontend/src/lib/mobile.js @@ -10,6 +10,7 @@ // 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-core.js' +import { todayISO } from './format.js' export const MOBILE = import.meta.env.VITE_MOBILE === '1' @@ -66,3 +67,20 @@ export async function shareExport(json, filename) { const w = await Filesystem.writeFile({ path: filename, directory: Directory.Cache, data: json, encoding: Encoding.UTF8 }) await Share.share({ title: filename, url: w.uri }) } + +// "Auto-backup on changes" (Settings): a dated snapshot dropped into the Documents folder — +// visible in Files (iOS) / a file manager (Android), unlike the private mirror nativeSave keeps +// — so whatever the user points at that folder (a sync app, a manual copy) always has something +// recent. One file per day; later triggers the same day just overwrite it. +export async function writeAutoBackup(state) { + try { + const { Filesystem, Directory, Encoding } = await import('@capacitor/filesystem') + await Filesystem.writeFile({ + path: `opengym-backup-${todayISO()}.json`, + directory: Directory.Documents, + data: JSON.stringify(state), + encoding: Encoding.UTF8, + recursive: true, + }) + } catch (e) { /* best effort — the private mirror in Directory.Data still has the data */ } +} diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js index 16d6823..9e1039e 100644 --- a/frontend/src/locales/es.js +++ b/frontend/src/locales/es.js @@ -286,6 +286,8 @@ export default { 'Data': 'Datos', 'Export backup (JSON)': 'Exportar copia (JSON)', 'Import backup': 'Importar copia', + 'Auto-backup on changes': 'Copia automática al modificar', + 'Saves a dated copy to the Documents folder after finishing a workout or editing a routine — point a sync app at it, or copy it out by hand.': 'Guarda una copia fechada en la carpeta Documentos al terminar un entrenamiento o editar una rutina — apunta una app de sincronización a esa carpeta, o copia el archivo a mano.', 'Reset everything?': '¿Restablecer todo?', 'Reset everything': 'Restablecer todo', 'Deletes your plan, workouts and body weight on this device. This cannot be undone.': 'Elimina tu plan, entrenamientos y peso corporal en este dispositivo. No se puede deshacer.', diff --git a/frontend/src/sheets.jsx b/frontend/src/sheets.jsx index f49140a..4b2c99b 100644 --- a/frontend/src/sheets.jsx +++ b/frontend/src/sheets.jsx @@ -1019,6 +1019,7 @@ function doFinishWorkout() { s.workouts.push(w) s.active = null }) + useStore.getState().autoBackupNow() useUI.getState().stopRest() beep(snd(), 880, 0.15); beep(snd(), 1100, 0.15, 0.18); beep(snd(), 1320, 0.3, 0.36) ui().openSheet(close => , { kind: 'center', locked: true }) diff --git a/frontend/src/store/useStore.js b/frontend/src/store/useStore.js index 96b2911..ebdb692 100644 --- a/frontend/src/store/useStore.js +++ b/frontend/src/store/useStore.js @@ -4,7 +4,7 @@ import { localTZ } from '../lib/format.js' import { registerCustom } from '../lib/exercises.js' import { DEMO, DEMO_SEEDED } from '../lib/demo.js' import { guestAllowed } from '../lib/guest.js' -import { MOBILE, nativeLoad, nativeSave, syncReminder } from '../lib/mobile.js' +import { MOBILE, nativeLoad, nativeSave, syncReminder, writeAutoBackup } from '../lib/mobile.js' const KEY = 'gym_state_v1' export const DEF = { @@ -16,7 +16,7 @@ export const DEF = { // that a profile which never chose (loaded state is overlaid on DEF, on every path: local, // server pull, backup import) still falls back to the `showRir` boolean this replaced and // keeps the column it had. See effortOf. - reminder: { on: false, time: '08:00', tz: null }, effort: null + reminder: { on: false, time: '08:00', tz: null }, effort: null, autoBackup: false, } const clone = o => JSON.parse(JSON.stringify(o)) @@ -93,6 +93,14 @@ export const useStore = create((set, get) => { }, replaceState(S, push = false) { persist(clone(S), push) }, + // Fires after the moments where losing local data would actually hurt — a workout just + // logged, a routine just edited — not on every keystroke. No-op off mobile or with the + // setting off; the private file mirror (nativePersist, above) already covers every change. + autoBackupNow() { + const S = get().S + if (MOBILE && S.autoBackup) writeAutoBackup(S) + }, + isGuest: () => localStorage.getItem('gym_guest') === '1', setGuest(v) { if (v) localStorage.setItem('gym_guest', '1'); else localStorage.removeItem('gym_guest'); set({}) }, diff --git a/frontend/src/views/RoutineEdit.jsx b/frontend/src/views/RoutineEdit.jsx index d12adfb..ca53625 100644 --- a/frontend/src/views/RoutineEdit.jsx +++ b/frontend/src/views/RoutineEdit.jsx @@ -21,6 +21,10 @@ export default function RoutineEdit() { const update = useStore(s => s.update) const r = S.routines.find(x => x.id === id) useEffect(() => { if (!r) nav('/plan') }, [!!r]) + // Editing here has no explicit "save" — every field change persists immediately. A single + // auto-backup on the way out (not per keystroke) covers the whole editing session, deletion + // included: this still unmounts after the delete button navigates away. + useEffect(() => () => useStore.getState().autoBackupNow(), []) if (!r) return null const edit = fn => update(s => { fn(s.routines.find(x => x.id === id).ex) }) diff --git a/frontend/src/views/Settings.jsx b/frontend/src/views/Settings.jsx index f4d0c41..8630e8b 100644 --- a/frontend/src/views/Settings.jsx +++ b/frontend/src/views/Settings.jsx @@ -186,6 +186,10 @@ export default function Settings() { accessory="chevron" onClick={() => importRef.current.click()} /> fileRef.current.click()} /> + {MOBILE && + update(s => { s.autoBackup = v })} /> + } confirmSheet({ title: t('Reset everything?'), message: t('Deletes your plan, workouts and body weight on this device. This cannot be undone.'), confirmText: t('Delete everything'), danger: true, onConfirm: () => { replaceState(JSON.parse(JSON.stringify(DEF)), true); nav('/home'); toast(t('All data reset')) } })} />