Merge remote-tracking branch 'origin/main' into feat/copy-routine

# Conflicts:
#	frontend/src/lib/pt-br-locale.test.js
This commit is contained in:
Sebastian G committed 2026-09-02 13:29:30 +02:00
commit 5375dcc758
41 files changed
+962 -116

No files matched your search

+56
View File
@@ -0,0 +1,56 @@
// Per-exercise bar weight (issue: plate math for barbell work). Logged weights stay the
// TOTAL on the bar — history, progression and 1RM keep meaning exactly what they always
// did. The bar weight is display metadata: it feeds the "X per side" plate math and
// nothing else.
//
// Unit: stored in the profile unit (S.unit), like every other weight in state — set
// weights, exWeights, bodyweight are all written in whatever unit the profile logs and a
// unit switch re-labels them without converting. A canonical-kg bar would be the one
// number that shifts under the user on a unit switch while the totals around it stay
// put, so the override follows the same rule. The equipment *defaults* therefore exist
// per unit too: a kg profile gets the 20 kg olympic bar, a lb profile the 45 lb bar its
// gym actually racks — not a 44.1 lb conversion no bar is stamped with.
import { EXIDX } from './exercises.js'
/** Equipment values (e.eq) that put a bar in your hands. */
export const BAR_EQ = new Set(['barbell', 'olympic barbell', 'ez barbell', 'smith machine', 'trap bar'])
/** Typical bar weights per equipment type, for a kg profile. */
export const DEFAULT_BAR_KG = { barbell: 20, 'olympic barbell': 20, 'ez barbell': 10, 'smith machine': 9, 'trap bar': 25 }
/** The same bars as a lb profile knows them — real markings, not converted kg. */
export const DEFAULT_BAR_LB = { barbell: 45, 'olympic barbell': 45, 'ez barbell': 25, 'smith machine': 20, 'trap bar': 55 }
const exOf = exOrId => (typeof exOrId === 'string' ? EXIDX[exOrId] : exOrId)
/** Whether this exercise (object or id) is done with a bar. */
export const usesBar = exOrId => BAR_EQ.has(exOf(exOrId)?.eq)
/** The default bar weight for an equipment type, in the given unit. null off the list. */
export const defaultBarWeight = (eq, unit) =>
(unit === 'lb' ? DEFAULT_BAR_LB : DEFAULT_BAR_KG)[eq] ?? null
/** True when the user has set their own bar weight for this exercise. */
export const hasBarOverride = (S, exId) => ((S?.barWeights || {})[exId] || 0) > 0
/**
* Effective bar weight for one exercise, in the profile unit: the explicit
* S.barWeights[exId] if set, else the default for the bar type. null for anything
* that is not a bar exercise.
*/
export function barWeightFor(S, exOrId) {
const ex = exOf(exOrId)
if (!BAR_EQ.has(ex?.eq)) return null
const own = (S?.barWeights || {})[ex.id]
if (own > 0) return own
return defaultBarWeight(ex.eq, S?.unit)
}
/**
* Plates per side: (total − bar) / 2, rounded to 2 decimals. null when there is nothing
* sensible to show — a missing number, or a total at or below the bar itself.
*/
export function plateSplit(total, bar) {
if (!(total > 0) || !(bar > 0) || total <= bar) return null
return Math.round(((total - bar) / 2) * 100) / 100
}
+94
View File
@@ -0,0 +1,94 @@
import { describe, expect, test } from 'vitest'
import { BAR_EQ, DEFAULT_BAR_KG, DEFAULT_BAR_LB, usesBar, defaultBarWeight, barWeightFor, hasBarOverride, plateSplit } from './bar.js'
import { EXDB } from './exercises-data.js'
const idOf = eq => EXDB.find(e => e.eq === eq).id
describe('bar equipment', () => {
test('covers the five bar types and the 228 catalogue exercises they carry', () => {
expect([...BAR_EQ].sort()).toEqual(['barbell', 'ez barbell', 'olympic barbell', 'smith machine', 'trap bar'])
expect(EXDB.filter(e => BAR_EQ.has(e.eq)).length).toBe(228)
})
test('usesBar answers for ids and exercise objects alike', () => {
for (const eq of BAR_EQ) {
expect(usesBar(idOf(eq)), eq).toBe(true)
expect(usesBar({ eq }), eq).toBe(true)
}
expect(usesBar({ eq: 'dumbbell' })).toBe(false)
expect(usesBar({ eq: 'body weight' })).toBe(false)
expect(usesBar('no-such-id')).toBe(false)
expect(usesBar(null)).toBe(false)
})
})
describe('per-unit defaults', () => {
test('every bar type has a default in both units', () => {
for (const eq of BAR_EQ) {
expect(DEFAULT_BAR_KG[eq], eq).toBeGreaterThan(0)
expect(DEFAULT_BAR_LB[eq], eq).toBeGreaterThan(0)
}
expect(defaultBarWeight('ez barbell', 'kg')).toBe(10)
expect(defaultBarWeight('ez barbell', 'lb')).toBe(25)
expect(defaultBarWeight('olympic barbell', 'kg')).toBe(20)
// A lb profile gets the bar its gym actually racks, not a 44.1 lb conversion.
expect(defaultBarWeight('barbell', 'lb')).toBe(45)
expect(defaultBarWeight('dumbbell', 'kg')).toBeNull()
})
})
describe('barWeightFor', () => {
const barbell = idOf('barbell')
const ez = idOf('ez barbell')
test('falls back to the equipment default in the profile unit', () => {
expect(barWeightFor({ unit: 'kg', barWeights: {} }, barbell)).toBe(20)
expect(barWeightFor({ unit: 'lb', barWeights: {} }, barbell)).toBe(45)
expect(barWeightFor({ unit: 'kg' }, ez)).toBe(10)
})
test('an explicit override wins over the default', () => {
const S = { unit: 'kg', barWeights: { [ez]: 7.5 } }
expect(barWeightFor(S, ez)).toBe(7.5)
expect(hasBarOverride(S, ez)).toBe(true)
expect(barWeightFor(S, barbell)).toBe(20) // other exercises keep their default
expect(hasBarOverride(S, barbell)).toBe(false)
})
test('a cleared (deleted or zeroed) override falls back to the default', () => {
const S = { unit: 'kg', barWeights: { [ez]: 12.5 } }
delete S.barWeights[ez]
expect(barWeightFor(S, ez)).toBe(10)
expect(barWeightFor({ unit: 'kg', barWeights: { [ez]: 0 } }, ez)).toBe(10)
expect(hasBarOverride({ unit: 'kg', barWeights: { [ez]: 0 } }, ez)).toBe(false)
})
test('is null for anything without a bar', () => {
const dumbbell = EXDB.find(e => e.eq === 'dumbbell')
expect(barWeightFor({ unit: 'kg', barWeights: {} }, dumbbell.id)).toBeNull()
expect(barWeightFor({ unit: 'kg', barWeights: {} }, 'no-such-id')).toBeNull()
})
})
describe('plateSplit', () => {
test('splits what is beyond the bar evenly per side', () => {
expect(plateSplit(62.5, 20)).toBe(21.25)
expect(plateSplit(100, 20)).toBe(40)
expect(plateSplit(30, 10)).toBe(10)
})
test('rounds to 2 decimals', () => {
expect(plateSplit(65.55, 20)).toBe(22.78)
expect(plateSplit(21.2, 20)).toBe(0.6)
})
test('is null when there is nothing sensible to show', () => {
expect(plateSplit(20, 20)).toBe(null) // bar only
expect(plateSplit(15, 20)).toBe(null) // below the bar
expect(plateSplit(0, 20)).toBe(null)
expect(plateSplit(100, 0)).toBe(null)
expect(plateSplit(null, 20)).toBe(null)
expect(plateSplit(100, null)).toBe(null)
expect(plateSplit(undefined, undefined)).toBe(null)
})
})
+4 -10
View File
@@ -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
+33 -7
View File
@@ -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)
+23 -3
View File
@@ -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 : {}
@@ -284,6 +284,25 @@ export function effectiveRoutine(S, iso) {
const id = effectiveRoutineId(S, iso)
return id ? S.routines.find(r => r.id === id) || null : null
}
/**
* The next day that actually has something to train, looking forward from `iso` (exclusive).
*
* Takes a date string rather than reading the clock so callers and tests agree on "today".
* A routine with no exercises does not count: starting one lands you in an empty session, so
* it is not an answer to "what is next" (the same guard TabBar applies before starting).
* Returns null when the whole week is rest.
*/
export function nextTrainingDay(S, iso) {
for (let i = 1; i <= 7; i++) {
const d = new Date(iso + 'T12:00:00')
d.setDate(d.getDate() + i)
const nextIso = isoOf(d)
const routine = effectiveRoutine(S, nextIso)
if (routine && (routine.ex || []).length) return { iso: nextIso, weekday: d.getDay(), routine }
}
return null
}
/**
* Build the rows a planned exercise starts a session with: its work sets, preceded by however
* many warm-up sets the routine asks for (`cfg.warmupSets`, 0 by default so an existing plan
@@ -454,11 +473,12 @@ export function unitOf(units, idx) { return units.find(u => u.includes(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)
+51 -1
View File
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest'
import { modeOf, isTimed, fmtSec, setLabel, defaultConfig, buildSets, freestyleConfig, exLine, workoutVolume, bestWeightFor, bestWeightForEntry, effortOf, stepEffort, capEffort, isBw, isPerSide, sideReps, repStep, cascadeWeight, insertWarmupRow, removeRowAt, workSetsDone, pairAdjacent, unpairSuperset, supersetUnits, applyIntensifierPlan, pinnedNoteFor, exNoteFor } from './history.js'
import { nextTrainingDay, modeOf, isTimed, fmtSec, setLabel, defaultConfig, buildSets, freestyleConfig, exLine, workoutVolume, bestWeightFor, bestWeightForEntry, effortOf, stepEffort, capEffort, isBw, isPerSide, sideReps, repStep, cascadeWeight, insertWarmupRow, removeRowAt, workSetsDone, pairAdjacent, unpairSuperset, supersetUnits, applyIntensifierPlan, pinnedNoteFor, exNoteFor } from './history.js'
import { EXDB } from './exercises.js'
// Real ids out of the shipped catalogue, so the body-part fallback is exercised for real.
@@ -853,3 +853,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 })
})
})
+9 -4
View File
@@ -9,7 +9,7 @@
import { isWarmupRow } from './workout-model.js'
import { EXIDX, smOf } from './exercises.js'
import { todayISO, weekKey } from './format.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.
@@ -260,12 +260,17 @@ 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. */
export function muscleBalanceWindow(workouts, win, now = Date.now(), today = todayISO()) {
/**
* 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) === weekKey(today)
? weekKey(workout.d, ws) === weekKey(today, ws)
: (workout.start || new Date(workout.d).getTime()) > now - win * 86400000)
}
+8 -6
View File
@@ -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) {
@@ -100,7 +101,7 @@ export function buildPlanBundle(S, name) {
.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 }
}
@@ -145,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
}
}
@@ -180,7 +181,7 @@ export function mergePlan(s, bundle, { schedule } = {}) {
})
})
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]
})
@@ -240,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>`
+3 -3
View File
@@ -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(340)
expect(inherited).toHaveLength(458)
expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(344)
expect(inherited).toHaveLength(463)
// 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('67edc754880ed2a392eee8839549a36bd8bf55b16f889b655b40fc6c493fc6dd')
expect(fingerprint, 'pt-PT inheritance changed; review the inherited pt-BR wording').toBe('cafd0b6fde9f8261563b5040aa6e1278f5b469dc2d6b9c81d7d5554bb6825a05')
})
test('does not leak European Portuguese UI terms', () => {
+133
View File
@@ -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)
})
})