Merge main (v1.2.14) in coach-providers
Konflikte: zwoelf Locale-Packs (beide Seiten haengen Strings an, sechs doppelte Schluessel bereinigt), Admin.jsx/admin.css (Coach-Karte bleibt, main-Umbau uebernommen), Workout/Home/Plan/sheets (main gewinnt), docs.html (Coach-Kapitel war doppelt). Ungarisch und Thai sind auf main dazugekommen und bekommen die 334 Coach-Strings. pt-BR-Fingerprint nachgezogen.
This commit is contained in:
commit
63cf1deaed
121 files changed
+17177
-747
No files matched your search
@@ -0,0 +1,44 @@
|
||||
import { supersetUnits, unitOf } from './history.js'
|
||||
|
||||
function hasLoggedSet(entry) {
|
||||
return Array.isArray(entry?.sets) && entry.sets.some(set => set?.done === true)
|
||||
}
|
||||
|
||||
/**
|
||||
* Swap one exact active-workout occurrence.
|
||||
*
|
||||
* Unlogged occurrences are replaced in place. Logged results are never relabelled: after explicit
|
||||
* confirmation, the replacement is inserted beside the original. A logged group member also
|
||||
* requires an explicit choice to keep the replacement in the group or detach it after the group.
|
||||
*/
|
||||
export function swapActiveExercise(active, index, replacement, {
|
||||
loggedConfirmed = false,
|
||||
groupDisposition
|
||||
} = {}) {
|
||||
if (!active || !Array.isArray(active.entries) || !replacement || index < 0 || index >= active.entries.length) return null
|
||||
|
||||
const current = active.entries[index]
|
||||
if (!hasLoggedSet(current)) {
|
||||
const metadata = Object.fromEntries(Object.entries(current).filter(([key]) => (
|
||||
!['id', 'target', 'plan', 'sets', 'sg'].includes(key)
|
||||
)))
|
||||
active.entries[index] = { ...metadata, ...replacement, ...(current.sg ? { sg: current.sg } : {}) }
|
||||
active.cur = index
|
||||
return { inserted: false, index }
|
||||
}
|
||||
|
||||
if (!loggedConfirmed) return { needsConfirmation: true, grouped: !!current.sg, index }
|
||||
if (current.sg && !['keep', 'detach'].includes(groupDisposition)) {
|
||||
return { needsConfirmation: true, grouped: true, index }
|
||||
}
|
||||
|
||||
const unit = unitOf(supersetUnits(active.entries), index)
|
||||
const keepGroup = current.sg && groupDisposition === 'keep'
|
||||
const insertAt = keepGroup ? index + 1 : (unit.length > 1 ? unit.at(-1) + 1 : index + 1)
|
||||
active.entries.splice(insertAt, 0, {
|
||||
...replacement,
|
||||
...(keepGroup ? { sg: current.sg } : {})
|
||||
})
|
||||
active.cur = insertAt
|
||||
return { inserted: true, index: insertAt }
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { swapActiveExercise } from './active-exercise-swap.js'
|
||||
|
||||
const entry = (id, { sg, done = false, target, sets } = {}) => ({
|
||||
id,
|
||||
...(sg ? { sg } : {}),
|
||||
target: target || { mode: 'reps', sets: 1, reps: 5, weight: 40 },
|
||||
sets: sets || [{ w: 40, r: 5, done }]
|
||||
})
|
||||
|
||||
const replacement = () => entry('incline', {
|
||||
target: { mode: 'reps', sets: 2, reps: 8, weight: 32.5, note: 'Keep elbows tucked.', intensifier: { type: 'dropset', count: 1, pct: 20 } },
|
||||
sets: [{ w: 32.5, r: 8, done: false }, { w: 32.5, r: 8, done: false }]
|
||||
})
|
||||
|
||||
describe('safe active exercise swap', () => {
|
||||
it('replaces only the selected duplicate occurrence and preserves its group and replacement metadata', () => {
|
||||
const first = entry('bench', { sg: 'pair' })
|
||||
const selected = entry('bench', { sg: 'pair' })
|
||||
selected.occurrenceId = 'bench#2'
|
||||
selected.provenance = { routineIndex: 4 }
|
||||
const unrelated = entry('row')
|
||||
const active = { cur: 1, entries: [first, selected, unrelated] }
|
||||
const next = replacement()
|
||||
|
||||
expect(swapActiveExercise(active, 1, next)).toEqual({ inserted: false, index: 1 })
|
||||
expect(active.entries.map(value => value.id)).toEqual(['bench', 'incline', 'row'])
|
||||
expect(active.entries[0]).toBe(first)
|
||||
expect(active.entries[2]).toBe(unrelated)
|
||||
expect(active.entries[1]).toEqual({
|
||||
...next,
|
||||
occurrenceId: 'bench#2',
|
||||
provenance: { routineIndex: 4 },
|
||||
sg: 'pair'
|
||||
})
|
||||
expect(active.cur).toBe(1)
|
||||
})
|
||||
|
||||
it('fails closed before a logged standalone occurrence is explicitly confirmed', () => {
|
||||
const logged = entry('bench', { sets: [{ w: 42.5, r: 7, done: true, rir: 1 }] })
|
||||
const active = { cur: 0, entries: [logged, entry('row')] }
|
||||
|
||||
expect(swapActiveExercise(active, 0, replacement())).toEqual({ needsConfirmation: true, grouped: false, index: 0 })
|
||||
expect(active.entries).toEqual([logged, active.entries[1]])
|
||||
expect(active.cur).toBe(0)
|
||||
})
|
||||
|
||||
it('preserves a confirmed logged occurrence and inserts the replacement after it', () => {
|
||||
const logged = entry('bench', { sets: [{ w: 42.5, r: 7, done: true, rir: 1 }] })
|
||||
const unrelated = entry('row')
|
||||
const active = { cur: 0, entries: [logged, unrelated] }
|
||||
|
||||
expect(swapActiveExercise(active, 0, replacement(), { loggedConfirmed: true })).toEqual({ inserted: true, index: 1 })
|
||||
expect(active.entries[0]).toBe(logged)
|
||||
expect(active.entries[0].sets[0]).toEqual({ w: 42.5, r: 7, done: true, rir: 1 })
|
||||
expect(active.entries[1].id).toBe('incline')
|
||||
expect(active.entries[2]).toBe(unrelated)
|
||||
expect(active.cur).toBe(1)
|
||||
})
|
||||
|
||||
it('requires an explicit grouped disposition before changing a logged group member', () => {
|
||||
const active = { cur: 0, entries: [entry('bench', { sg: 'pair', done: true }), entry('row', { sg: 'pair' }), entry('curl')] }
|
||||
const before = [...active.entries]
|
||||
|
||||
expect(swapActiveExercise(active, 0, replacement(), { loggedConfirmed: true }))
|
||||
.toEqual({ needsConfirmation: true, grouped: true, index: 0 })
|
||||
expect(active.entries).toEqual(before)
|
||||
})
|
||||
|
||||
it.each([
|
||||
['keep', ['bench', 'incline', 'row', 'curl'], ['pair', 'pair', 'pair', undefined], 1],
|
||||
['detach', ['bench', 'row', 'incline', 'curl'], ['pair', 'pair', undefined, undefined], 2]
|
||||
])('%s confirmation preserves logged group data and unrelated entries', (groupDisposition, ids, groups, cursor) => {
|
||||
const logged = entry('bench', { sg: 'pair', sets: [{ w: 45, r: 6, done: true }] })
|
||||
const partner = entry('row', { sg: 'pair' })
|
||||
const unrelated = entry('curl')
|
||||
const active = { cur: 0, entries: [logged, partner, unrelated] }
|
||||
|
||||
expect(swapActiveExercise(active, 0, replacement(), { loggedConfirmed: true, groupDisposition }))
|
||||
.toEqual({ inserted: true, index: cursor })
|
||||
expect(active.entries.map(value => value.id)).toEqual(ids)
|
||||
expect(active.entries.map(value => value.sg)).toEqual(groups)
|
||||
expect(active.entries[0]).toBe(logged)
|
||||
expect(active.entries.includes(partner)).toBe(true)
|
||||
expect(active.entries.at(-1)).toBe(unrelated)
|
||||
expect(active.cur).toBe(cursor)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,31 @@
|
||||
import { supersetUnits } from './history.js'
|
||||
|
||||
function moveTarget(active, index, direction) {
|
||||
if (!active || !Array.isArray(active.entries) || (direction !== -1 && direction !== 1)) return null
|
||||
const units = supersetUnits(active.entries)
|
||||
const source = units.findIndex(unit => unit.includes(index))
|
||||
const target = source + direction
|
||||
if (source < 0 || target < 0 || target >= units.length) return null
|
||||
return { units, source, target }
|
||||
}
|
||||
|
||||
export function canMoveActiveWorkoutUnit(active, index, direction) {
|
||||
return moveTarget(active, index, direction) !== null
|
||||
}
|
||||
|
||||
export function moveActiveWorkoutUnit(active, index, direction) {
|
||||
const move = moveTarget(active, index, direction)
|
||||
if (!move) return null
|
||||
|
||||
const selected = active.entries[index]
|
||||
const reorderedUnits = [...move.units]
|
||||
const sourceUnit = reorderedUnits[move.source]
|
||||
reorderedUnits[move.source] = reorderedUnits[move.target]
|
||||
reorderedUnits[move.target] = sourceUnit
|
||||
const indices = reorderedUnits.flat()
|
||||
const reorderedEntries = indices.map(entryIndex => active.entries[entryIndex])
|
||||
|
||||
active.entries.splice(0, active.entries.length, ...reorderedEntries)
|
||||
active.cur = active.entries.indexOf(selected)
|
||||
return { indices }
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { canMoveActiveWorkoutUnit, moveActiveWorkoutUnit } from './active-workout-order.js'
|
||||
import { LANGS } from './i18n-core.js'
|
||||
import { PT_BR_OVERRIDES } from '../locales/pt-BR.js'
|
||||
|
||||
const entry = (id, extra = {}) => ({
|
||||
id,
|
||||
target: { sets: 1, reps: 5 },
|
||||
sets: [{ w: 0, r: 5, done: false }],
|
||||
...extra,
|
||||
})
|
||||
|
||||
describe('active workout whole-unit order', () => {
|
||||
it('moves one standalone occurrence without conflating duplicate exercise ids', () => {
|
||||
const duplicateA = entry('duplicate', { occurrenceId: 'duplicate#1' })
|
||||
const selected = entry('duplicate', {
|
||||
occurrenceId: 'duplicate#2',
|
||||
target: { sets: 2, reps: 7, weight: 82.5, notes: 'Keep this target' },
|
||||
sets: [{ w: 77.5, r: 6, done: true, rir: 2 }],
|
||||
})
|
||||
const active = { cur: 2, entries: [duplicateA, entry('middle'), selected] }
|
||||
|
||||
expect(moveActiveWorkoutUnit(active, active.cur, -1)?.indices).toEqual([0, 2, 1])
|
||||
expect(active.entries.map(item => item.occurrenceId || item.id)).toEqual(['duplicate#1', 'duplicate#2', 'middle'])
|
||||
expect(active.entries[0]).toBe(duplicateA)
|
||||
expect(active.entries[1]).toBe(selected)
|
||||
expect(active.entries[1].target).toBe(selected.target)
|
||||
expect(active.entries[1].sets).toBe(selected.sets)
|
||||
expect(active.cur).toBe(1)
|
||||
})
|
||||
|
||||
it('moves a complete contiguous group one unit and preserves the selected member identity', () => {
|
||||
const first = entry('group-a', { sg: 'pair', occurrenceId: 'group-a#1' })
|
||||
const selected = entry('group-b', { sg: 'pair', occurrenceId: 'group-b#1' })
|
||||
const groupMeta = { pair: { kind: 'complex', label: 'Carry pair', cues: 'Stay braced.' } }
|
||||
const active = { cur: 2, entries: [entry('before'), first, selected, entry('after')], groupMeta }
|
||||
|
||||
expect(moveActiveWorkoutUnit(active, active.cur, -1)?.indices).toEqual([1, 2, 0, 3])
|
||||
expect(active.entries.map(item => item.id)).toEqual(['group-a', 'group-b', 'before', 'after'])
|
||||
expect(active.entries.slice(0, 2)).toEqual([first, selected])
|
||||
expect(active.entries.map(item => item.sg)).toEqual(['pair', 'pair', undefined, undefined])
|
||||
expect(active.groupMeta).toBe(groupMeta)
|
||||
expect(active.entries[active.cur]).toBe(selected)
|
||||
})
|
||||
|
||||
it('moves a group down by exactly one neighbouring unit', () => {
|
||||
const first = entry('group-a', { sg: 'pair' })
|
||||
const selected = entry('group-b', { sg: 'pair' })
|
||||
const active = { cur: 1, entries: [first, selected, entry('middle'), entry('last')] }
|
||||
|
||||
expect(moveActiveWorkoutUnit(active, active.cur, 1)?.indices).toEqual([2, 0, 1, 3])
|
||||
expect(active.entries.map(item => item.id)).toEqual(['middle', 'group-a', 'group-b', 'last'])
|
||||
expect(active.entries[active.cur]).toBe(selected)
|
||||
})
|
||||
|
||||
it('rejects boundaries and invalid directions without mutating the active workout', () => {
|
||||
const active = { cur: 0, entries: [entry('first'), entry('last')] }
|
||||
const entries = [...active.entries]
|
||||
|
||||
expect(canMoveActiveWorkoutUnit(active, 0, -1)).toBe(false)
|
||||
expect(canMoveActiveWorkoutUnit(active, 1, 1)).toBe(false)
|
||||
expect(moveActiveWorkoutUnit(active, 0, 0)).toBeNull()
|
||||
expect(moveActiveWorkoutUnit(active, 0, -1)).toBeNull()
|
||||
expect(active.entries).toEqual(entries)
|
||||
expect(active.cur).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('active workout move locale coverage', () => {
|
||||
const packs = import.meta.glob('../locales/*.js', { eager: true, import: 'default' })
|
||||
const localeCodes = Object.keys(LANGS).filter(code => code !== 'en')
|
||||
|
||||
it('defines both visible move labels in every current locale pack', () => {
|
||||
expect(Object.keys(packs)).toHaveLength(localeCodes.length)
|
||||
for (const code of localeCodes) {
|
||||
const pack = packs[`../locales/${code}.js`]
|
||||
expect(pack, `${code} locale pack is missing`).toBeTruthy()
|
||||
for (const key of ['Move up', 'Move down']) {
|
||||
expect(Object.hasOwn(pack, key), `${code} is missing ${key}`).toBe(true)
|
||||
expect(pack[key], `${code} has a blank ${key}`).toEqual(expect.any(String))
|
||||
expect(pack[key].trim(), `${code} has a blank ${key}`).not.toBe('')
|
||||
}
|
||||
}
|
||||
expect(Object.hasOwn(PT_BR_OVERRIDES, 'Move up')).toBe(true)
|
||||
expect(Object.hasOwn(PT_BR_OVERRIDES, 'Move down')).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,39 @@
|
||||
// Logging a workout after the fact. The session itself is the ordinary active workout with a
|
||||
// `backfill` field on it; these helpers are the parts that differ from a live session, kept
|
||||
// pure so the date arithmetic and the history surgery can be tested without the UI.
|
||||
|
||||
export const workoutsOn = (S, iso) => (S.workouts || []).filter(w => w.d === iso)
|
||||
|
||||
// Epoch of `iso` at the given wall-clock time, in the browser's zone — the same zone
|
||||
// todayISO() and isoOf() use, so `d` and `start` agree the way they do for a live session.
|
||||
export const backfillStart = (iso, time = '18:00') => {
|
||||
const [h, m] = String(time || '18:00').split(':').map(Number)
|
||||
const d = new Date(iso + 'T12:00:00')
|
||||
d.setHours(h || 0, m || 0, 0, 0)
|
||||
return d.getTime()
|
||||
}
|
||||
|
||||
// A live session ends when you tap finish; a logged one ends when you said it did.
|
||||
export const backfillEnd = active => active.start + Math.max(1, active.backfill?.durationMin || 60) * 60000
|
||||
|
||||
// The workouts array is chronological (History reverses it), so a past workout cannot just be
|
||||
// pushed — it goes where its date and start time put it, after anything from the same moment.
|
||||
export function insertChronological(workouts, w) {
|
||||
const key = x => [x.d || '', x.start || 0]
|
||||
const [d, s] = key(w)
|
||||
let i = workouts.length
|
||||
while (i > 0) {
|
||||
const [pd, ps] = key(workouts[i - 1])
|
||||
if (pd < d || (pd === d && ps <= s)) break
|
||||
i--
|
||||
}
|
||||
return [...workouts.slice(0, i), w, ...workouts.slice(i)]
|
||||
}
|
||||
|
||||
// The history after a backfilled session is filed: the workout it replaces (if any) is gone
|
||||
// and the new one sits in date order. Returns a new array; the caller stores it.
|
||||
export function completeBackfill(workouts, active, w) {
|
||||
const replaceId = active.backfill?.replaceId
|
||||
const kept = replaceId ? workouts.filter(x => x.id !== replaceId) : workouts
|
||||
return insertChronological(kept, w)
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { workoutsOn, backfillStart, backfillEnd, insertChronological, completeBackfill } from './backfill.js'
|
||||
|
||||
const w = (id, d, start = 0) => ({ id, d, start })
|
||||
|
||||
describe('workoutsOn', () => {
|
||||
it('returns every workout of that day and nothing else', () => {
|
||||
const S = { workouts: [w('a', '2026-01-01'), w('b', '2026-01-02'), w('c', '2026-01-02')] }
|
||||
expect(workoutsOn(S, '2026-01-02').map(x => x.id)).toEqual(['b', 'c'])
|
||||
expect(workoutsOn(S, '2026-01-03')).toEqual([])
|
||||
expect(workoutsOn({}, '2026-01-03')).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('backfillStart / backfillEnd', () => {
|
||||
it('lands on the chosen day at the chosen time in local zone', () => {
|
||||
const t = new Date(backfillStart('2026-03-10', '07:45'))
|
||||
expect([t.getFullYear(), t.getMonth() + 1, t.getDate(), t.getHours(), t.getMinutes()]).toEqual([2026, 3, 10, 7, 45])
|
||||
})
|
||||
it('defaults to 18:00 and ends after the given duration', () => {
|
||||
const start = backfillStart('2026-03-10')
|
||||
expect(new Date(start).getHours()).toBe(18)
|
||||
expect(backfillEnd({ start, backfill: { durationMin: 45 } })).toBe(start + 45 * 60000)
|
||||
expect(backfillEnd({ start, backfill: {} })).toBe(start + 60 * 60000)
|
||||
expect(backfillEnd({ start, backfill: { durationMin: 0 } })).toBe(start + 60 * 60000)
|
||||
})
|
||||
})
|
||||
|
||||
describe('insertChronological', () => {
|
||||
const list = [w('a', '2026-01-01', 10), w('b', '2026-01-05', 10), w('c', '2026-01-05', 20), w('d', '2026-01-09', 10)]
|
||||
it('places by date, then by start time, after equal keys', () => {
|
||||
expect(insertChronological(list, w('x', '2026-01-03')).map(x => x.id)).toEqual(['a', 'x', 'b', 'c', 'd'])
|
||||
expect(insertChronological(list, w('x', '2026-01-05', 15)).map(x => x.id)).toEqual(['a', 'b', 'x', 'c', 'd'])
|
||||
expect(insertChronological(list, w('x', '2026-01-05', 20)).map(x => x.id)).toEqual(['a', 'b', 'c', 'x', 'd'])
|
||||
})
|
||||
it('appends at the end and inserts at the front', () => {
|
||||
expect(insertChronological(list, w('x', '2026-02-01')).at(-1).id).toBe('x')
|
||||
expect(insertChronological(list, w('x', '2025-12-31'))[0].id).toBe('x')
|
||||
expect(insertChronological([], w('x', '2026-01-01')).map(x => x.id)).toEqual(['x'])
|
||||
})
|
||||
it('does not mutate the input', () => {
|
||||
const copy = [...list]
|
||||
insertChronological(list, w('x', '2026-01-03'))
|
||||
expect(list).toEqual(copy)
|
||||
})
|
||||
})
|
||||
|
||||
describe('completeBackfill', () => {
|
||||
const list = [w('a', '2026-01-01', 10), w('b', '2026-01-05', 10), w('d', '2026-01-09', 10)]
|
||||
it('adds a second workout on a day in order', () => {
|
||||
const out = completeBackfill(list, { backfill: { durationMin: 60, replaceId: null } }, w('x', '2026-01-05', 5))
|
||||
expect(out.map(x => x.id)).toEqual(['a', 'x', 'b', 'd'])
|
||||
})
|
||||
it('replaces the chosen workout', () => {
|
||||
const out = completeBackfill(list, { backfill: { durationMin: 60, replaceId: 'b' } }, w('x', '2026-01-05', 30))
|
||||
expect(out.map(x => x.id)).toEqual(['a', 'x', 'd'])
|
||||
expect(list).toHaveLength(3)
|
||||
})
|
||||
})
|
||||
@@ -7,7 +7,7 @@
|
||||
// RIR is the internal unit because it has a real zero — a set taken to failure — where RPE's
|
||||
// floor of 6 is only a convention about which sets are worth rating. RPE 8 == RIR 2.
|
||||
import { EFFORT, effortOf } from './history.js'
|
||||
import { weekKey } from './format.js'
|
||||
import { weekKey, weekStartOf, startOfWeek } from './format.js'
|
||||
import { isWarmupRow } from './workout-model.js'
|
||||
|
||||
// At or below this a set is close enough to failure to be the kind that drives adaptation.
|
||||
@@ -95,12 +95,13 @@ export function hasEffort(S) {
|
||||
* drawn — one tap should not become a peak in the curve.
|
||||
*/
|
||||
export function effortWeeks(S, days) {
|
||||
const ws = weekStartOf(S)
|
||||
const wk = new Map()
|
||||
eachDoneSet(S, (s, w) => {
|
||||
if (!inWindow(w, days)) return
|
||||
const k = weekKey(w.d)
|
||||
const k = weekKey(w.d, ws)
|
||||
let e = wk.get(k)
|
||||
if (!e) wk.set(k, e = { k, t: mondayOf(w.d), sum: 0, n: 0, sets: 0 })
|
||||
if (!e) wk.set(k, e = { k, t: startOfWeek(w.d, ws).getTime(), sum: 0, n: 0, sets: 0 })
|
||||
e.sets++
|
||||
const r = rirOf(s)
|
||||
if (r != null) { e.sum += r; e.n++ }
|
||||
@@ -108,13 +109,6 @@ export function effortWeeks(S, days) {
|
||||
return [...wk.values()].filter(e => e.n >= 2).sort((a, b) => a.t - b.t)
|
||||
.map(e => ({ t: e.t, rir: e.sum / e.n, n: e.n, sets: e.sets }))
|
||||
}
|
||||
// The Monday of an ISO date, as ms — the x position a week's point sits at.
|
||||
function mondayOf(iso) {
|
||||
const d = new Date(iso + 'T12:00:00')
|
||||
d.setDate(d.getDate() - ((d.getDay() + 6) % 7))
|
||||
d.setHours(12, 0, 0, 0)
|
||||
return +d
|
||||
}
|
||||
|
||||
/**
|
||||
* How the rated sets spread across the scale, in whole steps with everything past the top
|
||||
|
||||
@@ -35,6 +35,7 @@ export function buildCompletedWorkout(active, { end = Date.now(), prs = [], snap
|
||||
bw: active.bw,
|
||||
entries,
|
||||
prs,
|
||||
...(active.excludeFromProgression === true ? { excludeFromProgression: true } : {}),
|
||||
...(sessionNote ? { note: sessionNote } : {}),
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,18 @@ describe('completed workout boundary', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('persists progression exclusion only for a marked session', () => {
|
||||
const active = {
|
||||
id: 'active-1', d: '2026-08-08', start: 1000, routineId: 'routine-1', name: 'Deload', bw: 80,
|
||||
excludeFromProgression: true,
|
||||
entries: [{ id: '0025', sets: [{ done: true, w: 30, r: 8 }], target: { sets: 1, reps: 8 } }],
|
||||
}
|
||||
expect(buildCompletedWorkout(active, { end: 2000 }).excludeFromProgression).toBe(true)
|
||||
|
||||
const { excludeFromProgression, ...regular } = active
|
||||
expect(buildCompletedWorkout(regular, { end: 2000 })).not.toHaveProperty('excludeFromProgression')
|
||||
})
|
||||
|
||||
it('persists a muscle snapshot only when the caller supplies one', () => {
|
||||
const active = {
|
||||
id: 'active-1', d: '2026-08-08', start: 1000,
|
||||
|
||||
@@ -34,15 +34,41 @@ export const fmtVol = (v, unit) => fmtNum(v) + ' ' + unit
|
||||
// Plural forms are not automatic when the English string is the key.
|
||||
export const exCount = n => t(n === 1 ? '{0} exercise' : '{0} exercises', n)
|
||||
|
||||
export function weekKey(d) {
|
||||
const dt = new Date(d + 'T12:00:00')
|
||||
const day = (dt.getDay() + 6) % 7
|
||||
dt.setDate(dt.getDate() - day + 3)
|
||||
const jan4 = new Date(dt.getFullYear(), 0, 4)
|
||||
const week = 1 + Math.round(((dt - jan4) / 86400000 - 3 + ((jan4.getDay() + 6) % 7)) / 7)
|
||||
return dt.getFullYear() + '-' + week
|
||||
/* ---------------------------------------------------------------- week start --
|
||||
Where a week begins is a local convention, not a fact: most of Europe starts on
|
||||
Monday, most of the Americas and much of Asia on Sunday. The app used to assume
|
||||
Monday everywhere — the Plan list, the Home strip, the calendar grid and every
|
||||
"this week" total. It is now S.weekStart, a getDay() index, and every one of those
|
||||
places asks these helpers instead of writing the assumption down again.
|
||||
|
||||
Only 1 and 0 are offered in the UI, but the helpers work for any weekday, so a
|
||||
Saturday start (parts of the Middle East) would need a locale string and nothing
|
||||
else. */
|
||||
export const MONDAY = 1
|
||||
export const SUNDAY = 0
|
||||
/** The profile's first weekday, defaulting to Monday for every state written before this. */
|
||||
export const weekStartOf = S => (S?.weekStart === SUNDAY ? SUNDAY : MONDAY)
|
||||
/** getDay() indices in display order — [1..6,0] for a Monday start, [0..6] for a Sunday one. */
|
||||
export const weekOrder = (ws = MONDAY) => Array.from({ length: 7 }, (_, i) => (ws + i) % 7)
|
||||
/** How many days a weekday sits past the start of its week. 0..6, so it doubles as a column. */
|
||||
export const weekDayOffset = (day, ws = MONDAY) => (day - ws + 7) % 7
|
||||
|
||||
/** The Date (noon local, so DST cannot shift the day) that starts the week `iso` falls in. */
|
||||
export function startOfWeek(iso, ws = MONDAY) {
|
||||
const d = new Date(iso + 'T12:00:00')
|
||||
d.setDate(d.getDate() - weekDayOffset(d.getDay(), ws))
|
||||
return d
|
||||
}
|
||||
|
||||
/**
|
||||
* A key that is equal for two dates in the same week: the ISO date of the week's first day.
|
||||
*
|
||||
* Only ever compared or used as a map key — never shown, never stored — so it does not need
|
||||
* to be an ISO week number, and being one would be a liability here: "2026-35" is defined
|
||||
* Monday-first, and there is no Sunday-first equivalent to fall back to.
|
||||
*/
|
||||
export const weekKey = (iso, ws = MONDAY) => isoOf(startOfWeek(iso, ws))
|
||||
|
||||
export const localTZ = () => { try { return Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC' } catch { return 'UTC' } }
|
||||
|
||||
export const uid = () => Date.now().toString(36) + Math.random().toString(36).slice(2, 7)
|
||||
|
||||
@@ -0,0 +1,576 @@
|
||||
// AUTO-GENERATED by scripts/build-hevy-id-map.mjs — do not edit by hand.
|
||||
// Hevy exercise_template id → openGym catalogue id, plus English title → id for CSV exports
|
||||
// (Hevy CSV has titles, not template ids). Regenerated from the Hevy templates API +
|
||||
// verified title aliases. Five title aliases whose catalogue match was wrong (crunch → weighted
|
||||
// crunch, side plank → hip adduction, machine squat → barbell squat, cable triceps extension and
|
||||
// cable reverse fly → lever machines) are left out; those titles import as custom exercises.
|
||||
// 283 mapped · 168 left unmatched (import as custom).
|
||||
// Source templates: 451 (built-in only).
|
||||
|
||||
export const HEVY_ID_MAP = {
|
||||
"018ADC12": "3017",
|
||||
"01A35BF9": "2404",
|
||||
"023943F1": "0572",
|
||||
"026FD047": "0407",
|
||||
"0393F233": "0218",
|
||||
"040BA2E3": "2612",
|
||||
"046E25A2": "0673",
|
||||
"0482DA98": "0826",
|
||||
"05293BCA": "3142",
|
||||
"059E835D": "0603",
|
||||
"062AB91A": "0594",
|
||||
"06745E58": "1372",
|
||||
"073032BB": "1457",
|
||||
"07B38369": "0314",
|
||||
"084A67CA": "0128",
|
||||
"08590920": "0472",
|
||||
"08A2974E": "0606",
|
||||
"091737FA": "0573",
|
||||
"09C9F635": "0865",
|
||||
"0B4C1902": "0294",
|
||||
"0B841777": "0095",
|
||||
"0B9B92BA": "0085",
|
||||
"0EB695C9": "2611",
|
||||
"0F24286A": "0099",
|
||||
"0FBF7195": "0748",
|
||||
"1006DF48": "0401",
|
||||
"10313AFD": "0550",
|
||||
"10347BAC": "0591",
|
||||
"10D76E8F": "1273",
|
||||
"112FC6B7": "0080",
|
||||
"11A123F3": "0586",
|
||||
"12017185": "0308",
|
||||
"123EE239": "0439",
|
||||
"1283BBA6": "0043",
|
||||
"150E076B": "3655",
|
||||
"18487FA7": "0301",
|
||||
"19372ABC": "0662",
|
||||
"19A38071": "0604",
|
||||
"1B2B1E7C": "0652",
|
||||
"1B89CA1B": "0521",
|
||||
"1D4B3D6B": "0313",
|
||||
"1DF4A847": "1350",
|
||||
"1E42FD5F": "0743",
|
||||
"1E9A6B8E": "0592",
|
||||
"20870ED5": "0752",
|
||||
"20C1A3CB": "0809",
|
||||
"21310F5F": "0607",
|
||||
"218DA87C": "0803",
|
||||
"22578A94": "0168",
|
||||
"234897AB": "0165",
|
||||
"23A48484": "0175",
|
||||
"23E92538": "0292",
|
||||
"243710DE": "3666",
|
||||
"286C1D0B": "0246",
|
||||
"28BB4A95": "0591",
|
||||
"29083183": "1326",
|
||||
"29472BE1": "0251",
|
||||
"2982AA23": "0687",
|
||||
"2A48E443": "0116",
|
||||
"2B4B7310": "0085",
|
||||
"2C37EC5E": "0017",
|
||||
"2CFED196": "0069",
|
||||
"2F8D3067": "0607",
|
||||
"2FA77B28": "0459",
|
||||
"3092FADD": "0607",
|
||||
"32B0B590": "0507",
|
||||
"32C4D4A2": "0298",
|
||||
"32HKJ34K": "1460",
|
||||
"3303376C": "2141",
|
||||
"33EDD7DB": "1460",
|
||||
"35B51B87": "0030",
|
||||
"3601968B": "0289",
|
||||
"36E8F14E": "0165",
|
||||
"3765684D": "0607",
|
||||
"37FCC2BB": "0294",
|
||||
"392887AA": "0662",
|
||||
"39C99849": "0493",
|
||||
"3A6FA3D1": "0757",
|
||||
"3D0C7C75": "1760",
|
||||
"3F5F8D40": "3142",
|
||||
"3FF6A22E": "0544",
|
||||
"40C6A9FC": "0127",
|
||||
"4180C405": "0044",
|
||||
"422B08F1": "0334",
|
||||
"425805F4": "0499",
|
||||
"43573BB8": "0003",
|
||||
"4377A52B": "2311",
|
||||
"4377A52C": "2311",
|
||||
"473CF5B8": "0673",
|
||||
"47B036EF": "0978",
|
||||
"49C922A1": "1409",
|
||||
"4B4BF8C2": "0019",
|
||||
"4E5257DE": "2616",
|
||||
"4F5866F8": "0573",
|
||||
"4F942934": "0070",
|
||||
"5046D0A9": "0042",
|
||||
"50C613D0": "2133",
|
||||
"50DFDFAB": "0047",
|
||||
"5122E7D9": "1451",
|
||||
"51A0EDAA": "0677",
|
||||
"542F3CD5": "1700",
|
||||
"55E6546F": "0027",
|
||||
"56808FD2": "0970",
|
||||
"582ADA23": "1636",
|
||||
"5E10D0E6": "3142",
|
||||
"5E1A7777": "0054",
|
||||
"5F4E6DD3": "0300",
|
||||
"5F8903BF": "0551",
|
||||
"6120CAAB": "0795",
|
||||
"6182EE83": "0607",
|
||||
"651F844C": "1269",
|
||||
"6575F52D": "0283",
|
||||
"6622E5A0": "3142",
|
||||
"67280085": "0375",
|
||||
"68B83EE0": "3193",
|
||||
"68F8A292": "0060",
|
||||
"6A6C31A5": "2330",
|
||||
"6AC96645": "0405",
|
||||
"6DA40660": "0417",
|
||||
"6E6EE645": "0054",
|
||||
"6FCD7755": "0251",
|
||||
"70D4EBBF": "0514",
|
||||
"72297E8C": "5201",
|
||||
"724CDE60": "0297",
|
||||
"729237D1": "0652",
|
||||
"72CFFAD5": "1459",
|
||||
"74103F24": "0052",
|
||||
"742E5BD5": "0767",
|
||||
"75A4F6C4": "0585",
|
||||
"78683336": "0596",
|
||||
"7952B5CD": "0872",
|
||||
"796E8E2C": "0834",
|
||||
"797F0782": "0437",
|
||||
"79D0BB3A": "0025",
|
||||
"7AB9A362": "0120",
|
||||
"7B8D84E8": "0091",
|
||||
"7C0028C3": "0593",
|
||||
"7C50F118": "1429",
|
||||
"7E3BC8B6": "0312",
|
||||
"7EB3F7C3": "0577",
|
||||
"818BA121": "0078",
|
||||
"8293E554": "0310",
|
||||
"875F585F": "0060",
|
||||
"878CD1D0": "0405",
|
||||
"89304423": "0529",
|
||||
"8A2E6481": "0180",
|
||||
"8BAB2735": "0318",
|
||||
"8BEBFED6": "0598",
|
||||
"8C331CD8": "0196",
|
||||
"8C9D2928": "1494",
|
||||
"90427D4A": "1675",
|
||||
"90B04F96": "0471",
|
||||
"90E506D5": "3305",
|
||||
"91237BDD": "2289",
|
||||
"914F3A96": "0327",
|
||||
"91AF29E0": "0091",
|
||||
"9237BAD1": "0603",
|
||||
"923874CA": "0562",
|
||||
"9273BA17": "0237",
|
||||
"9283BABA": "0858",
|
||||
"92D858EA": "0243",
|
||||
"9372FFAA": "0396",
|
||||
"93A552C6": "0241",
|
||||
"947DAC23": "0259",
|
||||
"95F2E076": "1426",
|
||||
"9694DA61": "3543",
|
||||
"98237BA2": "0826",
|
||||
"991833C2": "3220",
|
||||
"9930DF71": "0091",
|
||||
"99507114": "0032",
|
||||
"99B49684": "3663",
|
||||
"99C1F2AD": "0151",
|
||||
"99D5F10E": "0857",
|
||||
"9B13BA4B": "0548",
|
||||
"9DCE2D64": "0596",
|
||||
"9F48F858": "0206",
|
||||
"9F9C164B": "0631",
|
||||
"A01BE509": "0443",
|
||||
"A05C064D": "0573",
|
||||
"A0D8FA1B": "2271",
|
||||
"A127DA73": "0534",
|
||||
"A2D838BD": "0243",
|
||||
"A41C7261": "0972",
|
||||
"A57D38D5": "0815",
|
||||
"A5AC6449": "0031",
|
||||
"A69FF221": "2137",
|
||||
"A733CC5B": "1460",
|
||||
"A8814C06": "1003",
|
||||
"AA1EB7D8": "0571",
|
||||
"AA52E8D2": "0773",
|
||||
"ABB00838": "0028",
|
||||
"ABEC557F": "0406",
|
||||
"AC5A4C58": "0046",
|
||||
"ADA8623C": "0868",
|
||||
"AF328E3D": "0575",
|
||||
"B05C2C29": "0605",
|
||||
"B09A1304": "0766",
|
||||
"B123DD01": "2285",
|
||||
"B2398CD1": "0277",
|
||||
"B3B1D947": "3360",
|
||||
"B537D09F": "0336",
|
||||
"B582299E": "0383",
|
||||
"B5D3A742": "0410",
|
||||
"B5EFBF9C": "0194",
|
||||
"B74A95BB": "3211",
|
||||
"B8127AD1": "0586",
|
||||
"B82D6418": "0043",
|
||||
"B923B230": "0811",
|
||||
"BB792A36": "1160",
|
||||
"BB83BDDE": "0687",
|
||||
"BC10A922": "0277",
|
||||
"BD4E7E53": "0535",
|
||||
"BD86EFD5": "0041",
|
||||
"BE289E45": "0178",
|
||||
"BE640BA0": "0203",
|
||||
"BF6ECE89": "0431",
|
||||
"C315DC2A": "0602",
|
||||
"C43825EA": "0279",
|
||||
"C469EA70": "0597",
|
||||
"C6272009": "0032",
|
||||
"C628D768": "0648",
|
||||
"C6C9B8A0": "2135",
|
||||
"C7973E0E": "0739",
|
||||
"C7AE420A": "0688",
|
||||
"C8706C80": "0624",
|
||||
"CC35A01F": "0043",
|
||||
"CC55119B": "0979",
|
||||
"CD6DC8E5": "0830",
|
||||
"D04AC939": "0043",
|
||||
"D20D7BBE": "0117",
|
||||
"D23C609B": "0572",
|
||||
"D2FE7B2E": "2330",
|
||||
"D3095577": "0028",
|
||||
"D3E2AB55": "0319",
|
||||
"D4A2FE7E": "2143",
|
||||
"D53F2886": "0065",
|
||||
"D5D0354D": "0584",
|
||||
"D8281C62": "0602",
|
||||
"D82EA543": "0983",
|
||||
"D8460FA6": "0385",
|
||||
"D8911FC4": "0276",
|
||||
"D8F7F851": "2331",
|
||||
"D928C232": "0832",
|
||||
"D950429E": "0038",
|
||||
"DA0F0470": "0033",
|
||||
"DBB91A3C": "0162",
|
||||
"DBE341AA": "1495",
|
||||
"DBF9273A": "0310",
|
||||
"DCF3B31B": "0832",
|
||||
"DCFF3E9F": "0413",
|
||||
"DDCC3821": "0770",
|
||||
"DE68C825": "0192",
|
||||
"DF200976": "0977",
|
||||
"E05C2C38": "0605",
|
||||
"E3EDA509": "1775",
|
||||
"E53CCBE5": "1372",
|
||||
"E5988A0A": "0383",
|
||||
"E644F828": "1258",
|
||||
"E9E4089F": "0009",
|
||||
"EA820646": "0027",
|
||||
"EAC7D9C5": "3124",
|
||||
"EB43ADD4": "1452",
|
||||
"EB813C91": "1359",
|
||||
"F1258206": "1004",
|
||||
"F1D60854": "0218",
|
||||
"F1E57334": "0292",
|
||||
"F2A37357": "1410",
|
||||
"F30A4F01": "1460",
|
||||
"F3717B0E": "3888",
|
||||
"F49E31D6": "0630",
|
||||
"F4B4C6EE": "0597",
|
||||
"F5DEF1EB": "1489",
|
||||
"F8356514": "0472",
|
||||
"F8A0FCCA": "0549",
|
||||
"F99C211D": "0535",
|
||||
"FAB6EB2F": "0372",
|
||||
"FAF31231": "0033",
|
||||
"FB09C938": "0067",
|
||||
"FBF92739": "1299",
|
||||
"FE389074": "0074",
|
||||
"FFABC123": "0220",
|
||||
"FFC106CB": "0753",
|
||||
"FFDA283B": "0381",
|
||||
}
|
||||
|
||||
/** Lowercased Hevy English title → catalogue id (CSV / name path). */
|
||||
export const HEVY_TITLE_MAP = {
|
||||
"ab wheel": "0857",
|
||||
"air bike": "0003",
|
||||
"arnold press (dumbbell)": "2137",
|
||||
"around the world": "2143",
|
||||
"back extension (hyperextension)": "0573",
|
||||
"back extension (machine)": "0573",
|
||||
"back extension (weighted hyperextension)": "0573",
|
||||
"battle ropes": "0128",
|
||||
"bear crawl": "3360",
|
||||
"bench dip": "0830",
|
||||
"bench press (barbell)": "0025",
|
||||
"bench press (cable)": "0151",
|
||||
"bench press (dumbbell)": "0289",
|
||||
"bench press (smith machine)": "0748",
|
||||
"bench press - close grip (barbell)": "0030",
|
||||
"bench press - wide grip (barbell)": "1258",
|
||||
"bent over row (band)": "0027",
|
||||
"bent over row (barbell)": "0027",
|
||||
"bent over row (dumbbell)": "0292",
|
||||
"bent over row (smith machine)": "1359",
|
||||
"bicep curl (barbell)": "0031",
|
||||
"bicep curl (cable)": "0868",
|
||||
"bicep curl (dumbbell)": "0294",
|
||||
"bicep curl (machine)": "0575",
|
||||
"bicep curl (suspension)": "0294",
|
||||
"bicycle crunch": "0972",
|
||||
"boxing": "2271",
|
||||
"bulgarian split squat (barbell)": "0099",
|
||||
"bulgarian split squat (dumbbell)": "0410",
|
||||
"burpee": "1160",
|
||||
"butterfly (pec deck)": "0596",
|
||||
"cable core pallof press": "0979",
|
||||
"cable crunch": "0175",
|
||||
"cable fly crossovers": "1269",
|
||||
"cable pull through": "0196",
|
||||
"cable twist (down to up)": "0243",
|
||||
"cable twist (up to down)": "0243",
|
||||
"calf press (machine)": "2289",
|
||||
"chest dip": "0251",
|
||||
"chest dip (assisted)": "0009",
|
||||
"chest dip (weighted)": "0251",
|
||||
"chest fly (dumbbell)": "0308",
|
||||
"chest fly (machine)": "0596",
|
||||
"chest press (band)": "3124",
|
||||
"chest press (machine)": "0577",
|
||||
"chest supported incline row (dumbbell)": "0327",
|
||||
"chest supported reverse fly (dumbbell)": "0383",
|
||||
"chin up": "1326",
|
||||
"chin up (assisted)": "0572",
|
||||
"chin up (weighted)": "0572",
|
||||
"clap push ups": "1273",
|
||||
"clean": "0028",
|
||||
"clean and press": "0028",
|
||||
"concentration curl": "0297",
|
||||
"cross body hammer curl": "0298",
|
||||
"crunch (machine)": "1452",
|
||||
"crunch (weighted)": "0832",
|
||||
"cycling": "2331",
|
||||
"dead bug": "0276",
|
||||
"deadlift (band)": "0032",
|
||||
"deadlift (barbell)": "0032",
|
||||
"deadlift (dumbbell)": "0300",
|
||||
"deadlift (smith machine)": "0752",
|
||||
"deadlift (trap bar)": "0811",
|
||||
"decline bench press (barbell)": "0033",
|
||||
"decline bench press (dumbbell)": "0301",
|
||||
"decline bench press (machine)": "0033",
|
||||
"decline bench press (smith machine)": "0753",
|
||||
"decline crunch": "0277",
|
||||
"decline crunch (weighted)": "0277",
|
||||
"decline push up": "0279",
|
||||
"diamond push up": "0283",
|
||||
"drag curl": "0038",
|
||||
"dumbbell row": "0292",
|
||||
"dumbbell snatch": "3888",
|
||||
"dumbbell step up": "0431",
|
||||
"elbow to knee": "0443",
|
||||
"elliptical trainer": "2141",
|
||||
"ez bar biceps curl": "2404",
|
||||
"face pull": "0203",
|
||||
"farmers walk": "2133",
|
||||
"floor press (barbell)": "0065",
|
||||
"floor triceps dip": "0815",
|
||||
"flutter kicks": "0459",
|
||||
"front raise (band)": "0978",
|
||||
"front raise (barbell)": "0041",
|
||||
"front raise (cable)": "0162",
|
||||
"front raise (dumbbell)": "0310",
|
||||
"front raise (suspension)": "0834",
|
||||
"front squat": "0042",
|
||||
"full squat": "0043",
|
||||
"glute bridge (barbell)": "1409",
|
||||
"glute ham raise": "3193",
|
||||
"goblet squat": "1760",
|
||||
"good morning (barbell)": "0044",
|
||||
"hack squat": "0046",
|
||||
"hack squat (machine)": "0743",
|
||||
"hammer curl (band)": "0313",
|
||||
"hammer curl (cable)": "0165",
|
||||
"hammer curl (dumbbell)": "0312",
|
||||
"handstand push up": "0471",
|
||||
"hang clean": "0535",
|
||||
"hanging knee raise": "0472",
|
||||
"hanging leg raise": "0472",
|
||||
"high knees": "3655",
|
||||
"hip abduction (cable)": "0597",
|
||||
"hip abduction (machine)": "0597",
|
||||
"hip adduction (cable)": "0168",
|
||||
"hip adduction (machine)": "0598",
|
||||
"incline bench press (barbell)": "0047",
|
||||
"incline bench press (dumbbell)": "0314",
|
||||
"incline bench press (smith machine)": "0757",
|
||||
"incline chest fly (dumbbell)": "0319",
|
||||
"incline chest press (machine)": "1299",
|
||||
"incline push ups": "0493",
|
||||
"inverted row": "0499",
|
||||
"iso-lateral row (machine)": "0571",
|
||||
"jackknife sit up": "0507",
|
||||
"jm press (barbell)": "0052",
|
||||
"jump rope": "2612",
|
||||
"jump squat": "0514",
|
||||
"jumping jack": "3220",
|
||||
"kettlebell clean": "0535",
|
||||
"kettlebell goblet squat": "0534",
|
||||
"kettlebell high pull": "0548",
|
||||
"kettlebell snatch": "0529",
|
||||
"kettlebell swing": "0549",
|
||||
"kettlebell turkish get up": "0551",
|
||||
"knee raise parallel bars": "0826",
|
||||
"kneeling pulldown (band)": "0983",
|
||||
"kneeling push up": "3211",
|
||||
"landmine 180": "0562",
|
||||
"lat pulldown (band)": "2330",
|
||||
"lat pulldown (cable)": "2330",
|
||||
"lat pulldown (machine)": "0673",
|
||||
"lat pulldown - close grip (cable)": "2616",
|
||||
"lateral lunge": "1410",
|
||||
"lateral raise (band)": "0977",
|
||||
"lateral raise (cable)": "0178",
|
||||
"lateral raise (dumbbell)": "0334",
|
||||
"lateral raise (machine)": "0584",
|
||||
"leg extension (machine)": "0585",
|
||||
"leg press (machine)": "0739",
|
||||
"leg press horizontal (machine)": "2611",
|
||||
"leg raise parallel bars": "0826",
|
||||
"low row (suspension)": "0180",
|
||||
"lunge": "0054",
|
||||
"lunge (barbell)": "0054",
|
||||
"lunge (dumbbell)": "0336",
|
||||
"lying leg curl (machine)": "0586",
|
||||
"lying leg raise": "0865",
|
||||
"mountain climber": "0630",
|
||||
"muscle up": "0631",
|
||||
"oblique crunch": "1495",
|
||||
"overhead curl (cable)": "1636",
|
||||
"overhead press (barbell)": "0091",
|
||||
"overhead press (dumbbell)": "0405",
|
||||
"overhead press (smith machine)": "0766",
|
||||
"overhead squat": "0069",
|
||||
"overhead triceps extension (cable)": "0194",
|
||||
"pendlay row (barbell)": "3017",
|
||||
"pistol squat": "0544",
|
||||
"plank": "2135",
|
||||
"plate front raise": "0310",
|
||||
"power clean": "0648",
|
||||
"preacher curl (barbell)": "0070",
|
||||
"preacher curl (dumbbell)": "0372",
|
||||
"preacher curl (machine)": "0592",
|
||||
"pull up": "0652",
|
||||
"pull up (assisted)": "0017",
|
||||
"pull up (band)": "0970",
|
||||
"pull up (weighted)": "0652",
|
||||
"pullover (dumbbell)": "0375",
|
||||
"pullover (machine)": "2285",
|
||||
"push press": "1700",
|
||||
"push up": "0662",
|
||||
"push up (weighted)": "0662",
|
||||
"push up - close grip": "0259",
|
||||
"rack pull": "0074",
|
||||
"rear delt reverse fly (dumbbell)": "0383",
|
||||
"rear delt reverse fly (machine)": "0602",
|
||||
"renegade row (dumbbell)": "0521",
|
||||
"reverse crunch": "0872",
|
||||
"reverse curl (barbell)": "0080",
|
||||
"reverse curl (cable)": "0206",
|
||||
"reverse grip lat pulldown (cable)": "0673",
|
||||
"reverse hyperextension": "0593",
|
||||
"reverse lunge (barbell)": "0078",
|
||||
"reverse lunge (dumbbell)": "0381",
|
||||
"reverse plank": "3663",
|
||||
"reverse wrist curl (dumbbell)": "0385",
|
||||
"ring dips": "0677",
|
||||
"romanian deadlift (barbell)": "0085",
|
||||
"romanian deadlift (dumbbell)": "1459",
|
||||
"romanian deadlift (smith machine)": "0085",
|
||||
"rope cable curl": "0165",
|
||||
"rope straight arm pulldown": "0237",
|
||||
"russian twist (bodyweight)": "0687",
|
||||
"russian twist (weighted)": "0687",
|
||||
"scapular pull ups": "0688",
|
||||
"seated cable row - bar grip": "0218",
|
||||
"seated cable row - v grip (cable)": "0218",
|
||||
"seated calf raise": "0594",
|
||||
"seated dip machine": "1451",
|
||||
"seated incline curl (dumbbell)": "0318",
|
||||
"seated lateral raise (dumbbell)": "0396",
|
||||
"seated leg curl (machine)": "0586",
|
||||
"seated overhead press (barbell)": "0091",
|
||||
"seated overhead press (dumbbell)": "0091",
|
||||
"seated palms up wrist curl": "0401",
|
||||
"seated row (machine)": "1350",
|
||||
"seated shoulder press (machine)": "0603",
|
||||
"seated wrist curl (barbell)": "1426",
|
||||
"shoulder press (dumbbell)": "0405",
|
||||
"shoulder press (machine plates)": "0603",
|
||||
"shrug (barbell)": "0095",
|
||||
"shrug (cable)": "0220",
|
||||
"shrug (dumbbell)": "0406",
|
||||
"shrug (machine)": "0604",
|
||||
"shrug (smith machine)": "0767",
|
||||
"side bend (dumbbell)": "0407",
|
||||
"single arm lateral raise (cable)": "0192",
|
||||
"single leg standing calf raise (machine)": "0605",
|
||||
"sissy squat (weighted)": "1489",
|
||||
"skullcrusher (barbell)": "0060",
|
||||
"skullcrusher (dumbbell)": "0060",
|
||||
"snatch": "0067",
|
||||
"spider curl (dumbbell)": "1675",
|
||||
"split squat (dumbbell)": "0809",
|
||||
"sprints": "0858",
|
||||
"squat (band)": "1004",
|
||||
"squat (barbell)": "0043",
|
||||
"squat (bodyweight)": "3543",
|
||||
"squat (dumbbell)": "0413",
|
||||
"squat (smith machine)": "0770",
|
||||
"squat (suspension)": "0043",
|
||||
"squat row": "1003",
|
||||
"stair machine (floors)": "2311",
|
||||
"stair machine (steps)": "2311",
|
||||
"standing calf raise": "1372",
|
||||
"standing calf raise (barbell)": "1372",
|
||||
"standing calf raise (dumbbell)": "0417",
|
||||
"standing calf raise (machine)": "0605",
|
||||
"standing calf raise (smith)": "0773",
|
||||
"standing leg curls": "0795",
|
||||
"standing military press (barbell)": "1457",
|
||||
"straight leg deadlift": "0116",
|
||||
"sumo deadlift": "0117",
|
||||
"sumo squat": "3142",
|
||||
"sumo squat (barbell)": "3142",
|
||||
"sumo squat (dumbbell)": "3142",
|
||||
"sumo squat (kettlebell)": "3142",
|
||||
"superman": "0803",
|
||||
"t bar row": "0606",
|
||||
"thruster (barbell)": "3305",
|
||||
"thruster (kettlebell)": "0550",
|
||||
"treadmill": "3666",
|
||||
"triceps dip": "0591",
|
||||
"triceps dip (assisted)": "0019",
|
||||
"triceps dip (weighted)": "0591",
|
||||
"triceps extension (barbell)": "0607",
|
||||
"triceps extension (dumbbell)": "0607",
|
||||
"triceps extension (machine)": "0607",
|
||||
"triceps extension (suspension)": "0607",
|
||||
"triceps pushdown": "0241",
|
||||
"upright row (barbell)": "0120",
|
||||
"upright row (cable)": "0246",
|
||||
"upright row (dumbbell)": "0437",
|
||||
"waiter curl (dumbbell)": "5201",
|
||||
"walking": "1460",
|
||||
"walking lunge": "1460",
|
||||
"walking lunge (dumbbell)": "1460",
|
||||
"walking lunge (sandbag)": "1460",
|
||||
"wall sit": "0624",
|
||||
"wide pull up": "1429",
|
||||
"yoga": "1494",
|
||||
"zercher squat": "0127",
|
||||
"zottman curl (dumbbell)": "0439",
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
// Pure helpers over the state object S (ported 1:1 from the vanilla app).
|
||||
import { todayISO, isoOf, weekKey, fmtNum } from './format.js'
|
||||
import { todayISO, isoOf, weekKey, weekStartOf, fmtNum } from './format.js'
|
||||
import { isCardio, isBodyweightEq } from './exercises.js'
|
||||
import { phaseForSet, modeForSet, modeForEntry, isWarmupRow, normalizeMode, extraVolumeOf, nextDropWeight, splitBurstReps } from './workout-model.js'
|
||||
const objectOf = value => value && typeof value === 'object' && !Array.isArray(value) ? value : {}
|
||||
@@ -327,13 +327,21 @@ export function buildSets(S, cfg, options = {}) {
|
||||
export const MAX_PLANNED_WARMUPS = 5
|
||||
|
||||
function buildWorkSets(S, cfg, options = {}) {
|
||||
const last = lastEntryFor(S, cfg.id)
|
||||
const preferLast = !!options.preferLast
|
||||
const useTarget = !!options.useTarget
|
||||
// A workout flagged excludeFromProgression (a planned deload) is not "last time" for the
|
||||
// next regular session either: its reps and durations must not seed the rows any more than
|
||||
// its weight seeds the prescription. The deload session itself reads the routine's own target.
|
||||
const regular = (S.workouts || []).some(w => w.excludeFromProgression === true)
|
||||
? { ...S, workouts: S.workouts.filter(w => w.excludeFromProgression !== true) }
|
||||
: S
|
||||
const last = lastEntryFor(regular, cfg.id)
|
||||
const n = Math.max(1, cfg.sets || 1)
|
||||
const mode = modeOf(cfg)
|
||||
const preferLast = !!options.preferLast
|
||||
const sets = []
|
||||
// Last time's set at the same position, falling back to its final set when the plan grew.
|
||||
const prevAt = i => (last ? (last.sets[i] || last.sets[last.sets.length - 1]) : null)
|
||||
// A deload routine must use its own prescription instead of carrying regular-session values
|
||||
// into the workout. Other planned sessions keep the existing history-first behaviour.
|
||||
const prevAt = i => (!useTarget && last ? (last.sets[i] || last.sets[last.sets.length - 1]) : null)
|
||||
|
||||
if (mode === 'cardio') {
|
||||
for (let i = 0; i < n; i++) {
|
||||
@@ -358,7 +366,12 @@ function buildWorkSets(S, cfg, options = {}) {
|
||||
const usable = prev && prev.r > 0 ? prev : null
|
||||
// Planned sessions may use the confirmed working weight, while freestyle should reproduce
|
||||
// the load of each matching set when that option is requested.
|
||||
const w = preferLast && usable ? usable.w : (conf && conf.w > 0 ? conf.w : (usable ? usable.w : cfg.weight))
|
||||
// A deload uses the routine's target weight; a routine that never set one (weight 0) falls
|
||||
// back to the last regular load rather than prescribing an empty bar.
|
||||
const lastRegular = last ? (last.sets[i] || last.sets[last.sets.length - 1]) : null
|
||||
const w = useTarget
|
||||
? (cfg.weight > 0 ? cfg.weight : (lastRegular && lastRegular.r > 0 ? lastRegular.w : cfg.weight))
|
||||
: preferLast && usable ? usable.w : (conf && conf.w > 0 ? conf.w : (usable ? usable.w : cfg.weight))
|
||||
sets.push({ w, r: usable ? usable.r : cfg.reps, done: false })
|
||||
}
|
||||
return sets
|
||||
@@ -440,15 +453,32 @@ export function supersetUnits(items) {
|
||||
})
|
||||
return units
|
||||
}
|
||||
|
||||
// Move the selected occurrence's complete display unit by one neighbouring unit. Returning a
|
||||
// new array keeps this helper pure; the caller decides how to persist it. Index identity matters
|
||||
// here because the same exercise id may appear more than once with different setup.
|
||||
export function moveSupersetUnit(items, index, direction) {
|
||||
if (!Array.isArray(items) || (direction !== -1 && direction !== 1)) return null
|
||||
const units = supersetUnits(items)
|
||||
const source = units.findIndex(unit => unit.includes(index))
|
||||
const target = source + direction
|
||||
if (source < 0 || target < 0 || target >= units.length) return null
|
||||
const reordered = [...units]
|
||||
const selected = reordered[source]
|
||||
reordered[source] = reordered[target]
|
||||
reordered[target] = selected
|
||||
return reordered.flat().map(i => items[i])
|
||||
}
|
||||
export function unitOf(units, idx) { return units.find(u => u.includes(idx)) || [idx] }
|
||||
|
||||
export function streakWeeks(S) {
|
||||
if (!S.workouts.length) return 0
|
||||
const weeks = new Set(S.workouts.map(w => weekKey(w.d)))
|
||||
const ws = weekStartOf(S)
|
||||
const weeks = new Set(S.workouts.map(w => weekKey(w.d, ws)))
|
||||
let streak = 0
|
||||
const cur = new Date()
|
||||
for (let i = 0; i < 520; i++) {
|
||||
const wk = weekKey(isoOf(cur))
|
||||
const wk = weekKey(isoOf(cur), ws)
|
||||
if (weeks.has(wk)) streak++
|
||||
else if (i > 0) break
|
||||
cur.setDate(cur.getDate() - 7)
|
||||
|
||||
@@ -493,6 +493,14 @@ describe('buildSets', () => {
|
||||
.toEqual([{ w: 60, r: 10, done: false }, { w: 62.5, r: 8, done: false }])
|
||||
})
|
||||
|
||||
it('can use a deload target without carrying regular-session values into it', () => {
|
||||
const S = { exWeights: { [LIFT]: { w: 75 } }, workouts: [{ d: '2026-01-01', entries: [{ id: LIFT, sets: [
|
||||
{ w: 75, r: 10, done: true }, { w: 75, r: 9, done: true }
|
||||
] }] }] }
|
||||
expect(buildSets(S, { id: LIFT, sets: 2, reps: 12, weight: 40 }, { useTarget: true }))
|
||||
.toEqual([{ w: 40, r: 12, done: false }, { w: 40, r: 12, done: false }])
|
||||
})
|
||||
|
||||
})
|
||||
|
||||
describe('applyIntensifierPlan', () => {
|
||||
@@ -895,3 +903,53 @@ describe('exNoteFor', () => {
|
||||
expect(exNoteFor({}, '0025')).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('nextTrainingDay', () => {
|
||||
// 2026-08-18 is a Tuesday; the week map is keyed by getDay(), so 0 is Sunday.
|
||||
const TUE = '2026-08-18'
|
||||
const base = (over = {}) => ({
|
||||
dayPlan: {},
|
||||
routines: [{ id: 'r1', name: 'A', ex: [{ id: '0001' }] }, { id: 'r2', name: 'B', ex: [{ id: '0002' }] }],
|
||||
week: {},
|
||||
...over
|
||||
})
|
||||
|
||||
it('finds the next scheduled day and names its routine', () => {
|
||||
const S = base({ week: { 4: 'r2' } }) // Thursday
|
||||
expect(nextTrainingDay(S, TUE)).toMatchObject({ iso: '2026-08-20', weekday: 4 })
|
||||
expect(nextTrainingDay(S, TUE).routine.name).toBe('B')
|
||||
})
|
||||
|
||||
it('looks forward only — today itself is never the answer', () => {
|
||||
// Only Tuesday is scheduled and today is Tuesday, so the next one is a week out. (The UI
|
||||
// cannot reach this: a day with a session takes the other branch and never asks.)
|
||||
const S = base({ week: { 2: 'r1' } })
|
||||
expect(nextTrainingDay(S, TUE)).toMatchObject({ iso: '2026-08-25', weekday: 2 })
|
||||
})
|
||||
|
||||
it('wraps around the end of the week', () => {
|
||||
const S = base({ week: { 1: 'r1' } }) // Monday, six days on
|
||||
expect(nextTrainingDay(S, TUE)).toMatchObject({ iso: '2026-08-24', weekday: 1 })
|
||||
})
|
||||
|
||||
it('is null when every day is rest', () => {
|
||||
expect(nextTrainingDay(base(), TUE)).toBeNull()
|
||||
})
|
||||
|
||||
it('skips a day whose routine no longer exists', () => {
|
||||
const S = base({ week: { 3: 'gone', 5: 'r1' } })
|
||||
expect(nextTrainingDay(S, TUE)).toMatchObject({ iso: '2026-08-21', weekday: 5 })
|
||||
})
|
||||
|
||||
it('skips a routine with no exercises — starting it would open an empty session', () => {
|
||||
const S = base({ routines: [{ id: 'r1', name: 'A', ex: [] }, { id: 'r2', name: 'B', ex: [{ id: '1' }] }], week: { 3: 'r1', 5: 'r2' } })
|
||||
expect(nextTrainingDay(S, TUE)).toMatchObject({ weekday: 5 })
|
||||
})
|
||||
|
||||
it('respects a per-date override in both directions', () => {
|
||||
const moved = base({ week: {}, dayPlan: { '2026-08-19': 'r1' } })
|
||||
expect(nextTrainingDay(moved, TUE)).toMatchObject({ iso: '2026-08-19' })
|
||||
const off = base({ week: { 3: 'r1', 5: 'r2' }, dayPlan: { '2026-08-19': 'rest' } })
|
||||
expect(nextTrainingDay(off, TUE)).toMatchObject({ weekday: 5 })
|
||||
})
|
||||
})
|
||||
@@ -7,13 +7,13 @@ export const LANGS = {
|
||||
en: 'English', de: 'Deutsch', es: 'Español', fr: 'Français', it: 'Italiano',
|
||||
pt: 'Português (Portugal)', 'pt-BR': 'Português (Brasil)', pl: 'Polski',
|
||||
tr: 'Türkçe', ru: 'Русский', zh: '中文',
|
||||
ko: '한국어', hi: 'हिन्दी'
|
||||
ko: '한국어', hi: 'हिन्दी', th: 'ไทย', hu: 'Magyar'
|
||||
}
|
||||
export const INSTR_LANGS = ['en', 'es', 'fr', 'it', 'tr', 'ru', 'zh', 'hi', 'pl', 'ko', 'pt-BR']
|
||||
export const EXERCISE_NAME_LANGS = ['pt-BR']
|
||||
export const INSTR_LANGS = ['en', 'es', 'fr', 'it', 'tr', 'ru', 'zh', 'hi', 'pl', 'ko', 'pt-BR', 'hu']
|
||||
export const EXERCISE_NAME_LANGS = ['pt-BR', 'hu']
|
||||
export const DATE_LOCALES = {
|
||||
en: 'en-GB', de: 'de-DE', es: 'es-ES', fr: 'fr-FR', it: 'it-IT', pt: 'pt-PT', 'pt-BR': 'pt-BR',
|
||||
pl: 'pl-PL', tr: 'tr-TR', ru: 'ru-RU', zh: 'zh-CN', ko: 'ko-KR', hi: 'hi-IN'
|
||||
pl: 'pl-PL', tr: 'tr-TR', ru: 'ru-RU', zh: 'zh-CN', ko: 'ko-KR', hi: 'hi-IN', th: 'th-TH', hu: 'hu-HU'
|
||||
}
|
||||
|
||||
let lang = 'en' // set only by _setLangState, called from i18n.js setLang
|
||||
@@ -41,9 +41,12 @@ export const instrFor = ex => (instr && instr[ex.id]) || ex.st || []
|
||||
export const exerciseNameFor = ex => {
|
||||
const translated = exerciseNames && ex && exerciseNames[ex.id]
|
||||
if (!translated) return ex?.n || ''
|
||||
// Some names (Burpee, Pilates, brand/model terms) are the established pt-BR term too.
|
||||
// Repeating an identical loanword in parentheses adds noise rather than context.
|
||||
return translated.toLocaleLowerCase('pt-BR') === ex.n.toLocaleLowerCase('en')
|
||||
// Some names (Burpee, Pilates, brand/model terms) are the established term in the target
|
||||
// language too. Repeating an identical loanword in parentheses adds noise rather than
|
||||
// context. Compared in the active language's own casing rules, not hardcoded to one —
|
||||
// this only ever differs from ordinary casing for languages with locale-specific rules
|
||||
// (e.g. Turkish dotless i), which does not include any language shipped here today.
|
||||
return translated.toLocaleLowerCase(lang) === ex.n.toLocaleLowerCase('en')
|
||||
? translated
|
||||
: `${translated} (${ex.n})`
|
||||
}
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
import { EXDB, EXIDX } from './exercises.js'
|
||||
import { uid } from './format.js'
|
||||
import { isWarmupRow } from './workout-model.js'
|
||||
import { HEVY_TITLE_MAP } from './hevy-id-map.js'
|
||||
|
||||
/* ----------------------------------------------------------------- CSV ---- */
|
||||
|
||||
@@ -251,6 +252,16 @@ export function matchExercise(name) {
|
||||
return ties === 1 ? best : null
|
||||
}
|
||||
|
||||
/**
|
||||
* Exact Hevy English title → catalogue id (from the generated title map).
|
||||
* Used when a CSV is detected as Hevy: same deterministic table as the API import,
|
||||
* keyed by title because Hevy's CSV has no template id column.
|
||||
*/
|
||||
export function matchHevyTitle(name) {
|
||||
const id = HEVY_TITLE_MAP[String(name || '').trim().toLowerCase()]
|
||||
return id && EXIDX[id] ? id : null
|
||||
}
|
||||
|
||||
// Hevy exports no category column, so every invented exercise fell through to the
|
||||
// 'upper legs' default and a third of an imported history was attributed to the legs in
|
||||
// the muscle map. When there is no category, read the body part off the name instead.
|
||||
@@ -389,7 +400,12 @@ export function parseWorkoutCSV(text, { unit = 'kg' } = {}) {
|
||||
|
||||
const key = keyOf(name)
|
||||
let id = resolved.get(key)
|
||||
if (id === undefined) { id = matchExercise(name); resolved.set(key, id) }
|
||||
if (id === undefined) {
|
||||
// Hevy CSV: prefer the generated English-title map (same table as the API import).
|
||||
// Localized titles still fall through to the word-bag matcher.
|
||||
id = (source === 'Hevy' ? matchHevyTitle(name) : null) || matchExercise(name)
|
||||
resolved.set(key, id)
|
||||
}
|
||||
if (id) matched++
|
||||
else {
|
||||
let c = created.get(key)
|
||||
|
||||
@@ -0,0 +1,448 @@
|
||||
// Import a Hevy account through the public API (https://api.hevyapp.com/docs/).
|
||||
//
|
||||
// Exercise identity is Hevy's `exercise_template_id`, looked up in the generated
|
||||
// `hevy-id-map.js` table — never the localized title on a set. Regenerate the map
|
||||
// with `node scripts/build-hevy-id-map.mjs`. The API key never leaves this module's
|
||||
// callers: nothing here stores it.
|
||||
|
||||
import { EXIDX } from './exercises.js'
|
||||
import { uid } from './format.js'
|
||||
import { isWarmupRow } from './workout-model.js'
|
||||
import { HEVY_ID_MAP, HEVY_TITLE_MAP } from './hevy-id-map.js'
|
||||
|
||||
export { HEVY_ID_MAP, HEVY_TITLE_MAP }
|
||||
export const HEVY_API = 'https://api.hevyapp.com'
|
||||
export const HEVY_DEV_SETTINGS = 'https://hevy.com/settings?developer'
|
||||
|
||||
const LB_TO_KG = 0.45359237
|
||||
|
||||
/* --------------------------------------------------------------- auth/fetch -- */
|
||||
|
||||
class HevyApiError extends Error {
|
||||
constructor(status, message) {
|
||||
super(message || `Hevy API error ${status}`)
|
||||
this.name = 'HevyApiError'
|
||||
this.status = status
|
||||
}
|
||||
}
|
||||
|
||||
async function hevyGet(path, apiKey, params = {}) {
|
||||
const url = new URL(path, HEVY_API)
|
||||
for (const [k, v] of Object.entries(params)) {
|
||||
if (v != null && v !== '') url.searchParams.set(k, String(v))
|
||||
}
|
||||
// Hevy publishes no rate limit, but a large account is 100+ sequential page requests; a 429
|
||||
// gets a short back-off and one more try before it surfaces as its own error kind.
|
||||
for (let attempt = 0; ; attempt++) {
|
||||
const res = await fetch(url, { headers: { 'api-key': apiKey } })
|
||||
if (res.status === 401 || res.status === 403) {
|
||||
throw new HevyApiError(res.status, 'auth')
|
||||
}
|
||||
if (res.status === 429 && attempt < 2) {
|
||||
const after = Number(res.headers?.get?.('retry-after'))
|
||||
await new Promise(r => setTimeout(r, (after > 0 && after <= 30 ? after : 2 * (attempt + 1)) * 1000))
|
||||
continue
|
||||
}
|
||||
if (res.status === 429) throw new HevyApiError(res.status, 'rate-limit')
|
||||
if (!res.ok) throw new HevyApiError(res.status, `http ${res.status}`)
|
||||
return res.json()
|
||||
}
|
||||
}
|
||||
|
||||
/** Page through a Hevy list endpoint. `pageSize` caps differ per resource. */
|
||||
export async function fetchHevyPages(path, apiKey, {
|
||||
resultKey,
|
||||
pageSize = 10,
|
||||
onProgress,
|
||||
} = {}) {
|
||||
const items = []
|
||||
let page = 1
|
||||
let pageCount = 1
|
||||
while (page <= pageCount) {
|
||||
const data = await hevyGet(path, apiKey, { page, pageSize })
|
||||
pageCount = Math.max(1, data.page_count || 1)
|
||||
const batch = data[resultKey] || []
|
||||
items.push(...batch)
|
||||
onProgress && onProgress({ page, pageCount, loaded: items.length, resultKey })
|
||||
if (!batch.length) break
|
||||
page++
|
||||
}
|
||||
return items
|
||||
}
|
||||
|
||||
export async function fetchHevyAccount(apiKey, { onProgress } = {}) {
|
||||
const key = String(apiKey || '').trim()
|
||||
if (!key) throw new HevyApiError(0, 'empty')
|
||||
|
||||
const templates = await fetchHevyPages('/v1/exercise_templates', key, {
|
||||
resultKey: 'exercise_templates', pageSize: 100,
|
||||
onProgress: p => onProgress && onProgress({ stage: 'templates', ...p }),
|
||||
})
|
||||
const workouts = await fetchHevyPages('/v1/workouts', key, {
|
||||
resultKey: 'workouts', pageSize: 10,
|
||||
onProgress: p => onProgress && onProgress({ stage: 'workouts', ...p }),
|
||||
})
|
||||
const routines = await fetchHevyPages('/v1/routines', key, {
|
||||
resultKey: 'routines', pageSize: 10,
|
||||
onProgress: p => onProgress && onProgress({ stage: 'routines', ...p }),
|
||||
})
|
||||
let bodyMeasurements = []
|
||||
try {
|
||||
bodyMeasurements = await fetchHevyPages('/v1/body_measurements', key, {
|
||||
resultKey: 'body_measurements', pageSize: 10,
|
||||
onProgress: p => onProgress && onProgress({ stage: 'body', ...p }),
|
||||
})
|
||||
} catch (e) {
|
||||
// Older keys / accounts may lack measurements — workouts still import.
|
||||
if (!(e instanceof HevyApiError) || e.message === 'auth') throw e
|
||||
}
|
||||
return { templates, workouts, routines, bodyMeasurements }
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------- template → id -- */
|
||||
|
||||
// Hevy primary_muscle_group → openGym body-part for exercises we invent.
|
||||
const HEVY_BP = {
|
||||
biceps: 'upper arms', triceps: 'upper arms', forearms: 'lower arms',
|
||||
chest: 'chest', lats: 'back', upper_back: 'back', lower_back: 'back',
|
||||
traps: 'back', shoulders: 'shoulders',
|
||||
abdominals: 'waist', abs: 'waist', obliques: 'waist',
|
||||
quadriceps: 'upper legs', hamstrings: 'upper legs', glutes: 'upper legs',
|
||||
abductors: 'upper legs', adductors: 'upper legs', calves: 'lower legs',
|
||||
cardio: 'cardio', full_body: 'upper legs', other: 'upper legs', neck: 'neck',
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a Hevy exercise template to a catalogue id.
|
||||
*
|
||||
* Deterministic: only `HEVY_ID_MAP` (generated by scripts/build-hevy-id-map.mjs).
|
||||
* No runtime name guessing — unmatched templates become custom exercises.
|
||||
*/
|
||||
export function matchHevyTemplate(template) {
|
||||
if (!template?.id) return null
|
||||
const id = HEVY_ID_MAP[template.id]
|
||||
return id && EXIDX[id] ? id : null
|
||||
}
|
||||
|
||||
/** Build templateId → catalogue id (or null) from a templates list. */
|
||||
export function buildHevyExerciseMap(templates) {
|
||||
const map = new Map()
|
||||
for (const t of templates || []) {
|
||||
if (!t?.id) continue
|
||||
map.set(t.id, matchHevyTemplate(t))
|
||||
}
|
||||
return map
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------------- parse ---- */
|
||||
|
||||
const p2 = n => String(n).padStart(2, '0')
|
||||
|
||||
/** Hevy ISO timestamps → local calendar date + ms-since-midnight (matches CSV import). */
|
||||
export function localWhen(iso) {
|
||||
const d = new Date(iso)
|
||||
if (isNaN(d.getTime())) return null
|
||||
const day = `${d.getFullYear()}-${p2(d.getMonth() + 1)}-${p2(d.getDate())}`
|
||||
const t = d.getHours() * 3600000 + d.getMinutes() * 60000 + d.getSeconds() * 1000
|
||||
return { d: day, t }
|
||||
}
|
||||
|
||||
function bpOfTemplate(t) {
|
||||
const g = String(t?.primary_muscle_group || '').toLowerCase()
|
||||
return HEVY_BP[g] || 'upper legs'
|
||||
}
|
||||
|
||||
/** Shared resolver: HEVY_ID_MAP hit, else one custom exercise per Hevy template id. */
|
||||
function makeResolver(templates) {
|
||||
const byId = new Map((templates || []).map(t => [t.id, t]))
|
||||
const created = new Map()
|
||||
const unmatched = new Set()
|
||||
const matchedIds = new Set()
|
||||
|
||||
const resolve = (templateId, fallbackTitle) => {
|
||||
const pinned = templateId && HEVY_ID_MAP[templateId]
|
||||
if (pinned && EXIDX[pinned]) {
|
||||
matchedIds.add(pinned)
|
||||
return pinned
|
||||
}
|
||||
const key = templateId || String(fallbackTitle || '').toLowerCase()
|
||||
if (!key) return null
|
||||
let c = created.get(key)
|
||||
if (!c) {
|
||||
const t = templateId ? byId.get(templateId) : null
|
||||
const name = (t?.title || fallbackTitle || 'exercise').toLowerCase()
|
||||
c = {
|
||||
id: 'im' + uid(), n: name, custom: true, eq: 'custom', tg: '', desc: '',
|
||||
bp: bpOfTemplate(t) || (t?.type === 'distance_duration' || t?.type === 'duration' ? 'cardio' : null)
|
||||
|| 'upper legs',
|
||||
}
|
||||
created.set(key, c)
|
||||
unmatched.add(t?.title || fallbackTitle || name)
|
||||
}
|
||||
return c.id
|
||||
}
|
||||
|
||||
return {
|
||||
resolve,
|
||||
byId,
|
||||
customEx: () => [...created.values()],
|
||||
unmatchedNames: () => [...unmatched].sort(),
|
||||
matchedCount: () => matchedIds.size,
|
||||
createdCount: () => created.size,
|
||||
}
|
||||
}
|
||||
|
||||
const toProfileWeight = (wKg, unit) => {
|
||||
if (wKg == null || !isFinite(wKg)) return 0
|
||||
if (unit === 'lb') return Math.round(wKg / LB_TO_KG * 10) / 10
|
||||
return Math.round(wKg * 10) / 10
|
||||
}
|
||||
|
||||
/**
|
||||
* Turn Hevy API workouts into the same shape `mergeImport` already understands.
|
||||
* Mapping is by `exercise_template_id` through `HEVY_ID_MAP` only — localized
|
||||
* titles on each set are never used to pick a catalogue entry.
|
||||
*/
|
||||
export function parseHevyWorkouts(workouts, templates, { unit = 'kg' } = {}) {
|
||||
const R = makeResolver(templates)
|
||||
const byDate = new Map()
|
||||
let sets = 0, skipped = 0, matched = 0, warmups = 0, rpeSets = 0
|
||||
|
||||
for (const w of workouts || []) {
|
||||
const start = localWhen(w.start_time)
|
||||
const end = localWhen(w.end_time)
|
||||
if (!start) { skipped++; continue }
|
||||
|
||||
let day = byDate.get(start.d)
|
||||
if (!day) {
|
||||
day = { ex: new Map(), name: w.title || '', start: start.t, end: end?.t ?? null }
|
||||
byDate.set(start.d, day)
|
||||
} else if (!day.name && w.title) day.name = w.title
|
||||
if (end?.t != null) day.end = end.t
|
||||
|
||||
for (const ex of w.exercises || []) {
|
||||
const id = R.resolve(ex.exercise_template_id, ex.title)
|
||||
if (!id) { skipped++; continue }
|
||||
if (EXIDX[id] && !String(id).startsWith('im')) matched++
|
||||
|
||||
if (!day.ex.has(id)) day.ex.set(id, [])
|
||||
const list = day.ex.get(id)
|
||||
|
||||
for (const s of ex.sets || []) {
|
||||
const warmup = /warm/i.test(String(s.type || ''))
|
||||
if (warmup) warmups++
|
||||
const reps = s.reps != null ? Math.round(s.reps) : 0
|
||||
const wgt = toProfileWeight(s.weight_kg, unit)
|
||||
const secs = s.duration_seconds != null ? Number(s.duration_seconds) : 0
|
||||
const km = s.distance_meters != null ? Number(s.distance_meters) / 1000 : 0
|
||||
if (!wgt && !reps && !secs && !km) { skipped++; continue }
|
||||
|
||||
const isCardio = (km > 0 || secs > 0) && !reps
|
||||
const mins = secs > 0 ? Math.round(secs / 60 * 10) / 10 : 0
|
||||
const set = isCardio
|
||||
? { min: mins, speed: mins > 0 ? Math.round(km / (mins / 60) * 10) / 10 : 0, done: true, ...(warmup ? { phase: 'warmup' } : {}) }
|
||||
: { w: wgt, r: reps || 0, done: true, ...(warmup ? { phase: 'warmup' } : {}) }
|
||||
|
||||
if (!isCardio && s.rpe != null && isFinite(Number(s.rpe)) && Number(s.rpe) > 0) {
|
||||
set.rpe = Math.min(10, Math.round(Number(s.rpe) * 100) / 100)
|
||||
rpeSets++
|
||||
}
|
||||
list.push(set)
|
||||
sets++
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const dates = [...byDate.keys()].sort()
|
||||
const outWorkouts = dates.map(d => {
|
||||
const day = byDate.get(d)
|
||||
const entries = [...day.ex.entries()].map(([id, ss]) => {
|
||||
const mx = Math.max(0, ...ss.filter(s => !isWarmupRow(s)).map(s => s.w || 0))
|
||||
return { id, sets: ss, topW: mx || null }
|
||||
})
|
||||
const base = new Date(d + 'T00:00:00').getTime()
|
||||
const startMs = base + (day.start ?? 18 * 3600000)
|
||||
const endMs = day.end != null ? base + day.end : startMs
|
||||
const workout = {
|
||||
id: 'iw' + uid(), d, start: startMs, end: endMs > startMs ? endMs : startMs,
|
||||
routineId: null, name: day.name || 'Imported', entries, prs: [],
|
||||
}
|
||||
workout.vol = entries.reduce((a, e) => a + e.sets.reduce((b, s) => b + (s.w || 0) * (s.r || 0), 0), 0)
|
||||
return workout
|
||||
})
|
||||
|
||||
return {
|
||||
kind: 'workouts',
|
||||
source: 'Hevy',
|
||||
workouts: outWorkouts,
|
||||
customEx: R.customEx(),
|
||||
matched: R.matchedCount(),
|
||||
matchedSets: matched,
|
||||
created: R.createdCount(),
|
||||
unmatchedNames: R.unmatchedNames(),
|
||||
sets, skipped, warmups,
|
||||
fileUnit: 'kg',
|
||||
mixedUnits: false,
|
||||
converted: unit === 'lb',
|
||||
rpeSets, rirSets: 0,
|
||||
from: dates[0] || null,
|
||||
to: dates[dates.length - 1] || null,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Hevy routine → openGym routine config.
|
||||
* Work sets become `sets`×`reps`/`weight`; warm-ups become `warmupSets`;
|
||||
* supersets keep adjacency via `sg`. Always imported as *new* routines.
|
||||
*/
|
||||
export function parseHevyRoutines(routines, templates, { unit = 'kg' } = {}) {
|
||||
const R = makeResolver(templates)
|
||||
const out = []
|
||||
|
||||
for (const r of routines || []) {
|
||||
const ex = []
|
||||
const sgMap = new Map() // Hevy superset_id → openGym sg token
|
||||
|
||||
for (const he of r.exercises || []) {
|
||||
const id = R.resolve(he.exercise_template_id, he.title)
|
||||
if (!id) continue
|
||||
|
||||
const allSets = he.sets || []
|
||||
const warm = allSets.filter(s => /warm/i.test(String(s.type || ''))).length
|
||||
const work = allSets.filter(s => !/warm/i.test(String(s.type || '')))
|
||||
if (!work.length && !warm) continue
|
||||
|
||||
const sample = work[0] || allSets[0]
|
||||
const reps = sample?.reps != null ? Math.round(sample.reps) : 0
|
||||
const secs = sample?.duration_seconds != null ? Number(sample.duration_seconds) : 0
|
||||
const km = sample?.distance_meters != null ? Number(sample.distance_meters) / 1000 : 0
|
||||
const wgt = toProfileWeight(sample?.weight_kg, unit)
|
||||
const nWork = Math.max(1, work.length)
|
||||
|
||||
let cfg
|
||||
if (km > 0 && !reps) {
|
||||
const mins = secs > 0 ? Math.round(secs / 60 * 10) / 10 : 20
|
||||
cfg = {
|
||||
id, sets: nWork, min: mins || 20,
|
||||
speed: mins > 0 ? Math.round(km / (mins / 60) * 10) / 10 : 0,
|
||||
}
|
||||
} else if (secs > 0 && !reps && !wgt) {
|
||||
cfg = { id, sets: nWork, sec: Math.round(secs), weight: 0, mode: 'time' }
|
||||
} else {
|
||||
cfg = { id, sets: nWork, reps: reps || 10, weight: wgt || 0, mode: 'reps' }
|
||||
}
|
||||
if (warm > 0) cfg.warmupSets = Math.min(5, warm)
|
||||
if (he.notes) cfg.note = String(he.notes).slice(0, 280)
|
||||
|
||||
if (he.superset_id != null && he.superset_id !== '') {
|
||||
const key = String(he.superset_id)
|
||||
if (!sgMap.has(key)) sgMap.set(key, 'hs' + uid())
|
||||
cfg.sg = sgMap.get(key)
|
||||
}
|
||||
ex.push(cfg)
|
||||
}
|
||||
|
||||
if (!ex.length) continue
|
||||
// Drop singleton supersets (partner missing after drops).
|
||||
ex.forEach((e, i) => {
|
||||
if (e.sg && !(ex[i - 1]?.sg === e.sg || ex[i + 1]?.sg === e.sg)) delete e.sg
|
||||
})
|
||||
|
||||
out.push({
|
||||
id: 'hr' + uid(),
|
||||
name: (r.title || 'Imported').trim() || 'Imported',
|
||||
emoji: 'figureStrength',
|
||||
hevyId: r.id || null,
|
||||
ex,
|
||||
})
|
||||
}
|
||||
|
||||
return {
|
||||
kind: 'routines',
|
||||
source: 'Hevy',
|
||||
routines: out,
|
||||
customEx: R.customEx(),
|
||||
matched: R.matchedCount(),
|
||||
created: R.createdCount(),
|
||||
unmatchedNames: R.unmatchedNames(),
|
||||
exerciseCount: out.reduce((n, r) => n + r.ex.length, 0),
|
||||
converted: unit === 'lb',
|
||||
}
|
||||
}
|
||||
|
||||
/** Merge Hevy routines into state — always added as new routines (fresh ids). */
|
||||
export function mergeHevyRoutines(S, parsed) {
|
||||
S.customEx = S.customEx || []
|
||||
S.routines = S.routines || []
|
||||
const exIdMap = {}
|
||||
;(parsed.customEx || []).forEach(c => {
|
||||
const same = S.customEx.find(x => (x.n || '').toLowerCase() === (c.n || '').toLowerCase() && x.bp === c.bp)
|
||||
if (same) { exIdMap[c.id] = same.id; return }
|
||||
// Keep the pre-assigned id from parse so routine configs already point at it.
|
||||
if (!S.customEx.some(x => x.id === c.id)) S.customEx.push(c)
|
||||
})
|
||||
// A second import must not double every plan: a routine that already carries the same Hevy
|
||||
// id is replaced in place (its exercises re-read from Hevy), everything else is appended.
|
||||
let added = 0, updated = 0
|
||||
for (const r of parsed.routines || []) {
|
||||
const ex = (r.ex || []).map(e => ({ ...e, id: exIdMap[e.id] || e.id }))
|
||||
const existing = r.hevyId ? S.routines.find(x => x.hevyId === r.hevyId) : null
|
||||
if (existing) {
|
||||
existing.name = r.name
|
||||
existing.ex = ex
|
||||
updated++
|
||||
continue
|
||||
}
|
||||
S.routines.push({
|
||||
id: uid(),
|
||||
name: r.name,
|
||||
emoji: r.emoji || 'figureStrength',
|
||||
...(r.hevyId ? { hevyId: r.hevyId } : {}),
|
||||
ex,
|
||||
})
|
||||
added++
|
||||
}
|
||||
return { added, updated }
|
||||
}
|
||||
|
||||
/** Body measurements from the Hevy API → `mergeImport` bodyweight shape. */
|
||||
export function parseHevyBodyweight(measurements, { unit = 'kg' } = {}) {
|
||||
const out = new Map()
|
||||
for (const m of measurements || []) {
|
||||
const d = String(m.date || '').slice(0, 10)
|
||||
if (!/^\d{4}-\d{2}-\d{2}$/.test(d)) continue
|
||||
let w = Number(m.weight_kg)
|
||||
if (!isFinite(w) || w <= 0) continue
|
||||
if (unit === 'lb') w = Math.round(w / LB_TO_KG * 10) / 10
|
||||
else w = Math.round(w * 10) / 10
|
||||
const t = m.created_at ? new Date(m.created_at).getTime() : new Date(d + 'T12:00:00').getTime()
|
||||
out.set(d, { d, w, t: isFinite(t) ? t : new Date(d + 'T12:00:00').getTime() })
|
||||
}
|
||||
const dates = [...out.keys()].sort()
|
||||
return {
|
||||
kind: 'bodyweight',
|
||||
source: 'Hevy',
|
||||
bodyweight: dates.map(d => out.get(d)),
|
||||
fileUnit: 'kg',
|
||||
converted: unit === 'lb',
|
||||
from: dates[0] || null,
|
||||
to: dates[dates.length - 1] || null,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch + parse. Returns `{ workouts, routines, bodyweight }` ready to merge,
|
||||
* or throws `HevyApiError`. The apiKey is only read here — never written.
|
||||
*/
|
||||
export async function importHevyData(apiKey, { unit = 'kg', onProgress } = {}) {
|
||||
const { templates, workouts, routines, bodyMeasurements } = await fetchHevyAccount(apiKey, { onProgress })
|
||||
onProgress && onProgress({ stage: 'parse' })
|
||||
return {
|
||||
workouts: parseHevyWorkouts(workouts, templates, { unit }),
|
||||
routines: parseHevyRoutines(routines, templates, { unit }),
|
||||
bodyweight: parseHevyBodyweight(bodyMeasurements, { unit }),
|
||||
templateCount: templates.length,
|
||||
}
|
||||
}
|
||||
|
||||
export { HevyApiError }
|
||||
@@ -0,0 +1,302 @@
|
||||
import { describe, expect, it, vi, afterEach } from 'vitest'
|
||||
import {
|
||||
matchHevyTemplate, buildHevyExerciseMap, parseHevyWorkouts, parseHevyBodyweight,
|
||||
parseHevyRoutines, mergeHevyRoutines, localWhen, importHevyData, HevyApiError, HEVY_ID_MAP,
|
||||
} from './import-hevy.js'
|
||||
import { EXIDX } from './exercises.js'
|
||||
import { mergeImport } from './import-csv.js'
|
||||
|
||||
const TEMPLATES = [
|
||||
{
|
||||
id: '3303376C', title: 'Elliptical Trainer', type: 'distance_duration',
|
||||
primary_muscle_group: 'cardio', secondary_muscle_groups: [], equipment: 'machine', is_custom: false,
|
||||
},
|
||||
{
|
||||
id: '4E5257DE', title: 'Lat Pulldown - Close Grip (Cable)', type: 'weight_reps',
|
||||
primary_muscle_group: 'lats', secondary_muscle_groups: [], equipment: 'machine', is_custom: false,
|
||||
},
|
||||
{
|
||||
id: 'DEADBEEF', title: 'My Invented Landmine Twist', type: 'weight_reps',
|
||||
primary_muscle_group: 'abdominals', secondary_muscle_groups: [], equipment: 'other', is_custom: true,
|
||||
},
|
||||
{
|
||||
id: '99D5F10E', title: 'Ab Wheel', type: 'reps_only',
|
||||
primary_muscle_group: 'abdominals', secondary_muscle_groups: [], equipment: 'other', is_custom: false,
|
||||
},
|
||||
]
|
||||
|
||||
const WORKOUT = {
|
||||
id: 'w1',
|
||||
title: 'Oberkörper 2',
|
||||
start_time: '2026-08-25T10:10:24+00:00',
|
||||
end_time: '2026-08-25T11:10:08+00:00',
|
||||
exercises: [
|
||||
{
|
||||
index: 0,
|
||||
title: 'Crosstrainer', // localized — must NOT drive the match
|
||||
exercise_template_id: '3303376C',
|
||||
sets: [{
|
||||
index: 0, type: 'normal', weight_kg: null, reps: null,
|
||||
distance_meters: 480, duration_seconds: 180, rpe: null,
|
||||
}],
|
||||
},
|
||||
{
|
||||
index: 1,
|
||||
title: 'Latzug - Enger Griff (Kabel)',
|
||||
exercise_template_id: '4E5257DE',
|
||||
sets: [
|
||||
{ index: 0, type: 'warmup', weight_kg: 25, reps: 15, distance_meters: null, duration_seconds: null, rpe: null },
|
||||
{ index: 1, type: 'normal', weight_kg: 52, reps: 15, distance_meters: null, duration_seconds: null, rpe: 8 },
|
||||
{ index: 2, type: 'normal', weight_kg: 52, reps: 10, distance_meters: null, duration_seconds: null, rpe: null },
|
||||
],
|
||||
},
|
||||
{
|
||||
index: 2,
|
||||
title: 'Meine Eigenkreation',
|
||||
exercise_template_id: 'DEADBEEF',
|
||||
sets: [
|
||||
{ index: 0, type: 'normal', weight_kg: 20, reps: 12, distance_meters: null, duration_seconds: null, rpe: null },
|
||||
],
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
describe('HEVY_ID_MAP', () => {
|
||||
it('only points at real catalogue ids', () => {
|
||||
for (const id of Object.values(HEVY_ID_MAP)) {
|
||||
expect(EXIDX[id], `catalogue missing ${id}`).toBeTruthy()
|
||||
}
|
||||
})
|
||||
|
||||
// Real import leftovers: same lifts under Hevy's naming. Map lookup is the
|
||||
// only resolution path — titles are never guessed at runtime.
|
||||
const PINNED = {
|
||||
B5D3A742: '0410', // Bulgarian Split Squat (Dumbbell)
|
||||
'914F3A96': '0327', // Chest Supported Incline Row (Dumbbell)
|
||||
'98237BA2': '0826', // Knee Raise Parallel Bars
|
||||
'4E5257DE': '2616', // Lat Pulldown - Close Grip (Cable)
|
||||
C315DC2A: '0602', // Rear Delt Reverse Fly (Cable)
|
||||
FFDA283B: '0381', // Reverse Lunge (Dumbbell)
|
||||
'8BAB2735': '0318', // Seated Incline Curl (Dumbbell)
|
||||
'9237BAD1': '0603', // Seated Shoulder Press (Machine)
|
||||
B05C2C29: '0605', // Single Leg Standing Calf Raise (Machine)
|
||||
'3303376C': '2141', // Elliptical Trainer
|
||||
'99D5F10E': '0857', // Ab Wheel
|
||||
}
|
||||
for (const [hid, want] of Object.entries(PINNED)) {
|
||||
it(`maps ${hid} → ${want} (${EXIDX[want]?.n})`, () => {
|
||||
expect(HEVY_ID_MAP[hid]).toBe(want)
|
||||
expect(matchHevyTemplate({ id: hid, title: 'ignored localized name' })).toBe(want)
|
||||
})
|
||||
}
|
||||
|
||||
it('leaves catalogue gaps unmapped (import as custom)', () => {
|
||||
for (const id of ['68CE0B9B', '0222DB42', 'D1CD146F']) {
|
||||
expect(HEVY_ID_MAP[id]).toBeUndefined()
|
||||
expect(matchHevyTemplate({ id, title: 'whatever' })).toBeNull()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('matchHevyTemplate', () => {
|
||||
it('is map-only — title never overrides the id', () => {
|
||||
expect(matchHevyTemplate({ id: '3303376C', title: 'Totally Wrong Name' })).toBe('2141')
|
||||
expect(matchHevyTemplate({ id: 'DEADBEEF', title: 'Bench Press' })).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('parseHevyWorkouts', () => {
|
||||
it('maps by template id, not the localized workout title', () => {
|
||||
const parsed = parseHevyWorkouts([WORKOUT], TEMPLATES, { unit: 'kg' })
|
||||
expect(parsed.error).toBeUndefined()
|
||||
expect(parsed.source).toBe('Hevy')
|
||||
expect(parsed.workouts).toHaveLength(1)
|
||||
|
||||
const entries = parsed.workouts[0].entries
|
||||
const elliptical = entries.find(e => e.id === '2141')
|
||||
expect(elliptical).toBeTruthy()
|
||||
expect(elliptical.sets[0]).toMatchObject({ min: 3, done: true })
|
||||
|
||||
const pulldown = entries.find(e => e.id === '2616')
|
||||
expect(pulldown).toBeTruthy()
|
||||
expect(pulldown.sets[0]).toMatchObject({ w: 25, r: 15, phase: 'warmup' })
|
||||
expect(pulldown.sets[1]).toMatchObject({ w: 52, r: 15, rpe: 8 })
|
||||
expect(pulldown.topW).toBe(52)
|
||||
expect(parsed.warmups).toBe(1)
|
||||
expect(parsed.rpeSets).toBe(1)
|
||||
|
||||
const custom = entries.find(e => String(e.id).startsWith('im'))
|
||||
expect(custom).toBeTruthy()
|
||||
expect(parsed.customEx.some(c => c.id === custom.id && c.n === 'my invented landmine twist')).toBe(true)
|
||||
expect(parsed.customEx.find(c => c.id === custom.id).bp).toBe('waist')
|
||||
expect(parsed.unmatchedNames).toContain('My Invented Landmine Twist')
|
||||
})
|
||||
|
||||
it('converts kg weights into a lb profile', () => {
|
||||
const parsed = parseHevyWorkouts([WORKOUT], TEMPLATES, { unit: 'lb' })
|
||||
const pulldown = parsed.workouts[0].entries.find(e => e.id === '2616')
|
||||
expect(pulldown.sets.find(s => s.r === 15 && !s.phase).w).toBeCloseTo(114.6, 0)
|
||||
expect(parsed.converted).toBe(true)
|
||||
})
|
||||
|
||||
it('merges two Hevy sessions on the same local day', () => {
|
||||
const a = { ...WORKOUT, id: 'a', title: 'AM', exercises: [WORKOUT.exercises[0]] }
|
||||
const b = {
|
||||
...WORKOUT, id: 'b', title: 'PM',
|
||||
start_time: '2026-08-25T18:00:00+00:00',
|
||||
end_time: '2026-08-25T19:00:00+00:00',
|
||||
exercises: [WORKOUT.exercises[1]],
|
||||
}
|
||||
const parsed = parseHevyWorkouts([a, b], TEMPLATES, { unit: 'kg' })
|
||||
expect(parsed.workouts).toHaveLength(1)
|
||||
expect(parsed.workouts[0].entries.length).toBeGreaterThanOrEqual(2)
|
||||
})
|
||||
})
|
||||
|
||||
describe('parseHevyBodyweight', () => {
|
||||
it('reads weigh-ins in the profile unit', () => {
|
||||
const parsed = parseHevyBodyweight([
|
||||
{ id: 1, date: '2026-08-23', weight_kg: 83.2, created_at: '2026-08-23T18:22:48.070Z' },
|
||||
], { unit: 'kg' })
|
||||
expect(parsed.bodyweight).toEqual([{ d: '2026-08-23', w: 83.2, t: expect.any(Number) }])
|
||||
})
|
||||
})
|
||||
|
||||
describe('mergeImport with Hevy payloads', () => {
|
||||
it('adds workouts and skips days that already exist', () => {
|
||||
const parsed = parseHevyWorkouts([WORKOUT], TEMPLATES, { unit: 'kg' })
|
||||
const S = { workouts: [], customEx: [], exWeights: {}, bodyweight: [] }
|
||||
const first = mergeImport(S, parsed)
|
||||
expect(first.added).toBe(1)
|
||||
expect(S.customEx.length).toBe(1)
|
||||
const second = mergeImport(S, parsed)
|
||||
expect(second.added).toBe(0)
|
||||
expect(S.workouts).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('localWhen', () => {
|
||||
it('parses an ISO timestamp into a local calendar day', () => {
|
||||
const w = localWhen('2026-08-25T10:10:24+00:00')
|
||||
expect(w.d).toMatch(/^\d{4}-\d{2}-\d{2}$/)
|
||||
expect(w.t).toBeGreaterThanOrEqual(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('importHevyData', () => {
|
||||
afterEach(() => { vi.unstubAllGlobals(); vi.restoreAllMocks() })
|
||||
|
||||
it('pages templates and workouts, never persists the key', async () => {
|
||||
const calls = []
|
||||
vi.stubGlobal('fetch', vi.fn(async (url, opts) => {
|
||||
calls.push({ url: String(url), key: opts.headers['api-key'] })
|
||||
const u = String(url)
|
||||
if (u.includes('/exercise_templates')) {
|
||||
return { ok: true, status: 200, json: async () => ({ page: 1, page_count: 1, exercise_templates: TEMPLATES }) }
|
||||
}
|
||||
if (u.includes('/workouts')) {
|
||||
return { ok: true, status: 200, json: async () => ({ page: 1, page_count: 1, workouts: [WORKOUT] }) }
|
||||
}
|
||||
if (u.includes('/routines')) {
|
||||
return { ok: true, status: 200, json: async () => ({ page: 1, page_count: 1, routines: [] }) }
|
||||
}
|
||||
if (u.includes('/body_measurements')) {
|
||||
return { ok: true, status: 200, json: async () => ({ page: 1, page_count: 1, body_measurements: [] }) }
|
||||
}
|
||||
return { ok: false, status: 404, json: async () => ({}) }
|
||||
}))
|
||||
|
||||
const result = await importHevyData('test-key-not-stored', { unit: 'kg' })
|
||||
expect(result.workouts.workouts).toHaveLength(1)
|
||||
expect(result.routines.routines).toHaveLength(0)
|
||||
expect(result.bodyweight.bodyweight).toHaveLength(0)
|
||||
expect(calls.every(c => c.key === 'test-key-not-stored')).toBe(true)
|
||||
})
|
||||
|
||||
it('surfaces a refused key as HevyApiError auth', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn(async () => ({ ok: false, status: 401, json: async () => ({}) })))
|
||||
await expect(importHevyData('bad')).rejects.toMatchObject({ name: 'HevyApiError', message: 'auth' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('parseHevyRoutines', () => {
|
||||
const ROUTINE = {
|
||||
id: 'r1',
|
||||
title: 'Oberkörper 2',
|
||||
exercises: [
|
||||
{
|
||||
title: 'Crosstrainer',
|
||||
exercise_template_id: '3303376C',
|
||||
superset_id: null,
|
||||
sets: [{ type: 'normal', weight_kg: null, reps: null, distance_meters: 480, duration_seconds: 180 }],
|
||||
},
|
||||
{
|
||||
title: 'Latzug',
|
||||
exercise_template_id: '4E5257DE',
|
||||
superset_id: 1,
|
||||
sets: [
|
||||
{ type: 'warmup', weight_kg: 25, reps: 15 },
|
||||
{ type: 'normal', weight_kg: 52, reps: 15 },
|
||||
{ type: 'normal', weight_kg: 52, reps: 12 },
|
||||
{ type: 'normal', weight_kg: 52, reps: 10 },
|
||||
],
|
||||
},
|
||||
{
|
||||
title: 'Row partner',
|
||||
exercise_template_id: '914F3A96', // chest supported incline row → 0327
|
||||
superset_id: 1,
|
||||
sets: [
|
||||
{ type: 'normal', weight_kg: 20, reps: 12 },
|
||||
{ type: 'normal', weight_kg: 20, reps: 12 },
|
||||
],
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
it('builds openGym routine configs from Hevy sets', () => {
|
||||
const parsed = parseHevyRoutines([ROUTINE], TEMPLATES, { unit: 'kg' })
|
||||
expect(parsed.routines).toHaveLength(1)
|
||||
expect(parsed.routines[0].name).toBe('Oberkörper 2')
|
||||
expect(parsed.exerciseCount).toBe(3)
|
||||
|
||||
const [cardio, pull, row] = parsed.routines[0].ex
|
||||
expect(cardio.id).toBe('2141')
|
||||
expect(cardio).toMatchObject({ sets: 1, min: 3 })
|
||||
expect(pull.id).toBe('2616')
|
||||
expect(pull).toMatchObject({ sets: 3, reps: 15, weight: 52, warmupSets: 1 })
|
||||
expect(row.id).toBe('0327')
|
||||
expect(pull.sg).toBeTruthy()
|
||||
expect(pull.sg).toBe(row.sg)
|
||||
})
|
||||
|
||||
it('mergeHevyRoutines replaces a routine it imported before instead of duplicating it', () => {
|
||||
const parsed = parseHevyRoutines([ROUTINE], TEMPLATES, { unit: 'kg' })
|
||||
const S = { routines: [], customEx: [] }
|
||||
expect(mergeHevyRoutines(S, parsed)).toEqual({ added: 1, updated: 0 })
|
||||
expect(S.routines).toHaveLength(1)
|
||||
expect(S.routines[0].hevyId).toBe(ROUTINE.id)
|
||||
const firstId = S.routines[0].id
|
||||
S.routines[0].name = 'renamed locally'
|
||||
expect(mergeHevyRoutines(S, parsed)).toEqual({ added: 0, updated: 1 })
|
||||
expect(S.routines).toHaveLength(1)
|
||||
expect(S.routines[0].id).toBe(firstId)
|
||||
expect(S.routines[0].name).toBe(ROUTINE.title)
|
||||
})
|
||||
|
||||
it('mergeHevyRoutines still adds a routine that carries no Hevy id', () => {
|
||||
const parsed = parseHevyRoutines([{ ...ROUTINE, id: undefined }], TEMPLATES, { unit: 'kg' })
|
||||
const S = { routines: [], customEx: [] }
|
||||
mergeHevyRoutines(S, parsed); mergeHevyRoutines(S, parsed)
|
||||
expect(S.routines).toHaveLength(2)
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildHevyExerciseMap', () => {
|
||||
it('indexes every template id from the static map', () => {
|
||||
const map = buildHevyExerciseMap(TEMPLATES)
|
||||
expect(map.get('3303376C')).toBe('2141')
|
||||
expect(map.get('4E5257DE')).toBe('2616')
|
||||
expect(map.get('DEADBEEF')).toBeNull()
|
||||
expect(map.size).toBe(TEMPLATES.length)
|
||||
})
|
||||
})
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { matchExercise, parseWorkoutCSV } from './import-csv.js'
|
||||
import { matchExercise, matchHevyTitle, parseWorkoutCSV, detectSource } from './import-csv.js'
|
||||
import { EXIDX } from './exercises.js'
|
||||
|
||||
// The names other apps actually export, and the catalogue entry each has to land on.
|
||||
@@ -109,3 +109,36 @@ describe('invented exercises get a body part from their name', () => {
|
||||
expect(r.customEx[0].bp).toBe('shoulders')
|
||||
})
|
||||
})
|
||||
|
||||
describe('Hevy CSV uses the generated title map', () => {
|
||||
const HEVY_CSV = [
|
||||
'title,start_time,end_time,description,exercise_title,superset_id,exercise_notes,set_index,set_type,weight_kg,reps,distance_km,duration_seconds,rpe',
|
||||
'Push,2026-08-01 10:00:00,2026-08-01 11:00:00,,Bulgarian Split Squat (Dumbbell),,,0,normal,40,10,0,,',
|
||||
'Push,2026-08-01 10:00:00,2026-08-01 11:00:00,,Lat Pulldown - Close Grip (Cable),,,0,warmup,25,15,0,,',
|
||||
'Push,2026-08-01 10:00:00,2026-08-01 11:00:00,,Lat Pulldown - Close Grip (Cable),,,1,normal,52,12,0,,8',
|
||||
'Push,2026-08-01 10:00:00,2026-08-01 11:00:00,,Reverse Lunge (Dumbbell),,,0,normal,20,10,0,,',
|
||||
].join('\n')
|
||||
|
||||
it('detects the Hevy export dialect', () => {
|
||||
expect(detectSource(HEVY_CSV.split('\n')[0].split(','))).toBe('Hevy')
|
||||
})
|
||||
|
||||
it('resolves English Hevy titles through HEVY_TITLE_MAP before the word-bag', () => {
|
||||
expect(matchHevyTitle('Bulgarian Split Squat (Dumbbell)')).toBe('0410')
|
||||
expect(matchHevyTitle('Lat Pulldown - Close Grip (Cable)')).toBe('2616')
|
||||
expect(matchHevyTitle('Reverse Lunge (Dumbbell)')).toBe('0381')
|
||||
// Word-bag alone still misses these — the title map is what makes CSV work.
|
||||
expect(matchExercise('Bulgarian Split Squat (Dumbbell)')).toBeNull()
|
||||
})
|
||||
|
||||
it('imports a Hevy CSV onto catalogue ids, not customs', () => {
|
||||
const parsed = parseWorkoutCSV(HEVY_CSV, { unit: 'kg' })
|
||||
expect(parsed.source).toBe('Hevy')
|
||||
expect(parsed.created).toBe(0)
|
||||
const ids = parsed.workouts[0].entries.map(e => e.id).sort()
|
||||
expect(ids).toEqual(['0410', '0381', '2616'].sort())
|
||||
const pull = parsed.workouts[0].entries.find(e => e.id === '2616')
|
||||
expect(pull.sets[0]).toMatchObject({ w: 25, r: 15, phase: 'warmup' })
|
||||
expect(pull.sets[1]).toMatchObject({ w: 52, r: 12, rpe: 8 })
|
||||
})
|
||||
})
|
||||
+69
-19
@@ -4,13 +4,14 @@
|
||||
// mode in a browser, this is the user's only copy of their training log, so it can't depend
|
||||
// on WebView localStorage alone (iOS evicts that under storage pressure). Every persist()
|
||||
// therefore also lands in a JSON file in the app's private data directory, and boot()
|
||||
// restores from it. The workout reminder uses native local notifications scheduled per
|
||||
// planned weekday — no server involved, unlike Web Push in the self-hosted version.
|
||||
// restores from it. The workout reminder uses native local notifications scheduled per future
|
||||
// calendar date — no server involved, unlike Web Push in the self-hosted version.
|
||||
//
|
||||
// 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'
|
||||
import { isoOf, todayISO } from './format.js'
|
||||
import { effectiveRoutineId } from './history.js'
|
||||
|
||||
export const MOBILE = import.meta.env.VITE_MOBILE === '1'
|
||||
|
||||
@@ -68,34 +69,83 @@ export async function saveRemoteFile(data) {
|
||||
} catch (e) { /* worst case: onboarding asks again next launch */ }
|
||||
}
|
||||
|
||||
// (Re)schedule the workout-day reminder: one repeating notification per weekday that has a
|
||||
// routine in the weekly plan. Cheap enough to run after any state change — the plan or the
|
||||
// reminder time may just have been edited. `interactive` gates the OS permission prompt to
|
||||
// the Settings toggle; a background resync never pops a dialog.
|
||||
// Keep enough dates queued to cover normal app use between foregrounds without creating an
|
||||
// unbounded notification list. The next sync cancels and replaces this whole window.
|
||||
export const REMINDER_WINDOW_DAYS = 60
|
||||
const REMINDER_ID_BASE = 1000
|
||||
const LEGACY_REMINDER_IDS = Array.from({ length: 7 }, (_, d) => ({ id: 100 + d }))
|
||||
|
||||
// Pure date expansion for the native reminder. `now` is injectable so the calendar boundary,
|
||||
// completed-day suppression, and today's past-time rule stay deterministic in tests.
|
||||
export function buildReminderNotifications(S, now = new Date()) {
|
||||
const r = S?.reminder
|
||||
if (!r?.on) return []
|
||||
const routines = Array.isArray(S.routines) ? S.routines : []
|
||||
const completed = new Set((S.workouts || []).map(w => w.d))
|
||||
const state = { ...S, routines, week: S.week || {}, dayPlan: S.dayPlan || {} }
|
||||
const [hour, minute] = (r.time || '08:00').split(':').map(Number)
|
||||
if (!Number.isInteger(hour) || !Number.isInteger(minute)) return []
|
||||
const date = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 12)
|
||||
const notifications = []
|
||||
for (let offset = 0; offset < REMINDER_WINDOW_DAYS; offset++) {
|
||||
const day = new Date(date)
|
||||
day.setDate(date.getDate() + offset)
|
||||
const iso = isoOf(day)
|
||||
if (completed.has(iso)) continue
|
||||
const rid = effectiveRoutineId(state, iso)
|
||||
const routine = routines.find(x => x.id === rid)
|
||||
if (!routine) continue
|
||||
const at = new Date(day)
|
||||
at.setHours(hour, minute, 0, 0)
|
||||
if (at <= now) continue
|
||||
notifications.push({
|
||||
id: REMINDER_ID_BASE + offset,
|
||||
title: t('Workout day'),
|
||||
body: t('{0} is on the plan today — let’s go!', routine.name),
|
||||
schedule: { at, allowWhileIdle: true },
|
||||
})
|
||||
}
|
||||
return notifications
|
||||
}
|
||||
|
||||
// (Re)schedule the workout-day reminder: one one-off notification per future calendar date in
|
||||
// the bounded window. Cheap enough to run after any state change — the plan or the reminder time
|
||||
// may just have been edited. `interactive` gates the OS permission prompt to the Settings toggle;
|
||||
// a background resync never pops a dialog.
|
||||
export async function syncReminder(S, interactive = false) {
|
||||
try {
|
||||
const { LocalNotifications } = await import('@capacitor/local-notifications')
|
||||
await LocalNotifications.cancel({ notifications: [0, 1, 2, 3, 4, 5, 6].map(d => ({ id: 100 + d })) }).catch(() => {})
|
||||
await LocalNotifications.cancel({ notifications: [
|
||||
...LEGACY_REMINDER_IDS,
|
||||
...Array.from({ length: REMINDER_WINDOW_DAYS }, (_, d) => ({ id: REMINDER_ID_BASE + d })),
|
||||
] }).catch(() => {})
|
||||
const r = S.reminder
|
||||
if (!r?.on) return true
|
||||
let perm = await LocalNotifications.checkPermissions()
|
||||
if (perm.display !== 'granted' && interactive) perm = await LocalNotifications.requestPermissions()
|
||||
if (perm.display !== 'granted') return false
|
||||
const [hour, minute] = (r.time || '08:00').split(':').map(Number)
|
||||
const notifications = Object.entries(S.week || {})
|
||||
.filter(([, rid]) => rid && (S.routines || []).some(x => x.id === rid))
|
||||
.map(([day, rid]) => ({
|
||||
id: 100 + Number(day),
|
||||
title: t('Workout day'),
|
||||
body: t('{0} is on the plan today — let’s go!', S.routines.find(x => x.id === rid).name),
|
||||
// Capacitor weekdays are 1 (Sunday) … 7 (Saturday); S.week uses getDay() 0…6.
|
||||
schedule: { on: { weekday: Number(day) + 1, hour, minute }, allowWhileIdle: true },
|
||||
}))
|
||||
const notifications = buildReminderNotifications(S)
|
||||
if (notifications.length) await LocalNotifications.schedule({ notifications })
|
||||
return true
|
||||
} catch (e) { return false }
|
||||
}
|
||||
|
||||
// Capacitor emits appStateChange when the native shell returns to the foreground. The visibility
|
||||
// listener also covers WebView/browser transitions, and both are harmless on a non-mobile build.
|
||||
let reminderSyncStarted = false
|
||||
export function initReminderSync(getState) {
|
||||
if (!MOBILE || reminderSyncStarted) return
|
||||
reminderSyncStarted = true
|
||||
const resync = () => {
|
||||
if (document.visibilityState === 'hidden') return
|
||||
syncReminder(getState()).catch(() => {})
|
||||
}
|
||||
document.addEventListener('visibilitychange', resync)
|
||||
import('@capacitor/app').then(({ App }) => {
|
||||
App.addListener('appStateChange', ({ isActive }) => { if (isActive) resync() })
|
||||
}).catch(() => {})
|
||||
}
|
||||
|
||||
// WKWebView can't do blob-URL downloads, so the backup goes out through the OS share sheet
|
||||
// (Files, AirDrop, mail, …) from a temp file instead.
|
||||
export async function shareExport(json, filename) {
|
||||
@@ -120,4 +170,4 @@ export async function writeAutoBackup(state) {
|
||||
recursive: true,
|
||||
})
|
||||
} catch (e) { /* best effort — the private mirror in Directory.Data still has the data */ }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { isoOf } from './format.js'
|
||||
import { buildReminderNotifications } from './mobile.js'
|
||||
|
||||
const push = { id: 'push', name: 'Push' }
|
||||
const pull = { id: 'pull', name: 'Pull' }
|
||||
const legs = { id: 'legs', name: 'Legs' }
|
||||
const state = (patch = {}) => ({
|
||||
routines: [push, pull, legs], week: {}, dayPlan: {}, workouts: [],
|
||||
reminder: { on: true, time: '08:00' }, ...patch,
|
||||
})
|
||||
const iso = d => isoOf(d)
|
||||
|
||||
describe('buildReminderNotifications', () => {
|
||||
it('expands the weekly baseline into future dated notifications', () => {
|
||||
const now = new Date(2026, 5, 1, 7, 0) // Monday
|
||||
const notifications = buildReminderNotifications(state({ week: { 1: 'push', 3: 'pull' } }), now)
|
||||
|
||||
expect(notifications.slice(0, 2).map(n => iso(n.schedule.at))).toEqual([
|
||||
iso(now), iso(new Date(2026, 5, 3)),
|
||||
])
|
||||
expect(notifications[0].body).toContain('Push')
|
||||
expect(notifications[0].schedule.allowWhileIdle).toBe(true)
|
||||
})
|
||||
|
||||
it('uses rest today and a routine override tomorrow when rescheduling', () => {
|
||||
const now = new Date(2026, 5, 1, 7, 0) // Monday
|
||||
const today = iso(now), tomorrow = iso(new Date(2026, 5, 2))
|
||||
const notifications = buildReminderNotifications(state({
|
||||
week: { 1: 'push' }, dayPlan: { [today]: 'rest', [tomorrow]: 'pull' },
|
||||
}), now)
|
||||
|
||||
expect(notifications.slice(0, 1).map(n => [iso(n.schedule.at), n.body])).toEqual([
|
||||
[tomorrow, expect.stringContaining('Pull')],
|
||||
])
|
||||
})
|
||||
|
||||
it('schedules a valid override on a weekly rest day', () => {
|
||||
const now = new Date(2026, 5, 1, 7, 0) // Monday
|
||||
const wednesday = new Date(2026, 5, 3)
|
||||
const notifications = buildReminderNotifications(state({ dayPlan: { [iso(wednesday)]: 'legs' } }), now)
|
||||
|
||||
expect(notifications.some(n => iso(n.schedule.at) === iso(wednesday) && n.body.includes('Legs'))).toBe(true)
|
||||
})
|
||||
|
||||
it('suppresses dates that already have a completed workout', () => {
|
||||
const now = new Date(2026, 5, 1, 7, 0) // Monday
|
||||
const notifications = buildReminderNotifications(state({
|
||||
week: { 1: 'push' }, workouts: [{ d: iso(now) }],
|
||||
}), now)
|
||||
|
||||
expect(notifications.some(n => iso(n.schedule.at) === iso(now))).toBe(false)
|
||||
})
|
||||
|
||||
it("skips today's reminder after the configured local time has passed", () => {
|
||||
const now = new Date(2026, 5, 1, 9, 0) // Monday
|
||||
const notifications = buildReminderNotifications(state({ week: { 1: 'push' } }), now)
|
||||
|
||||
expect(notifications.some(n => iso(n.schedule.at) === iso(now))).toBe(false)
|
||||
expect(notifications.some(n => iso(n.schedule.at) === iso(new Date(2026, 5, 8)))).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -9,6 +9,7 @@
|
||||
|
||||
import { isWarmupRow } from './workout-model.js'
|
||||
import { EXIDX, smOf } from './exercises.js'
|
||||
import { todayISO, weekKey, MONDAY } from './format.js'
|
||||
|
||||
// The muscles a map can shade, in head-to-toe order — also the order of any list
|
||||
// built from them, so "what am I neglecting" reads top-down like a body.
|
||||
@@ -160,7 +161,7 @@ export function muscleGroupsOf(entry) {
|
||||
? [...parts.primary, ...parts.secondary]
|
||||
: explicit || [ex?.tg, ex?.mg, ...arrayOf(smOf(ex))]
|
||||
const out = canonicalUnique(source)
|
||||
if (!out.length && !useParts && explicit == null) {
|
||||
if (!out.length && !useParts) {
|
||||
canonicalUnique(Object.keys(BY_BODYPART[ex?.bp] || {})).forEach(slug => out.push(slug))
|
||||
}
|
||||
return out
|
||||
@@ -259,6 +260,20 @@ export const loadOfWorkouts = (workouts, pick) =>
|
||||
loadOf((workouts || []).flatMap(w =>
|
||||
(w.entries || []).map(e => ({ id: e.id, ex: e.exercise || e, sets: (e.sets || []).filter(s => s.done && !isWarmupRow(s) && (!pick || pick(s))).length }))))
|
||||
|
||||
/**
|
||||
* Workouts in one existing Muscle balance range, with time injected for deterministic tests.
|
||||
*
|
||||
* The 7-day range is "this week", not "the last seven days", so it moves with the profile's
|
||||
* first weekday — the caller passes it since this takes workouts rather than the whole state.
|
||||
*/
|
||||
export function muscleBalanceWindow(workouts, win, now = Date.now(), today = todayISO(), ws = MONDAY) {
|
||||
return (workouts || []).filter(workout => win === 0
|
||||
? true
|
||||
: win === 7
|
||||
? weekKey(workout.d, ws) === weekKey(today, ws)
|
||||
: (workout.start || new Date(workout.d).getTime()) > now - win * 86400000)
|
||||
}
|
||||
|
||||
/** Load a routine *would* produce, from its planned set counts. */
|
||||
export const loadOfRoutine = routine =>
|
||||
loadOf((routine?.ex || []).map(c => ({ id: c.id, ex: c, sets: c.sets || 1 })))
|
||||
@@ -304,7 +319,8 @@ export function levelsOf(load, thresholds) {
|
||||
|
||||
/** Muscles sorted hardest-worked first; untrained ones last, in body order. */
|
||||
export function rankOf(load) {
|
||||
const worked = MUSCLES.filter(m => (load[m] || 0) > 0).sort((a, b) => load[b] - load[a])
|
||||
const worked = MUSCLES.filter(m => (load[m] || 0) > 0)
|
||||
.sort((a, b) => load[b] - load[a] || MUSCLES.indexOf(a) - MUSCLES.indexOf(b))
|
||||
const missed = MUSCLES.filter(m => !(load[m] > 0))
|
||||
return { worked, missed }
|
||||
}
|
||||
@@ -1,6 +1,9 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { EXIDX, EXDB, smOf } from './exercises.js'
|
||||
import { MUSCLE_NAME, exerciseMuscleSnapshot, hasExplicitMuscleMetadata, loadOf, loadOfWorkouts, matchesMuscleGroups, muscleGroupsOf, musclesOf } from './muscles.js'
|
||||
import {
|
||||
MUSCLE_NAME, exerciseMuscleSnapshot, hasExplicitMuscleMetadata, levelsOf, loadOf,
|
||||
loadOfWorkouts, matchesMuscleGroups, muscleBalanceWindow, muscleGroupsOf, musclesOf, rankOf
|
||||
} from './muscles.js'
|
||||
|
||||
describe('multi-muscle exercise metadata', () => {
|
||||
it('normalizes legacy primary/secondary fields and removes duplicate groups', () => {
|
||||
@@ -20,6 +23,12 @@ describe('multi-muscle exercise metadata', () => {
|
||||
expect(matchesMuscleGroups({ bp: 'back', muscleGroups: [] }, ['lower-back'])).toBe(true)
|
||||
})
|
||||
|
||||
it('falls back consistently when explicit groups contain only unknown names', () => {
|
||||
const ex = { bp: 'back', muscleGroups: ['not-a-drawable-name'] }
|
||||
expect(muscleGroupsOf(ex)).toEqual(['upper-back', 'lower-back'])
|
||||
expect(musclesOf(ex)).toEqual({ 'upper-back': 0.75, 'lower-back': 0.25 })
|
||||
})
|
||||
|
||||
it('matches an exercise when any requested muscle group matches', () => {
|
||||
const ex = { muscleGroups: ['chest', 'triceps'] }
|
||||
expect(matchesMuscleGroups(ex, ['hamstring', 'triceps'])).toBe(true)
|
||||
@@ -172,3 +181,32 @@ describe('warm-up boundary', () => {
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('muscle balance windows and ranking', () => {
|
||||
const now = new Date('2026-08-27T12:00:00').getTime()
|
||||
const workouts = [
|
||||
{ id: 'monday', d: '2026-08-24', start: new Date('2026-08-24T12:00:00').getTime() },
|
||||
{ id: 'sunday', d: '2026-08-23', start: new Date('2026-08-23T12:00:00').getTime() },
|
||||
{ id: 'boundary', d: '2026-07-28', start: now - 30 * 86400000 },
|
||||
{ id: 'inside', d: '2026-07-29', start: now - 29 * 86400000 },
|
||||
]
|
||||
|
||||
it('preserves calendar-week, strict trailing-day, and all-history semantics', () => {
|
||||
expect(muscleBalanceWindow(workouts, 7, now, '2026-08-27').map(w => w.id)).toEqual(['monday'])
|
||||
expect(muscleBalanceWindow(workouts, 30, now, '2026-08-27').map(w => w.id)).toEqual(['monday', 'sunday', 'inside'])
|
||||
expect(muscleBalanceWindow(workouts, 0, now, '2026-08-27')).toEqual(workouts)
|
||||
})
|
||||
|
||||
it('uses relative levels and canonical order to break load ties', () => {
|
||||
const load = { chest: 2, deltoids: 2, biceps: 1 }
|
||||
expect(rankOf(load).worked).toEqual(['deltoids', 'chest', 'biceps'])
|
||||
expect(levelsOf(load)).toMatchObject({ deltoids: 4, chest: 4, biceps: 2, abs: 0 })
|
||||
})
|
||||
|
||||
it('keeps catalogue precedence and deleted-custom snapshot weights', () => {
|
||||
const known = { id: '0025', muscleGroups: ['quadriceps'], sets: [{ done: true }] }
|
||||
const deleted = { id: 'deleted', muscleSnapshot: { muscleWeights: { chest: 1 } }, sets: [{ done: true }] }
|
||||
expect(loadOfWorkouts([{ entries: [known] }])).toEqual({ chest: 1, triceps: 0.4, deltoids: 0.4, biceps: 0.4 })
|
||||
expect(loadOfWorkouts([{ entries: [deleted] }])).toEqual({ chest: 1 })
|
||||
})
|
||||
})
|
||||
@@ -10,11 +10,12 @@
|
||||
|
||||
import { EXIDX, isBodyweightEq } from './exercises.js'
|
||||
import { modeOf, fmtSec, isBw, isPerSide, sideReps, MAX_PLANNED_WARMUPS } from './history.js'
|
||||
import { uid, todayISO, DAYN, fmtNum, exCount } from './format.js'
|
||||
import { uid, todayISO, DAYN, weekOrder, weekStartOf, fmtNum, exCount } from './format.js'
|
||||
import { t, exerciseNameFor } from './i18n-core.js'
|
||||
|
||||
const PLAN_FMT = 1
|
||||
const WEEK_ORDER = [1, 2, 3, 4, 5, 6, 0] // Mon-first, matching the Plan screen
|
||||
const WEEK_DAYS = [1, 2, 3, 4, 5, 6, 0] // every getDay() index; only the reader's own
|
||||
// screen puts them in an order (see weekOrder)
|
||||
|
||||
// Keep only the meaningful config fields, so the file stays small and readable.
|
||||
function cleanEx(e) {
|
||||
@@ -44,6 +45,10 @@ function cleanEx(e) {
|
||||
if (e.inc > 0) o.inc = e.inc
|
||||
if (e.repsMin != null) o.repsMin = e.repsMin
|
||||
if (e.repsMax != null) o.repsMax = e.repsMax
|
||||
// The exercise's own rest (issue #10) is part of how it is prescribed, so it travels too —
|
||||
// only when set, so a plan that never asked for one leaves the recipient's own default
|
||||
// timer in charge. parsePlan and mergePlan carry it through by spread.
|
||||
if (e.restSec > 0) o.restSec = e.restSec
|
||||
if (e.sg) o.sg = e.sg
|
||||
if (e.note) o.note = e.note
|
||||
const warm = cleanWarmupSets(e.warmupSets)
|
||||
@@ -63,6 +68,13 @@ function cleanWarmupSets(v) {
|
||||
return n > 0 ? Math.min(MAX_PLANNED_WARMUPS, n) : 0
|
||||
}
|
||||
|
||||
/** A positive whole number of seconds or nothing — the same gate cleanEx applies on the way
|
||||
* out, so a hand-edited plan file can't hand the rest timer a string or a negative. */
|
||||
function cleanRestSec(v) {
|
||||
const n = Math.round(Number(v)) || 0
|
||||
return n > 0 ? n : 0
|
||||
}
|
||||
|
||||
/** Keep the floors the config sheet and applyIntensifierPlan already enforce, and nothing else:
|
||||
* a plan file is someone else's data, so anything unrecognised is dropped rather than trusted. */
|
||||
function cleanIntensifier(x) {
|
||||
@@ -79,14 +91,17 @@ function cleanIntensifier(x) {
|
||||
/** Build the shareable bundle: every routine, the week schedule, referenced customs. */
|
||||
export function buildPlanBundle(S, name) {
|
||||
const routines = (S.routines || []).map(r => ({
|
||||
id: r.id, name: r.name, emoji: r.emoji, ...(r.prog ? { prog: r.prog } : {}), ex: (r.ex || []).map(cleanEx)
|
||||
id: r.id, name: r.name, emoji: r.emoji,
|
||||
...(r.prog ? { prog: r.prog } : {}),
|
||||
...(r.excludeFromProgression === true ? { excludeFromProgression: true } : {}),
|
||||
ex: (r.ex || []).map(cleanEx)
|
||||
}))
|
||||
const usedIds = new Set(routines.flatMap(r => r.ex.map(e => e.id)))
|
||||
const customEx = (S.customEx || [])
|
||||
.filter(c => usedIds.has(c.id))
|
||||
.map(c => ({ id: c.id, n: c.n, bp: c.bp, ...(c.desc ? { desc: c.desc } : {}) }))
|
||||
const week = {}
|
||||
WEEK_ORDER.forEach(d => { if (S.week?.[d]) week[d] = S.week[d] })
|
||||
WEEK_DAYS.forEach(d => { if (S.week?.[d]) week[d] = S.week[d] })
|
||||
return { opengym_plan: PLAN_FMT, exported: todayISO(), name: name || '', week, routines, customEx }
|
||||
}
|
||||
|
||||
@@ -114,12 +129,13 @@ export function parsePlan(raw) {
|
||||
if (!ok) dropped++
|
||||
return ok
|
||||
}).map(e => {
|
||||
// The exercises pass through as written, so the two fields that carry numbers into the
|
||||
// The exercises pass through as written, so the fields that carry numbers into the
|
||||
// planner get the same clamps on the way in that they get on the way out.
|
||||
const warm = cleanWarmupSets(e.warmupSets)
|
||||
const intens = cleanIntensifier(e.intensifier)
|
||||
const { warmupSets, intensifier, ...rest } = e
|
||||
return { ...rest, ...(warm ? { warmupSets: warm } : {}), ...(intens ? { intensifier: intens } : {}) }
|
||||
const rest = cleanRestSec(e.restSec)
|
||||
const { warmupSets, intensifier, restSec, ...passthrough } = e
|
||||
return { ...passthrough, ...(warm ? { warmupSets: warm } : {}), ...(intens ? { intensifier: intens } : {}), ...(rest ? { restSec: rest } : {}) }
|
||||
})
|
||||
}))
|
||||
return {
|
||||
@@ -130,7 +146,7 @@ export function parsePlan(raw) {
|
||||
dropped,
|
||||
routineCount: routines.length,
|
||||
exerciseCount: routines.reduce((n, r) => n + r.ex.length, 0),
|
||||
scheduledDays: WEEK_ORDER.filter(d => data.week?.[d]).length
|
||||
scheduledDays: WEEK_DAYS.filter(d => data.week?.[d]).length
|
||||
}
|
||||
}
|
||||
|
||||
@@ -160,11 +176,12 @@ export function mergePlan(s, bundle, { schedule } = {}) {
|
||||
name: r.name || t('Shared routine'),
|
||||
emoji: r.emoji,
|
||||
...(r.prog ? { prog: r.prog } : {}),
|
||||
...(r.excludeFromProgression === true ? { excludeFromProgression: true } : {}),
|
||||
ex: (r.ex || []).map(e => ({ ...e, id: exIdMap[e.id] || e.id }))
|
||||
})
|
||||
})
|
||||
if (schedule) {
|
||||
WEEK_ORDER.forEach(d => { delete s.week[d] })
|
||||
WEEK_DAYS.forEach(d => { delete s.week[d] })
|
||||
Object.entries(bundle.week || {}).forEach(([d, oldId]) => {
|
||||
if (ridMap[oldId]) s.week[d] = ridMap[oldId]
|
||||
})
|
||||
@@ -224,7 +241,8 @@ function routineHTML(r, unit) {
|
||||
}
|
||||
|
||||
function weekHTML(S) {
|
||||
const rows = WEEK_ORDER.map(d => {
|
||||
// The printout is read by whoever exported it, so the week runs in their order.
|
||||
const rows = weekOrder(weekStartOf(S)).map(d => {
|
||||
const r = S.routines.find(x => x.id === S.week?.[d])
|
||||
const val = r ? esc(r.name) : `<span class="rest">${esc(t('Rest'))}</span>`
|
||||
return `<div class="w-row"><div class="w-day">${esc(t(DAYN[d]))}</div><div class="w-r">${val}</div></div>`
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { buildPlanBundle, parsePlan } from './plan-share.js'
|
||||
import { buildPlanBundle, mergePlan, parsePlan } from './plan-share.js'
|
||||
|
||||
// There was no test file for plan sharing at all, which is how a whole prescription field
|
||||
// went missing without anyone noticing.
|
||||
@@ -24,6 +24,37 @@ describe('what survives a shared plan', () => {
|
||||
expect(roundTrip({ warmupSets: 3 }).warmupSets).toBe(3)
|
||||
})
|
||||
|
||||
it('carries progression exclusion on a routine through export and merge', () => {
|
||||
const source = stateWith({})
|
||||
source.routines[0].excludeFromProgression = true
|
||||
const bundle = parsePlan(buildPlanBundle(source, 'Plan'))
|
||||
const target = { routines: [], week: {}, customEx: [] }
|
||||
|
||||
expect(bundle.routines[0].excludeFromProgression).toBe(true)
|
||||
mergePlan(target, bundle)
|
||||
expect(target.routines[0].excludeFromProgression).toBe(true)
|
||||
})
|
||||
|
||||
// Issue #10: the rest an exercise prescribes is part of the prescription. A shared 5x5 whose
|
||||
// rests arrive as the recipient's 60 s default is a different session than the one written.
|
||||
it('carries a per-exercise rest', () => {
|
||||
expect(roundTrip({ restSec: 180 }).restSec).toBe(180)
|
||||
})
|
||||
|
||||
// The absence has to survive too: writing a 0 would pin the recipient's timer to "off"
|
||||
// instead of letting the exercise keep inheriting whatever their own default is.
|
||||
it('leaves an exercise that set no rest free of the field', () => {
|
||||
expect('restSec' in roundTrip({})).toBe(false)
|
||||
expect('restSec' in roundTrip({ restSec: 0 })).toBe(false)
|
||||
})
|
||||
|
||||
it('carries the rest onto the routine mergePlan adds', () => {
|
||||
const bundle = parsePlan(JSON.stringify(buildPlanBundle(stateWith({ restSec: 180 }), 'Plan')))
|
||||
const s = { routines: [], customEx: [], week: {} }
|
||||
mergePlan(s, bundle, { schedule: false })
|
||||
expect(s.routines[0].ex[0].restSec).toBe(180)
|
||||
})
|
||||
|
||||
it('drops an intensifier it does not recognise rather than passing it on', () => {
|
||||
expect(roundTrip({ intensifier: { type: 'nonsense', count: 3 } }).intensifier).toBeUndefined()
|
||||
})
|
||||
@@ -33,6 +64,16 @@ describe('what survives a shared plan', () => {
|
||||
expect(parsePlan(bundle).routines[0].ex[0].warmupSets).toBe(5)
|
||||
})
|
||||
|
||||
// A plan file is someone else's data: a rest that arrives as a string would reach the timer's
|
||||
// arithmetic as one, and a negative or garbage one has no meaning to keep.
|
||||
it('normalises a hand-edited rest to a positive whole number or drops it', () => {
|
||||
const withRest = restSec => ({ opengym_plan: 1, name: 'x', routines: [{ id: 'r', name: 'R', ex: [{ id: '0025', sets: 3, reps: 5, restSec }] }], week: {}, customEx: [] })
|
||||
expect(parsePlan(withRest('120')).routines[0].ex[0].restSec).toBe(120)
|
||||
expect(parsePlan(withRest(90.6)).routines[0].ex[0].restSec).toBe(91)
|
||||
expect('restSec' in parsePlan(withRest(-30)).routines[0].ex[0]).toBe(false)
|
||||
expect('restSec' in parsePlan(withRest('abc')).routines[0].ex[0]).toBe(false)
|
||||
})
|
||||
|
||||
// The floors are the config sheet's own (count >= 1, pct >= 5); a value that is present but
|
||||
// out of range is pulled up to the floor, while a missing one falls back to the default.
|
||||
it('clamps out-of-range intensifier numbers to the floors the app enforces', () => {
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import { POLICY_NAME } from './progression.js'
|
||||
|
||||
/**
|
||||
* Presentation-only view of a progression result. The engine remains the source of truth for
|
||||
* both the outcome and its explanation; this helper only makes the policy behind that result
|
||||
* explicit in the workout guidance.
|
||||
*/
|
||||
export function progressionGuidance(plan) {
|
||||
if (!plan?.why || plan.kind === 'off' || plan.policy === 'off') return null
|
||||
const policyLabel = POLICY_NAME[plan.policy]
|
||||
if (!policyLabel) return null
|
||||
return { policyLabel, why: plan.why }
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { progressionGuidance } from './progression-copy.js'
|
||||
|
||||
describe('policy-labelled progression guidance', () => {
|
||||
it('keeps the calculated outcome and identifies the policy that produced it', () => {
|
||||
const why = ['Every rep last time — {0} {1} more.', 2.5, 'kg']
|
||||
|
||||
expect(progressionGuidance({ policy: 'linear', kind: 'up', weight: 62.5, why }))
|
||||
.toEqual({ policyLabel: 'Linear progression', why })
|
||||
})
|
||||
|
||||
it('labels hold and deload outcomes without changing their calculated reasons', () => {
|
||||
const hold = ['Missed reps last time — same weight again ({0} of {1} to go).', 2, 3]
|
||||
const deload = ['Missed reps — reset to {0} {1} and work back up.', 55, 'kg']
|
||||
|
||||
expect(progressionGuidance({ policy: 'double', kind: 'hold', why: hold }))
|
||||
.toEqual({ policyLabel: 'Double progression', why: hold })
|
||||
expect(progressionGuidance({ policy: 'greyskull', kind: 'deload', why: deload }))
|
||||
.toEqual({ policyLabel: 'Greyskull LP', why: deload })
|
||||
})
|
||||
|
||||
it('labels a baseline outcome and omits policies with no visible outcome', () => {
|
||||
const baseline = ['Nothing logged yet — this session sets the baseline.']
|
||||
expect(progressionGuidance({ policy: 'linear', kind: 'first', why: baseline }))
|
||||
.toEqual({ policyLabel: 'Linear progression', why: baseline })
|
||||
expect(progressionGuidance({ policy: 'off', kind: 'off' })).toBeNull()
|
||||
expect(progressionGuidance({ policy: 'linear', kind: 'first' })).toBeNull()
|
||||
expect(progressionGuidance(null)).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -19,6 +19,7 @@
|
||||
import { modeOf, repStep, rerampWarmups } from './history.js'
|
||||
import { EXIDX } from './exercises.js'
|
||||
import { isWarmupRow } from './workout-model.js'
|
||||
import { normalizeRepRange } from './rep-range.js'
|
||||
|
||||
export const POLICIES = ['off', 'linear', 'greyskull', 'double', 'time']
|
||||
|
||||
@@ -134,6 +135,10 @@ export function readSession(entry, fallback) {
|
||||
export function sessionsFor(S, exId, fallback) {
|
||||
const out = []
|
||||
;(S.workouts || []).forEach(w => {
|
||||
// A planned deload remains a real workout for history and statistics, but it cannot become
|
||||
// the baseline for the next regular prescription. The routine flag is copied onto the
|
||||
// active session, then onto this completed workout, so later routine edits do not rewrite it.
|
||||
if (w.excludeFromProgression === true) return
|
||||
const entry = w.entries.find(e => e.id === exId)
|
||||
if (entry && entry.sets.some(s => s.done && !isWarmupRow(s))) out.push({ d: w.d, ...readSession(entry, fallback) })
|
||||
})
|
||||
@@ -210,8 +215,9 @@ export function nextPrescription(S, cfg, routine) {
|
||||
return { policy, kind: 'up', weight: 0, reps: next, why: ['Bodyweight — every rep last time, so go for {0} this time.', next] }
|
||||
}
|
||||
if (policy === 'double') {
|
||||
const top = cfg.reps || last.goal || 10
|
||||
const bottom = Math.min(cfg.repsMin || Math.max(1, top - 2), top)
|
||||
const range = normalizeRepRange(cfg.reps || last.goal || 10, cfg.repsMin, repStep(cfg))
|
||||
const top = range.reps
|
||||
const bottom = range.repsMin
|
||||
if (last.ok) return { policy, kind: 'up', weight: snap(w + inc, inc), reps: bottom, why: ['Top of the rep range in every set — {0} {1} more, back to {2} reps.', inc, unit, bottom] }
|
||||
if (stalls >= deloadAt) {
|
||||
const dw = deloadTo(w, inc)
|
||||
|
||||
@@ -311,6 +311,13 @@ describe('double progression', () => {
|
||||
expect(p.reps).toBe(8)
|
||||
expect(p.weight).toBe(35) // 40 × 0.9 = 36 → nearest loadable 2.5 step
|
||||
})
|
||||
|
||||
it('normalizes persisted per-side bounds before prescribing', () => {
|
||||
const perSide = { ...cfg, reps: 13, repsMin: 7, side: true }
|
||||
const p = nextPrescription(hist(LIFT, [[40, 12, 12, 12]], { sets: 3, reps: 13 }), perSide)
|
||||
expect(p.kind).toBe('hold')
|
||||
expect(p.reps).toBe(14)
|
||||
})
|
||||
})
|
||||
|
||||
describe('timed progression', () => {
|
||||
@@ -374,6 +381,25 @@ describe('sessionsFor', () => {
|
||||
expect(sessionsFor(S, LIFT).map(s => s.d)).toEqual(['2026-01-01'])
|
||||
})
|
||||
|
||||
it('ignores marked deload workouts when it calculates the next regular target', () => {
|
||||
const target = { sets: 3, reps: 5, weight: 60 }
|
||||
const entry = (weight, reps) => ({
|
||||
id: LIFT,
|
||||
target: { ...target, weight },
|
||||
sets: reps.map(r => ({ w: weight, r, done: true }))
|
||||
})
|
||||
const S = {
|
||||
unit: 'kg',
|
||||
workouts: [
|
||||
{ d: '2026-01-01', entries: [entry(60, [5, 5, 5])] },
|
||||
{ d: '2026-01-08', excludeFromProgression: true, entries: [entry(30, [8, 8])] }
|
||||
]
|
||||
}
|
||||
|
||||
expect(sessionsFor(S, LIFT).map(s => s.d)).toEqual(['2026-01-01'])
|
||||
expect(nextPrescription(S, { id: LIFT, ...target, prog: 'linear' }).weight).toBe(62.5)
|
||||
})
|
||||
|
||||
it('reads a legacy entry that has no target without crashing', () => {
|
||||
const S = { unit: 'kg', workouts: [{ d: '2026-01-01', entries: [{ id: LIFT, sets: [{ w: 60, r: 5, done: true }] }] }] }
|
||||
expect(sessionsFor(S, LIFT)).toHaveLength(1)
|
||||
|
||||
@@ -27,11 +27,11 @@ describe('Brazilian Portuguese locale', () => {
|
||||
.sort(byCodeUnit)
|
||||
const fingerprint = createHash('sha256').update(JSON.stringify(inherited)).digest('hex')
|
||||
|
||||
expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(539)
|
||||
expect(inherited).toHaveLength(545)
|
||||
expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(586)
|
||||
expect(inherited).toHaveLength(553)
|
||||
// If this fails, review the changed keys and wording before accepting a new hash. From
|
||||
// frontend/: node scripts/pt-br-inheritance-fingerprint.mjs --list
|
||||
expect(fingerprint, 'pt-PT inheritance changed; review the inherited pt-BR wording').toBe('206471a00deba14ead15903b2334353d9fcc1fadc645c00db985db2bc73d35ad')
|
||||
expect(fingerprint, 'pt-PT inheritance changed; review the inherited pt-BR wording').toBe('4a550b06e44cabd2b69834c15607220ca547854f2b0934843cadaa60a7f61a27')
|
||||
})
|
||||
|
||||
test('does not leak European Portuguese UI terms', () => {
|
||||
|
||||
@@ -61,6 +61,12 @@ function emptyMuscleMap(value) {
|
||||
return Object.fromEntries(MUSCLES.map(slug => [slug, value]))
|
||||
}
|
||||
|
||||
// Current catalogue metadata stays authoritative. Finished entries retain a nested muscle
|
||||
// snapshot specifically so deleted custom exercises can still contribute to recovery maps.
|
||||
function exerciseFor(entry) {
|
||||
return EXIDX[entry?.id] || entry
|
||||
}
|
||||
|
||||
// Epley one-rep-max estimate, matching onerm.js (REP_CAP included so high-rep sets do not
|
||||
// inflate the estimate). Used only to express a set's intensity relative to the lifter's own
|
||||
// capacity - the same formula the app already shows for estimated 1RM.
|
||||
@@ -161,7 +167,7 @@ function loadKgFor(ex, entry, set, workout, opts = {}) {
|
||||
function session1RMs(workout, opts = {}) {
|
||||
const best = new Map()
|
||||
for (const entry of workout?.entries || []) {
|
||||
const ex = EXIDX[entry.id]
|
||||
const ex = exerciseFor(entry)
|
||||
for (const set of entry.sets || []) {
|
||||
const load = loadKgFor(ex, entry, set, workout, opts)
|
||||
if (set?.done !== true || !(load > 0) || !(set.r > 0)) continue
|
||||
@@ -221,10 +227,11 @@ function sessionTonnages(workout, opts = {}) {
|
||||
const sums = emptyMuscleMap(0)
|
||||
const oneRms = session1RMs(workout, opts)
|
||||
for (const entry of workout?.entries || []) {
|
||||
const weights = musclesOf(EXIDX[entry.id])
|
||||
const ex = exerciseFor(entry)
|
||||
const weights = musclesOf(ex)
|
||||
for (const set of entry.sets || []) {
|
||||
if (set?.done !== true) continue
|
||||
const measured = setTonnage(EXIDX[entry.id], entry, set, workout, oneRms.get(entry.id), opts)
|
||||
const measured = setTonnage(ex, entry, set, workout, oneRms.get(entry.id), opts)
|
||||
const tonnage = Number.isFinite(measured) && measured > 0 ? measured : ZERO_LOAD_SET_STIMULUS
|
||||
for (const [slug, weight] of Object.entries(weights)) {
|
||||
if (Object.prototype.hasOwnProperty.call(MUSCLES_BY_SLUG, slug)) sums[slug] += tonnage * weight
|
||||
@@ -326,7 +333,7 @@ export function strengthOf(workouts, now, opts = {}) {
|
||||
if (!Number.isFinite(timestamp)) continue
|
||||
for (const entry of workout.entries || []) {
|
||||
if (!(entry.sets || []).some(set => set?.done === true && !isWarmupRow(set))) continue
|
||||
for (const slug of Object.keys(musclesOf(EXIDX[entry.id]))) {
|
||||
for (const slug of Object.keys(musclesOf(exerciseFor(entry)))) {
|
||||
if (Object.prototype.hasOwnProperty.call(MUSCLES_BY_SLUG, slug) && timestamp > latest[slug]) {
|
||||
latest[slug] = timestamp
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ import {
|
||||
strengthOf,
|
||||
} from './recovery.js'
|
||||
import { EXDB, registerCustom } from './exercises.js'
|
||||
import { MUSCLES, musclesOf } from './muscles.js'
|
||||
import { MUSCLES, exerciseMuscleSnapshot, musclesOf } from './muscles.js'
|
||||
import { fatigueStateOf } from './recovery-view.js'
|
||||
|
||||
const HOUR = 60 * 60 * 1000
|
||||
@@ -128,6 +128,42 @@ describe('fatigueOf and strengthOf', () => {
|
||||
expect(fatigueOf(highRep, NOW)[SINGLE_SLUG]).toBeGreaterThan(0.5)
|
||||
})
|
||||
|
||||
it('uses a deleted exercise snapshot for the same bounded primary and secondary fatigue', () => {
|
||||
const resolved = doneWorkoutAt(WEIGHTED.id, NOW)
|
||||
const deleted = {
|
||||
...resolved,
|
||||
entries: [{
|
||||
...resolved.entries[0],
|
||||
id: 'deleted-weighted-exercise',
|
||||
muscleSnapshot: exerciseMuscleSnapshot(WEIGHTED),
|
||||
}],
|
||||
}
|
||||
|
||||
expect(fatigueOf([deleted], NOW)).toEqual(fatigueOf([resolved], NOW))
|
||||
expect(fatigueOf([deleted], NOW)[WEIGHTED_PRIMARY_SLUG]).toBeGreaterThan(0)
|
||||
expect(fatigueOf([deleted], NOW)[SECONDARY_SLUG]).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('uses a deleted exercise snapshot for strength without changing decay or floor semantics', () => {
|
||||
const start = NOW - 15 * DAY
|
||||
const resolved = doneWorkoutAt(WEIGHTED.id, start)
|
||||
const deleted = {
|
||||
...resolved,
|
||||
entries: [{
|
||||
...resolved.entries[0],
|
||||
id: 'deleted-weighted-exercise',
|
||||
muscleSnapshot: exerciseMuscleSnapshot(WEIGHTED),
|
||||
}],
|
||||
}
|
||||
const untouchedSlug = MUSCLES.find(slug => !WEIGHTED_WEIGHTS[slug])
|
||||
const strength = strengthOf([deleted], NOW)
|
||||
|
||||
expect(strength).toEqual(strengthOf([resolved], NOW))
|
||||
expect(strength[WEIGHTED_PRIMARY_SLUG]).toBeCloseTo(0.5 ** (1 / 28), 10)
|
||||
expect(strength[SECONDARY_SLUG]).toBeCloseTo(0.5 ** (1 / 28), 10)
|
||||
expect(strength[untouchedSlug]).toBe(STRENGTH_FLOOR)
|
||||
})
|
||||
|
||||
it('raises starting fatigue with volume, never pins, and fades without a cliff', () => {
|
||||
const at0 = count => fatigueOf([doneWorkoutAt(SINGLE.id, NOW, count)], NOW)[SINGLE_SLUG]
|
||||
expect(at0(1)).toBeCloseTo(1 - Math.exp(-V / FATIGUE_REF_VOLUME), 10)
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
// Normalize the two bounds used by double progression.
|
||||
// `reps` is the upper bound and `repsMin` is the lower bound in persisted configs.
|
||||
export function normalizeRepRange(reps, repsMin, stride = 1) {
|
||||
const step = Number.isInteger(stride) && stride > 0 ? stride : 1
|
||||
const upper = align(positiveInt(reps, 10), step)
|
||||
const lower = align(positiveInt(repsMin, Math.max(1, upper - 2)), step)
|
||||
return lower >= upper
|
||||
? { reps: lower + step, repsMin: lower }
|
||||
: { reps: upper, repsMin: lower }
|
||||
}
|
||||
|
||||
function align(value, stride) {
|
||||
return Math.max(stride, Math.ceil(value / stride) * stride)
|
||||
}
|
||||
|
||||
function positiveInt(value, fallback) {
|
||||
const n = Number(value)
|
||||
return Number.isFinite(n) && n > 0 ? Math.max(1, Math.round(n)) : fallback
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { normalizeRepRange } from './rep-range.js'
|
||||
|
||||
describe('normalizeRepRange', () => {
|
||||
it('keeps valid positive integer bounds unchanged', () => {
|
||||
expect(normalizeRepRange(12, 8)).toEqual({ reps: 12, repsMin: 8 })
|
||||
})
|
||||
|
||||
it('rounds bounds to positive integers', () => {
|
||||
expect(normalizeRepRange(12.4, 7.6)).toEqual({ reps: 12, repsMin: 8 })
|
||||
expect(normalizeRepRange(0, -2)).toEqual({ reps: 10, repsMin: 8 })
|
||||
})
|
||||
|
||||
it('raises the upper bound when the lower bound reaches it', () => {
|
||||
expect(normalizeRepRange(8, 8)).toEqual({ reps: 9, repsMin: 8 })
|
||||
})
|
||||
|
||||
it('raises the upper bound when the lower bound exceeds it', () => {
|
||||
expect(normalizeRepRange(8, 12)).toEqual({ reps: 13, repsMin: 12 })
|
||||
})
|
||||
|
||||
it('keeps the lower bound at least one below a lowered upper bound', () => {
|
||||
expect(normalizeRepRange(6, 8)).toEqual({ reps: 9, repsMin: 8 })
|
||||
})
|
||||
|
||||
it('supplies a usable default lower bound for a small upper bound', () => {
|
||||
expect(normalizeRepRange(1, undefined)).toEqual({ reps: 2, repsMin: 1 })
|
||||
})
|
||||
|
||||
it('aligns both bounds to an even stride', () => {
|
||||
expect(normalizeRepRange(13, 7, 2)).toEqual({ reps: 14, repsMin: 8 })
|
||||
})
|
||||
|
||||
it('keeps a valid gap when per-side bounds are invalid', () => {
|
||||
expect(normalizeRepRange(8, 9, 2)).toEqual({ reps: 12, repsMin: 10 })
|
||||
expect(normalizeRepRange(0, -2, 2)).toEqual({ reps: 10, repsMin: 8 })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,21 @@
|
||||
// How a session's exercise entries are built from a routine. Shared by the live start and by
|
||||
// "log a past workout", which is the same screen pointed at another day — both must walk up
|
||||
// to identical entries, or the two paths drift apart the first time a prescription rule changes.
|
||||
// Imports both history.js and progression.js (which itself imports history.js); nothing in
|
||||
// either imports this file, so there is no cycle.
|
||||
import { buildSets, applyIntensifierPlan } from './history.js'
|
||||
import { nextPrescription, applyPrescription, defaultIncrement } from './progression.js'
|
||||
|
||||
export function buildSessionEntries(st, r) {
|
||||
// The prescription is applied as the session is built, so you walk up to the bar with the
|
||||
// right weight already on the screen instead of being told about it afterwards. `plan` is
|
||||
// kept on the entry purely so the workout can explain the number it chose.
|
||||
const excluded = r?.excludeFromProgression === true
|
||||
const entries = (r ? r.ex : []).map(cfg => {
|
||||
const plan = excluded ? { policy: 'off', kind: 'off' } : nextPrescription(st, cfg, r)
|
||||
const step = defaultIncrement(cfg.id, st.unit)
|
||||
const sets = applyIntensifierPlan(applyPrescription(buildSets(st, cfg, { step, useTarget: excluded }), plan, step), cfg)
|
||||
return { id: cfg.id, sg: cfg.sg, target: { ...cfg }, plan, sets }
|
||||
})
|
||||
return { entries, excluded }
|
||||
}
|
||||
@@ -2,6 +2,27 @@
|
||||
// the stores makes the uneven-round and re-check rules explicit and directly testable.
|
||||
const hasWork = (entries, idx) => !!entries[idx]?.sets?.some(set => !set.done)
|
||||
|
||||
// Return the first unfinished navigation unit after the current one, wrapping once so a user
|
||||
// who completed units out of order is never offered workout completion while earlier work remains.
|
||||
export function nextUnfinishedUnit(entries, units, fromIdx) {
|
||||
if (!Array.isArray(entries) || !Array.isArray(units) || units.length === 0) return null
|
||||
const current = units.findIndex(unit => unit.includes(fromIdx))
|
||||
const ordered = current < 0
|
||||
? units
|
||||
: [...units.slice(current + 1), ...units.slice(0, current)]
|
||||
return ordered.find(unit => unit.some(idx => hasWork(entries, idx))) || null
|
||||
}
|
||||
|
||||
// The current exercise may be one member of a contiguous superset. Insert after that complete
|
||||
// navigation unit; invalid/empty state safely falls back to the end of the entry list.
|
||||
export function insertionIndexAfterCurrentUnit(units, currentIndex, entryCount) {
|
||||
const length = Math.max(0, Number(entryCount) || 0)
|
||||
if (!Array.isArray(units) || units.length === 0) return length
|
||||
const unit = units.find(candidate => candidate.includes(currentIndex))
|
||||
if (!unit?.length) return length
|
||||
return Math.min(length, Math.max(...unit) + 1)
|
||||
}
|
||||
|
||||
// A completion is new progress only when it takes this exercise beyond the largest number of
|
||||
// simultaneously completed sets seen in this mounted session. Uncheck/re-check therefore does
|
||||
// not repeat navigation or rest side effects, while completing an added set still can.
|
||||
@@ -42,6 +63,32 @@ export function restOnRecheck({ timerRunning, unitDone, lastUnit }) {
|
||||
return !timerRunning && restAfterSet({ unitDone, lastUnit })
|
||||
}
|
||||
|
||||
/**
|
||||
* How long the rest after a completed set should run, in seconds.
|
||||
*
|
||||
* An exercise may carry its own `restSec` in its target (issue #10) — a heavy triple and a set
|
||||
* of curls do not want the same break. One that carries none inherits `defaultRestSec`, the
|
||||
* global rest timer, which is what every routine did before the field existed.
|
||||
*
|
||||
* `unit` is the superset group the set belongs to, as entry indices — a plain exercise is a
|
||||
* group of one. A group rests once, after the round, so it takes the LONGEST rest any of its
|
||||
* members asked for: the shortest would send you back to the bar before the member that needs
|
||||
* the most recovery is ready.
|
||||
*
|
||||
* `defaultRestSec` of 0 is the rest timer turned off (v1.2.11). That silences the members that
|
||||
* have no rest of their own, but an exercise that explicitly asks for one still gets it — the
|
||||
* setting is a default, and this field overrides the default.
|
||||
*/
|
||||
export function restSecFor(entries, unit, defaultRestSec) {
|
||||
const fallback = defaultRestSec > 0 ? defaultRestSec : 0
|
||||
const idxs = Array.isArray(unit) && unit.length ? unit : []
|
||||
if (!idxs.length) return fallback
|
||||
return idxs.reduce((longest, idx) => {
|
||||
const own = entries?.[idx]?.target?.restSec
|
||||
return Math.max(longest, own > 0 ? own : fallback)
|
||||
}, 0)
|
||||
}
|
||||
|
||||
// Decide where a newly completed superset set goes next. Spent members are skipped, including
|
||||
// across the wrap. A round ends when no later member in display order has work left; this makes
|
||||
// the last *active* member the boundary rather than blindly using the group's last array index.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { setProgressHighWater, supersetFlowStep, restAfterSet, restOnRecheck } from './supersetFlow.js'
|
||||
import { insertionIndexAfterCurrentUnit, nextUnfinishedUnit, setProgressHighWater, supersetFlowStep, restAfterSet, restOnRecheck, restSecFor } from './supersetFlow.js'
|
||||
|
||||
const entry = done => ({ sets: done.map(value => ({ done: value })) })
|
||||
|
||||
@@ -52,6 +52,26 @@ describe('supersetFlowStep', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('active workout unit ordering', () => {
|
||||
it('inserts after the whole current unit', () => {
|
||||
expect(insertionIndexAfterCurrentUnit([[0, 1], [2]], 0, 3)).toBe(2)
|
||||
expect(insertionIndexAfterCurrentUnit([[0], [1]], 1, 2)).toBe(2)
|
||||
expect(insertionIndexAfterCurrentUnit([], 0, 0)).toBe(0)
|
||||
})
|
||||
|
||||
it('finds the next unfinished unit, skips completed units, and wraps once', () => {
|
||||
const entries = [entry([false]), entry([true]), entry([false]), entry([true])]
|
||||
const units = [[0], [1], [2, 3]]
|
||||
expect(nextUnfinishedUnit(entries, units, 0)).toEqual([2, 3])
|
||||
expect(nextUnfinishedUnit(entries, units, 2)).toEqual([0])
|
||||
})
|
||||
|
||||
it('returns null only when every unit is complete', () => {
|
||||
const entries = [entry([true]), entry([true])]
|
||||
expect(nextUnfinishedUnit(entries, [[0], [1]], 1)).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
// Issue #3 has two halves. restAfterSet covers "no break after the LAST set of an exercise";
|
||||
// this covers "after the first set, sometimes a break doesn't appear" — the uncheck/re-check
|
||||
// that the high-water rule swallows.
|
||||
@@ -72,3 +92,48 @@ describe('rest on a re-check', () => {
|
||||
expect(restOnRecheck({ timerRunning: false, unitDone: true, lastUnit: false })).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
// Issue #10: a routine can give an exercise its own rest, and the global timer stops being the
|
||||
// only answer. The resolution is the whole feature — the UI just writes the number down.
|
||||
describe('restSecFor', () => {
|
||||
// 0: no rest of its own, 1: 180 s, 2: 45 s — a heavy pull, a light accessory, a plain one.
|
||||
const entries = [
|
||||
{ id: 'a', target: { mode: 'reps' } },
|
||||
{ id: 'b', target: { mode: 'reps', restSec: 180 } },
|
||||
{ id: 'c', target: { mode: 'reps', restSec: 45 } },
|
||||
]
|
||||
|
||||
it('prefers the exercise’s own rest over the global default', () => {
|
||||
expect(restSecFor(entries, [1], 90)).toBe(180)
|
||||
expect(restSecFor(entries, [2], 90)).toBe(45)
|
||||
})
|
||||
|
||||
it('falls back to the global default when the exercise sets none', () => {
|
||||
expect(restSecFor(entries, [0], 90)).toBe(90)
|
||||
})
|
||||
|
||||
it('gives a superset the longest rest its members asked for', () => {
|
||||
// Not the member that closed the round, and not the shortest: the group rests once, and
|
||||
// the 180 s exercise is the one still recovering when the 45 s one is ready to go again.
|
||||
expect(restSecFor(entries, [1, 2], 90)).toBe(180)
|
||||
// A member with no rest of its own pulls in the global, which can be the longest of all.
|
||||
expect(restSecFor(entries, [0, 2], 90)).toBe(90)
|
||||
})
|
||||
|
||||
it('honours an explicit rest even with the global timer switched off', () => {
|
||||
expect(restSecFor(entries, [1], 0)).toBe(180)
|
||||
expect(restSecFor(entries, [0, 1], 0)).toBe(180)
|
||||
})
|
||||
|
||||
it('stays off when the timer is off and nothing asked for a rest', () => {
|
||||
expect(restSecFor(entries, [0], 0)).toBe(0)
|
||||
expect(restSecFor(entries, [0, 0], 0)).toBe(0)
|
||||
})
|
||||
|
||||
it('survives a missing unit or entry rather than timing NaN', () => {
|
||||
expect(restSecFor(entries, null, 90)).toBe(90)
|
||||
expect(restSecFor(entries, [], 90)).toBe(90)
|
||||
expect(restSecFor(entries, [7], 90)).toBe(90)
|
||||
expect(restSecFor(undefined, [0], undefined)).toBe(0)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,78 @@
|
||||
import { useCallback, useEffect } from 'react'
|
||||
|
||||
/* Keyboard-aware sheets. When the mobile keyboard comes up the layout viewport keeps its
|
||||
size, only the visual viewport shrinks — so a bottom sheet with a text input near its
|
||||
foot ends up half under the keys. index.css reads two custom properties on the sheet
|
||||
(--picker-keyboard-bottom / --picker-visual-height) to lift and cap it. SelectSheet in
|
||||
components/ui.jsx does exactly this sync inline; the exercise picker, the custom-exercise
|
||||
form and the note sheets need the same thing, hence this hook. The logic is deliberately
|
||||
duplicated rather than imported so ui.jsx keeps no public surface for it.
|
||||
|
||||
`inputRef` points at the text input (or textarea) whose closest `.sheet` gets the vars.
|
||||
`enabled` lets a caller switch the sync off (e.g. a picker without a search box). */
|
||||
export function useSheetKeyboard(inputRef, enabled = true) {
|
||||
const sync = useCallback(() => {
|
||||
const input = inputRef.current
|
||||
const sheet = input?.closest?.('.sheet')
|
||||
const viewport = typeof window !== 'undefined' ? window.visualViewport : null
|
||||
if (!sheet || !viewport) return
|
||||
const visualHeight = Math.max(0, viewport.height || window.innerHeight)
|
||||
const visualBottom = (viewport.offsetTop || 0) + visualHeight
|
||||
const bottomInset = Math.max(0, window.innerHeight - visualBottom)
|
||||
sheet.style.setProperty('--picker-keyboard-bottom', `${bottomInset}px`)
|
||||
sheet.style.setProperty('--picker-visual-height', `${visualHeight}px`)
|
||||
}, [inputRef])
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled) return
|
||||
const viewport = typeof window !== 'undefined' ? window.visualViewport : null
|
||||
if (!viewport) return
|
||||
sync()
|
||||
viewport.addEventListener('resize', sync)
|
||||
viewport.addEventListener('scroll', sync)
|
||||
return () => {
|
||||
viewport.removeEventListener('resize', sync)
|
||||
viewport.removeEventListener('scroll', sync)
|
||||
// The sheet element outlives this input when the sheet swaps content, so leave it
|
||||
// the way we found it rather than pinning a stale keyboard inset on it.
|
||||
const sheet = inputRef.current?.closest?.('.sheet')
|
||||
sheet?.style.removeProperty('--picker-keyboard-bottom')
|
||||
sheet?.style.removeProperty('--picker-visual-height')
|
||||
}
|
||||
}, [enabled, sync, inputRef])
|
||||
|
||||
// Hand back as onFocus so the first measurement happens as the keyboard opens, before
|
||||
// the visualViewport events land (on iOS they can arrive a frame late).
|
||||
return sync
|
||||
}
|
||||
|
||||
/* Chip strips scroll sideways, and a filter set from code ("★ Chosen", a reset) can land the
|
||||
active chip off-screen. Pull it into view along the strip only — block:'nearest' never moves
|
||||
the page when the strip is already visible, which is the case for every strip we have. */
|
||||
export function useRevealActiveChip(stripRef, active) {
|
||||
useEffect(() => {
|
||||
const strip = stripRef.current
|
||||
const chip = strip?.querySelector?.('.chip.on')
|
||||
if (!chip || typeof chip.scrollIntoView !== 'function') return
|
||||
chip.scrollIntoView({ inline: 'nearest', block: 'nearest' })
|
||||
}, [stripRef, active])
|
||||
}
|
||||
|
||||
/* Props that make a clickable <div> behave like a button for keyboard and screen-reader
|
||||
users. Kept as a div because some rows nest a real <Button> (Library), and a button inside
|
||||
a button is invalid HTML. Space is swallowed so the page does not scroll under the row. */
|
||||
export function tappable(onClick) {
|
||||
if (!onClick) return {}
|
||||
return {
|
||||
role: 'button',
|
||||
tabIndex: 0,
|
||||
onClick,
|
||||
onKeyDown: e => {
|
||||
if (e.target !== e.currentTarget) return // a nested control handles its own keys
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault()
|
||||
onClick(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { tappable } from './use-sheet-keyboard.js'
|
||||
|
||||
const keyEvent = (key, target) => {
|
||||
const ev = { key, target, currentTarget: target, preventDefault: vi.fn() }
|
||||
return ev
|
||||
}
|
||||
|
||||
describe('tappable', () => {
|
||||
it('turns a plain onClick into a keyboard-reachable button', () => {
|
||||
const onClick = vi.fn()
|
||||
const p = tappable(onClick)
|
||||
expect(p.role).toBe('button')
|
||||
expect(p.tabIndex).toBe(0)
|
||||
expect(p.onClick).toBe(onClick)
|
||||
const el = {}
|
||||
p.onKeyDown(keyEvent('Enter', el))
|
||||
expect(onClick).toHaveBeenCalledTimes(1)
|
||||
const space = keyEvent(' ', el)
|
||||
p.onKeyDown(space)
|
||||
expect(onClick).toHaveBeenCalledTimes(2)
|
||||
expect(space.preventDefault).toHaveBeenCalled() // Space must not scroll the page
|
||||
})
|
||||
|
||||
it('ignores other keys and keys from nested controls', () => {
|
||||
const onClick = vi.fn()
|
||||
const p = tappable(onClick)
|
||||
const el = {}
|
||||
p.onKeyDown(keyEvent('a', el))
|
||||
p.onKeyDown(keyEvent('Escape', el))
|
||||
expect(onClick).not.toHaveBeenCalled()
|
||||
const nested = { key: 'Enter', target: {}, currentTarget: el, preventDefault: vi.fn() }
|
||||
p.onKeyDown(nested)
|
||||
expect(onClick).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('gives an inert row nothing to react to', () => {
|
||||
expect(tappable(undefined)).toEqual({})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,133 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { MONDAY, SUNDAY, weekStartOf, weekOrder, weekDayOffset, startOfWeek, weekKey, isoOf } from './format.js'
|
||||
import { streakWeeks } from './history.js'
|
||||
import { muscleBalanceWindow } from './muscles.js'
|
||||
import { effortWeeks } from './effort.js'
|
||||
|
||||
// 2026-08-19 is a Wednesday. Its Monday-first week runs Mon 17th → Sun 23rd; its Sunday-first
|
||||
// week runs Sun 16th → Sat 22nd. Every case below is picked so the two disagree — a date that
|
||||
// lands in the same week either way would pass without testing anything.
|
||||
const WED = '2026-08-19'
|
||||
|
||||
describe('weekStartOf', () => {
|
||||
it('defaults to Monday for state written before the setting existed', () => {
|
||||
expect(weekStartOf({})).toBe(MONDAY)
|
||||
expect(weekStartOf(undefined)).toBe(MONDAY)
|
||||
expect(weekStartOf({ weekStart: undefined })).toBe(MONDAY)
|
||||
})
|
||||
|
||||
it('only 0 means Sunday — a junk value is not a third week shape', () => {
|
||||
expect(weekStartOf({ weekStart: SUNDAY })).toBe(SUNDAY)
|
||||
expect(weekStartOf({ weekStart: 3 })).toBe(MONDAY)
|
||||
expect(weekStartOf({ weekStart: null })).toBe(MONDAY)
|
||||
})
|
||||
})
|
||||
|
||||
describe('weekOrder', () => {
|
||||
it('lists all seven getDay() indices from the chosen start', () => {
|
||||
expect(weekOrder(MONDAY)).toEqual([1, 2, 3, 4, 5, 6, 0])
|
||||
expect(weekOrder(SUNDAY)).toEqual([0, 1, 2, 3, 4, 5, 6])
|
||||
})
|
||||
})
|
||||
|
||||
describe('weekDayOffset', () => {
|
||||
it('is the column a weekday sits in', () => {
|
||||
expect(weekDayOffset(1, MONDAY)).toBe(0) // Monday, Monday-first
|
||||
expect(weekDayOffset(0, MONDAY)).toBe(6) // Sunday closes a Monday-first week
|
||||
expect(weekDayOffset(0, SUNDAY)).toBe(0)
|
||||
expect(weekDayOffset(1, SUNDAY)).toBe(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('startOfWeek', () => {
|
||||
it('walks back to the chosen first day', () => {
|
||||
expect(isoOf(startOfWeek(WED, MONDAY))).toBe('2026-08-17')
|
||||
expect(isoOf(startOfWeek(WED, SUNDAY))).toBe('2026-08-16')
|
||||
})
|
||||
|
||||
it('leaves a date that already is the first day alone', () => {
|
||||
expect(isoOf(startOfWeek('2026-08-17', MONDAY))).toBe('2026-08-17')
|
||||
expect(isoOf(startOfWeek('2026-08-16', SUNDAY))).toBe('2026-08-16')
|
||||
})
|
||||
|
||||
it('is noon local, so a DST jump cannot move it to the day before', () => {
|
||||
// Europe/Zurich springs forward on 2026-03-29, a Sunday.
|
||||
expect(isoOf(startOfWeek('2026-03-29', SUNDAY))).toBe('2026-03-29')
|
||||
expect(isoOf(startOfWeek('2026-03-29', MONDAY))).toBe('2026-03-23')
|
||||
})
|
||||
})
|
||||
|
||||
describe('weekKey', () => {
|
||||
it('is equal for two days in the same week and different across the boundary', () => {
|
||||
// Sunday the 16th and Wednesday the 19th: one week Sunday-first, two Monday-first.
|
||||
expect(weekKey('2026-08-16', SUNDAY)).toBe(weekKey(WED, SUNDAY))
|
||||
expect(weekKey('2026-08-16', MONDAY)).not.toBe(weekKey(WED, MONDAY))
|
||||
})
|
||||
|
||||
it('defaults to Monday when no start is passed', () => {
|
||||
expect(weekKey(WED)).toBe(weekKey(WED, MONDAY))
|
||||
})
|
||||
|
||||
it('does not collide across years', () => {
|
||||
expect(weekKey('2025-08-19', MONDAY)).not.toBe(weekKey('2026-08-19', MONDAY))
|
||||
})
|
||||
})
|
||||
|
||||
describe('the week streak counts the profile’s own weeks', () => {
|
||||
// Two sessions on the Sunday and the Monday that straddle a Monday-first boundary. To a
|
||||
// Monday profile that is a session in each of two consecutive weeks; to a Sunday profile
|
||||
// both fall in the same week and there is only one.
|
||||
const iso = d => isoOf(new Date(Date.now() - d * 86400000))
|
||||
const sundayBack = () => {
|
||||
// The most recent Sunday that is not today, so both dates are in the past.
|
||||
const d = new Date()
|
||||
d.setDate(d.getDate() - ((d.getDay() + 7) % 7 || 7))
|
||||
return d
|
||||
}
|
||||
|
||||
it('splits a Sun/Mon pair into two weeks for a Monday profile, one for a Sunday profile', () => {
|
||||
const sun = sundayBack()
|
||||
const mon = new Date(sun); mon.setDate(sun.getDate() + 1)
|
||||
const workouts = [{ d: isoOf(sun) }, { d: isoOf(mon) }]
|
||||
expect(weekKey(isoOf(sun), MONDAY)).not.toBe(weekKey(isoOf(mon), MONDAY))
|
||||
expect(weekKey(isoOf(sun), SUNDAY)).toBe(weekKey(isoOf(mon), SUNDAY))
|
||||
expect(streakWeeks({ workouts, weekStart: SUNDAY })).toBe(1)
|
||||
})
|
||||
|
||||
it('is zero without workouts whatever the week start', () => {
|
||||
expect(streakWeeks({ workouts: [], weekStart: SUNDAY })).toBe(0)
|
||||
expect(iso(0)).toBe(isoOf(new Date()))
|
||||
})
|
||||
})
|
||||
|
||||
describe('“this week” ranges follow the setting', () => {
|
||||
const workouts = [{ d: '2026-08-16' }, { d: WED }] // Sunday, then Wednesday
|
||||
|
||||
it('muscle balance: the 7-day window is a week, not the last seven days', () => {
|
||||
const mon = muscleBalanceWindow(workouts, 7, Date.now(), WED, MONDAY)
|
||||
expect(mon.map(w => w.d)).toEqual([WED])
|
||||
const sun = muscleBalanceWindow(workouts, 7, Date.now(), WED, SUNDAY)
|
||||
expect(sun.map(w => w.d)).toEqual(['2026-08-16', WED])
|
||||
})
|
||||
|
||||
it('muscle balance defaults to Monday when no start is passed', () => {
|
||||
expect(muscleBalanceWindow(workouts, 7, Date.now(), WED).map(w => w.d)).toEqual([WED])
|
||||
})
|
||||
|
||||
it('the effort chart groups and positions its points by the same week', () => {
|
||||
// Four rated sets: two on the Sunday, two on the Wednesday. Monday-first that is two
|
||||
// points (one per week, each with its two rated sets); Sunday-first it is one point.
|
||||
const set = r => ({ done: true, w: 60, r: 8, rir: r })
|
||||
const workout = d => ({ d, start: new Date(d + 'T10:00:00').getTime(), entries: [{ id: '0025', sets: [set(2), set(3)] }] })
|
||||
const S = { effort: 'rir', workouts: [workout('2026-08-16'), workout(WED)] }
|
||||
|
||||
const mon = effortWeeks({ ...S, weekStart: MONDAY }, 0)
|
||||
expect(mon).toHaveLength(2)
|
||||
expect(mon.map(p => isoOf(new Date(p.t)))).toEqual(['2026-08-10', '2026-08-17'])
|
||||
|
||||
const sun = effortWeeks({ ...S, weekStart: SUNDAY }, 0)
|
||||
expect(sun).toHaveLength(1)
|
||||
expect(isoOf(new Date(sun[0].t))).toBe('2026-08-16')
|
||||
expect(sun[0].sets).toBe(4)
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user