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.
JavaScript apple-watchbodyweightdockerfitnessfitness-trackergymhealthiosmcpnodejspasskeysprogressive-web-applicationspwareactself-hostedself-hostingvitewebauthnweightliftingworkout-tracker
perf: the saved copy reuses the history's JSON while the history is unchanged
Duarte Santos141dcfa6a74c
diff --git a/frontend/src/lib/mobile.js b/frontend/src/lib/mobile.jsindex c77b93f0f..82a228100 100644--- a/frontend/src/lib/mobile.js+++ b/frontend/src/lib/mobile.js@@ -14,6 +14,7 @@ import { isoOf, todayISO } from './format.js'import { effectiveRoutineIds } from './history.js'import { NUDGE_COPY, lineIndex, nudgeFor, nudgeMinute, toneOf } from './nudge.js'import { excusedOn } from './day-notes.js'+import { stateJson } from './state-json.js'export const MOBILE = import.meta.env.VITE_MOBILE === '1'@@ -70,7 +71,7 @@ export async function nativeLoad() {export async function nativeSave(state) {try {const { Filesystem, Directory, Encoding } = await import('@capacitor/filesystem')- const data = JSON.stringify(state)+ const data = stateJson(state)if (typeof Filesystem.rename === 'function') {try {await Filesystem.writeFile({ path: FILE_NEW, directory: Directory.Data, data, encoding: Encoding.UTF8 })diff --git a/frontend/src/lib/state-json.js b/frontend/src/lib/state-json.jsnew file mode 100644index 000000000..c2409157a--- /dev/null+++ b/frontend/src/lib/state-json.js@@ -0,0 +1,27 @@+// The saved copy of the state as JSON, written to localStorage on every change (store/useStore.js+// persist) and to the phone's file mirror (lib/mobile.js nativeSave). The workout history is most+// of it (a 400-workout profile: ~90 % of 360 KB) and a ticked set never changes it: since update()+// keeps a field it did not touch as the very same object (draftOf), the history's JSON is kept+// from the last write while the array is that same object, and only the rest is serialised again.+// The text is exactly JSON.stringify(state): same keys, same order, same values.+//+// That is only right as long as nothing changes a saved history in place, which nothing may (every+// change goes through a copy). The test suite checks it on every call: a history changed in place+// throws there instead of being saved stale.+let histRef = null+let histJson = null++export function stateJson(S) {+ const w = S && S.workouts+ if (!S || typeof S !== 'object' || Array.isArray(S) || typeof S.toJSON === 'function' || !Array.isArray(w)) return JSON.stringify(S)+ let wj+ if (w === histRef) wj = histJson+ else { wj = JSON.stringify(w); histRef = w; histJson = wj }+ if (import.meta.env?.MODE === 'test' && wj !== JSON.stringify(w)) throw new Error('state-json: the saved workout history was changed in place')+ const parts = []+ for (const k of Object.keys(S)) {+ const v = k === 'workouts' ? wj : JSON.stringify(S[k])+ if (v !== undefined) parts.push(JSON.stringify(k) + ':' + v)+ }+ return '{' + parts.join(',') + '}'+}diff --git a/frontend/src/lib/state-json.test.js b/frontend/src/lib/state-json.test.jsnew file mode 100644index 000000000..8b59eb243--- /dev/null+++ b/frontend/src/lib/state-json.test.js@@ -0,0 +1,29 @@+import { describe, expect, it } from 'vitest'+import { stateJson } from './state-json.js'++describe('stateJson', () => {+ it('is exactly JSON.stringify of the state', () => {+ const S = { unit: 'kg', gone: undefined, fn: () => 1, bad: NaN, workouts: [{ id: 'a', d: '2026-10-01', sets: [1, undefined] }], active: null, d: new Date(0) }+ expect(stateJson(S)).toBe(JSON.stringify(S))+ expect(stateJson({ workouts: [] })).toBe('{"workouts":[]}')+ expect(stateJson({ unit: 'kg' })).toBe('{"unit":"kg"}')+ expect(stateJson(null)).toBe('null')+ })++ it('reuses the history of the last write while it is the same array', () => {+ const workouts = [{ id: 'a' }, { id: 'b' }]+ const one = { unit: 'kg', workouts, active: { cur: 0 } }+ const two = { ...one, active: { cur: 1 } }+ expect(stateJson(one)).toBe(JSON.stringify(one))+ expect(stateJson(two)).toBe(JSON.stringify(two))+ const three = { ...two, workouts: [...workouts, { id: 'c' }] }+ expect(stateJson(three)).toBe(JSON.stringify(three))+ })++ it('refuses, under test, a history changed in place after it was written', () => {+ const workouts = [{ id: 'a' }]+ stateJson({ workouts })+ workouts[0].id = 'changed'+ expect(() => stateJson({ workouts })).toThrow(/changed in place/)+ })+})diff --git a/frontend/src/store/useStore.js b/frontend/src/store/useStore.jsindex 3fe778222..8ad818750 100644--- a/frontend/src/store/useStore.js+++ b/frontend/src/store/useStore.js@@ -6,6 +6,7 @@ import { registerCustom, healCustomEx } from '../lib/exercises.js'import { DEMO, DEMO_SEEDED } from '../lib/demo.js'import { rememberDefaultLang } from '../lib/default-lang.js'import { guestAllowed } from '../lib/guest.js'+import { stateJson } from '../lib/state-json.js'import { MOBILE, initReminderSync, nativeLoad, nativeSave, onAppActive, readJsonFile, syncReminder, writeAutoBackup, writeJsonFile } from '../lib/mobile.js'import { initHealthSync, syncHealth } from '../lib/health-sync.js'import { refillIfComplete } from '../lib/rotation.js'@@ -618,7 +619,7 @@ export const useStore = create((set, get) => {// The marker goes first: a tab that loads the copy in between gets an older base than the// copy's, which costs one merge at worst — never a newer one, which would lose data.saveMarker(base)- localStorage.setItem(KEY, JSON.stringify(S))+ localStorage.setItem(KEY, stateJson(S))localStorage.setItem(WID_OWNER_KEY, seenOwner || '')const wid = Date.now().toString(36) + Math.random().toString(36).slice(2, 8)localStorage.setItem(WID_KEY, wid)