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
Workouts: adding or removing a photo keeps the refs this version cannot show on the record
Duarte Santos13577c03b190
diff --git a/frontend/src/lib/backup-media.js b/frontend/src/lib/backup-media.jsindex d1ef0f3b3..be134d6e8 100644--- a/frontend/src/lib/backup-media.js+++ b/frontend/src/lib/backup-media.js@@ -41,8 +41,8 @@ Do not unpack and re-zip it: the app reads zips that are stored, not compressed./** The media refs and links of an imported state — each custom exercise's picture and link, each* logged workout's photos and videos — kept only where they pass the same checks as anywhere- * else (a workout's list also deduplicated and capped, workoutMediaOf); the rest of the state is- * left as it is. Mutates and returns it. */+ * else (a workout's list also deduplicated, but not capped: workoutMediaOf caps what shows);+ * the rest of the state is left as it is. Mutates and returns it. */export function sanitizeCustomMedia(state) {for (const c of Array.isArray(state?.customEx) ? state.customEx : []) {if (!c || typeof c !== 'object') continue@@ -51,7 +51,9 @@ export function sanitizeCustomMedia(state) {}for (const w of Array.isArray(state?.workouts) ? state.workouts : []) {if (!w || typeof w !== 'object' || !('media' in w)) continue- const list = workoutMediaOf(w)+ // Every ref that passes, not only the ones shown: a file with more than the cap keeps them+ // all, and the workout shows the first WORKOUT_MEDIA_MAX as it would anywhere else.+ const list = workoutMediaOf(w, Infinity)if (list.length) w.media = list; else delete w.media}return statediff --git a/frontend/src/lib/backup-media.test.js b/frontend/src/lib/backup-media.test.jsindex 03db36b83..d7221406e 100644--- a/frontend/src/lib/backup-media.test.js+++ b/frontend/src/lib/backup-media.test.js@@ -4,6 +4,7 @@ import { createMediaStore, memoryBackend } from './media-store.js'import { zipStore, readZip } from './zip.js'import { sha256Hex } from './sha256.js'import { jpeg, png, mp4 } from './media-samples.test-util.js'+import { workoutMediaOf } from './media-refs.js'const refFor = async (bytes, mime, kind = 'image') => ({ kind, hash: await sha256Hex(bytes), mime, size: bytes.length, width: 4, height: 3, at: 1 })const stateWith = customEx => ({ unit: 'kg', workouts: [], routines: [], bodyweight: [], customEx })@@ -86,7 +87,7 @@ describe('import', () => {expect(sanitizeCustomMedia({ workouts: [] })).toEqual({ workouts: [] })})- it('a workout\'s photos and videos come in through the same gates: bad refs dropped, one per file, at most six', () => {+ it('a workout\'s photos and videos come in through the same gates: bad refs dropped, one per file — past the cap kept, shown up to six', () => {const ok = n => ({ kind: 'image', hash: String(n).repeat(64), mime: 'image/webp', size: 10, width: 4, height: 3, at: 1 })const S = { workouts: [{ id: 'w1', media: [ok(1), { ...ok(2), mime: 'text/html' }, ok(1), ok(3), ok(4), ok(5), ok(6), ok(7), ok(8)] },@@ -94,7 +95,8 @@ describe('import', () => {{ id: 'w3' }] }sanitizeCustomMedia(S)- expect(S.workouts[0].media.map(m => m.hash[0])).toEqual(['1', '3', '4', '5', '6', '7'])+ expect(S.workouts[0].media.map(m => m.hash[0])).toEqual(['1', '3', '4', '5', '6', '7', '8'])+ expect(workoutMediaOf(S.workouts[0]).map(m => m.hash[0])).toEqual(['1', '3', '4', '5', '6', '7'])expect('media' in S.workouts[1]).toBe(false)expect(S.workouts[2]).toEqual({ id: 'w3' })})diff --git a/frontend/src/lib/media-refs.js b/frontend/src/lib/media-refs.jsindex bda7ca5fe..bc06547eb 100644--- a/frontend/src/lib/media-refs.js+++ b/frontend/src/lib/media-refs.js@@ -91,10 +91,12 @@ export const WORKOUT_MEDIA_MAX = 6/*** The photos and videos of a logged workout as they may be shown: each passes normalizeMediaRef,- * a file listed twice shows once, and never more than WORKOUT_MEDIA_MAX (a hand-edited or- * foreign copy can hold anything). Oldest first, the order they were added in.+ * a file listed twice shows once, and never more than `max` — WORKOUT_MEDIA_MAX unless the+ * caller asks otherwise (a hand-edited or foreign copy can hold anything). Oldest first, the+ * order they were added in. A reading, never a rewrite: the list on the record keeps whatever+ * this leaves out (lib/workout-media.js edits it as it stands).*/-export function workoutMediaOf(w) {+export function workoutMediaOf(w, max = WORKOUT_MEDIA_MAX) {const raw = w && typeof w === 'object' && Array.isArray(w.media) ? w.media : []const out = []const seen = new Set()@@ -103,7 +105,7 @@ export function workoutMediaOf(w) {if (!m || seen.has(m.hash)) continueseen.add(m.hash)out.push(m)- if (out.length >= WORKOUT_MEDIA_MAX) break+ if (out.length >= max) break}return out}diff --git a/frontend/src/lib/workout-media.js b/frontend/src/lib/workout-media.jsindex 2ce29b422..d79be7223 100644--- a/frontend/src/lib/workout-media.js+++ b/frontend/src/lib/workout-media.js@@ -11,12 +11,20 @@// photo added on the phone is not lost to the desktop's copy just because that one logged a// weigh-in since (lib/sync-merge.js). Only a real change stamps — a stamp outranks whatever// another device wrote since.+//+// Both edit the list as it stands on the record — take one hash out, put one ref on the end —+// and never write back the normalised, capped reading of it (workoutMediaOf): a ref this+// version cannot show (a kind or a field from a newer one) or one past the cap (a list merged+// from two devices, an imported backup) stays on the record for the version or the removal that+// can. The cap only decides what shows and whether Add still has room.import { normalizeMediaRef, workoutMediaOf, WORKOUT_MEDIA_MAX } from './media-refs.js'import { sameWorkout } from './workout-date.js'import { stampWorkout } from './sync-merge.js'const recordOf = (state, w) => (Array.isArray(state?.workouts) ? state.workouts.find(x => x && sameWorkout(x, w)) : null) || null+const rawOf = rec => (Array.isArray(rec.media) ? rec.media : [])+function write(rec, list, now) {if (list.length) rec.media = listelse delete rec.media@@ -26,35 +34,32 @@ function write(rec, list, now) {/*** Adds a photo or video to the saved workout `w` (the record or a copy of it) inside `state`.* Returns 'added', or why not: 'gone' (the workout was deleted meanwhile), 'invalid' (not a- * MediaRef normalizeMediaRef accepts), 'full' (already WORKOUT_MEDIA_MAX) or 'dup' (that very- * file is already on it). Mutates `state` — made for useStore's update().+ * MediaRef normalizeMediaRef accepts), 'full' (already shows WORKOUT_MEDIA_MAX) or 'dup' (that+ * very file is already on it). Mutates `state` — made for useStore's update().*/export function addWorkoutMedia(state, w, ref, now = Date.now()) {const rec = recordOf(state, w)if (!rec) return 'gone'const m = normalizeMediaRef(ref)if (!m) return 'invalid'- const list = workoutMediaOf(rec)- if (list.some(x => x.hash === m.hash)) return 'dup'- if (list.length >= WORKOUT_MEDIA_MAX) return 'full'- write(rec, [...list, m], now)+ const raw = rawOf(rec)+ if (raw.some(x => x && x.hash === m.hash)) return 'dup'+ if (workoutMediaOf(rec).length >= WORKOUT_MEDIA_MAX) return 'full'+ write(rec, [...raw, m], now)return 'added'}/**- * Takes the file `hash` off the saved workout `w`. Returns whether anything changed. The file- * itself is left to the GCs: another device, a stash or an exercise may still refer to it, and- * the server keeps it for its grace period either way.+ * Takes the file `hash` off the saved workout `w` (every entry that names it). Returns whether+ * anything changed. The file itself is left to the GCs: another device, a stash or an exercise+ * may still refer to it, and the server keeps it for its grace period either way.*/export function removeWorkoutMedia(state, w, hash, now = Date.now()) {const rec = recordOf(state, w)if (!rec) return false- const list = workoutMediaOf(rec)- const left = list.filter(x => x.hash !== hash)- if (left.length === list.length) return false+ const raw = rawOf(rec)+ const left = raw.filter(x => !(x && x.hash === hash))+ if (left.length === raw.length) return falsewrite(rec, left, now)return true}--/** Whether another photo or video still fits on `w`. */-export const workoutMediaRoom = w => workoutMediaOf(w).length < WORKOUT_MEDIA_MAXdiff --git a/frontend/src/lib/workout-media.test.js b/frontend/src/lib/workout-media.test.jsindex fd419f55d..71a69dcca 100644--- a/frontend/src/lib/workout-media.test.js+++ b/frontend/src/lib/workout-media.test.js@@ -2,7 +2,7 @@// stamp), what the sync merge keeps of it, what the history editor does with it, and the places// that must never carry it (copy as text, a routine saved from the workout, a plan file).import { describe, expect, it } from 'vitest'-import { addWorkoutMedia, removeWorkoutMedia, workoutMediaRoom } from './workout-media.js'+import { addWorkoutMedia, removeWorkoutMedia } from './workout-media.js'import { WORKOUT_MEDIA_MAX, workoutMediaOf, referencedHashes, referencedFiles, stateMediaRefs } from './media-refs.js'import { mergeStates } from './sync-merge.js'import { editCompletedSession, saveWorkoutEdit } from './session-edit.js'@@ -40,7 +40,7 @@ describe('addWorkoutMedia / removeWorkoutMedia', () => {expect(addWorkoutMedia(S, { id: 'nope' }, photo(H(1)), 9)).toBe('gone')expect(S.workouts[0]._ts).toBe(3)for (let i = 0; i < WORKOUT_MEDIA_MAX; i++) expect(addWorkoutMedia(S, { id: 'w1' }, photo(H(i)), 10 + i)).toBe('added')- expect(workoutMediaRoom(S.workouts[0])).toBe(false)+ expect(workoutMediaOf(S.workouts[0])).toHaveLength(WORKOUT_MEDIA_MAX)const stamp = S.workouts[0]._tsexpect(addWorkoutMedia(S, { id: 'w1' }, photo(H(0)), 99)).toBe('dup')expect(addWorkoutMedia(S, { id: 'w1' }, photo(H(9)), 99)).toBe('full')@@ -60,6 +60,27 @@ describe('addWorkoutMedia / removeWorkoutMedia', () => {// …and its files are no longer referenced: the GCs take them (after the server's grace).expect(referencedHashes(S).size).toBe(0)})++ it('edits the list as it stands: a ref it cannot show, one past the cap and unknown fields stay on the record', () => {+ const future = { kind: 'model3d', hash: H(7), mime: 'model/gltf-binary', size: 10, width: 1, height: 1, at: 1 }+ const tagged = { ...photo(H(1)), caption: 'front' }+ const many = [tagged, future, ...[2, 3, 4, 5, 6, 8].map(n => photo(H(n)))] // seven that show+ const S = state(workout({ _ts: 3, media: structuredClone(many) }))+ expect(workoutMediaOf(S.workouts[0])).toHaveLength(WORKOUT_MEDIA_MAX)+ expect(addWorkoutMedia(S, { id: 'w1' }, photo(H(9)), 9)).toBe('full')+ expect(addWorkoutMedia(S, { id: 'w1' }, photo(H(8)), 9)).toBe('dup') // past the cap, still on it+ expect(S.workouts[0].media).toEqual(many)+ expect(removeWorkoutMedia(S, { id: 'w1' }, H(3), 10)).toBe(true)+ expect(S.workouts[0].media).toEqual(many.filter(m => m.hash !== H(3)))+ // The one past the cap moves up into view; the unknown kind and the caption are still there.+ expect(workoutMediaOf(S.workouts[0]).map(m => m.hash)).toEqual([1, 2, 4, 5, 6, 8].map(H))+ expect(S.workouts[0].media[0].caption).toBe('front')+ // With room again, an add goes on the end of the raw list.+ expect(removeWorkoutMedia(S, { id: 'w1' }, H(4), 11)).toBe(true)+ expect(addWorkoutMedia(S, { id: 'w1' }, photo(H(9)), 12)).toBe('added')+ expect(S.workouts[0].media.at(-1)).toEqual(photo(H(9)))+ expect(S.workouts[0].media[1]).toEqual(future)+ })})describe('workoutMediaOf / the state walk', () => {