diff --git a/README.md b/README.md index 47f40f9..833faf8 100644 --- a/README.md +++ b/README.md @@ -62,7 +62,9 @@ as a home-screen app, passkey sign-in, offline support, sync across your phone a - ⚖️ **Body-weight tracking** — interactive chart with a goal line you set, gains/losses colored by whether they move toward it - 🏋️ **Weekly plan** — a routine per weekday, over a library of **1,324 exercises** (searchable, with animated demos) - 🗓️ **Reschedule any day** — sick, missed a session, or fewer gym days this week? Move a workout to another day without touching your weekly plan -- ▶️ **Guided workouts** — it knows what day it is and starts today's session; asks your body weight first, pre-fills your weights from last time, rest timer, PR detection, per-exercise weight tracking +- 📅 **Your week starts where you say** — Monday or Sunday, in Settings. The weekly plan, the day strip on Home, the calendar and every "this week" total follow it, so the app reads the way the calendar on your wall does +- ▶️ **Guided workouts** — it knows what day it is and starts today's session; asks your body weight first, pre-fills your weights from last time, rest timer, PR detection, per-exercise weight tracking. On a rest day it doesn't just say "rest day" — it names when your next session is and what it is +- 🙈 **Animations are your call** — the exercise demos can be full size, small, or hidden entirely during a workout. Hidden collapses the media rather than leaving a gap, for anyone who finds a looping GIF between sets more distracting than useful - ☀️ **The screen stays awake while you train** — no unlocking the phone and finding your place again between every set. On for as long as a workout is running, released the moment you finish it, and switchable off in Settings - 🔗 **Supersets** — plan them into a routine or pair two exercises *mid-session* with “make superset with previous/next”, then work through the group back-to-back with a single rest at the end of each round. Unpair at any time; a group of one dissolves itself - 🔥 **Warm-up sets** — mark the ramp-up rows as warm-ups and they stay out of the numbers that should not see them: no effect on your estimated 1RM, your progression, or the fatigue map, while still being there in the session where you need them. A weight change cascades down the rows that share their phase, not across the divide @@ -75,6 +77,7 @@ as a home-screen app, passkey sign-in, offline support, sync across your phone a - 🎯 **Effort per set, in your scale** — an optional third column rating how hard a set was, as **RIR** (reps left in the tank) or **RPE** (the same judgement on a 10-point scale). Off by default; each set keeps the scale it was logged with, and nothing else reads the value — your progression and 1RM are unaffected - 💪 **Bodyweight exercises, logged as bodyweight** — push-ups, pull-ups, dips and 300-odd others arrive knowing they carry no load, so there's no weight column and no working-weight prompt: one stepper, log the reps. Add a dip belt and it reads as an addition, and progression goes back to following the weight. Without one, reps climb — and past a ceiling you set, a set is added instead of a rep, up to the point where the honest advice is load or a harder variation - ↔️ **Reps per side** — for lunges, single-arm rows and the rest. You log the total, the app shows the split ("8 per side"), and the target steps in twos so it never lands on a number one side can't have +- 🏋️ **Plate math for barbell work** — barbell, EZ, trap bar and Smith machine carry a bar weight (20 kg / 45 lb and friends, or your own per exercise), and the workout screen tells you what goes on each side: *Bar 20 kg · 30 kg per side*. You still log the total, so your history, progression and 1RM keep meaning exactly what they always did - 📝 **Log a past workout** — forgot your phone, trained on paper, or switched apps? Add a session after the fact from History: date, start time, duration, routine or freestyle, then the normal workout screen — weights, reps, RIR/RPE, timed sets and all. If that day already has a workout you choose: replace it, keep both, or cancel. Backfilled sessions never claim PRs against workouts that came later - 🎲 **Freestyle sessions** — train without a plan and pick exercises as you go. Each one arrives prefilled from the last time you did it — same sets, same reps and weight by position — so an unplanned session doesn't start by asking you to retype last week - 🏃 **Cardio** — log time + speed, not just weight × reps diff --git a/frontend/src/admin.css b/frontend/src/admin.css new file mode 100644 index 0000000..a4b96bd --- /dev/null +++ b/frontend/src/admin.css @@ -0,0 +1,32 @@ +/* Admin dashboard — operator-facing, English-only. Sits on top of the app's tokens; nothing + here is used outside views/Admin.jsx. The page is looked at maybe twice a year, so every + card says what it is for in a sentence and every state is a word, not a colour to decode. */ + +.adm-intro{color:var(--label-2);font-size:14px;line-height:1.45;margin:-6px 0 16px} + +/* one sentence under a card heading that says what the card is for */ +.adm-lead{color:var(--label-2);font-size:13px;line-height:1.45;margin:2px 0 12px} + +/* status pill: a word and a colour, never a paragraph */ +.adm-pill{ + display:inline-flex;align-items:center;gap:6px;padding:3px 10px;border-radius:999px; + font-size:12.5px;font-weight:600;letter-spacing:-.004em;line-height:1.5;white-space:nowrap; + background:var(--surface-2);color:var(--label-2) +} +.adm-pill::before{content:'';width:7px;height:7px;border-radius:50%;background:currentColor;flex:none} +.adm-pill.bad{background:color-mix(in srgb,var(--red) 16%,transparent);color:var(--red)} +.adm-pill.acc{background:var(--acc-soft);color:var(--acc)} + +/* a dim explainer that reads like a sentence, not a footnote */ +.adm-hint{font-size:13px;color:var(--label-2);line-height:1.45;margin:6px 0 10px} + +/* a small heading over a group of rows ("Unused · tap to copy") */ +.adm-group-t{font-size:11.5px;font-weight:600;letter-spacing:.04em;text-transform:uppercase;color:var(--label-3);margin:0 0 7px} + +/* an invite code, sized to be tapped and read out loud */ +.adm-code{ + font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-weight:600;letter-spacing:.08em; + background:var(--surface-2);padding:4px 9px;border-radius:8px;font-size:14px +} +.adm-iconbtn{width:44px;height:44px;border-radius:12px;font-size:17px} +.adm-empty{color:var(--label-3);font-size:13.5px;padding:10px 2px} diff --git a/frontend/src/lib/bar.js b/frontend/src/lib/bar.js new file mode 100644 index 0000000..fa75348 --- /dev/null +++ b/frontend/src/lib/bar.js @@ -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 +} diff --git a/frontend/src/lib/bar.test.js b/frontend/src/lib/bar.test.js new file mode 100644 index 0000000..e8a94e6 --- /dev/null +++ b/frontend/src/lib/bar.test.js @@ -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) + }) +}) 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 0850fc2..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 : {} @@ -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) diff --git a/frontend/src/lib/history.test.js b/frontend/src/lib/history.test.js index f74c6a4..685066a 100644 --- a/frontend/src/lib/history.test.js +++ b/frontend/src/lib/history.test.js @@ -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 }) + }) +}) 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 871df7f..da6c2fe 100644 --- a/frontend/src/lib/pt-br-locale.test.js +++ b/frontend/src/lib/pt-br-locale.test.js @@ -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', () => { 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 81f21b4..6ce69c3 100644 --- a/frontend/src/locales/de.js +++ b/frontend/src/locales/de.js @@ -118,6 +118,7 @@ export default { 'Sick, missed a day or want a different session? Pick what to train instead.': 'Krank, Tag verpasst oder Lust auf was anderes? Wähle, was du stattdessen trainierst.', 'Rest / skip this day': 'Pause / Tag überspringen', 'Rest day': 'Pausentag', + 'Next session: {0}, {1}': 'Nächste Einheit: {0}, {1}', '{0} workout': '{0} Training', '{0} workouts': '{0} Trainings', 'No workouts this month': 'Keine Trainings in diesem Monat', @@ -307,6 +308,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', @@ -752,4 +754,12 @@ export default { 'Add as second workout': 'Als zweites Training hinzufügen', 'Finish the current workout first.': 'Beende zuerst das laufende Training.', 'Logging a past workout — no rest timers.': 'Vergangenes Training — keine Pausen-Timer.', + // --- bar weight (plate math) --- + 'Bar weight': 'Stangengewicht', + 'Bar ({0})': 'Stange ({0})', + 'Bar {0}': 'Stange {0}', + 'Default for this bar type.': 'Standard für diesen Stangentyp.', + 'Set to 0 to go back to the default ({0}).': 'Auf 0 stellen, um zum Standard ({0}) zurückzukehren.', + 'Applies to this exercise everywhere, not just this plan.': 'Gilt überall für diese Übung, nicht nur in diesem Plan.', + 'You still log the total weight — the bar only feeds the per-side plate math.': 'Eingetragen wird weiterhin das Gesamtgewicht — die Stange zählt nur für die Scheiben-Rechnung pro Seite.', } diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js index a9e4ff5..0db0e27 100644 --- a/frontend/src/locales/es.js +++ b/frontend/src/locales/es.js @@ -113,6 +113,7 @@ export default { 'Sick, missed a day or want a different session? Pick what to train instead.': '¿Enfermo, te saltaste un día o quieres otra sesión? Elige qué entrenar en su lugar.', 'Rest / skip this day': 'Descansar / saltar este día', 'Rest day': 'Día de descanso', + 'Next session: {0}, {1}': 'Próxima sesión: {0}, {1}', '{0} workout': '{0} entrenamiento', '{0} workouts': '{0} entrenamientos', 'No workouts this month': 'Sin entrenamientos este mes', @@ -293,6 +294,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', @@ -735,4 +737,12 @@ export default { 'Add as second workout': 'Añadir como segundo entrenamiento', 'Finish the current workout first.': 'Termina primero el entrenamiento actual.', 'Logging a past workout — no rest timers.': 'Registrando un entrenamiento pasado — sin temporizadores de descanso.', + // --- bar weight (plate math) --- + 'Bar weight': 'Peso de la barra', + 'Bar ({0})': 'Barra ({0})', + 'Bar {0}': 'Barra {0}', + 'Default for this bar type.': 'Valor por defecto para este tipo de barra.', + 'Set to 0 to go back to the default ({0}).': 'Pon 0 para volver al valor por defecto ({0}).', + 'Applies to this exercise everywhere, not just this plan.': 'Se aplica a este ejercicio en todas partes, no solo en este plan.', + 'You still log the total weight — the bar only feeds the per-side plate math.': 'Sigues registrando el peso total — la barra solo se usa para calcular los discos por lado.', } diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.js index 08cab46..22dfd9a 100644 --- a/frontend/src/locales/fr.js +++ b/frontend/src/locales/fr.js @@ -113,6 +113,7 @@ export default { 'Sick, missed a day or want a different session? Pick what to train instead.': 'Malade, jour manqué ou envie d’autre chose ? Choisis quoi entraîner à la place.', 'Rest / skip this day': 'Repos / sauter ce jour', 'Rest day': 'Jour de repos', + 'Next session: {0}, {1}': 'Prochaine séance : {0}, {1}', '{0} workout': '{0} séance', '{0} workouts': '{0} séances', 'No workouts this month': 'Aucune séance ce mois-ci', @@ -293,6 +294,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', @@ -735,4 +737,12 @@ export default { 'Add as second workout': 'Ajouter comme deuxième séance', 'Finish the current workout first.': 'Termine d’abord la séance en cours.', 'Logging a past workout — no rest timers.': 'Séance passée — pas de minuteurs de repos.', + // --- bar weight (plate math) --- + 'Bar weight': 'Poids de la barre', + 'Bar ({0})': 'Barre ({0})', + 'Bar {0}': 'Barre {0}', + 'Default for this bar type.': 'Valeur par défaut pour ce type de barre.', + 'Set to 0 to go back to the default ({0}).': 'Mets 0 pour revenir à la valeur par défaut ({0}).', + 'Applies to this exercise everywhere, not just this plan.': 'S’applique à cet exercice partout, pas seulement dans ce plan.', + 'You still log the total weight — the bar only feeds the per-side plate math.': 'Tu enregistres toujours le poids total — la barre ne sert qu’au calcul des disques par côté.', } diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.js index faf2e5d..004369c 100644 --- a/frontend/src/locales/hi.js +++ b/frontend/src/locales/hi.js @@ -113,6 +113,7 @@ export default { 'Sick, missed a day or want a different session? Pick what to train instead.': 'बीमार हैं, दिन छूट गया या कुछ और करना है? चुनें कि इसके बदले क्या ट्रेन करें।', 'Rest / skip this day': 'आराम / यह दिन छोड़ें', 'Rest day': 'आराम का दिन', + 'Next session: {0}, {1}': 'अगला सत्र: {0}, {1}', '{0} workout': '{0} वर्कआउट', '{0} workouts': '{0} वर्कआउट', 'No workouts this month': 'इस महीने कोई वर्कआउट नहीं', @@ -293,6 +294,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': 'टाइमर खत्म होने पर स्क्रीन फ्लैश करें', @@ -735,4 +737,12 @@ export default { 'Add as second workout': 'दूसरे वर्कआउट के रूप में जोड़ें', 'Finish the current workout first.': 'पहले मौजूदा वर्कआउट पूरा करें।', 'Logging a past workout — no rest timers.': 'पिछला वर्कआउट दर्ज हो रहा है — कोई रेस्ट टाइमर नहीं।', + // --- bar weight (plate math) --- + 'Bar weight': 'बार का वज़न', + 'Bar ({0})': 'बार ({0})', + 'Bar {0}': 'बार {0}', + 'Default for this bar type.': 'इस तरह की बार का डिफ़ॉल्ट मान।', + 'Set to 0 to go back to the default ({0}).': 'डिफ़ॉल्ट ({0}) पर लौटने के लिए 0 सेट करें।', + 'Applies to this exercise everywhere, not just this plan.': 'यह इस एक्सरसाइज़ पर हर जगह लागू होता है, सिर्फ़ इसी प्लान पर नहीं।', + 'You still log the total weight — the bar only feeds the per-side plate math.': 'आप अब भी कुल वज़न ही दर्ज करते हैं — बार सिर्फ़ हर तरफ़ की प्लेट गिनती में काम आता है।', } diff --git a/frontend/src/locales/hu.js b/frontend/src/locales/hu.js index 64b6009..a66a0dd 100644 --- a/frontend/src/locales/hu.js +++ b/frontend/src/locales/hu.js @@ -110,6 +110,7 @@ export default { 'Sick, missed a day or want a different session? Pick what to train instead.': 'Beteg vagy, kihagytál egy napot, vagy másra van kedved? Válaszd ki, mit edzel helyette.', 'Rest / skip this day': 'Pihenő / nap kihagyása', 'Rest day': 'Pihenőnap', + 'Next session: {0}, {1}': 'Következő edzés: {0}, {1}', '{0} workout': '{0} edzés', '{0} workouts': '{0} edzés', 'No workouts this month': 'Nincs edzés ebben a hónapban', @@ -296,6 +297,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.', @@ -740,4 +742,12 @@ export default { 'Add as second workout': 'Hozzáadás második edzésként', 'Finish the current workout first.': 'Előbb fejezd be a folyó edzést.', 'Logging a past workout — no rest timers.': 'Korábbi edzés rögzítése — nincs pihenőidőzítő.', + // --- bar weight (plate math) --- + 'Bar weight': 'Rúd súlya', + 'Bar ({0})': 'Rúd ({0})', + 'Bar {0}': 'Rúd {0}', + 'Default for this bar type.': 'Alapérték ehhez a rúdtípushoz.', + 'Set to 0 to go back to the default ({0}).': 'Állítsd 0-ra az alapérték ({0}) visszaállításához.', + 'Applies to this exercise everywhere, not just this plan.': 'Mindenhol érvényes erre a gyakorlatra, nem csak ebben a tervben.', + 'You still log the total weight — the bar only feeds the per-side plate math.': 'Továbbra is a teljes súlyt rögzíted — a rúd csak az oldalankénti tárcsaszámításhoz kell.', } diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.js index 2d2b4e4..e07a25f 100644 --- a/frontend/src/locales/it.js +++ b/frontend/src/locales/it.js @@ -113,6 +113,7 @@ export default { 'Sick, missed a day or want a different session? Pick what to train instead.': 'Malato, giorno saltato o voglia di altro? Scegli cosa allenare al suo posto.', 'Rest / skip this day': 'Riposo / salta questo giorno', 'Rest day': 'Giorno di riposo', + 'Next session: {0}, {1}': 'Prossima sessione: {0}, {1}', '{0} workout': '{0} allenamento', '{0} workouts': '{0} allenamenti', 'No workouts this month': 'Nessun allenamento questo mese', @@ -293,6 +294,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', @@ -735,4 +737,12 @@ export default { 'Add as second workout': 'Aggiungi come secondo allenamento', 'Finish the current workout first.': 'Termina prima l’allenamento in corso.', 'Logging a past workout — no rest timers.': 'Allenamento passato — nessun timer di recupero.', + // --- bar weight (plate math) --- + 'Bar weight': 'Peso del bilanciere', + 'Bar ({0})': 'Bilanciere ({0})', + 'Bar {0}': 'Bilanciere {0}', + 'Default for this bar type.': 'Valore predefinito per questo tipo di bilanciere.', + 'Set to 0 to go back to the default ({0}).': 'Imposta 0 per tornare al valore predefinito ({0}).', + 'Applies to this exercise everywhere, not just this plan.': 'Vale per questo esercizio ovunque, non solo in questo piano.', + 'You still log the total weight — the bar only feeds the per-side plate math.': 'Registri comunque il peso totale — il bilanciere serve solo al calcolo dei dischi per lato.', } diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.js index febce99..1a5682d 100644 --- a/frontend/src/locales/ko.js +++ b/frontend/src/locales/ko.js @@ -113,6 +113,7 @@ export default { 'Sick, missed a day or want a different session? Pick what to train instead.': '아프거나, 하루를 놓쳤거나, 다른 운동이 하고 싶나요? 대신 할 운동을 선택하세요.', 'Rest / skip this day': '휴식 / 이 날 건너뛰기', 'Rest day': '휴식일', + 'Next session: {0}, {1}': '다음 세션: {0}, {1}', '{0} workout': '운동 {0}회', '{0} workouts': '운동 {0}회', 'No workouts this month': '이번 달 운동 없음', @@ -293,6 +294,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': '타이머 종료 시 화면 깜박임', @@ -735,4 +737,12 @@ export default { 'Add as second workout': '두 번째 운동으로 추가', 'Finish the current workout first.': '먼저 진행 중인 운동을 마치세요.', 'Logging a past workout — no rest timers.': '지난 운동 기록 중 — 휴식 타이머 없음.', + // --- bar weight (plate math) --- + 'Bar weight': '바 무게', + 'Bar ({0})': '바 ({0})', + 'Bar {0}': '바 {0}', + 'Default for this bar type.': '이 바 종류의 기본값입니다.', + 'Set to 0 to go back to the default ({0}).': '0으로 두면 기본값({0})으로 돌아갑니다.', + 'Applies to this exercise everywhere, not just this plan.': '이 플랜만이 아니라 어디서든 이 운동에 적용됩니다.', + 'You still log the total weight — the bar only feeds the per-side plate math.': '기록은 여전히 총 무게입니다 — 바 무게는 한쪽에 끼울 원판 계산에만 쓰입니다.', } diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.js index 9f1a6b7..1b71dab 100644 --- a/frontend/src/locales/pl.js +++ b/frontend/src/locales/pl.js @@ -113,6 +113,7 @@ export default { 'Sick, missed a day or want a different session? Pick what to train instead.': 'Choroba, opuszczony dzień albo ochota na coś innego? Wybierz, co trenować zamiast tego.', 'Rest / skip this day': 'Odpoczynek / pomiń ten dzień', 'Rest day': 'Dzień odpoczynku', + 'Next session: {0}, {1}': 'Następny trening: {0}, {1}', '{0} workout': '{0} trening', '{0} workouts': '{0} treningów', 'No workouts this month': 'Brak treningów w tym miesiącu', @@ -293,6 +294,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', @@ -735,4 +737,12 @@ export default { 'Add as second workout': 'Dodaj jako drugi trening', 'Finish the current workout first.': 'Najpierw zakończ bieżący trening.', 'Logging a past workout — no rest timers.': 'Zapisywanie minionego treningu — bez minutników przerw.', + // --- bar weight (plate math) --- + 'Bar weight': 'Ciężar gryfu', + 'Bar ({0})': 'Gryf ({0})', + 'Bar {0}': 'Gryf {0}', + 'Default for this bar type.': 'Wartość domyślna dla tego typu gryfu.', + 'Set to 0 to go back to the default ({0}).': 'Ustaw 0, aby wrócić do wartości domyślnej ({0}).', + 'Applies to this exercise everywhere, not just this plan.': 'Dotyczy tego ćwiczenia wszędzie, nie tylko w tym planie.', + 'You still log the total weight — the bar only feeds the per-side plate math.': 'Nadal zapisujesz ciężar całkowity — gryf służy tylko do wyliczenia talerzy na stronę.', } diff --git a/frontend/src/locales/pt-BR.js b/frontend/src/locales/pt-BR.js index 13a14ce..969d927 100644 --- a/frontend/src/locales/pt-BR.js +++ b/frontend/src/locales/pt-BR.js @@ -355,6 +355,11 @@ export const PT_BR_OVERRIDES = { 'Pick a day up to today': 'Escolha um dia até hoje', 'Finish the current workout first.': 'Termine primeiro o treino atual.', 'Logging a past workout — no rest timers.': 'Registrando um treino passado — sem temporizadores de descanso.', + // --- bar weight (plate math) --- ('Peso da barra', 'Barra ({0})', 'Barra {0}' inherit) + 'Default for this bar type.': 'Padrão para este tipo de barra.', + 'Set to 0 to go back to the default ({0}).': 'Defina 0 para voltar ao padrão ({0}).', + 'Applies to this exercise everywhere, not just this plan.': 'Vale para este exercício em todos os lugares, não só neste plano.', + 'You still log the total weight — the bar only feeds the per-side plate math.': 'Você continua registrando o peso total — a barra só entra no cálculo das anilhas por lado.' } export default { ...pt, ...PT_BR_OVERRIDES } diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.js index 44036bd..f8a0833 100644 --- a/frontend/src/locales/pt.js +++ b/frontend/src/locales/pt.js @@ -113,6 +113,7 @@ export default { 'Sick, missed a day or want a different session? Pick what to train instead.': 'Doente, falhaste um dia ou queres outra sessão? Escolhe o que treinar em vez disso.', 'Rest / skip this day': 'Descansar / saltar este dia', 'Rest day': 'Dia de descanso', + 'Next session: {0}, {1}': 'Próxima sessão: {0}, {1}', '{0} workout': '{0} treino', '{0} workouts': '{0} treinos', 'No workouts this month': 'Sem treinos este mês', @@ -293,6 +294,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', @@ -735,4 +737,12 @@ export default { 'Add as second workout': 'Adicionar como segundo treino', 'Finish the current workout first.': 'Termina primeiro o treino em curso.', 'Logging a past workout — no rest timers.': 'A registar um treino passado — sem temporizadores de descanso.', + // --- bar weight (plate math) --- + 'Bar weight': 'Peso da barra', + 'Bar ({0})': 'Barra ({0})', + 'Bar {0}': 'Barra {0}', + 'Default for this bar type.': 'Predefinição para este tipo de barra.', + 'Set to 0 to go back to the default ({0}).': 'Coloca 0 para voltar à predefinição ({0}).', + 'Applies to this exercise everywhere, not just this plan.': 'Aplica-se a este exercício em todo o lado, não só neste plano.', + 'You still log the total weight — the bar only feeds the per-side plate math.': 'Continuas a registar o peso total — a barra só conta para o cálculo dos discos por lado.', } diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.js index 2aaa76b..8229fd8 100644 --- a/frontend/src/locales/ru.js +++ b/frontend/src/locales/ru.js @@ -113,6 +113,7 @@ export default { 'Sick, missed a day or want a different session? Pick what to train instead.': 'Заболел, пропустил день или хочешь другую тренировку? Выбери, что делать вместо этого.', 'Rest / skip this day': 'Отдых / пропустить день', 'Rest day': 'День отдыха', + 'Next session: {0}, {1}': 'Следующая тренировка: {0}, {1}', '{0} workout': 'Тренировок: {0}', '{0} workouts': 'Тренировок: {0}', 'No workouts this month': 'В этом месяце тренировок нет', @@ -293,6 +294,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': 'Мигать экраном по окончании таймера', @@ -735,4 +737,12 @@ export default { 'Add as second workout': 'Добавить как вторую тренировку', 'Finish the current workout first.': 'Сначала заверши текущую тренировку.', 'Logging a past workout — no rest timers.': 'Запись прошлой тренировки — без таймеров отдыха.', + // --- bar weight (plate math) --- + 'Bar weight': 'Вес грифа', + 'Bar ({0})': 'Гриф ({0})', + 'Bar {0}': 'Гриф {0}', + 'Default for this bar type.': 'Значение по умолчанию для этого типа грифа.', + 'Set to 0 to go back to the default ({0}).': 'Поставь 0, чтобы вернуться к значению по умолчанию ({0}).', + 'Applies to this exercise everywhere, not just this plan.': 'Действует для этого упражнения везде, а не только в этом плане.', + 'You still log the total weight — the bar only feeds the per-side plate math.': 'Записывается по-прежнему общий вес — гриф нужен только для расчёта блинов на сторону.', } diff --git a/frontend/src/locales/th.js b/frontend/src/locales/th.js index 30c6550..1311111 100644 --- a/frontend/src/locales/th.js +++ b/frontend/src/locales/th.js @@ -110,6 +110,7 @@ export default { 'Sick, missed a day or want a different session? Pick what to train instead.': 'ป่วย, ขาดวัน หรืออยากเปลี่ยนโปรแกรม? เลือกสิ่งที่จะฝึกแทนได้เลย', 'Rest / skip this day': 'พัก / ข้ามวันนี้', 'Rest day': 'วันพัก', + 'Next session: {0}, {1}': 'เซสชันถัดไป: {0}, {1}', '{0} workout': '{0} ครั้ง', '{0} workouts': '{0} ครั้ง', 'No workouts this month': 'ไม่มีการออกกำลังกายในเดือนนี้', @@ -296,6 +297,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.': 'หมายเหตุ: การเปลี่ยนหน่วยจะเปลี่ยนแค่ป้ายกำกับ — ตัวเลขที่บันทึกไว้จะไม่ถูกแปลง', @@ -748,4 +750,12 @@ export default { 'Add as second workout': 'เพิ่มเป็นการฝึกครั้งที่สอง', 'Finish the current workout first.': 'จบการฝึกปัจจุบันก่อน', 'Logging a past workout — no rest timers.': 'กำลังบันทึกการฝึกย้อนหลัง — ไม่มีตัวจับเวลาพัก', + // --- bar weight (plate math) --- + 'Bar weight': 'น้ำหนักบาร์', + 'Bar ({0})': 'บาร์ ({0})', + 'Bar {0}': 'บาร์ {0}', + 'Default for this bar type.': 'ค่าเริ่มต้นสำหรับบาร์ชนิดนี้', + 'Set to 0 to go back to the default ({0}).': 'ตั้งเป็น 0 เพื่อกลับไปใช้ค่าเริ่มต้น ({0})', + 'Applies to this exercise everywhere, not just this plan.': 'มีผลกับท่านี้ทุกที่ ไม่ใช่เฉพาะในแผนนี้', + 'You still log the total weight — the bar only feeds the per-side plate math.': 'คุณยังบันทึกน้ำหนักรวมเหมือนเดิม — บาร์ใช้สำหรับคำนวณแผ่นน้ำหนักต่อข้างเท่านั้น', } diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.js index d01b3a3..1b9cd60 100644 --- a/frontend/src/locales/tr.js +++ b/frontend/src/locales/tr.js @@ -113,6 +113,7 @@ export default { 'Sick, missed a day or want a different session? Pick what to train instead.': 'Hasta mısın, gün mü kaçırdın ya da farklı bir seans mı istiyorsun? Yerine ne çalışacağını seç.', 'Rest / skip this day': 'Dinlen / bu günü atla', 'Rest day': 'Dinlenme günü', + 'Next session: {0}, {1}': 'Sonraki antrenman: {0}, {1}', '{0} workout': '{0} antrenman', '{0} workouts': '{0} antrenman', 'No workouts this month': 'Bu ay antrenman yok', @@ -293,6 +294,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', @@ -735,4 +737,12 @@ export default { 'Add as second workout': 'İkinci antrenman olarak ekle', 'Finish the current workout first.': 'Önce mevcut antrenmanı bitir.', 'Logging a past workout — no rest timers.': 'Geçmiş antrenman kaydediliyor — dinlenme zamanlayıcısı yok.', + // --- bar weight (plate math) --- + 'Bar weight': 'Bar ağırlığı', + 'Bar ({0})': 'Bar ({0})', + 'Bar {0}': 'Bar {0}', + 'Default for this bar type.': 'Bu bar türü için varsayılan.', + 'Set to 0 to go back to the default ({0}).': 'Varsayılana ({0}) dönmek için 0 yap.', + 'Applies to this exercise everywhere, not just this plan.': 'Yalnızca bu planda değil, bu egzersiz için her yerde geçerli.', + 'You still log the total weight — the bar only feeds the per-side plate math.': 'Yine de toplam ağırlığı kaydedersin — bar yalnızca taraf başına plaka hesabına girer.', } diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.js index 4488aef..6fcdd47 100644 --- a/frontend/src/locales/zh.js +++ b/frontend/src/locales/zh.js @@ -113,6 +113,7 @@ export default { 'Sick, missed a day or want a different session? Pick what to train instead.': '生病、错过一天或想换个训练?选择改练什么。', 'Rest / skip this day': '休息 / 跳过这天', 'Rest day': '休息日', + 'Next session: {0}, {1}': '下次训练:{0},{1}', '{0} workout': '{0} 次训练', '{0} workouts': '{0} 次训练', 'No workouts this month': '本月没有训练', @@ -293,6 +294,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': '计时结束时闪烁屏幕', @@ -735,4 +737,12 @@ export default { 'Add as second workout': '添加为第二次训练', 'Finish the current workout first.': '请先完成当前训练。', 'Logging a past workout — no rest timers.': '正在补记过去的训练 — 没有休息计时器。', + // --- bar weight (plate math) --- + 'Bar weight': '杠铃杆重量', + 'Bar ({0})': '杆 ({0})', + 'Bar {0}': '杆 {0}', + 'Default for this bar type.': '此类杠铃杆的默认值。', + 'Set to 0 to go back to the default ({0}).': '设为 0 即恢复默认值({0})。', + 'Applies to this exercise everywhere, not just this plan.': '对这个动作处处生效,不只在此计划中。', + 'You still log the total weight — the bar only feeds the per-side plate math.': '记录的仍是总重量——杆重只用于每侧杠铃片的计算。', } diff --git a/frontend/src/sheets.jsx b/frontend/src/sheets.jsx index 94ee1d4..8ccba30 100644 --- a/frontend/src/sheets.jsx +++ b/frontend/src/sheets.jsx @@ -3,8 +3,9 @@ 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' import { t, instrFor, exerciseNameFor, getLang, INSTR_LANGS } from './lib/i18n.js' import { nav } from './lib/nav.js' @@ -470,6 +471,44 @@ function GoalSheet({ close }) { } export const goalSheet = () => ui().openSheet(close => ) +/* ============================ bar weight ============================ */ +// One editor for every place the bar weight shows up (exercise detail, exercise config, +// mid-workout sheet): a stepper over the effective value. What it saves is per exercise +// and lives in S.barWeights, in the profile unit (see lib/bar.js) — stepping or typing +// down to 0 clears the override and the field falls back to the default for the bar +// type, the same "0 drops the key" shape a nullable set field has. +function BarWeightEditor({ ex, extra }) { + const st = useStore(s => s.S) + const explicit = hasBarOverride(st, ex.id) + const def = defaultBarWeight(ex.eq, st.unit) + const setBar = v => update(s => { + s.barWeights = s.barWeights || {} + const n = Math.max(0, Math.round((v || 0) * 100) / 100) + if (n > 0) s.barWeights[ex.id] = n; else delete s.barWeights[ex.id] + }) + return <> +
+ +
+
+ {explicit ? t('Set to 0 to go back to the default ({0}).', fmtNum(def) + ' ' + st.unit) : t('Default for this bar type.')} + {extra ? ' ' + extra : ''} +
+ +} + +// Tiny mid-workout sheet behind the "Bar … · … per side" chip — same value, same editor. +function BarWeightSheet({ exId, close }) { + const ex = exOr(exId) + return <> +

