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.
This commit is contained in:
1 parent
02ea938b2c
commit
50194442b6
6 files changed
+39
-2
No files matched your search
@@ -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 */ }
|
||||
}
|
||||
@@ -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.',
|
||||
|
||||
@@ -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 => <FinishSummary w={w} prs={prs} e1prs={e1prs} close={close} />, { kind: 'center', locked: true })
|
||||
|
||||
@@ -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({}) },
|
||||
|
||||
|
||||
@@ -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) })
|
||||
|
||||
@@ -186,6 +186,10 @@ export default function Settings() {
|
||||
accessory="chevron" onClick={() => importRef.current.click()} />
|
||||
<Row icon="upload" iconTint="var(--blue)" title={t('Import backup')} accessory="chevron" onClick={() => fileRef.current.click()} />
|
||||
<Row icon="download" iconTint="var(--blue)" title={t('Export backup (JSON)')} accessory="chevron" onClick={doExport} />
|
||||
{MOBILE && <Row icon="history" iconTint="var(--blue)" title={t('Auto-backup on changes')}
|
||||
subtitle={t('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.')}>
|
||||
<Switch checked={!!S.autoBackup} onChange={v => update(s => { s.autoBackup = v })} />
|
||||
</Row>}
|
||||
<Row icon="trash" iconTint="var(--red)" title={t('Reset everything')} danger onClick={() => 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')) } })} />
|
||||
</Section>
|
||||
<input ref={fileRef} type="file" accept=".json,application/json" style={{ display: 'none' }} onChange={doImport} />
|
||||
|
||||
Reference in new issue
Block a user