Skip to content

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.

Follow-up to #194: plates counted or a plate loading picked on one device survive a sync with the other, and so does going back to the standard set or the equipment's own loading

Duarte Santosa156551c410a
diff --git a/frontend/src/lib/plates.js b/frontend/src/lib/plates.js
index 03c369ce4..0ad96df53 100644
--- a/frontend/src/lib/plates.js
+++ b/frontend/src/lib/plates.js
@@ -1,7 +1,7 @@
// Plate loading for a set row: which plates go on for THIS weight, from the plates you own.
//
// bar.js knows the bar and splits what is beyond it per side. This module turns that number
-// into plates ("45 · 5"), and does the same for a single stack (a dip belt, a landmine, a
+// into plates ("45 + 5"), and does the same for a single stack (a dip belt, a landmine, a
// plate-loaded machine, a sled). Both read the plate inventory in S.plates: pairs per
// denomination, kept per unit like the bar weight is — a 45 lb plate is a 45 lb plate, a unit
// switch does not turn it into a 20.4 kg one — so a profile with no inventory of its own gets
@@ -28,27 +28,73 @@ const SINGLE_EQ = new Set(['weighted', 'sled machine'])
const exOf = exOrId => (typeof exOrId === 'string' ? EXIDX[exOrId] : exOrId)
const num = v => (typeof v === 'number' && Number.isFinite(v) ? v : Number(v) || 0)
+const unitOf = S => (S?.unit === 'lb' ? 'lb' : 'kg')
+
+// Both choices this module reads are stored with the time they were made, the way a Structural
+// Balance override is: S.loadKind[exId] is `{ kind, _ts }` and S.plates[unit] is
+// `{ [size]: pairs, …, _ts }`. Going back to the default — the equipment's own loading, the
+// standard plate set — is written as a stamped entry too (`kind: null`; a list with no sizes)
+// rather than a deleted key, so it wins a sync against the other device's older choice instead
+// of coming back from it (lib/sync-merge.js keeps whichever side set a key last).
+
+/** The sizes of a stored plate list with their counts, `_ts` and junk keys left out. */
+const sizesOf = entry => (entry && typeof entry === 'object' && !Array.isArray(entry)
+ ? Object.entries(entry).filter(([k]) => num(k) > 0)
+ : [])
+
+/** Whether this profile counts its own plates for its unit, rather than loading the standard set. */
+export const ownsPlates = S => sizesOf(S?.plates?.[unitOf(S)]).length > 0
/**
* The plates this profile can load, heaviest first: [{ w, n }] with n pairs (or plates, for a
- * single stack) of each size. S.plates[unit] is { [size]: count }; absent → the default set.
+ * single stack) of each size. S.plates[unit] is { [size]: count, _ts }; absent or without any
+ * size → the default set.
*/
export function inventoryFor(S) {
- const unit = S?.unit === 'lb' ? 'lb' : 'kg'
- const own = S?.plates?.[unit]
- const sizes = PLATE_SIZES[unit]
+ const unit = unitOf(S)
+ const own = sizesOf(S?.plates?.[unit])
const out = []
- if (own && typeof own === 'object') {
- for (const [k, v] of Object.entries(own)) {
+ if (own.length) {
+ for (const [k, v] of own) {
const w = num(k), n = Math.floor(num(v))
if (w > 0 && n > 0) out.push({ w, n })
}
} else {
- for (const w of sizes) if (!UNCOMMON[unit].has(w)) out.push({ w, n: DEFAULT_PAIRS })
+ for (const w of PLATE_SIZES[unit]) if (!UNCOMMON[unit].has(w)) out.push({ w, n: DEFAULT_PAIRS })
}
return out.sort((a, b) => b.w - a.w)
}
+/**
+ * S.plates with `n` pairs of size `w` for the profile's unit, stamped. The first change copies
+ * the standard set in, so the list the inventory sheet shows is always the one the rows load from.
+ */
+export function withPlatePairs(S, w, n, now = Date.now()) {
+ const unit = unitOf(S)
+ const list = ownsPlates(S)
+ ? Object.fromEntries(sizesOf(S.plates[unit]))
+ : Object.fromEntries(inventoryFor(S).map(p => [p.w, p.n]))
+ list[w] = Math.max(0, Math.round(num(n)))
+ return { ...(S?.plates || {}), [unit]: { ...list, _ts: now } }
+}
+
+/** S.plates with the profile's unit back on the standard set: a stamped list with no sizes. */
+export const withStandardPlates = (S, now = Date.now()) => ({ ...(S?.plates || {}), [unitOf(S)]: { _ts: now } })
+
+/**
+ * An exercise's own loading as S.loadKind stores it: 'pairs' | 'single' | 'none', or null when
+ * the equipment decides. A bare string is how the first builds of plate loading stored it, and
+ * still reads as that kind.
+ */
+export function loadKindOf(value) {
+ const k = value && typeof value === 'object' ? value.kind : value
+ return k === 'pairs' || k === 'single' || k === 'none' ? k : null
+}
+
+/** S.loadKind with the exercise's loading set to `kind`, or back on its equipment's for null. */
+export const withLoadKind = (map, exId, kind, now = Date.now()) =>
+ ({ ...(map || {}), [exId]: { kind: loadKindOf(kind), _ts: now } })
+
/** The count of one size in this profile's inventory (0 when it has none). */
export const pairsOf = (S, w) => inventoryFor(S).find(p => p.w === w)?.n || 0
@@ -129,15 +175,16 @@ export function plateDelta(prev, next) {
* How an exercise's weight is loaded: 'pairs' (a bar or a two-post machine — plates split per
* side beyond the bar), 'single' (one stack: dip belt, landmine, plate-loaded machine, sled — all
* of it beyond the base weight), 'none' (dumbbells, kettlebells, cables, pin machines, bands).
- * The user's own choice in S.loadKind wins; otherwise bar equipment → pairs, body-weight and
- * "weighted" exercises and sleds → single (the added load is what you hang on), the rest → none.
+ * The user's own choice in S.loadKind (loadKindOf) wins; otherwise bar equipment → pairs,
+ * body-weight and "weighted" exercises and sleds → single (the added load is what you hang on),
+ * the rest → none.
* A band's "weight" is its tension, not plates, so bands are none even though isBw counts them.
*/
export function loadKindFor(S, cfgOrId) {
const cfg = typeof cfgOrId === 'string' ? { id: cfgOrId } : (cfgOrId || {})
const ex = exOf(cfg.id)
- const own = S?.loadKind?.[cfg.id]
- if (own === 'pairs' || own === 'single' || own === 'none') return own
+ const own = loadKindOf(S?.loadKind?.[cfg.id])
+ if (own) return own
if (usesBar(ex)) return 'pairs'
if (ex?.eq === 'band' || ex?.eq === 'resistance band') return 'none'
if (SINGLE_EQ.has(ex?.eq) || isBw(cfg)) return 'single'
diff --git a/frontend/src/lib/plates.test.js b/frontend/src/lib/plates.test.js
index 128903ef8..b1c00f074 100644
--- a/frontend/src/lib/plates.test.js
+++ b/frontend/src/lib/plates.test.js
@@ -1,5 +1,5 @@
import { describe, expect, test } from 'vitest'
-import { PLATE_SIZES, DEFAULT_PAIRS, inventoryFor, pairsOf, plateStack, plateDelta, loadKindFor, baseWeightFor, rowLoad, sameLoad } from './plates.js'
+import { PLATE_SIZES, DEFAULT_PAIRS, inventoryFor, pairsOf, ownsPlates, withPlatePairs, withStandardPlates, loadKindOf, withLoadKind, plateStack, plateDelta, loadKindFor, baseWeightFor, rowLoad, sameLoad } from './plates.js'
import { EXDB } from './exercises-data.js'
const idOf = eq => EXDB.find(e => e.eq === eq).id
@@ -30,6 +30,47 @@ describe('inventoryFor', () => {
const S = { unit: 'kg', plates: { kg: { 20: 2, 10: 0, 5: 'x', 2.5: 1.9 }, lb: { 45: 9 } } }
expect(inventoryFor(S)).toEqual([{ w: 20, n: 2 }, { w: 2.5, n: 1 }])
})
+
+ test('a list\'s stamp is not a plate, and a stamped list with no sizes is the standard set', () => {
+ expect(inventoryFor({ unit: 'lb', plates: { lb: { 45: 1, _ts: 1700 } } })).toEqual([{ w: 45, n: 1 }])
+ expect(ownsPlates({ unit: 'lb', plates: { lb: { 45: 1, _ts: 1700 } } })).toBe(true)
+ const reset = { unit: 'lb', plates: { lb: { _ts: 1800 } } }
+ expect(ownsPlates(reset)).toBe(false)
+ expect(inventoryFor(reset)).toEqual(inventoryFor({ unit: 'lb' }))
+ // Owning none of anything is a list of its own, not the standard set.
+ const none = { unit: 'lb', plates: { lb: { 45: 0, 25: 0, _ts: 1900 } } }
+ expect(ownsPlates(none)).toBe(true)
+ expect(inventoryFor(none)).toEqual([])
+ expect(ownsPlates({ unit: 'kg', plates: { lb: { 45: 1 } } })).toBe(false)
+ })
+})
+
+describe('stored choices carry the time they were made', () => {
+ test('the first count copies the standard set in; later ones change one size; both stamped', () => {
+ const first = withPlatePairs({ unit: 'lb', plates: {} }, 45, 1, 100)
+ expect(first).toEqual({ lb: { 45: 1, 35: 6, 25: 6, 10: 6, 5: 6, 2.5: 6, _ts: 100 } })
+ const next = withPlatePairs({ unit: 'lb', plates: { ...first, kg: { 20: 2, _ts: 50 } } }, 15, 2.6, 200)
+ expect(next.lb).toEqual({ 45: 1, 35: 6, 25: 6, 15: 3, 10: 6, 5: 6, 2.5: 6, _ts: 200 })
+ expect(next.kg).toEqual({ 20: 2, _ts: 50 }) // the other unit is left alone
+ expect(withPlatePairs({ unit: 'lb', plates: first }, 45, -3, 300).lb[45]).toBe(0)
+ })
+
+ test('back to the standard set is a stamped list with no sizes, for this unit only', () => {
+ const S = { unit: 'kg', plates: { kg: { 20: 1, _ts: 100 }, lb: { 45: 1, _ts: 90 } } }
+ expect(withStandardPlates(S, 200)).toEqual({ kg: { _ts: 200 }, lb: { 45: 1, _ts: 90 } })
+ expect(withStandardPlates({ unit: 'kg' }, 200)).toEqual({ kg: { _ts: 200 } })
+ })
+
+ test('a load kind is stored with its time; null is the equipment\'s own, stamped too', () => {
+ expect(withLoadKind(undefined, 'a', 'single', 100)).toEqual({ a: { kind: 'single', _ts: 100 } })
+ expect(withLoadKind({ a: { kind: 'single', _ts: 100 } }, 'a', null, 200)).toEqual({ a: { kind: null, _ts: 200 } })
+ expect(withLoadKind({}, 'a', 'weird', 100)).toEqual({ a: { kind: null, _ts: 100 } })
+ expect(loadKindOf({ kind: 'none', _ts: 1 })).toBe('none')
+ expect(loadKindOf({ kind: null, _ts: 1 })).toBe(null)
+ expect(loadKindOf('pairs')).toBe('pairs') // how the first builds stored it
+ expect(loadKindOf('weird')).toBe(null)
+ expect(loadKindOf(undefined)).toBe(null)
+ })
})
describe('plateStack', () => {
@@ -105,6 +146,13 @@ describe('loadKindFor', () => {
expect(loadKindFor({ loadKind: { [barbell]: 'none' } }, barbell)).toBe('none')
expect(loadKindFor({ loadKind: { [barbell]: 'weird' } }, barbell)).toBe('pairs')
})
+
+ test('a stamped choice reads like a bare one; a stamped null is the equipment\'s own', () => {
+ expect(loadKindFor({ loadKind: { [db]: { kind: 'single', _ts: 5 } } }, db)).toBe('single')
+ expect(loadKindFor({ loadKind: { [barbell]: { kind: 'none', _ts: 5 } } }, barbell)).toBe('none')
+ expect(loadKindFor({ loadKind: { [barbell]: { kind: null, _ts: 5 } } }, barbell)).toBe('pairs')
+ expect(loadKindFor({ loadKind: { [bw]: { kind: null, _ts: 5 } } }, { id: bw, bodyweight: false })).toBe('none')
+ })
})
describe('baseWeightFor', () => {
diff --git a/frontend/src/lib/sync-merge.js b/frontend/src/lib/sync-merge.js
index 5727a5e11..55196f2d5 100644
--- a/frontend/src/lib/sync-merge.js
+++ b/frontend/src/lib/sync-merge.js
@@ -23,9 +23,10 @@
* forgotten, whichever way it runs). An exercise in a workout whose edited version was kept
* is the exception: the edit may have taken away the set the kept weight came from, so it
* is the best of the merged history and of the editing copy's own, and the other copy's
- * can no longer bring a corrected typo back. exNotes, barWeights, loadKind, plates: key union
- * - balanceOverrides: key union; of a key both have, the entry set last by its own `_ts`, a
- * clear included (mergeStampedMap), the newer copy's on a tie
+ * can no longer bring a corrected typo back. exNotes, barWeights: key union
+ * - balanceOverrides, loadKind, plates: key union; of a key both have, the entry set last by
+ * its own `_ts`, a clear included (mergeStampedMap), the newer copy's on a tie. For plates the
+ * key is the unit, so the inventory of one unit is kept whole, as last edited
* - `_ts`: the later of the two; `_rev` dropped (the server sets it); `active` left to the caller
*
* Known limit: with no record of what each side deleted, an entry removed on one device inside
@@ -118,7 +119,7 @@ const isMap = v => !!v && typeof v === 'object' && !Array.isArray(v)
/**
* A settings map whose entries carry their own edit time (`{ …, _ts }`), such as the Structural
- * Balance overrides: every key of either side, and of a key both have, the entry set last — the
+ * Balance overrides or the plate-loading choices: every key of either side, and of a key both have, the entry set last — the
* same rule a routine follows. Taking the newer copy's entry lost a choice made on one device
* whenever the other had since logged a set; a plain key union brought a cleared entry back
* from the side that still had it. So a clear is written as a stamped entry, not a delete, and
@@ -188,10 +189,15 @@ export function mergeStates(a, b, { prefer } = {}) {
if (kept) out.exWeights[id] = clone(kept)
else delete out.exWeights[id]
}
- for (const f of ['exNotes', 'barWeights', 'loadKind', 'plates']) {
+ for (const f of ['exNotes', 'barWeights']) {
if (n[f] || o[f]) out[f] = clone({ ...(o[f] || {}), ...(n[f] || {}) })
}
- if (n.balanceOverrides || o.balanceOverrides) out.balanceOverrides = clone(mergeStampedMap(n.balanceOverrides, o.balanceOverrides, prefer))
+ // The plate-loading choices (lib/plates.js) are stamped the same way: an exercise's loading and
+ // a unit's plate inventory are each one choice, made on one device, that a later set logged on
+ // the other must not undo.
+ for (const f of ['balanceOverrides', 'loadKind', 'plates']) {
+ if (n[f] || o[f]) out[f] = clone(mergeStampedMap(n[f], o[f], prefer))
+ }
out._ts = Math.max(a._ts || 0, b._ts || 0)
delete out._rev
return out
diff --git a/frontend/src/lib/sync-merge.test.js b/frontend/src/lib/sync-merge.test.js
index 1b8ea5743..4fe671fe0 100644
--- a/frontend/src/lib/sync-merge.test.js
+++ b/frontend/src/lib/sync-merge.test.js
@@ -1,6 +1,7 @@
import { describe, expect, it } from 'vitest'
import { localExtras, mergeBodyweight, mergeStampedMap, mergeStates, newerOf, stampRoutines, stampWorkout, unionById } from './sync-merge.js'
import { retimeWorkout } from './workout-date.js'
+import { inventoryFor, loadKindFor, withLoadKind, withPlatePairs, withStandardPlates } from './plates.js'
const workout = (id, d = '2026-09-01', start = 1) => ({ id, d, start, entries: [] })
const routine = (id, name = id) => ({ id, name, ex: [] })
@@ -347,3 +348,67 @@ describe('balanceOverrides keep the choice made last', () => {
expect(a.balanceOverrides.k.id).toBe('x')
})
})
+
+// Plate loading (lib/plates.js): an exercise's loading and each unit's plate inventory are
+// stamped like a Structural Balance override, the way back to the default included, so the
+// change made last survives a conflict either way round. A plain key union let the copy that was
+// newer as a whole undo a choice made on the other device, and brought a reset list back.
+describe('plate loading keeps the choice made last', () => {
+ const SQUAT = '0043' // barbell: per side unless you say otherwise
+
+ it('a load kind picked on the older copy survives the newer copy\'s earlier pick', () => {
+ const phone = base({ _ts: 100, loadKind: withLoadKind({}, SQUAT, 'none', 90) })
+ const desk = base({ _ts: 200, workouts: [workout('w2')], loadKind: withLoadKind({}, SQUAT, 'single', 20) })
+ for (const m of [mergeStates(phone, desk), mergeStates(desk, phone)]) {
+ expect(ids(m.workouts)).toEqual(['w2'])
+ expect(loadKindFor(m, SQUAT)).toBe('none')
+ }
+ })
+
+ it('going back to the equipment\'s loading is not undone by an older pick, and a later pick beats it', () => {
+ const back = base({ _ts: 100, loadKind: withLoadKind({}, SQUAT, null, 80) })
+ const stale = base({ _ts: 300, loadKind: withLoadKind({}, SQUAT, 'single', 40) })
+ expect(loadKindFor(mergeStates(back, stale), SQUAT)).toBe('pairs')
+ expect(loadKindFor(mergeStates(stale, back), SQUAT)).toBe('pairs')
+ const later = base({ _ts: 50, loadKind: withLoadKind({}, SQUAT, 'single', 95) })
+ expect(loadKindFor(mergeStates(back, later), SQUAT)).toBe('single')
+ })
+
+ it('exercises set on different devices are all kept; a bare kind from the first builds loses to a stamped one', () => {
+ const a = base({ _ts: 100, loadKind: { ...withLoadKind({}, 'a', 'single', 10), c: 'none' } })
+ const b = base({ _ts: 200, loadKind: { ...withLoadKind({}, 'b', 'none', 30), c: withLoadKind({}, 'c', 'single', 5).c } })
+ const m = mergeStates(b, a)
+ expect(Object.keys(m.loadKind).sort()).toEqual(['a', 'b', 'c'])
+ expect(m.loadKind.c).toEqual({ kind: 'single', _ts: 5 })
+ })
+
+ it('a unit\'s plate list is kept whole as last counted; the other unit\'s comes along', () => {
+ const home = withPlatePairs({ unit: 'lb' }, 45, 1, 90)
+ const phone = base({ _ts: 100, unit: 'lb', plates: home })
+ const desk = base({ _ts: 200, unit: 'lb', workouts: [workout('w2')], plates: { ...withPlatePairs({ unit: 'lb' }, 25, 2, 20), kg: { 20: 1, _ts: 15 } } })
+ for (const m of [mergeStates(phone, desk), mergeStates(desk, phone)]) {
+ expect(m.plates.lb).toEqual(home.lb)
+ expect(inventoryFor(m).find(p => p.w === 45).n).toBe(1)
+ expect(inventoryFor(m).find(p => p.w === 25).n).toBe(6) // not the desk's 2: one list, not a mix
+ expect(m.plates.kg).toEqual({ 20: 1, _ts: 15 })
+ }
+ })
+
+ it('"Back to the standard set" wins against the other device\'s older list', () => {
+ const own = { unit: 'lb', plates: withPlatePairs({ unit: 'lb' }, 45, 1, 40) }
+ const reset = base({ _ts: 100, unit: 'lb', plates: withStandardPlates(own, 80) })
+ const stale = base({ _ts: 300, unit: 'lb', plates: own.plates })
+ for (const m of [mergeStates(reset, stale), mergeStates(stale, reset)]) {
+ expect(inventoryFor(m)).toEqual(inventoryFor({ unit: 'lb' }))
+ }
+ })
+
+ it('sign-in keeps the server\'s choices and adds what only the device has', () => {
+ const server = base({ _ts: 10, loadKind: withLoadKind({}, SQUAT, 'single', 5), plates: { kg: { 20: 1, _ts: 5 } } })
+ const local = base({ _ts: 90, loadKind: withLoadKind(withLoadKind({}, SQUAT, 'none', 80), 'b', 'single', 80), plates: { kg: { 20: 4, _ts: 80 }, lb: { 45: 2, _ts: 80 } } })
+ const m = mergeStates(server, local, { prefer: 'a' })
+ expect(m.loadKind).toEqual({ [SQUAT]: { kind: 'single', _ts: 5 }, b: { kind: 'single', _ts: 80 } })
+ expect(m.plates).toEqual({ kg: { 20: 1, _ts: 5 }, lb: { 45: 2, _ts: 80 } })
+ expect(mergeStates(base({ _ts: 500 }), base({ _ts: 1 })).plates).toBeUndefined()
+ })
+})
diff --git a/frontend/src/sheets.jsx b/frontend/src/sheets.jsx
index 9f78feadc..bbb321e1c 100644
--- a/frontend/src/sheets.jsx
+++ b/frontend/src/sheets.jsx
@@ -6,7 +6,7 @@ import { activeProfile, exAvailable, ALL_EQUIPMENT, newProfile } from './lib/equ
import { fmtDate, fmtNum, fmtPlate, capWords, fmtVol, fmtDur, durPart, todayISO, isoOf, uid, exCount, routineCount, DAYN, DAYS, weekOrder, weekStartOf, weekDayOffset, MONTHS_LONG, ACCENTS } from './lib/format.js'
import { lastEntryFor, bestWeightFor, bestWeightForEntry, buildSets, effectiveRoutineIds, workoutDay, workoutVolume, setsDone, setsDoneActive, setUnitsTotal, lastBW, supersetUnits, sessionSections, unitOf, setLabel, defaultConfig, cleanupSg, modeOf, effortOf, EFFORT, capEffort, stepEffort, isBw, isPerSide, sideReps, workSetsDone, applyIntensifierPlan, MAX_PLANNED_WARMUPS, NOTE_MAX } from './lib/history.js'
import { usesBar, defaultBarWeight, hasBarOverride, isNoBar } from './lib/bar.js'
-import { PLATE_SIZES, inventoryFor, pairsOf, loadKindFor, baseWeightFor } from './lib/plates.js'
+import { PLATE_SIZES, pairsOf, ownsPlates, withPlatePairs, withStandardPlates, withLoadKind, loadKindFor, baseWeightFor } from './lib/plates.js'
import { toScale, rirOf, EFFORT_PRESETS, effortColor } from './lib/effort.js'
import { beep, vibrate } from './lib/sound.js'
import { t, dateLocale, instrFor, exerciseNameFor, exerciseNameClass, getLang, INSTR_LANGS } from './lib/i18n.js'
@@ -664,10 +664,10 @@ function BarWeightEditor({ ex, cfg, extra }) {
const noBar = bar && isNoBar(st, ex.id)
const def = defaultBarWeight(ex.eq, st.unit)
const base = baseWeightFor(st, ex)
+ // Picking what the equipment already implies puts the exercise back on it (a stamped null,
+ // lib/plates.js), so a later change of the equipment's own default still reaches it.
const setKind = k => update(s => {
- s.loadKind = s.loadKind || {}
- // Picking what the equipment already implies stores nothing.
- if (k === loadKindFor(null, ctx)) delete s.loadKind[ex.id]; else s.loadKind[ex.id] = k
+ s.loadKind = withLoadKind(s.loadKind, ex.id, k === loadKindFor(null, ctx) ? null : k)
})
const setBar = v => update(s => {
s.barWeights = s.barWeights || {}
@@ -722,18 +722,14 @@ export const barWeightSheet = (exId, cfg) => ui().openSheet(close => <BarWeightS
// The plates you own, as pairs per size, for the profile's unit (Settings → Equipment → Plates).
// The first edit copies the standard set into S.plates[unit] and changes one count in it, so the
-// list you see is always the list the set rows load from. "Back to the standard set" drops the
-// unit's entry again.
+// list you see is always the list the set rows load from. "Back to the standard set" empties the
+// unit's list again. Both are stamped (lib/plates.js), so the last change wins a sync.
function PlateInventorySheet({ close }) {
const st = useStore(s => s.S)
const unit = st.unit === 'lb' ? 'lb' : 'kg'
- const own = !!st.plates?.[unit]
- const setPairs = (w, n) => update(s => {
- s.plates = s.plates || {}
- if (!s.plates[unit]) s.plates[unit] = Object.fromEntries(inventoryFor(s).map(p => [p.w, p.n]))
- s.plates[unit][w] = Math.max(0, Math.round(n || 0))
- })
- const reset = () => update(s => { if (s.plates) delete s.plates[unit] })
+ const own = ownsPlates(st)
+ const setPairs = (w, n) => update(s => { s.plates = withPlatePairs(s, w, n) })
+ const reset = () => update(s => { s.plates = withStandardPlates(s) })
return <>
<h3>{t('Plates')}</h3>
<div className="muted small" style={{ marginBottom: 14 }}>
diff --git a/frontend/src/sheets.plates.test.jsx b/frontend/src/sheets.plates.test.jsx
index 6f4dff3a4..de65767e3 100644
--- a/frontend/src/sheets.plates.test.jsx
+++ b/frontend/src/sheets.plates.test.jsx
@@ -1,6 +1,8 @@
// @vitest-environment happy-dom
// The plate-loading editor (barWeightSheet) and the plate inventory sheet write S.loadKind,
-// S.barWeights and S.plates the way lib/plates.js reads them.
+// S.barWeights and S.plates the way lib/plates.js reads them: a load kind and a unit's plate list
+// are stamped with the time they were set, the way back to the default included, so the last
+// change wins a sync (lib/sync-merge.js).
import React, { act } from 'react'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { createRoot } from 'react-dom/client'
@@ -24,6 +26,7 @@ function mountTopSheet() {
return host
}
const S = () => useStore.getState().S
+const stamped = kind => ({ kind, _ts: expect.any(Number) })
const segButton = (host, text) => [...host.querySelectorAll('.seg button')].find(b => b.textContent.trim() === text)
const button = (host, text) => [...host.querySelectorAll('button')].find(b => b.textContent.trim() === text)
// A labelled Stepper is .stp-w > .stp-l (label) + .stp (Decrease, value input, Increase).
@@ -54,7 +57,7 @@ describe('plate loading editor', () => {
const host = mountTopSheet()
expect(segButton(host, 'Off').classList.contains('on')).toBe(true)
act(() => segButton(host, 'Single stack').click())
- expect(S().loadKind[COCOONS]).toBe('single')
+ expect(S().loadKind[COCOONS]).toEqual(stamped('single'))
// Without a config the equipment decides: body weight → single stack by default.
useStore.setState(s => ({ S: { ...s.S, loadKind: {} } }))
act(() => barWeightSheet(COCOONS))
@@ -69,11 +72,14 @@ describe('plate loading editor', () => {
expect(segButton(host, 'Per side').classList.contains('on')).toBe(true)
expect(S().loadKind).toEqual({})
act(() => segButton(host, 'Single stack').click())
- expect(S().loadKind[SQUAT]).toBe('single')
+ expect(S().loadKind[SQUAT]).toEqual(stamped('single'))
act(() => segButton(host, 'Per side').click())
- expect(S().loadKind[SQUAT]).toBeUndefined() // back to what the equipment implies → key dropped
+ // Back to what the equipment implies: a stamped null, not a dropped key, so the way back
+ // wins a sync against the other device's older 'single' instead of losing to it.
+ expect(S().loadKind[SQUAT]).toEqual(stamped(null))
+ expect(segButton(host, 'Per side').classList.contains('on')).toBe(true)
act(() => segButton(host, 'Off').click())
- expect(S().loadKind[SQUAT]).toBe('none')
+ expect(S().loadKind[SQUAT]).toEqual(stamped('none'))
expect(host.textContent).toContain('No plate line under the sets.')
})
@@ -109,7 +115,7 @@ describe('plate loading editor', () => {
const host = mountTopSheet()
expect(segButton(host, 'Off').classList.contains('on')).toBe(true)
act(() => segButton(host, 'Single stack').click())
- expect(S().loadKind[LEG_PRESS]).toBe('single')
+ expect(S().loadKind[LEG_PRESS]).toEqual(stamped('single'))
const st = stepperOf(host, 'Base weight (lb)')
expect(st).toBeTruthy()
expect(host.textContent).not.toContain('No bar')
@@ -141,6 +147,7 @@ describe('plate inventory sheet', () => {
expect(S().plates.lb[45]).toBe(1)
expect(S().plates.lb[35]).toBe(6) // the rest of the standard set came along
expect(S().plates.lb[15]).toBeUndefined()
+ expect(S().plates.lb._ts).toEqual(expect.any(Number))
act(() => inc(stepperOf(host, '15 lb')).click())
expect(S().plates.lb[15]).toBe(1)
expect(valueOf(stepperOf(host, '45 lb'))).toBe('1')
@@ -148,12 +155,22 @@ describe('plate inventory sheet', () => {
expect(host.textContent).toContain('Your own list for lb.')
})
- it('"Back to the standard set" drops the unit\'s own list', () => {
- useStore.setState(s => ({ S: { ...s.S, plates: { lb: { 45: 1 }, kg: { 20: 2 } } } }))
+ it('"Back to the standard set" empties the unit\'s own list, stamped', () => {
+ useStore.setState(s => ({ S: { ...s.S, plates: { lb: { 45: 1, _ts: 5 }, kg: { 20: 2 } } } }))
act(() => plateInventorySheet())
const host = mountTopSheet()
+ expect(valueOf(stepperOf(host, '45 lb'))).toBe('1')
act(() => button(host, 'Back to the standard set').click())
- expect(S().plates).toEqual({ kg: { 20: 2 } })
+ // A list with no sizes, not a deleted unit: the reset has to win a sync against the other
+ // device's older list rather than get it back.
+ expect(S().plates).toEqual({ lb: { _ts: expect.any(Number) }, kg: { 20: 2 } })
+ expect(S().plates.lb._ts).toBeGreaterThan(5)
expect(button(host, 'Back to the standard set')).toBeUndefined()
+ expect(valueOf(stepperOf(host, '45 lb'))).toBe('6')
+ expect(host.textContent).toContain('The standard set, plenty of each')
+ // …and the next change starts from the standard set again.
+ act(() => dec(stepperOf(host, '45 lb')).click())
+ expect(S().plates.lb[45]).toBe(5)
+ expect(S().plates.lb[35]).toBe(6)
})
})
diff --git a/frontend/src/store/useStore.js b/frontend/src/store/useStore.js
index e307aa46c..d98936af1 100644
--- a/frontend/src/store/useStore.js
+++ b/frontend/src/store/useStore.js
@@ -84,14 +84,16 @@ export const DEF = {
// lib/bar.js). Personal equipment, so it syncs with the account but never travels in a
// shared plan. Logged weights stay the total — this only feeds the plate math.
barWeights: {},
- // Plate inventory, per unit: { lb: { 45: 1, 35: 1, … }, kg: { … } } — pairs of each size you
- // own (lib/plates.js). Kept per unit like the bar weight: a 45 lb plate is not a 20.4 kg
- // one, so a unit switch shows the other unit's inventory instead of converting this one.
- // Absent for a unit = the standard set, plenty of each. Display only, like barWeights.
+ // Plate inventory, per unit: { lb: { 45: 1, 35: 1, …, _ts }, kg: { … } } — pairs of each size
+ // you own (lib/plates.js), stamped with when the list was last changed so a sync keeps the
+ // later one (lib/sync-merge.js). Kept per unit: a 45 lb plate is not a 20.4 kg one, so a unit
+ // switch shows the other unit's inventory instead of converting this one. Absent for a unit,
+ // or a list with no sizes = the standard set, plenty of each. Display only, like barWeights.
plates: {},
- // How an exercise is plate-loaded when the equipment does not say: 'pairs' | 'single' |
- // 'none', keyed by exercise id (lib/plates.js loadKindFor). A plate-loaded leg press is
- // 'single'; a barbell you never load plates on is 'none'. Absent = derived from equipment.
+ // How an exercise is plate-loaded when the equipment does not say, keyed by exercise id:
+ // { kind: 'pairs' | 'single' | 'none' | null, _ts } (lib/plates.js loadKindFor). A plate-loaded
+ // leg press is 'single'; a barbell you never load plates on is 'none'. Absent or null = derived
+ // from the equipment. Stamped like the plate list, for the same reason.
loadKind: {},
// Gym check-in cards (see views/CheckIn.jsx). Each is a membership
// code shown as a QR/barcode at the gym's turnstile — added by typing it, importing a photo
diff --git a/frontend/src/views/Settings.jsx b/frontend/src/views/Settings.jsx
index adb374932..aa8d16bd9 100644
--- a/frontend/src/views/Settings.jsx
+++ b/frontend/src/views/Settings.jsx
@@ -7,7 +7,7 @@ import { speedUnitOf } from '../lib/speed.js'
import { copyText } from '../lib/clipboard.js'
import { useUI } from '../store/useUI.js'
import { ACCENTS, todayISO, localTZ, weekStartOf, MONDAY, SUNDAY, fmtPlate } from '../lib/format.js'
-import { inventoryFor } from '../lib/plates.js'
+import { inventoryFor, ownsPlates } from '../lib/plates.js'
import { effortOf } from '../lib/history.js'
import { unlock, playOnSilentSupported, vibrateSupported } from '../lib/sound.js'
import { api, webauthnOK, passkeyRegister, IS_ANDROID } from '../lib/api.js'
@@ -733,9 +733,7 @@ function EquipmentCard({ S, update }) {
}),
})
// The plates you own, per unit (lib/plates.js) — what the set rows' plate lines load from.
- const unit = S.unit === 'lb' ? 'lb' : 'kg'
- const ownPlates = !!S.plates?.[unit]
- const plateSummary = ownPlates
+ const plateSummary = ownsPlates(S)
? inventoryFor(S).map(p => fmtPlate(p.w) + '×' + p.n).join(' · ') || t('None')
: t('Standard set — tap to count the pairs you own.')
return <Section title={t('Equipment')} footer={t('Filters the exercise library and picker, and flags routine exercises that need something you don’t have in the active profile.')}>