diff --git a/frontend/src/lib/effort.js b/frontend/src/lib/effort.js index 2417353..e6448da 100644 --- a/frontend/src/lib/effort.js +++ b/frontend/src/lib/effort.js @@ -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 diff --git a/frontend/src/lib/format.js b/frontend/src/lib/format.js index cd11e2b..d15f7ee 100644 --- a/frontend/src/lib/format.js +++ b/frontend/src/lib/format.js @@ -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) diff --git a/frontend/src/lib/history.js b/frontend/src/lib/history.js index 9eb3aa2..a44751e 100644 --- a/frontend/src/lib/history.js +++ b/frontend/src/lib/history.js @@ -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 : {} @@ -473,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) diff --git a/frontend/src/lib/muscles.js b/frontend/src/lib/muscles.js index 8869e7b..ff744f1 100644 --- a/frontend/src/lib/muscles.js +++ b/frontend/src/lib/muscles.js @@ -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) } diff --git a/frontend/src/lib/plan-share.js b/frontend/src/lib/plan-share.js index c6b8c36..8dfb721 100644 --- a/frontend/src/lib/plan-share.js +++ b/frontend/src/lib/plan-share.js @@ -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) : `${esc(t('Rest'))}` return `
${esc(t(DAYN[d]))}
${val}
` diff --git a/frontend/src/lib/pt-br-locale.test.js b/frontend/src/lib/pt-br-locale.test.js index d37a3fd..6298de3 100644 --- a/frontend/src/lib/pt-br-locale.test.js +++ b/frontend/src/lib/pt-br-locale.test.js @@ -28,10 +28,10 @@ describe('Brazilian Portuguese locale', () => { const fingerprint = createHash('sha256').update(JSON.stringify(inherited)).digest('hex') expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(342) - expect(inherited).toHaveLength(462) + 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('1ee637df4fe0a6e4bf56c5d728981ebd713147b23886b1ee533f1e6d18ec59bb') + expect(fingerprint, 'pt-PT inheritance changed; review the inherited pt-BR wording').toBe('cafd0b6fde9f8261563b5040aa6e1278f5b469dc2d6b9c81d7d5554bb6825a05') }) test('does not leak European Portuguese UI terms', () => { diff --git a/frontend/src/lib/week-start.test.js b/frontend/src/lib/week-start.test.js new file mode 100644 index 0000000..5733b7d --- /dev/null +++ b/frontend/src/lib/week-start.test.js @@ -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) + }) +}) diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.js index dba325d..0059d37 100644 --- a/frontend/src/locales/de.js +++ b/frontend/src/locales/de.js @@ -306,6 +306,7 @@ export default { 'Keep screen awake': 'Bildschirm anlassen', 'The screen stays on while a workout is running, so you don’t have to unlock your phone between sets.': 'Der Bildschirm bleibt an, solange ein Workout läuft — so musst du zwischen den Sätzen nicht entsperren.', 'Weight unit': 'Gewichtseinheit', + 'Week starts on': 'Woche beginnt am', 'Rest timer': 'Pausen-Timer', 'Sounds': 'Töne', 'Flash screen when timer ends': 'Bildschirm bei Timer-Ende blinken lassen', diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js index b328d09..1167792 100644 --- a/frontend/src/locales/es.js +++ b/frontend/src/locales/es.js @@ -292,6 +292,7 @@ export default { 'Keep screen awake': 'Mantener la pantalla encendida', 'The screen stays on while a workout is running, so you don’t have to unlock your phone between sets.': 'La pantalla se mantiene encendida mientras hay un entrenamiento en curso, así no tienes que desbloquear el móvil entre series.', 'Weight unit': 'Unidad de peso', + 'Week starts on': 'La semana empieza el', 'Rest timer': 'Temporizador de descanso', 'Sounds': 'Sonidos', 'Flash screen when timer ends': 'Hacer parpadear la pantalla al finalizar el temporizador', diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.js index f01c6d4..7765ede 100644 --- a/frontend/src/locales/fr.js +++ b/frontend/src/locales/fr.js @@ -292,6 +292,7 @@ export default { 'Keep screen awake': 'Garder l’écran allumé', 'The screen stays on while a workout is running, so you don’t have to unlock your phone between sets.': 'L’écran reste allumé tant qu’une séance est en cours, pas besoin de déverrouiller ton téléphone entre les séries.', 'Weight unit': 'Unité de poids', + 'Week starts on': 'La semaine commence le', 'Rest timer': 'Minuteur de repos', 'Sounds': 'Sons', 'Flash screen when timer ends': 'Faire clignoter l’écran à la fin du minuteur', diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.js index 7a72877..4096f21 100644 --- a/frontend/src/locales/hi.js +++ b/frontend/src/locales/hi.js @@ -292,6 +292,7 @@ export default { 'Keep screen awake': 'स्क्रीन चालू रखें', 'The screen stays on while a workout is running, so you don’t have to unlock your phone between sets.': 'वर्कआउट चलने के दौरान स्क्रीन चालू रहती है, ताकि सेट के बीच फ़ोन अनलॉक न करना पड़े।', 'Weight unit': 'वज़न की इकाई', + 'Week starts on': 'सप्ताह शुरू होता है', 'Rest timer': 'आराम टाइमर', 'Sounds': 'ध्वनियाँ', 'Flash screen when timer ends': 'टाइमर खत्म होने पर स्क्रीन फ्लैश करें', diff --git a/frontend/src/locales/hu.js b/frontend/src/locales/hu.js index d08a1af..fd2b760 100644 --- a/frontend/src/locales/hu.js +++ b/frontend/src/locales/hu.js @@ -295,6 +295,7 @@ export default { 'Keep screen awake': 'Képernyő ébren tartása', 'The screen stays on while a workout is running, so you don’t have to unlock your phone between sets.': 'A képernyő edzés közben bekapcsolva marad, így sorozatok között nem kell feloldanod a telefonod.', 'Weight unit': 'Súlymértékegység', + 'Week starts on': 'A hét kezdőnapja', 'Rest timer': 'Pihenő időzítő', 'Sounds': 'Hangok', 'Note: switching units only changes the label — logged numbers are not converted.': 'Megjegyzés: a mértékegység váltása csak a feliratot módosítja — a rögzített számok nem lesznek átváltva.', diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.js index a957f92..8f80be2 100644 --- a/frontend/src/locales/it.js +++ b/frontend/src/locales/it.js @@ -292,6 +292,7 @@ export default { 'Keep screen awake': 'Mantieni lo schermo acceso', 'The screen stays on while a workout is running, so you don’t have to unlock your phone between sets.': 'Lo schermo resta acceso mentre un allenamento è in corso, così non devi sbloccare il telefono tra una serie e l’altra.', 'Weight unit': 'Unità di peso', + 'Week starts on': 'La settimana inizia il', 'Rest timer': 'Timer di riposo', 'Sounds': 'Suoni', 'Flash screen when timer ends': 'Fai lampeggiare lo schermo alla fine del timer', diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.js index 13e481e..d341d8a 100644 --- a/frontend/src/locales/ko.js +++ b/frontend/src/locales/ko.js @@ -292,6 +292,7 @@ export default { 'Keep screen awake': '화면 켜두기', 'The screen stays on while a workout is running, so you don’t have to unlock your phone between sets.': '운동이 진행되는 동안 화면이 켜져 있어 세트 사이에 잠금을 해제할 필요가 없습니다.', 'Weight unit': '무게 단위', + 'Week starts on': '주 시작 요일', 'Rest timer': '휴식 타이머', 'Sounds': '소리', 'Flash screen when timer ends': '타이머 종료 시 화면 깜박임', diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.js index 1ab0b0c..d3668cd 100644 --- a/frontend/src/locales/pl.js +++ b/frontend/src/locales/pl.js @@ -292,6 +292,7 @@ export default { 'Keep screen awake': 'Nie wygaszaj ekranu', 'The screen stays on while a workout is running, so you don’t have to unlock your phone between sets.': 'Ekran pozostaje włączony w trakcie treningu, więc nie musisz odblokowywać telefonu między seriami.', 'Weight unit': 'Jednostka wagi', + 'Week starts on': 'Tydzień zaczyna się w', 'Rest timer': 'Minutnik przerwy', 'Sounds': 'Dźwięki', 'Flash screen when timer ends': 'Migaj ekranem po zakończeniu minutnika', diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.js index 78ea22f..67c2ef2 100644 --- a/frontend/src/locales/pt.js +++ b/frontend/src/locales/pt.js @@ -292,6 +292,7 @@ export default { 'Keep screen awake': 'Manter o ecrã ligado', 'The screen stays on while a workout is running, so you don’t have to unlock your phone between sets.': 'O ecrã fica ligado enquanto há um treino a decorrer, para não teres de desbloquear o telemóvel entre séries.', 'Weight unit': 'Unidade de peso', + 'Week starts on': 'Início da semana', 'Rest timer': 'Temporizador de descanso', 'Sounds': 'Sons', 'Flash screen when timer ends': 'Piscar o ecrã quando o temporizador terminar', diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.js index 704f619..93dd646 100644 --- a/frontend/src/locales/ru.js +++ b/frontend/src/locales/ru.js @@ -292,6 +292,7 @@ export default { 'Keep screen awake': 'Не гасить экран', 'The screen stays on while a workout is running, so you don’t have to unlock your phone between sets.': 'Экран не гаснет, пока идёт тренировка, — не нужно разблокировать телефон между подходами.', 'Weight unit': 'Единица веса', + 'Week starts on': 'Неделя начинается с', 'Rest timer': 'Таймер отдыха', 'Sounds': 'Звуки', 'Flash screen when timer ends': 'Мигать экраном по окончании таймера', diff --git a/frontend/src/locales/th.js b/frontend/src/locales/th.js index fa4331f..e7c9406 100644 --- a/frontend/src/locales/th.js +++ b/frontend/src/locales/th.js @@ -295,6 +295,7 @@ export default { 'Keep screen awake': 'ไม่ให้จอปิด', 'The screen stays on while a workout is running, so you don’t have to unlock your phone between sets.': 'จอจะไม่ปิดขณะออกกำลังกาย จะได้ไม่ต้องปลดล็อกโทรศัพท์ระหว่างเซ็ต', 'Weight unit': 'หน่วยน้ำหนัก', + 'Week starts on': 'สัปดาห์เริ่มวัน', 'Rest timer': 'ตัวจับเวลาพัก', 'Sounds': 'เสียง', 'Note: switching units only changes the label — logged numbers are not converted.': 'หมายเหตุ: การเปลี่ยนหน่วยจะเปลี่ยนแค่ป้ายกำกับ — ตัวเลขที่บันทึกไว้จะไม่ถูกแปลง', diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.js index 7f740f9..0ccd514 100644 --- a/frontend/src/locales/tr.js +++ b/frontend/src/locales/tr.js @@ -292,6 +292,7 @@ export default { 'Keep screen awake': 'Ekranı açık tut', 'The screen stays on while a workout is running, so you don’t have to unlock your phone between sets.': 'Antrenman sürerken ekran açık kalır, böylece setler arasında telefonunu açmak zorunda kalmazsın.', 'Weight unit': 'Ağırlık birimi', + 'Week starts on': 'Hafta başlangıcı', 'Rest timer': 'Dinlenme sayacı', 'Sounds': 'Sesler', 'Flash screen when timer ends': 'Zamanlayıcı bitince ekranı yanıp söndür', diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.js index 618aff3..2580efb 100644 --- a/frontend/src/locales/zh.js +++ b/frontend/src/locales/zh.js @@ -292,6 +292,7 @@ export default { 'Keep screen awake': '保持屏幕常亮', 'The screen stays on while a workout is running, so you don’t have to unlock your phone between sets.': '训练进行时屏幕保持常亮,组间无需再解锁手机。', 'Weight unit': '重量单位', + 'Week starts on': '一周开始于', 'Rest timer': '休息计时', 'Sounds': '声音', 'Flash screen when timer ends': '计时结束时闪烁屏幕', diff --git a/frontend/src/sheets.jsx b/frontend/src/sheets.jsx index 037348b..8ccba30 100644 --- a/frontend/src/sheets.jsx +++ b/frontend/src/sheets.jsx @@ -3,7 +3,7 @@ import { useStore } from './store/useStore.js' import { useUI } from './store/useUI.js' import { EXDB, EXIDX, BODYPARTS, isCardio, isBodyweightEq, allExercises, equipmentOf, smOf, matchExercise, exOr } from './lib/exercises.js' import { activeProfile, exAvailable, ALL_EQUIPMENT, newProfile } from './lib/equipment.js' -import { fmtDate, fmtNum, fmtVol, fmtDur, durPart, todayISO, isoOf, uid, exCount, DAYN, MONTHS_LONG, ACCENTS } from './lib/format.js' +import { fmtDate, fmtNum, fmtVol, fmtDur, durPart, todayISO, isoOf, uid, exCount, DAYN, DAYS, weekOrder, weekStartOf, weekDayOffset, MONTHS_LONG, ACCENTS } from './lib/format.js' import { lastEntryFor, bestWeightFor, buildSets, effectiveRoutineId, workoutVolume, setsDone, setsDoneActive, lastBW, supersetUnits, unitOf, setLabel, defaultConfig, cleanupSg, modeOf, effortOf, isBw, isPerSide, sideReps, workSetsDone, applyIntensifierPlan, MAX_PLANNED_WARMUPS, NOTE_MAX } from './lib/history.js' import { usesBar, barWeightFor, defaultBarWeight, hasBarOverride } from './lib/bar.js' import { beep, vibrate } from './lib/sound.js' @@ -1374,7 +1374,9 @@ function Calendar({ start, close }) { const y = cur.getFullYear(), mo = cur.getMonth() const byDay = {} st.workouts.forEach(w => (byDay[w.d] = byDay[w.d] || []).push(w)) - const startOffset = (new Date(y, mo, 1).getDay() + 6) % 7 + // Which column the 1st sits in, and therefore how many blanks come before it. + const ws = weekStartOf(st) + const startOffset = weekDayOffset(new Date(y, mo, 1).getDay(), ws) const daysIn = new Date(y, mo + 1, 0).getDate() const monthWs = st.workouts.filter(w => w.d.startsWith(y + '-' + String(mo + 1).padStart(2, '0'))) const monthVol = monthWs.reduce((a, w) => a + (w.vol || 0), 0) @@ -1398,7 +1400,7 @@ function Calendar({ start, close }) {
{monthWs.length ? `${t(monthWs.length === 1 ? '{0} workout' : '{0} workouts', monthWs.length)} · ${fmtDur(monthMs)} · ${fmtVol(monthVol, st.unit)}` : t('No workouts this month')}
-
{['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'].map(l =>
{t(l)}
)}{cells}
+
{weekOrder(ws).map(d =>
{t(DAYS[d])}
)}{cells}
{t('Trained')} {t('Planned')} diff --git a/frontend/src/store/useStore.js b/frontend/src/store/useStore.js index 028f766..c86f7a8 100644 --- a/frontend/src/store/useStore.js +++ b/frontend/src/store/useStore.js @@ -21,6 +21,10 @@ export const DEF = { // Equipment profiles (issue: filter Library/picker/routines by what you actually own — // e.g. "Home" vs "Gym" — building on the session-only equipment filter from issue #6). equipProfiles: [], activeEquipId: null, equipFilterOn: false, + // First day of the week as a getDay() index — 1 Monday, 0 Sunday. Monday is the default so + // every profile written before this setting existed keeps the week it has been looking at. + // See lib/format.js: nothing reads this field directly, everything goes through the helpers. + weekStart: 1, // Per-exercise bar weight overrides, keyed by exercise id, in the profile unit (see // lib/bar.js). Personal equipment, so it syncs with the account but never travels in a // shared plan. Logged weights stay the total — this only feeds the plate math. diff --git a/frontend/src/views/Home.jsx b/frontend/src/views/Home.jsx index 54f79c1..158a459 100644 --- a/frontend/src/views/Home.jsx +++ b/frontend/src/views/Home.jsx @@ -2,7 +2,7 @@ import { useState } from 'react' import { useNavigate } from 'react-router-dom' import { useStore } from '../store/useStore.js' import { effectiveRoutine, effectiveRoutineId, nextTrainingDay, streakWeeks, lastBW, setsDoneActive } from '../lib/history.js' -import { fmtNum, fmtDate, todayISO, isoOf, weekKey, DAYS, DAYN } from '../lib/format.js' +import { fmtNum, fmtDate, todayISO, isoOf, weekKey, weekStartOf, weekDayOffset, DAYS, DAYN } from '../lib/format.js' import { t, dateLocale } from '../lib/i18n.js' import { bwSheet, goalSheet, dayOverrideSheet, calendarSheet, startFlow, loadStarterPlan, bwDeltaColor } from '../sheets.jsx' import LineChart from '../components/LineChart.jsx' @@ -27,24 +27,28 @@ export default function Home() { const prevBW = S.bodyweight.length > 1 ? S.bodyweight[S.bodyweight.length - 2] : null const delta = bw && prevBW ? bw.w - prevBW.w : null - const monday = new Date(today); monday.setDate(today.getDate() - ((today.getDay() + 6) % 7) + weekOffset * 7) + const ws = weekStartOf(S) + // The first day of the shown week. Named for the role, not for Monday — which day that is + // is the setting. + const wkStart = new Date(today) + wkStart.setDate(today.getDate() - weekDayOffset(today.getDay(), ws) + weekOffset * 7) const doneDays = new Set(S.workouts.map(w => w.d)) // The last session logged for today, if any — what the row below reports instead of asking // you to start the one you already did. Last wins, so a second session names itself. const doneToday = S.workouts.filter(w => w.d === todayISO()).at(-1) || null const strip = [] for (let i = 0; i < 7; i++) { - const d = new Date(monday); d.setDate(monday.getDate() + i) + const d = new Date(wkStart); d.setDate(wkStart.getDate() + i) const iso = isoOf(d) const eff = effectiveRoutineId(S, iso), ovr = S.dayPlan[iso] !== undefined, done = doneDays.has(iso) const dot = done ? ' done' : ovr && eff ? ' ovr' : eff ? ' plan' : '' strip.push(
dayOverrideSheet(iso))}>
{t(DAYS[d.getDay()])}
{d.getDate()}
) } - const sunday = new Date(monday); sunday.setDate(monday.getDate() + 6) - const wkLabel = weekOffset === 0 ? t('This week') : `${monday.getDate()} ${monday.toLocaleDateString(dateLocale(), { month: 'short' })} – ${sunday.getDate()} ${sunday.toLocaleDateString(dateLocale(), { month: 'short' })}` + const wkEnd = new Date(wkStart); wkEnd.setDate(wkStart.getDate() + 6) + const wkLabel = weekOffset === 0 ? t('This week') : `${wkStart.getDate()} ${wkStart.toLocaleDateString(dateLocale(), { month: 'short' })} – ${wkEnd.getDate()} ${wkEnd.toLocaleDateString(dateLocale(), { month: 'short' })}` - const wThisWeek = S.workouts.filter(w => weekKey(w.d) === weekKey(todayISO())).length + const wThisWeek = S.workouts.filter(w => weekKey(w.d, ws) === weekKey(todayISO(), ws)).length const plannedPerWeek = Object.keys(S.week).filter(k => S.week[k]).length const bwPoints = S.bodyweight.slice(-30).map(b => ({ t: b.t || new Date(b.d).getTime(), y: b.w, d: b.d })) diff --git a/frontend/src/views/Plan.jsx b/frontend/src/views/Plan.jsx index bdf26dc..87ad651 100644 --- a/frontend/src/views/Plan.jsx +++ b/frontend/src/views/Plan.jsx @@ -1,6 +1,6 @@ import { useNavigate } from 'react-router-dom' import { useStore } from '../store/useStore.js' -import { DAYN, uid, exCount } from '../lib/format.js' +import { DAYN, weekOrder, weekStartOf, uid, exCount } from '../lib/format.js' import { t } from '../lib/i18n.js' import { dayAssignSheet, loadStarterPlan, planToolsSheet } from '../sheets.jsx' import Icon from '../components/Icon.jsx' @@ -27,7 +27,7 @@ export default function Plan() {

{t('Week schedule')}

- {[1, 2, 3, 4, 5, 6, 0].map(d => { + {weekOrder(weekStartOf(S)).map(d => { const r = S.routines.find(x => x.id === S.week[d]) return
dayAssignSheet(d))}>
{t(DAYN[d])}
diff --git a/frontend/src/views/Settings.jsx b/frontend/src/views/Settings.jsx index c288252..1845148 100644 --- a/frontend/src/views/Settings.jsx +++ b/frontend/src/views/Settings.jsx @@ -2,7 +2,7 @@ import { useEffect, useRef, useState } from 'react' import { useNavigate } from 'react-router-dom' import { useStore, DEF, hasData } from '../store/useStore.js' import { useUI } from '../store/useUI.js' -import { ACCENTS, todayISO, localTZ } from '../lib/format.js' +import { ACCENTS, todayISO, localTZ, weekStartOf, MONDAY, SUNDAY } from '../lib/format.js' import { effortOf } from '../lib/history.js' import { api, webauthnOK, passkeyLogin, passkeyRegister, IS_ANDROID } from '../lib/api.js' import { pushSupported, enablePush, disablePush, sendTestPush } from '../lib/push.js' @@ -125,6 +125,13 @@ export default function Settings() { options={[{ value: 'kg', label: 'kg' }, { value: 'lb', label: 'lb' }]} value={S.unit} onChange={v => update(s => { s.unit = v })} /> + {/* Monday or Sunday — the Plan list, the Home strip, the calendar grid and every + "this week" total follow it. Stored as a getDay() index (see lib/format.js). */} + + update(s => { s.weekStart = v })} /> + {/* ---------- during a workout ---------- */} diff --git a/frontend/src/views/Stats.jsx b/frontend/src/views/Stats.jsx index fec0334..9fab504 100644 --- a/frontend/src/views/Stats.jsx +++ b/frontend/src/views/Stats.jsx @@ -3,7 +3,7 @@ import { useNavigate } from 'react-router-dom' import { useStore } from '../store/useStore.js' import { EXIDX, matchExercise } from '../lib/exercises.js' import { lastBW, streakWeeks, setLabel, modeOf, effortOf, metricModeForEntry, metricRowsForEntry, bestWeightForEntry } from '../lib/history.js' -import { fmtNum, fmtDate, fmtVol, todayISO } from '../lib/format.js' +import { fmtNum, fmtDate, fmtVol, todayISO, weekStartOf } from '../lib/format.js' import { t, exerciseNameFor, getLang } from '../lib/i18n.js' import { bwSheet, goalSheet, calendarSheet, workoutDetailSheet, WorkoutRow, bwDeltaColor } from '../sheets.jsx' import LineChart from '../components/LineChart.jsx' @@ -123,7 +123,7 @@ function MuscleBalance({ S }) { return t('Weeks since training: {0}', weeks) } const toggleSel = m => setSel(s => (s === m ? null : m)) - const inWin = muscleBalanceWindow(S.workouts, win, now) + const inWin = muscleBalanceWindow(S.workouts, win, now, todayISO(), weekStartOf(S)) // Counting only the sets taken near failure turns the map from "where did the volume go" // into "where did the stimulus go" — a muscle can lead on sets and still never be trained // hard. Offered only when the window holds ratings at all, since with none the hard map diff --git a/frontend/src/views/week-start.test.jsx b/frontend/src/views/week-start.test.jsx new file mode 100644 index 0000000..34bf2a3 --- /dev/null +++ b/frontend/src/views/week-start.test.jsx @@ -0,0 +1,120 @@ +// @vitest-environment happy-dom +// The setting is only worth anything if the screens actually follow it: the toggle has to +// write the field, and the Plan list has to draw the week in that order. +import React, { act } from 'react' +import { createRoot } from 'react-dom/client' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import Settings from './Settings.jsx' +import Plan from './Plan.jsx' + +globalThis.IS_REACT_ACT_ENVIRONMENT = true + +const mocks = vi.hoisted(() => { + const state = { S: null } + state.snapshot = () => ({ + S: state.S, + user: null, + update: mut => { + const next = structuredClone(state.S) + mut(next) + state.S = next + }, + replaceState: vi.fn(), setUser: vi.fn(), pullState: vi.fn(), pushState: vi.fn(), + signOut: vi.fn(), signOutAll: vi.fn(), resetDemo: vi.fn(), disconnectServer: vi.fn(), + }) + return state +}) +vi.mock('../store/useStore.js', () => { + const useStore = selector => (selector ? selector(mocks.snapshot()) : mocks.snapshot()) + useStore.getState = mocks.snapshot + return { useStore, DEF: { reminder: { time: '17:30' } }, hasData: () => false } +}) +vi.mock('../store/useUI.js', () => { + const snap = () => ({ toast: vi.fn(), openSheet: vi.fn() }) + const useUI = selector => (selector ? selector(snap()) : snap()) + useUI.getState = snap + return { useUI } +}) +vi.mock('react-router-dom', () => ({ useNavigate: () => () => {} })) +vi.mock('../lib/api.js', () => ({ + api: vi.fn(), webauthnOK: () => false, passkeyLogin: vi.fn(), passkeyRegister: vi.fn(), IS_ANDROID: false, +})) +vi.mock('../lib/push.js', () => ({ pushSupported: () => false, enablePush: vi.fn(), disablePush: vi.fn(), sendTestPush: vi.fn() })) +vi.mock('../lib/wakelock.js', () => ({ wakeLockSupported: () => false })) +vi.mock('../lib/mobile.js', () => ({ MOBILE: false, shareExport: vi.fn(), syncReminder: vi.fn() })) +vi.mock('./MobileOnboarding.jsx', () => ({ ConnectSheet: () => null })) +vi.mock('../sheets.jsx', () => ({ + loadStarterPlan: vi.fn(), confirmSheet: vi.fn(), importFromApp: vi.fn(), + importFromHevy: vi.fn(), equipmentProfileSheet: vi.fn(), + dayAssignSheet: vi.fn(), planToolsSheet: vi.fn(), +})) + +globalThis.__APP_VERSION__ ??= 'test' + +let host, root +beforeEach(() => { + mocks.S = { + unit: 'kg', restSec: 90, restPauseSec: 15, sound: false, effort: 'none', + gifSize: 'full', workouts: [], routines: [], exWeights: {}, week: {}, dayPlan: {}, + } + host = document.createElement('div') + document.body.appendChild(host) + root = createRoot(host) +}) +afterEach(() => { + act(() => root.unmount()) + host.remove() +}) + +const segButton = label => [...host.querySelectorAll('.seg button')].find(b => b.textContent === label) +const dayRows = () => [...host.querySelectorAll('.item .tt')].map(e => e.textContent) + +describe('Settings — week starts on', () => { + const mount = () => act(() => root.render()) + + it('offers Monday and Sunday and writes the getDay() index', () => { + mount() + expect(segButton('Monday').getAttribute('aria-pressed')).toBe('true') + act(() => { segButton('Sunday').click() }) + expect(mocks.S.weekStart).toBe(0) + mount() + expect(segButton('Sunday').getAttribute('aria-pressed')).toBe('true') + act(() => { segButton('Monday').click() }) + expect(mocks.S.weekStart).toBe(1) + }) + + it('shows a profile written before the setting existed as Monday', () => { + delete mocks.S.weekStart + mount() + expect(segButton('Monday').getAttribute('aria-pressed')).toBe('true') + expect(segButton('Sunday').getAttribute('aria-pressed')).toBe('false') + }) +}) + +describe('Plan — the week schedule follows the setting', () => { + const mount = () => act(() => root.render()) + + it('runs Monday to Sunday by default', () => { + mount() + expect(dayRows().slice(0, 7)).toEqual( + ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']) + }) + + it('runs Sunday to Saturday for a Sunday profile', () => { + mocks.S.weekStart = 0 + mount() + expect(dayRows().slice(0, 7)).toEqual( + ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']) + }) + + it('keeps a routine attached to its day, not to its position in the list', () => { + mocks.S.routines = [{ id: 'r1', name: 'Push', emoji: null, ex: [] }] + mocks.S.week = { 0: 'r1' } // Sunday + mocks.S.weekStart = 0 + mount() + const rows = [...host.querySelectorAll('.item')] + expect(rows[0].querySelector('.tt').textContent).toBe('Sunday') + expect(rows[0].textContent).toContain('Push') + expect(rows[1].textContent).not.toContain('Push') + }) +})