{t('Bar weight')}

+
{exerciseNameFor(ex)}
+ + + +} +export const barWeightSheet = exId => ui().openSheet(close => ) + /* ============================ exercise detail ============================ */ // Estimated 1RM for one exercise (issue #18): what the log already implies, plus a calculator // for a set you have not done — so the number is reachable before there is any history. @@ -519,6 +558,10 @@ function ExerciseDetail({ ex, close }) { } + {usesBar(ex) && <> +

{t('Bar weight')}

+ + } {!isCardio(ex) && } {instrFor(ex).length > 0 &&<>

{t('How to')}{!INSTR_LANGS.includes(getLang()) && · {t('instructions in English')}}

    {instrFor(ex).map((s, i) =>
  1. {s}
  2. )}
} @@ -1105,6 +1148,12 @@ function ExConfig({ ex, existing, onSave, onDelete, close, routine, initial }) { : t('Every set becomes rest-pause: {0} reps to start, then {1} more split into short bursts, {2}s rest before each, roughly halving each time.', c.reps || 0, c.intensifier.totalReps, c.intensifier.restSec)} } } + {/* The bar's own weight, for the plate math — per exercise, not per plan, so it sits + apart from the config fields above and writes straight to S.barWeights. */} + {usesBar(ex) && <> +

{t('Bar weight')}

+ + }