Merge upstream main into fix/clear-line-chart-hover
This commit is contained in:
commit
0a69ee8450
43 files changed
+1287
-118
No files matched your search
@@ -7,8 +7,8 @@ android {
|
||||
applicationId "ch.duartesantos.opengym"
|
||||
minSdkVersion rootProject.ext.minSdkVersion
|
||||
targetSdkVersion rootProject.ext.targetSdkVersion
|
||||
versionCode 10
|
||||
versionName "1.2.9"
|
||||
versionCode 11
|
||||
versionName "1.2.10"
|
||||
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
||||
aaptOptions {
|
||||
// Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps.
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "opengym-frontend",
|
||||
"version": "1.2.9",
|
||||
"version": "1.2.10",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "opengym-frontend",
|
||||
"version": "1.2.9",
|
||||
"version": "1.2.10",
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"dependencies": {
|
||||
"@capacitor/app": "^7.1.2",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "opengym-frontend",
|
||||
"private": true,
|
||||
"version": "1.2.9",
|
||||
"version": "1.2.10",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
|
||||
@@ -97,7 +97,10 @@ export default function LineChart({ points, h = 150, unit = '', color = 'var(--a
|
||||
const poly = pts.map(p => X(p.t).toFixed(1) + ',' + Y(p.y).toFixed(1)).join(' ')
|
||||
const last = pts[pts.length - 1]
|
||||
const gid = 'g' + Math.round(t0 % 1e7) + '_' + H
|
||||
const hoverPts = (single ? [points[0]] : points).map(p => ({ x: X(p.t), y: Y(p.y), iso: p.d || isoOf(new Date(p.t)), v: p.y, note: p.note }))
|
||||
const hoverSource = single ? [points[0]] : points
|
||||
const hoverDates = hoverSource.map(p => p.d || isoOf(new Date(p.t)))
|
||||
const showYear = new Set(hoverDates.map(iso => new Date(iso + 'T12:00:00').getFullYear())).size > 1
|
||||
const hoverPts = hoverSource.map((p, i) => ({ x: X(p.t), y: Y(p.y), iso: hoverDates[i], v: p.y, note: p.note }))
|
||||
const marked = points.some(p => p.m != null)
|
||||
|
||||
const onMove = e => {
|
||||
@@ -138,8 +141,8 @@ export default function LineChart({ points, h = 150, unit = '', color = 'var(--a
|
||||
</g>}
|
||||
</svg>
|
||||
{hover && <div className="ctip" ref={tipRef}>
|
||||
{fmtDate(hover.iso, true)} · {fmtNum(hover.v)}{unit ? ' ' + unit : ''}{hover.note ? ' · ' + hover.note : ''}
|
||||
{fmtDate(hover.iso, true, showYear)} · {fmtNum(hover.v)}{unit ? ' ' + unit : ''}{hover.note ? ' · ' + hover.note : ''}
|
||||
</div>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,31 @@
|
||||
// @vitest-environment happy-dom
|
||||
import React, { act } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import { Window } from 'happy-dom'
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
|
||||
import LineChart from './LineChart.jsx'
|
||||
import { fmtDate, isoOf } from '../lib/format.js'
|
||||
|
||||
globalThis.IS_REACT_ACT_ENVIRONMENT = true
|
||||
|
||||
let dom
|
||||
let root
|
||||
let container
|
||||
let root
|
||||
|
||||
beforeEach(() => {
|
||||
container = document.createElement('div')
|
||||
document.body.appendChild(container)
|
||||
root = createRoot(container)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
act(() => root.unmount())
|
||||
container.remove()
|
||||
})
|
||||
|
||||
const point = (year, month, day, y) => ({
|
||||
d: `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`,
|
||||
t: new Date(year, month - 1, day, 12).getTime(),
|
||||
y
|
||||
})
|
||||
|
||||
const firstPoints = [
|
||||
{ t: Date.UTC(2026, 0, 1), y: 80, d: '2026-01-01' },
|
||||
@@ -17,65 +36,68 @@ const nextPoints = [
|
||||
{ t: Date.UTC(2026, 1, 15), y: 79, d: '2026-02-15' },
|
||||
]
|
||||
|
||||
function installDom() {
|
||||
dom = new Window({ url: 'http://localhost/' })
|
||||
globalThis.window = dom
|
||||
globalThis.document = dom.document
|
||||
Object.defineProperty(globalThis, 'navigator', { configurable: true, value: dom.navigator })
|
||||
for (const key of ['HTMLElement', 'SVGElement', 'Node', 'Element', 'Event', 'MouseEvent']) {
|
||||
globalThis[key] = dom[key]
|
||||
}
|
||||
globalThis.IS_REACT_ACT_ENVIRONMENT = true
|
||||
container = document.createElement('div')
|
||||
document.body.append(container)
|
||||
root = createRoot(container)
|
||||
function renderChart(points) {
|
||||
act(() => root.render(<LineChart points={points} axes={false} unit="kg" />))
|
||||
}
|
||||
|
||||
async function render(points) {
|
||||
await act(async () => { root.render(<LineChart points={points} unit="kg" />) })
|
||||
const svg = container.querySelector('svg')
|
||||
Object.defineProperty(svg, 'getBoundingClientRect', {
|
||||
configurable: true,
|
||||
value: () => ({ left: 0, width: 340 }),
|
||||
function hoverAt(clientX) {
|
||||
act(() => {
|
||||
container.querySelector('.chart-i').dispatchEvent(new MouseEvent('mousemove', { bubbles: true, clientX }))
|
||||
})
|
||||
return container.querySelector('.ctip').textContent
|
||||
}
|
||||
|
||||
async function hoverAt(clientX) {
|
||||
await act(async () => {
|
||||
container.querySelector('.chart-i').dispatchEvent(new dom.MouseEvent('mousemove', {
|
||||
bubbles: true,
|
||||
clientX,
|
||||
}))
|
||||
describe('LineChart hover date', () => {
|
||||
it('keeps same-year points in the compact format', () => {
|
||||
const first = point(2026, 1, 15, 70)
|
||||
renderChart([first, point(2026, 2, 15, 71)])
|
||||
|
||||
expect(hoverAt(0)).toBe(`${fmtDate(first.d, true)} · 70 kg`)
|
||||
})
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
installDom()
|
||||
})
|
||||
it('includes the calendar year at a short cross-year boundary', () => {
|
||||
const first = point(2025, 11, 30, 70)
|
||||
const last = point(2026, 2, 1, 71)
|
||||
renderChart([first, last])
|
||||
|
||||
afterEach(async () => {
|
||||
if (root) await act(async () => { root.unmount() })
|
||||
root = null
|
||||
container = null
|
||||
dom.close()
|
||||
dom = null
|
||||
expect(hoverAt(0)).toBe(`${fmtDate(first.d, true, true)} · 70 kg`)
|
||||
expect(hoverAt(340)).toBe(`${fmtDate(last.d, true, true)} · 71 kg`)
|
||||
})
|
||||
|
||||
it('keeps a single point compact', () => {
|
||||
const only = point(2026, 7, 4, 70)
|
||||
renderChart([only])
|
||||
|
||||
expect(hoverAt(170)).toBe(`${fmtDate(only.d, true)} · 70 kg`)
|
||||
})
|
||||
|
||||
it('uses timestamp-only points when deciding whether to show the year', () => {
|
||||
const first = point(2025, 12, 31, 70)
|
||||
const last = point(2026, 1, 1, 71)
|
||||
const timestampOnly = [{ t: first.t, y: first.y }, { t: last.t, y: last.y }]
|
||||
renderChart(timestampOnly)
|
||||
|
||||
const lastIso = isoOf(new Date(last.t))
|
||||
expect(hoverAt(340)).toBe(`${fmtDate(lastIso, true, true)} · 71 kg`)
|
||||
})
|
||||
})
|
||||
|
||||
describe('LineChart hover state', () => {
|
||||
it('clears the tooltip and hover marker when points are replaced, then allows hovering again', async () => {
|
||||
await render(firstPoints)
|
||||
await hoverAt(170)
|
||||
it('clears the tooltip and hover markers when points are replaced, then allows hovering again', () => {
|
||||
renderChart(firstPoints)
|
||||
hoverAt(170)
|
||||
|
||||
expect(container.querySelector('.ctip')).toBeTruthy()
|
||||
expect(container.querySelector('.cvl')).toBeTruthy()
|
||||
expect(container.querySelector('.chl')).toBeTruthy()
|
||||
|
||||
await render(nextPoints)
|
||||
renderChart(nextPoints)
|
||||
|
||||
expect(container.querySelector('.ctip')).toBeNull()
|
||||
expect(container.querySelector('.cvl')).toBeNull()
|
||||
expect(container.querySelector('.chl')).toBeNull()
|
||||
|
||||
await hoverAt(170)
|
||||
hoverAt(170)
|
||||
expect(container.querySelector('.ctip')).toBeTruthy()
|
||||
expect(container.querySelector('.cvl')).toBeTruthy()
|
||||
})
|
||||
|
||||
+35
-7
@@ -272,15 +272,21 @@ h4.sec{
|
||||
.btn:disabled{opacity:.32;pointer-events:none}
|
||||
|
||||
/* ----------------------------------------------------------- tab bar ----- */
|
||||
/* Nearly opaque, and deliberately so. At the old 72% the page read straight through the bar
|
||||
and the labels had to compete with whatever was scrolling behind them — nobody needs to read
|
||||
the content under a navigation bar. 94% keeps a hint of movement behind the glass without
|
||||
letting text through. The blur is also down from 24px to 10px: this is a fixed element, so
|
||||
the WebView recomposites the blurred region on every scroll frame, and on Android that is
|
||||
the single most expensive thing on the screen. See @supports below for the no-blur case. */
|
||||
#tabbar{
|
||||
position:fixed;left:0;right:0;bottom:0;z-index:50;
|
||||
display:flex;justify-content:space-around;align-items:flex-end;
|
||||
padding:7px 6px calc(6px + var(--sab));
|
||||
background:color-mix(in srgb,var(--bg-el) 72%,transparent);
|
||||
backdrop-filter:saturate(180%) blur(24px);-webkit-backdrop-filter:saturate(180%) blur(24px);
|
||||
background:color-mix(in srgb,var(--bg-el) 94%,transparent);
|
||||
-webkit-backdrop-filter:saturate(180%) blur(10px);backdrop-filter:saturate(180%) blur(10px);
|
||||
border-top:var(--hair) solid var(--sep-op);
|
||||
}
|
||||
:root[data-theme="light"] #tabbar{background:rgba(249,249,251,.78)}
|
||||
:root[data-theme="light"] #tabbar{background:rgba(249,249,251,.94)}
|
||||
#tabbar button{
|
||||
flex:1;display:flex;flex-direction:column;align-items:center;gap:3px;
|
||||
color:var(--label-3);font-size:10px;font-weight:500;letter-spacing:.005em;padding-top:3px;
|
||||
@@ -317,6 +323,21 @@ h4.sec{
|
||||
}
|
||||
@keyframes ping{0%{transform:scale(1);opacity:.7}100%{transform:scale(1.45);opacity:0}}
|
||||
|
||||
/* NOTE on every backdrop-filter pair in this file: the -webkit- line comes first and the
|
||||
standard property last, which is the order a prefixed/standard pair wants — whichever is
|
||||
written last wins in the cascade, and that should be the standard name.
|
||||
|
||||
Where backdrop-filter is genuinely unsupported there is no glass either — only the alpha,
|
||||
and the page shows through unblurred, which is the worst of both. Older Android WebViews
|
||||
never had it, and "reduce transparency" accessibility settings drop it. Those surfaces go
|
||||
fully opaque instead. Keep this in sync with the rules above. */
|
||||
@supports not ((backdrop-filter:blur(1px)) or (-webkit-backdrop-filter:blur(1px))){
|
||||
#tabbar{background:var(--bg-el)}
|
||||
:root[data-theme="light"] #tabbar{background:#f9f9fb}
|
||||
#timer{background:var(--surface)}
|
||||
#toast{background:var(--surface-2)}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ week strip -- */
|
||||
.week{display:flex;justify-content:space-between;gap:4px}
|
||||
.wday{
|
||||
@@ -536,7 +557,7 @@ h4.sec{
|
||||
position:absolute;bottom:9px;display:inline-flex;align-items:center;gap:4px;
|
||||
background:rgba(0,0,0,.45);color:#fff;border-radius:99px;padding:5px 11px;
|
||||
font-size:12px;font-weight:500;
|
||||
backdrop-filter:blur(12px);-webkit-backdrop-filter:blur(12px);
|
||||
-webkit-backdrop-filter:blur(12px);backdrop-filter:blur(12px);
|
||||
}
|
||||
.exmedia .gifhint{right:9px}
|
||||
.exmedia .giftoggle{left:9px}
|
||||
@@ -626,7 +647,7 @@ h4.sec{
|
||||
/* nearly opaque: the set rows underneath were reading through the old 82% and made the
|
||||
clock hard to pick out mid-set. The blur stays, so it still sits above the page. */
|
||||
background:color-mix(in srgb,var(--surface) 97%,transparent);
|
||||
backdrop-filter:saturate(180%) blur(24px);-webkit-backdrop-filter:saturate(180%) blur(24px);
|
||||
-webkit-backdrop-filter:saturate(180%) blur(10px);backdrop-filter:saturate(180%) blur(10px);
|
||||
border-radius:var(--r-lg);padding:12px 14px;
|
||||
display:flex;align-items:center;gap:12px;
|
||||
box-shadow:0 12px 34px -8px rgba(0,0,0,.55);
|
||||
@@ -659,7 +680,7 @@ h4.sec{
|
||||
#modal-root.open{display:block}
|
||||
.mback{
|
||||
position:absolute;inset:0;background:rgba(0,0,0,.4);
|
||||
backdrop-filter:blur(2px);-webkit-backdrop-filter:blur(2px);
|
||||
-webkit-backdrop-filter:blur(2px);backdrop-filter:blur(2px);
|
||||
touch-action:none;overscroll-behavior:none;
|
||||
}
|
||||
.sheet{
|
||||
@@ -846,7 +867,7 @@ h4.sec{
|
||||
position:fixed;left:50%;transform:translateX(-50%) translateY(6px);
|
||||
bottom:calc(96px + var(--sab));z-index:200;
|
||||
background:color-mix(in srgb,var(--surface-2) 88%,transparent);
|
||||
backdrop-filter:saturate(180%) blur(20px);-webkit-backdrop-filter:saturate(180%) blur(20px);
|
||||
-webkit-backdrop-filter:saturate(180%) blur(20px);backdrop-filter:saturate(180%) blur(20px);
|
||||
border-radius:99px;padding:11px 20px;font-size:15px;font-weight:500;
|
||||
box-shadow:0 10px 30px -6px rgba(0,0,0,.5);
|
||||
opacity:0;pointer-events:none;transition:opacity var(--med),transform var(--med) var(--ease);
|
||||
@@ -898,6 +919,13 @@ h4.sec{
|
||||
border-radius:var(--r-lg);padding:14px;
|
||||
background:var(--surface);box-shadow:inset 0 0 0 1.5px var(--acc-line);
|
||||
}
|
||||
/* A superset nests a card inside the page's own gutter, so its inset is paid twice. On a
|
||||
narrow phone that left the weight and reps steppers too tight to show a three-digit
|
||||
number — reported as "the reps textbox becomes too small when superset on mobile". The
|
||||
card only gives up its own padding; the rows inside keep their spacing. */
|
||||
@media (max-width:400px){
|
||||
.ss-card{padding:10px 8px}
|
||||
}
|
||||
.ss-hd{
|
||||
font-size:12px;font-weight:600;color:var(--acc);margin-bottom:12px;
|
||||
text-align:center;display:flex;align-items:center;justify-content:center;gap:5px;
|
||||
|
||||
@@ -12,9 +12,19 @@ export function buildCompletedWorkout(active, { end = Date.now(), prs = [], snap
|
||||
if (snapshot && typeof snapshot === 'object' && !Array.isArray(snapshot) && Object.keys(snapshot).length) {
|
||||
completed.muscleSnapshot = { ...snapshot }
|
||||
}
|
||||
// What you typed about this exercise today, and whether you asked to see it again next
|
||||
// time. Written only when there is something to keep, so an untouched entry is byte-for-byte
|
||||
// the shape it always was.
|
||||
const note = (entry.note || '').trim()
|
||||
if (note) {
|
||||
completed.note = note
|
||||
if (entry.notePin) completed.notePin = true
|
||||
}
|
||||
return completed
|
||||
}).filter(entry => entry.sets.some(set => set.done))
|
||||
|
||||
const sessionNote = (active?.note || '').trim()
|
||||
|
||||
return {
|
||||
id: active.id,
|
||||
d: active.d,
|
||||
@@ -25,5 +35,6 @@ export function buildCompletedWorkout(active, { end = Date.now(), prs = [], snap
|
||||
bw: active.bw,
|
||||
entries,
|
||||
prs,
|
||||
...(sessionNote ? { note: sessionNote } : {}),
|
||||
}
|
||||
}
|
||||
@@ -36,3 +36,36 @@ describe('completed workout boundary', () => {
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
// Notes written during a session have to survive it, or "write a note during your workout"
|
||||
// means "write a note and lose it when you tap Finish".
|
||||
describe('session notes', () => {
|
||||
const active = (entry) => ({
|
||||
id: 'w1', d: '2026-08-25', start: 1, routineId: 'r1', name: 'Push', bw: null,
|
||||
entries: [{ id: '0025', sets: [{ w: 100, r: 5, done: true }], ...entry }],
|
||||
})
|
||||
|
||||
it('keeps a per-exercise note and its pin', () => {
|
||||
const w = buildCompletedWorkout(active({ note: ' narrower grip next time ', notePin: true }))
|
||||
expect(w.entries[0].note).toBe('narrower grip next time')
|
||||
expect(w.entries[0].notePin).toBe(true)
|
||||
})
|
||||
|
||||
it('keeps an unpinned note without inventing a pin', () => {
|
||||
const w = buildCompletedWorkout(active({ note: 'shoulder twinged' }))
|
||||
expect(w.entries[0].note).toBe('shoulder twinged')
|
||||
expect('notePin' in w.entries[0]).toBe(false)
|
||||
})
|
||||
|
||||
it('writes no note fields at all when nothing was typed', () => {
|
||||
const w = buildCompletedWorkout(active({ note: ' ', notePin: true }))
|
||||
expect('note' in w.entries[0]).toBe(false)
|
||||
expect('notePin' in w.entries[0]).toBe(false)
|
||||
})
|
||||
|
||||
it('keeps a whole-session note on the workout', () => {
|
||||
const a = active({})
|
||||
expect(buildCompletedWorkout({ ...a, note: 'slept badly' }).note).toBe('slept badly')
|
||||
expect('note' in buildCompletedWorkout(a)).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -12,9 +12,11 @@ export const DAYS = ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa']
|
||||
export const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
|
||||
export const MONTHS_LONG = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
|
||||
|
||||
export function fmtDate(iso, long) {
|
||||
export function fmtDate(iso, long, withYear = false) {
|
||||
const d = new Date(iso + 'T12:00:00')
|
||||
return d.toLocaleDateString(dateLocale(), long ? { weekday: 'short', day: 'numeric', month: 'short' } : { day: 'numeric', month: 'short' })
|
||||
const options = long ? { weekday: 'short', day: 'numeric', month: 'short' } : { day: 'numeric', month: 'short' }
|
||||
if (withYear) options.year = 'numeric'
|
||||
return d.toLocaleDateString(dateLocale(), options)
|
||||
}
|
||||
export function fmtDur(ms) {
|
||||
const m = Math.floor(ms / 60000)
|
||||
@@ -44,4 +46,4 @@ export function weekKey(d) {
|
||||
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)
|
||||
export const ACCENTS = { lime: '#30d158', sky: '#0a84ff', orange: '#ff9f0a', violet: '#bf5af2', pink: '#ff375f', red: '#ff453a', teal: '#40c8e0', gold: '#ffd60a' }
|
||||
export const ACCENTS = { lime: '#30d158', sky: '#0a84ff', orange: '#ff9f0a', violet: '#bf5af2', pink: '#ff375f', red: '#ff453a', teal: '#40c8e0', gold: '#ffd60a' }
|
||||
@@ -209,14 +209,49 @@ export function unpairSuperset(items, idx) {
|
||||
export function lastEntryFor(S, exId) {
|
||||
for (let i = S.workouts.length - 1; i >= 0; i--) {
|
||||
const en = S.workouts[i].entries.find(e => e.id === exId)
|
||||
if (!en) continue
|
||||
// Work sets only. Every caller asks the same question — "what did you actually lift last
|
||||
// time" — to seed the next session's rows, to size a freestyle config, and to print "Last
|
||||
// time" on the card. A warm-up answers none of them: seeding position 0 from a 50% ramp row
|
||||
// walks the working weight DOWN a little every session, and counting the ramp rows makes a
|
||||
// 3x5 come back as a 5-set exercise. Warm-ups are already excluded from volume, records and
|
||||
// progression; this is the same rule one level up.
|
||||
const done = en.sets.filter(s => s.done && !isWarmupRow(s))
|
||||
// `target` is what the session prescribed; finished workouts carry it so labels and the
|
||||
// progression engine can read a session back the way it was logged. Older workouts have
|
||||
// none — modeOf() falls back to the body part for them, which is what they were.
|
||||
if (en && en.sets.some(s => s.done)) return { d: S.workouts[i].d, sets: en.sets.filter(s => s.done), target: en.target || null }
|
||||
if (done.length) return { d: S.workouts[i].d, sets: done, target: en.target || null }
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** How long any single note may get. Long enough for a paragraph, short enough to stay a note. */
|
||||
export const NOTE_MAX = 500
|
||||
|
||||
/**
|
||||
* The most recent session note the user pinned for this exercise, or null.
|
||||
*
|
||||
* A note written mid-session is about that session — "shoulder twinged today". Some of them are
|
||||
* about the NEXT one instead: "go a notch narrower". The pin is how the user says which, at the
|
||||
* moment of writing, when they are the only one who knows. Pinned notes surface again the next
|
||||
* time the exercise comes up; unpinned ones stay in that day's history.
|
||||
*
|
||||
* Only the newest pinned note is returned: a pin is a message to your next self, and a stack of
|
||||
* them from six sessions ago is noise, not context.
|
||||
*/
|
||||
export function pinnedNoteFor(S, exId) {
|
||||
const workouts = S?.workouts || []
|
||||
for (let i = workouts.length - 1; i >= 0; i--) {
|
||||
const en = (workouts[i].entries || []).find(e => e.id === exId)
|
||||
const note = (en?.note || '').trim()
|
||||
if (note && en.notePin) return { note, d: workouts[i].d }
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** The standing note for an exercise — the one that is true every session. */
|
||||
export const exNoteFor = (S, exId) => ((S?.exNotes || {})[exId] || '').trim() || null
|
||||
|
||||
// A freestyle exercise starts with the last target the user actually trained, rather than the
|
||||
// generic config sheet defaults used when there is no history. The set rows themselves are still
|
||||
// built by buildSets(), which copies each completed set by position; only the target shape and
|
||||
@@ -249,7 +284,30 @@ export function effectiveRoutine(S, iso) {
|
||||
const id = effectiveRoutineId(S, iso)
|
||||
return id ? S.routines.find(r => r.id === id) || null : 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
|
||||
* behaves exactly as before).
|
||||
*
|
||||
* The warm-ups are stacked with insertWarmupRow, one call each, so the ramp is the same one
|
||||
* the in-session "Add warm-up set" button produces: each row halves the gap left to the work
|
||||
* weight, giving 50% / 75% / 87.5% for three. `options.step` is the exercise's loading step,
|
||||
* passed in by the caller (see insertWarmupRow for why this module cannot read it itself).
|
||||
*/
|
||||
export function buildSets(S, cfg, options = {}) {
|
||||
const rows = buildWorkSets(S, cfg, options)
|
||||
const warm = Math.max(0, Math.min(MAX_PLANNED_WARMUPS, Math.round(cfg.warmupSets) || 0))
|
||||
if (!warm) return rows
|
||||
const mode = modeOf(cfg)
|
||||
let out = rows
|
||||
for (let i = 0; i < warm; i++) out = insertWarmupRow(out, mode, cfg, options.step)
|
||||
return out
|
||||
}
|
||||
|
||||
/** Beyond this a "warm-up" is its own workout; the config stepper stops here too. */
|
||||
export const MAX_PLANNED_WARMUPS = 5
|
||||
|
||||
function buildWorkSets(S, cfg, options = {}) {
|
||||
const last = lastEntryFor(S, cfg.id)
|
||||
const n = Math.max(1, cfg.sets || 1)
|
||||
const mode = modeOf(cfg)
|
||||
@@ -388,16 +446,49 @@ export function cascadeWeight(rows, from, value) {
|
||||
return next
|
||||
}
|
||||
|
||||
/** Insert a warm-up row before the first work row, copying the preceding warm-up's values. */
|
||||
export function insertWarmupRow(rows, mode, target) {
|
||||
/**
|
||||
* Insert a warm-up row at the end of the warm-up block, ramping toward the working weight.
|
||||
*
|
||||
* Each added row halves what is left between the last warm-up and the first work set, so the
|
||||
* first one lands at half the working weight, a second at three quarters, and so on — and a
|
||||
* row you edited by hand is what the next one ramps from. `step` is the exercise's own loading
|
||||
* step (progression.js's defaultIncrement, passed in by the caller so this module keeps no
|
||||
* dependency on progression — that one already imports from here): a warm-up you cannot
|
||||
* actually load onto the bar is noise.
|
||||
*
|
||||
* The reference is the first WORK row, never `rows[at - 1]` alone: for the first warm-up
|
||||
* `at` is 0, and reading `rows[-1]` used to fall through to the *last* row — the heaviest
|
||||
* work set — so "add warm-up set" handed you a full-weight set to correct by hand.
|
||||
*/
|
||||
export function insertWarmupRow(rows, mode, target, step = 2.5) {
|
||||
const firstWork = rows.findIndex(x => !isWarmupRow(x))
|
||||
const at = firstWork === -1 ? rows.length : firstWork
|
||||
const l = rows[at - 1] || rows[rows.length - 1]
|
||||
const prev = at > 0 ? rows[at - 1] : null // the warm-up this one ramps from
|
||||
const work = firstWork === -1 ? null : rows[firstWork]
|
||||
const rampTo = to => {
|
||||
const from = prev ? (prev.w || 0) : 0
|
||||
if (!(to > 0) || to <= from) return from
|
||||
// Rounded DOWN to the step: a warm-up that lands a notch light costs nothing, one that
|
||||
// lands a notch heavy is a set you have to strip plates off before you can use it.
|
||||
return Math.max(0, Math.min(to, Math.floor((from + (to - from) / 2) / step) * step))
|
||||
}
|
||||
const warm = mode === 'cardio'
|
||||
? { min: l ? l.min : (target.min || 20), speed: l ? l.speed : (target.speed || 8), done: false, phase: 'warmup', warmup: true }
|
||||
? {
|
||||
min: prev ? prev.min : (work ? work.min : (target.min || 20)),
|
||||
speed: prev ? prev.speed : (work ? work.speed : (target.speed || 8)),
|
||||
done: false, phase: 'warmup', warmup: true,
|
||||
}
|
||||
: mode === 'time'
|
||||
? { sec: l ? l.sec : (target.sec || 45), w: l ? (l.w || 0) : (target.weight || 0), done: false, phase: 'warmup', warmup: true }
|
||||
: { w: l ? l.w : 0, r: l ? l.r : target.reps, done: false, phase: 'warmup', warmup: true }
|
||||
? {
|
||||
sec: prev ? prev.sec : (work ? work.sec : (target.sec || 45)),
|
||||
w: rampTo(work ? (work.w || 0) : (target.weight || 0)),
|
||||
done: false, phase: 'warmup', warmup: true,
|
||||
}
|
||||
: {
|
||||
w: rampTo(work ? (work.w || 0) : (target.weight || 0)),
|
||||
r: work ? work.r : (prev ? prev.r : target.reps),
|
||||
done: false, phase: 'warmup', warmup: true,
|
||||
}
|
||||
const next = rows.slice()
|
||||
next.splice(at, 0, warm)
|
||||
return next
|
||||
|
||||
@@ -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 } from './history.js'
|
||||
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 { EXDB } from './exercises.js'
|
||||
|
||||
// Real ids out of the shipped catalogue, so the body-part fallback is exercised for real.
|
||||
@@ -365,6 +365,42 @@ describe('freestyleConfig', () => {
|
||||
])
|
||||
})
|
||||
|
||||
// Planned warm-ups: the routine says how many, buildSets stacks them onto the work sets with
|
||||
// the same ramp the in-session button uses. A plan without the field must not change shape.
|
||||
it('adds no rows when the config asks for no warm-ups', () => {
|
||||
const S = { exWeights: {}, workouts: [] }
|
||||
const cfg = { id: '0025', mode: 'reps', sets: 2, reps: 5, weight: 100 }
|
||||
expect(buildSets(S, cfg)).toEqual([
|
||||
{ w: 100, r: 5, done: false },
|
||||
{ w: 100, r: 5, done: false },
|
||||
])
|
||||
})
|
||||
|
||||
it('prepends the planned warm-ups as a ramp toward the work weight', () => {
|
||||
const S = { exWeights: {}, workouts: [] }
|
||||
const cfg = { id: '0025', mode: 'reps', sets: 2, reps: 5, weight: 100, warmupSets: 3 }
|
||||
const rows = buildSets(S, cfg, { step: 2.5 })
|
||||
expect(rows.map(r => r.w)).toEqual([50, 75, 87.5, 100, 100])
|
||||
expect(rows.slice(0, 3).every(r => r.phase === 'warmup')).toBe(true)
|
||||
expect(rows.slice(3).every(r => r.phase === undefined)).toBe(true)
|
||||
})
|
||||
|
||||
it('caps the planned warm-ups and ignores nonsense values', () => {
|
||||
const S = { exWeights: {}, workouts: [] }
|
||||
const base = { id: '0025', mode: 'reps', sets: 1, reps: 5, weight: 100 }
|
||||
expect(buildSets(S, { ...base, warmupSets: 99 }, { step: 2.5 }).filter(r => r.phase === 'warmup')).toHaveLength(5)
|
||||
expect(buildSets(S, { ...base, warmupSets: -2 }, { step: 2.5 })).toHaveLength(1)
|
||||
expect(buildSets(S, { ...base, warmupSets: 'x' }, { step: 2.5 })).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('keeps planned warm-ups out of the work-set count', () => {
|
||||
const S = { exWeights: {}, workouts: [] }
|
||||
const rows = buildSets(S, { id: '0025', mode: 'reps', sets: 3, reps: 5, weight: 100, warmupSets: 2 }, { step: 2.5 })
|
||||
const logged = { entries: [{ id: '0025', sets: rows.map(r => ({ ...r, done: true })) }] }
|
||||
expect(logged.entries[0].sets).toHaveLength(5)
|
||||
expect(workSetsDone(logged)).toBe(3)
|
||||
})
|
||||
|
||||
it('inherits the target for timed and cardio exercises too', () => {
|
||||
const timed = {
|
||||
exWeights: {},
|
||||
@@ -705,19 +741,48 @@ describe('session row helpers', () => {
|
||||
expect('w' in next[2]).toBe(false)
|
||||
})
|
||||
|
||||
it('insertWarmupRow inserts before the first work row and copies the last warm-up values', () => {
|
||||
it('insertWarmupRow inserts before the first work row, ramping toward the work weight', () => {
|
||||
const rows = [
|
||||
{ warmup: true, w: 20, r: 8, done: true },
|
||||
{ warmup: true, w: 30, r: 8, done: false },
|
||||
{ w: 60, r: 8, done: false },
|
||||
]
|
||||
const next = insertWarmupRow(rows, 'reps', { reps: 8 })
|
||||
const next = insertWarmupRow(rows, 'reps', { reps: 8 }, 2.5)
|
||||
expect(next.length).toBe(4)
|
||||
expect(next[2].warmup).toBe(true)
|
||||
expect(next[2].w).toBe(30) // copies the preceding warm-up
|
||||
expect(next[2].w).toBe(45) // halfway from the last warm-up (30) to the work set (60)
|
||||
expect(next[3].w).toBe(60) // work row still after the warm-up block
|
||||
})
|
||||
|
||||
// The first warm-up is the case that was broken: `at` is 0, so the old code read rows[-1],
|
||||
// fell through to `rows[rows.length - 1]` — the heaviest work set — and handed you a
|
||||
// "warm-up" at your full working weight.
|
||||
it('gives the first warm-up half the working weight, not the working weight itself', () => {
|
||||
const next = insertWarmupRow([{ w: 100, r: 5, done: false }], 'reps', { reps: 5 }, 2.5)
|
||||
expect(next.length).toBe(2)
|
||||
expect(next[0]).toMatchObject({ w: 50, r: 5, phase: 'warmup', warmup: true, done: false })
|
||||
expect(next[1].w).toBe(100)
|
||||
})
|
||||
|
||||
it('rounds the ramp to the exercise loading step', () => {
|
||||
// 0 -> 95 halves to 47.5, which is not loadable in 5 kg steps: 45 is.
|
||||
expect(insertWarmupRow([{ w: 95, r: 5 }], 'reps', { reps: 5 }, 5)[0].w).toBe(45)
|
||||
})
|
||||
|
||||
it('keeps bodyweight warm-ups at zero and never exceeds the work set', () => {
|
||||
expect(insertWarmupRow([{ w: 0, r: 12 }], 'reps', { reps: 12 }, 2.5)[0].w).toBe(0)
|
||||
// A warm-up already at the working weight cannot ramp any further.
|
||||
const at100 = insertWarmupRow([{ warmup: true, w: 100, r: 5 }, { w: 100, r: 5 }], 'reps', { reps: 5 }, 2.5)
|
||||
expect(at100[1].w).toBe(100)
|
||||
})
|
||||
|
||||
it('ramps a timed hold the same way and leaves cardio on the work row values', () => {
|
||||
expect(insertWarmupRow([{ sec: 45, w: 40, done: false }], 'time', { sec: 45 }, 2.5)[0])
|
||||
.toMatchObject({ sec: 45, w: 20, phase: 'warmup' })
|
||||
expect(insertWarmupRow([{ min: 20, speed: 10, done: false }], 'cardio', { min: 20 }, 2.5)[0])
|
||||
.toMatchObject({ min: 20, speed: 10, phase: 'warmup' })
|
||||
})
|
||||
|
||||
it('removeRowAt never empties an entry below one row', () => {
|
||||
expect(removeRowAt([{ w: 60 }], 0).length).toBe(1)
|
||||
const rows = [{ w: 60 }, { w: 70 }]
|
||||
@@ -748,3 +813,35 @@ describe('warm-up rows identified by phase alone', () => {
|
||||
expect(next[2].w).toBe(100)
|
||||
})
|
||||
})
|
||||
|
||||
describe('pinnedNoteFor', () => {
|
||||
const S = {
|
||||
workouts: [
|
||||
{ d: '2026-08-01', entries: [{ id: '0025', note: 'felt heavy', notePin: true }] },
|
||||
{ d: '2026-08-08', entries: [{ id: '0025', note: 'just a diary line' }] },
|
||||
{ d: '2026-08-15', entries: [{ id: '0025', note: 'go narrower', notePin: true }] },
|
||||
{ d: '2026-08-22', entries: [{ id: '0293', note: 'other exercise', notePin: true }] },
|
||||
],
|
||||
}
|
||||
|
||||
it('returns only the newest pinned note for that exercise', () => {
|
||||
expect(pinnedNoteFor(S, '0025')).toEqual({ note: 'go narrower', d: '2026-08-15' })
|
||||
})
|
||||
|
||||
it('ignores notes that were not pinned', () => {
|
||||
expect(pinnedNoteFor({ workouts: [{ d: '2026-08-08', entries: [{ id: '0025', note: 'diary' }] }] }, '0025')).toBeNull()
|
||||
})
|
||||
|
||||
it('is null for an exercise with no notes, and safe on empty state', () => {
|
||||
expect(pinnedNoteFor(S, '9999')).toBeNull()
|
||||
expect(pinnedNoteFor({}, '0025')).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('exNoteFor', () => {
|
||||
it('reads the standing note and trims it away when blank', () => {
|
||||
expect(exNoteFor({ exNotes: { '0025': ' seat 4, pin 7 ' } }, '0025')).toBe('seat 4, pin 7')
|
||||
expect(exNoteFor({ exNotes: { '0025': ' ' } }, '0025')).toBeNull()
|
||||
expect(exNoteFor({}, '0025')).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -111,7 +111,9 @@ export function detectSource(header) {
|
||||
const SYN = [
|
||||
[/\bbb\b/g, 'barbell'], [/\bdb\b/g, 'dumbbell'], [/\bkb\b/g, 'kettlebell'],
|
||||
[/\bohp\b/g, 'overhead press'], [/\bbw\b/g, 'body weight'], [/\bbodyweight\b/g, 'body weight'],
|
||||
[/\bmachine\b/g, 'lever'], [/\bsmith machine\b/g, 'smith'], [/\bez bar\b/g, 'ez barbell'],
|
||||
// 'smith machine' first: the generic machine->lever rule would otherwise eat the word
|
||||
// and leave 'smith lever', which matches no entry in the dataset.
|
||||
[/\bsmith machine\b/g, 'smith'], [/\bmachine\b/g, 'lever'], [/\bez bar\b/g, 'ez barbell'],
|
||||
[/\bpull ups?\b/g, 'pull up'], [/\bchin ups?\b/g, 'chin up'], [/\bpush ups?\b/g, 'push up'],
|
||||
[/\bsit ups?\b/g, 'sit up'], [/\bdips?\b/g, 'dip'], [/\braises?\b/g, 'raise'],
|
||||
[/\bcurls?\b/g, 'curl'], [/\bpresses\b/g, 'press'], [/\bextensions?\b/g, 'extension'],
|
||||
@@ -185,6 +187,25 @@ const ALIAS_EX = {
|
||||
// same movement, wrong equipment label, which beats leaving it uncategorised.
|
||||
'pallof press': '0979', 'cable pallof press': '0979', 'vertical pallof press': '1015',
|
||||
'cable core pallof press': '0979', 'core pallof press': '0979',
|
||||
// Hevy's own vocabulary, from a real export. Hevy writes the equipment in parentheses
|
||||
// and uses "bicep"/"chest fly"/"reverse fly" where the dataset says "biceps"/"fly"/
|
||||
// "reverse fly", so these are near-misses the word-bag cannot close on its own.
|
||||
'bicep curl (dumbbell)': '0294', 'bicep curl (cable)': '0868', 'bicep curl (barbell)': '0031',
|
||||
'chest fly (dumbbell)': '0308', 'chest fly (machine)': '0596', 'butterfly (pec deck)': '0596',
|
||||
'incline chest fly (dumbbell)': '0319', 'cable fly crossovers': '1269',
|
||||
'rear delt reverse fly (dumbbell)': '0383', 'rear delt reverse fly (machine)': '0602',
|
||||
'chest supported reverse fly (dumbbell)': '0383',
|
||||
'bench press (smith machine)': '0748', 'overhead press (smith machine)': '0766',
|
||||
'hack squat (machine)': '0743', 'iso-lateral row (machine)': '0571',
|
||||
'seated cable row - bar grip': '0218', 'reverse grip lat pulldown (cable)': '0673',
|
||||
'single arm lateral raise (cable)': '0192', 'plate front raise': '0310',
|
||||
'back extension (weighted hyperextension)': '0573',
|
||||
'behind the back bicep wrist curl (barbell)': '0104',
|
||||
// A face pull is a rope rear-delt row; the dataset has no entry under that name.
|
||||
'face pull': '0203',
|
||||
// Cardio again: the only candidates in a 29-entry cardio vocabulary.
|
||||
'jumping jack': '3220', 'jumping jacks': '3220', 'battle ropes': '0128',
|
||||
'stair machine (steps)': '2311', 'stair machine': '2311',
|
||||
}
|
||||
|
||||
let ALIAS_IDX = null
|
||||
@@ -230,6 +251,23 @@ export function matchExercise(name) {
|
||||
return ties === 1 ? best : null
|
||||
}
|
||||
|
||||
// Hevy exports no category column, so every invented exercise fell through to the
|
||||
// 'upper legs' default and a third of an imported history was attributed to the legs in
|
||||
// the muscle map. When there is no category, read the body part off the name instead.
|
||||
const NAME_BP = [
|
||||
[/\b(curl|bicep|biceps|tricep|triceps|skullcrusher|pushdown)\b/, 'upper arms'],
|
||||
[/\b(wrist|forearm|forearms|grip)\b/, 'lower arms'],
|
||||
[/\b(bench|chest|pec|fly|flye|crossover|crossovers|dip)\b/, 'chest'],
|
||||
[/\b(row|pulldown|pullup|pull up|chin up|lat|lats|back|deadlift|shrug)\b/, 'back'],
|
||||
[/\b(shoulder|delt|delts|overhead|lateral raise|front raise|face pull|press up)\b/, 'shoulders'],
|
||||
[/\b(calf|calves)\b/, 'lower legs'],
|
||||
[/\b(squat|lunge|leg|glute|hamstring|quad|hip thrust|deadlift)\b/, 'upper legs'],
|
||||
[/\b(ab|abs|core|plank|crunch|sit up|oblique|russian twist)\b/, 'waist'],
|
||||
[/\b(run|running|jog|bike|cycling|rope|ropes|jump|jacks|burpee|sprint|treadmill|stair)\b/, 'cardio'],
|
||||
[/\bneck\b/, 'neck'],
|
||||
]
|
||||
const bpFromName = name => (NAME_BP.find(([re]) => re.test(name)) || [])[1] || null
|
||||
|
||||
// Categories the exporters use -> the dataset's body parts, for exercises we invent.
|
||||
const CATEGORY_BP = {
|
||||
chest: 'chest', back: 'back', lats: 'back', shoulders: 'shoulders', delts: 'shoulders',
|
||||
@@ -358,7 +396,8 @@ export function parseWorkoutCSV(text, { unit = 'kg' } = {}) {
|
||||
if (!c) {
|
||||
c = {
|
||||
id: 'im' + uid(), n: name.toLowerCase(), custom: true, eq: 'custom', tg: '', desc: '',
|
||||
bp: CATEGORY_BP[cell(r, 'category').toLowerCase()] || (km || (mins && !reps) ? 'cardio' : 'upper legs'),
|
||||
bp: CATEGORY_BP[cell(r, 'category').toLowerCase()] || (km || (mins && !reps) ? 'cardio' : null)
|
||||
|| bpFromName(name.toLowerCase()) || 'upper legs',
|
||||
}
|
||||
created.set(key, c)
|
||||
unmatched.add(name)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { matchExercise } from './import-csv.js'
|
||||
import { matchExercise, parseWorkoutCSV } from './import-csv.js'
|
||||
import { EXIDX } from './exercises.js'
|
||||
|
||||
// The names other apps actually export, and the catalogue entry each has to land on.
|
||||
@@ -12,6 +12,20 @@ const MAPS = {
|
||||
'Cable Core Pallof Press': '0979',
|
||||
Elliptical: '2141',
|
||||
'Stationary Bike': '2138',
|
||||
// Hevy's vocabulary, from a real export. It writes the equipment in parentheses and says
|
||||
// "bicep"/"chest fly" where the catalogue says "biceps"/"fly", so the word-bag lands one
|
||||
// word off on every one of these and they arrived as custom exercises.
|
||||
'Bicep Curl (Dumbbell)': '0294',
|
||||
'Bicep Curl (Cable)': '0868',
|
||||
'Chest Fly (Machine)': '0596',
|
||||
'Butterfly (Pec Deck)': '0596',
|
||||
'Incline Chest Fly (Dumbbell)': '0319',
|
||||
'Rear Delt Reverse Fly (Dumbbell)': '0383',
|
||||
'Face Pull': '0203',
|
||||
'Battle Ropes': '0128',
|
||||
'Hack Squat (Machine)': '0743',
|
||||
'Seated Cable Row - Bar Grip': '0218',
|
||||
'Single Arm Lateral Raise (Cable)': '0192',
|
||||
}
|
||||
|
||||
describe('foreign exercise names resolve to the catalogue', () => {
|
||||
@@ -43,8 +57,55 @@ describe('foreign exercise names resolve to the catalogue', () => {
|
||||
expect(matchExercise('Deadlift')).toBe('0032')
|
||||
})
|
||||
|
||||
// SYN rewrote 'machine' -> 'lever' before it ever reached 'smith machine' -> 'smith',
|
||||
// so every Smith-machine name arrived as "smith lever ..." and could not match anything
|
||||
// in the catalogue. The two rules are order-dependent; this pins the order.
|
||||
it('resolves Smith-machine names rather than leaving a stray "lever"', () => {
|
||||
expect(matchExercise('Bench Press (Smith Machine)')).toBe('0748')
|
||||
expect(matchExercise('Overhead Press (Smith Machine)')).toBe('0766')
|
||||
expect(matchExercise('Smith Machine Bench Press')).toBe('0748')
|
||||
})
|
||||
|
||||
// The generic machine -> lever rule still has to work on its own.
|
||||
it('keeps the plain machine alias working', () => {
|
||||
expect(matchExercise('Seated Fly (Machine)')).toBe('0596')
|
||||
})
|
||||
|
||||
it('still refuses to guess', () => {
|
||||
expect(matchExercise('Some Movement I Invented')).toBe(null)
|
||||
expect(matchExercise('')).toBe(null)
|
||||
})
|
||||
})
|
||||
|
||||
// Hevy exports no category column, so every invented exercise took the 'upper legs' default
|
||||
// and a third of an imported history was attributed to the legs in the muscle map. With no
|
||||
// category to read, the body part comes off the name instead.
|
||||
describe('invented exercises get a body part from their name', () => {
|
||||
const HEAD = 'title,start_time,end_time,description,exercise_title,superset_id,exercise_notes,set_index,set_type,weight_kg,reps,distance_km,duration_seconds,rpe'
|
||||
const row = name => `W,"09 Oct 2025, 19:22","09 Oct 2025, 20:22",,"${name}",,,0,normal,40,10,,,`
|
||||
const bpOf = name => {
|
||||
const r = parseWorkoutCSV([HEAD, row(name)].join('\n'), { unit: 'kg' })
|
||||
return r.customEx[0] && r.customEx[0].bp
|
||||
}
|
||||
|
||||
it('reads the body part off names the catalogue does not have', () => {
|
||||
expect(bpOf('Kirk Shrug Machine Thing')).toBe('back')
|
||||
expect(bpOf('Bicep Curl Contraption')).toBe('upper arms')
|
||||
expect(bpOf('Standing Calf Thing')).toBe('lower legs')
|
||||
})
|
||||
|
||||
it('no longer files everything under the legs', () => {
|
||||
expect(bpOf('Some Chest Contraption')).not.toBe('upper legs')
|
||||
expect(bpOf('Some Chest Contraption')).toBe('chest')
|
||||
})
|
||||
|
||||
it('leaves a genuine leg movement on the legs', () => {
|
||||
expect(bpOf('Bulgarian Split Squat Machine v9')).toBe('upper legs')
|
||||
})
|
||||
|
||||
it('still prefers an explicit category column when the file has one', () => {
|
||||
const head = 'Date,Exercise,Category,Weight,Reps'
|
||||
const r = parseWorkoutCSV([head, '2025-10-09,Some Invented Lift,Shoulders,40,10'].join('\n'), { unit: 'kg' })
|
||||
expect(r.customEx[0].bp).toBe('shoulders')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,89 @@
|
||||
// @vitest-environment happy-dom
|
||||
// The note sheet is new JSX and nothing else mounts it, so a bad hook order, a missing import or
|
||||
// a wrong store path would only surface on a real device. Render it through the real sheet stack
|
||||
// and drive a save, so the wiring is checked and not just the shape of the module.
|
||||
import { describe, expect, it, beforeEach, afterEach } from 'vitest'
|
||||
import React, { act } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import { useStore } from '../store/useStore.js'
|
||||
import { useUI } from '../store/useUI.js'
|
||||
import { exerciseNoteSheet } from '../sheets.jsx'
|
||||
|
||||
const activeWith = entry => ({ id: 'w1', d: '2026-08-25', start: 1, routineId: 'r1', name: 'Push', entries: [entry] })
|
||||
|
||||
// Roots have to be torn down between tests: the sheet subscribes to the store, so a root left
|
||||
// mounted reacts to the next test's setState — outside act(), which React rightly complains about.
|
||||
const mounted = []
|
||||
|
||||
function renderSheet() {
|
||||
exerciseNoteSheet(0)
|
||||
const sheet = useUI.getState().sheets.at(-1)
|
||||
const host = document.createElement('div')
|
||||
document.body.appendChild(host)
|
||||
const root = createRoot(host)
|
||||
mounted.push(root)
|
||||
act(() => root.render(sheet.render(sheet_close(sheet))))
|
||||
return host
|
||||
}
|
||||
const sheet_close = sheet => () => useUI.getState().closeSheet(sheet.id)
|
||||
|
||||
const type = (el, value) => {
|
||||
const setter = Object.getOwnPropertyDescriptor(el.constructor.prototype, 'value').set
|
||||
setter.call(el, value)
|
||||
el.dispatchEvent(new Event('input', { bubbles: true }))
|
||||
}
|
||||
|
||||
describe('exercise note sheet', () => {
|
||||
beforeEach(() => {
|
||||
// React only treats act() as real when told it is in a test environment, and vitest shares
|
||||
// a worker across files — so set it per test rather than once at module scope.
|
||||
globalThis.IS_REACT_ACT_ENVIRONMENT = true
|
||||
useUI.setState({ sheets: [] })
|
||||
useStore.setState(s => ({
|
||||
S: { ...s.S, exNotes: {}, active: activeWith({ id: 'bench', sets: [] }) },
|
||||
}))
|
||||
document.body.innerHTML = ''
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
act(() => { mounted.splice(0).forEach(r => r.unmount()) })
|
||||
})
|
||||
|
||||
it('renders the session note, the pin and the standing note', () => {
|
||||
const host = renderSheet()
|
||||
const areas = host.querySelectorAll('textarea')
|
||||
expect(areas).toHaveLength(2)
|
||||
// The pin cannot be set on an empty note — it would pin nothing.
|
||||
expect(host.querySelector('[role="switch"]').disabled).toBe(true)
|
||||
})
|
||||
|
||||
it('saves the session note with its pin and the standing note separately', () => {
|
||||
const host = renderSheet()
|
||||
const [today, always] = host.querySelectorAll('textarea')
|
||||
act(() => { type(today, 'shoulder twinged'); type(always, 'seat at 4') })
|
||||
act(() => { host.querySelector('[role="switch"]').click() })
|
||||
const save = [...host.querySelectorAll('button')].find(b => /save/i.test(b.textContent))
|
||||
act(() => { save.click() })
|
||||
|
||||
const S = useStore.getState().S
|
||||
expect(S.active.entries[0].note).toBe('shoulder twinged')
|
||||
expect(S.active.entries[0].notePin).toBe(true)
|
||||
// The standing note belongs to the exercise, not to today's entry.
|
||||
expect(S.exNotes.bench).toBe('seat at 4')
|
||||
expect(useUI.getState().sheets).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('clearing the session note drops the pin with it', () => {
|
||||
useStore.setState(s => ({
|
||||
S: { ...s.S, active: activeWith({ id: 'bench', sets: [], note: 'old', notePin: true }) },
|
||||
}))
|
||||
const host = renderSheet()
|
||||
const [today] = host.querySelectorAll('textarea')
|
||||
act(() => { type(today, '') })
|
||||
const save = [...host.querySelectorAll('button')].find(b => /save/i.test(b.textContent))
|
||||
act(() => { save.click() })
|
||||
const e = useStore.getState().S.active.entries[0]
|
||||
expect(e.note).toBeUndefined()
|
||||
expect(e.notePin).toBeUndefined()
|
||||
})
|
||||
})
|
||||
@@ -46,6 +46,7 @@ function cleanEx(e) {
|
||||
if (e.repsMax != null) o.repsMax = e.repsMax
|
||||
if (e.sg) o.sg = e.sg
|
||||
if (e.note) o.note = e.note
|
||||
if (e.warmupSets) o.warmupSets = e.warmupSets
|
||||
return o
|
||||
}
|
||||
|
||||
|
||||
@@ -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(283)
|
||||
expect(inherited).toHaveLength(437)
|
||||
expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(291)
|
||||
expect(inherited).toHaveLength(447)
|
||||
// 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('70fd93bc049da76bc578701a82ecde33b1521ddae37a403076ad48b9694cc4e3')
|
||||
expect(fingerprint, 'pt-PT inheritance changed; review the inherited pt-BR wording').toBe('5eca6d8b564c208b41f1be1890e3eaa0313e0ab901ed40a03b5d3071a65bd9f1')
|
||||
})
|
||||
|
||||
test('does not leak European Portuguese UI terms', () => {
|
||||
|
||||
@@ -10,6 +10,38 @@ export function setProgressHighWater(entry, previous = 0) {
|
||||
return { isNew: done > previous, highWater: Math.max(previous, done) }
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether completing a set should start a rest timer.
|
||||
*
|
||||
* A rest belongs after every completed set — the last set of an exercise included, because
|
||||
* another exercise follows it and you rest before that one too. The only set with nothing
|
||||
* left to time is the last set of the last exercise, where the session is over.
|
||||
*
|
||||
* Ordinary exercises used to "finish quietly" instead: an exercise started no rest on its
|
||||
* closing set, so a two-set exercise timed one rest instead of two (issue #3) and a rest
|
||||
* never carried across the gap into the next exercise. Supersets already did it this way.
|
||||
*/
|
||||
export function restAfterSet({ unitDone, lastUnit }) {
|
||||
return !unitDone || !lastUnit
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether re-checking an already-completed set should start a rest.
|
||||
*
|
||||
* The high-water rule deliberately swallows a re-check so that unchecking and re-checking
|
||||
* finished work does not replay navigation or reopen sheets. But a re-check is still you
|
||||
* telling the app a set is done, and that is the other half of issue #3 — "after the first
|
||||
* set, sometimes a break doesn't appear". That is what it looks like when you uncheck a set
|
||||
* to correct the reps after its rest has already run out: nothing times the rest you are
|
||||
* actually about to take.
|
||||
*
|
||||
* So: fill a gap, never disturb a rest that is already counting down. A timer that is running
|
||||
* belongs to the set you finished most recently, which is a better answer than restarting it.
|
||||
*/
|
||||
export function restOnRecheck({ timerRunning, unitDone, lastUnit }) {
|
||||
return !timerRunning && restAfterSet({ unitDone, lastUnit })
|
||||
}
|
||||
|
||||
// Decide where a newly completed superset set goes next. Spent members are skipped, including
|
||||
// across the wrap. A round ends when no later member in display order has work left; this makes
|
||||
// the last *active* member the boundary rather than blindly using the group's last array index.
|
||||
|
||||
@@ -1,8 +1,25 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { setProgressHighWater, supersetFlowStep } from './supersetFlow.js'
|
||||
import { setProgressHighWater, supersetFlowStep, restAfterSet, restOnRecheck } from './supersetFlow.js'
|
||||
|
||||
const entry = done => ({ sets: done.map(value => ({ done: value })) })
|
||||
|
||||
describe('restAfterSet', () => {
|
||||
it('rests between the sets of an exercise', () => {
|
||||
expect(restAfterSet({ unitDone: false, lastUnit: false })).toBe(true)
|
||||
expect(restAfterSet({ unitDone: false, lastUnit: true })).toBe(true)
|
||||
})
|
||||
|
||||
// Issue #3: a two-set exercise timed one rest instead of two, because the closing set
|
||||
// "finished quietly". The next exercise still follows it, so the rest belongs there.
|
||||
it('rests after the closing set when another exercise follows', () => {
|
||||
expect(restAfterSet({ unitDone: true, lastUnit: false })).toBe(true)
|
||||
})
|
||||
|
||||
it('stays quiet only on the very last set of the session', () => {
|
||||
expect(restAfterSet({ unitDone: true, lastUnit: true })).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('supersetFlowStep', () => {
|
||||
it('does not create navigation or rest flow for a normal singleton exercise', () => {
|
||||
const entries = [entry([true]), entry([false])]
|
||||
@@ -34,3 +51,24 @@ describe('supersetFlowStep', () => {
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
// Issue #3 has two halves. restAfterSet covers "no break after the LAST set of an exercise";
|
||||
// this covers "after the first set, sometimes a break doesn't appear" — the uncheck/re-check
|
||||
// that the high-water rule swallows.
|
||||
describe('rest on a re-check', () => {
|
||||
it('starts the rest a swallowed re-check would otherwise cost you', () => {
|
||||
expect(restOnRecheck({ timerRunning: false, unitDone: false, lastUnit: false })).toBe(true)
|
||||
})
|
||||
|
||||
it('leaves a rest that is already counting alone', () => {
|
||||
expect(restOnRecheck({ timerRunning: true, unitDone: false, lastUnit: false })).toBe(false)
|
||||
})
|
||||
|
||||
it('still stays quiet on the last set of the last exercise', () => {
|
||||
expect(restOnRecheck({ timerRunning: false, unitDone: true, lastUnit: true })).toBe(false)
|
||||
})
|
||||
|
||||
it('rests after closing an exercise that is not the last one', () => {
|
||||
expect(restOnRecheck({ timerRunning: false, unitDone: true, lastUnit: false })).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,39 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { buildSets } from './history.js'
|
||||
|
||||
// A session that logged warm-ups, the way finish-workout persists it: warm-up rows and work
|
||||
// rows in one `sets` array, all done.
|
||||
const S = {
|
||||
workouts: [{
|
||||
d: '2026-08-24',
|
||||
entries: [{
|
||||
id: 'bench',
|
||||
target: { id: 'bench', sets: 3, reps: 5, weight: 100 },
|
||||
sets: [
|
||||
{ w: 50, r: 5, done: true, phase: 'warmup', warmup: true },
|
||||
{ w: 75, r: 5, done: true, phase: 'warmup', warmup: true },
|
||||
{ w: 100, r: 5, done: true },
|
||||
{ w: 100, r: 5, done: true },
|
||||
{ w: 100, r: 5, done: true },
|
||||
],
|
||||
}],
|
||||
}],
|
||||
exWeights: {}, // no confirmed working weight for this exercise
|
||||
routines: [],
|
||||
}
|
||||
|
||||
describe('seeding the next session from one that had warm-ups', () => {
|
||||
it('does not seed the work sets from the warm-up rows', () => {
|
||||
const cfg = { id: 'bench', sets: 3, reps: 5, weight: 100 }
|
||||
const rows = buildSets(S, cfg)
|
||||
const work = rows.filter(r => r.phase !== 'warmup')
|
||||
expect(work.map(r => r.w)).toEqual([100, 100, 100])
|
||||
})
|
||||
|
||||
it('freestyle reproducing last time also skips the warm-ups', () => {
|
||||
const cfg = { id: 'bench', sets: 3, reps: 5, weight: 100 }
|
||||
const rows = buildSets(S, cfg, { preferLast: true })
|
||||
const work = rows.filter(r => r.phase !== 'warmup')
|
||||
expect(work.map(r => r.w)).toEqual([100, 100, 100])
|
||||
})
|
||||
})
|
||||
@@ -668,5 +668,25 @@ export default {
|
||||
'Connect': 'Verbinden',
|
||||
'How do you want to use openGym?': 'Wie möchtest du openGym nutzen?',
|
||||
'Use on this device': 'Auf diesem Gerät nutzen',
|
||||
'Local keeps everything on this phone. Connecting syncs to your own openGym server instead — you can switch later in Settings.': 'Lokal behält alles auf diesem Handy. Verbinden synchronisiert stattdessen mit deinem eigenen openGym-Server — du kannst das später in den Einstellungen ändern.'
|
||||
'Local keeps everything on this phone. Connecting syncs to your own openGym server instead — you can switch later in Settings.': 'Lokal behält alles auf diesem Handy. Verbinden synchronisiert stattdessen mit deinem eigenen openGym-Server — du kannst das später in den Einstellungen ändern.',
|
||||
|
||||
// --- workout notes and planned warm-ups ---
|
||||
'{0} — done': '{0} — erledigt',
|
||||
'Workout done': 'Training erledigt',
|
||||
'reps': 'Wdh.',
|
||||
'Most reps in a set per workout': 'Meiste Wdh. in einem Satz pro Training',
|
||||
'Warm-up sets': 'Aufwärmsätze',
|
||||
'Added before your work sets and left out of volume, records and progression. Each one closes half the gap to the work weight — you can still change any of them mid-session.': 'Kommen vor deine Arbeitssätze und zählen nicht für Volumen, Rekorde und Progression. Jeder halbiert den Abstand zum Arbeitsgewicht — im Training kannst du sie trotzdem jederzeit ändern.',
|
||||
'Ramp-up sets added before the work sets, so you do not have to add them by hand each session.': 'Aufwärmsätze vor den Arbeitssätzen, damit du sie nicht jedes Mal von Hand hinzufügen musst.',
|
||||
'Note': 'Notiz',
|
||||
'This session': 'Dieses Training',
|
||||
'How it went, what to change — kept with today’s workout.': 'Wie es lief, was du ändern willst — bleibt beim heutigen Training.',
|
||||
'Show this next time': 'Nächstes Mal anzeigen',
|
||||
'Brings it up again the next time you train this exercise.': 'Erscheint wieder, wenn du diese Übung das nächste Mal trainierst.',
|
||||
'Always for this exercise': 'Immer bei dieser Übung',
|
||||
'Seat height, pin position, a form cue — shown every session.': 'Sitzhöhe, Pin-Position, ein Hinweis zur Ausführung — bei jedem Training sichtbar.',
|
||||
'From {0}:': 'Vom {0}:',
|
||||
'Session note': 'Notiz zum Training',
|
||||
'How the session went as a whole.': 'Wie das Training insgesamt lief.',
|
||||
'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': 'Rest-Pause trainiert immer als ein Aufwärmsatz mit dieser Wiederholungszahl und ein Rest-Pause-Arbeitssatz — „Sätze“ wird nicht verwendet.'
|
||||
}
|
||||
@@ -651,5 +651,25 @@ export default {
|
||||
'Connect': 'Conectar',
|
||||
'How do you want to use openGym?': '¿Cómo quieres usar openGym?',
|
||||
'Use on this device': 'Usar en este dispositivo',
|
||||
'Local keeps everything on this phone. Connecting syncs to your own openGym server instead — you can switch later in Settings.': 'Local mantiene todo en este teléfono. Conectar sincroniza con tu propio servidor de openGym — puedes cambiarlo luego en Ajustes.'
|
||||
'Local keeps everything on this phone. Connecting syncs to your own openGym server instead — you can switch later in Settings.': 'Local mantiene todo en este teléfono. Conectar sincroniza con tu propio servidor de openGym — puedes cambiarlo luego en Ajustes.',
|
||||
|
||||
// --- workout notes and planned warm-ups ---
|
||||
'{0} — done': '{0} — hecho',
|
||||
'Workout done': 'Entrenamiento hecho',
|
||||
'reps': 'reps',
|
||||
'Most reps in a set per workout': 'Más reps en una serie por entrenamiento',
|
||||
'Warm-up sets': 'Series de calentamiento',
|
||||
'Added before your work sets and left out of volume, records and progression. Each one closes half the gap to the work weight — you can still change any of them mid-session.': 'Se añaden antes de tus series de trabajo y no cuentan para el volumen, los récords ni la progresión. Cada una reduce a la mitad la distancia hasta el peso de trabajo — puedes cambiarlas durante la sesión.',
|
||||
'Ramp-up sets added before the work sets, so you do not have to add them by hand each session.': 'Series de aproximación antes de las series de trabajo, para no añadirlas a mano cada vez.',
|
||||
'Note': 'Nota',
|
||||
'This session': 'Esta sesión',
|
||||
'How it went, what to change — kept with today’s workout.': 'Cómo fue, qué cambiar — se guarda con el entrenamiento de hoy.',
|
||||
'Show this next time': 'Mostrar la próxima vez',
|
||||
'Brings it up again the next time you train this exercise.': 'Vuelve a aparecer la próxima vez que entrenes este ejercicio.',
|
||||
'Always for this exercise': 'Siempre en este ejercicio',
|
||||
'Seat height, pin position, a form cue — shown every session.': 'Altura del asiento, posición del pin, una indicación técnica — visible en cada sesión.',
|
||||
'From {0}:': 'Del {0}:',
|
||||
'Session note': 'Nota de la sesión',
|
||||
'How the session went as a whole.': 'Cómo fue la sesión en conjunto.',
|
||||
'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': 'Rest-pause siempre entrena como una serie de calentamiento con estas reps y una serie de trabajo rest-pause — «Series» no se usa.'
|
||||
}
|
||||
@@ -651,5 +651,25 @@ export default {
|
||||
'Connect': 'Connecter',
|
||||
'How do you want to use openGym?': 'Comment voulez-vous utiliser openGym ?',
|
||||
'Use on this device': 'Utiliser sur cet appareil',
|
||||
'Local keeps everything on this phone. Connecting syncs to your own openGym server instead — you can switch later in Settings.': 'Local garde tout sur ce téléphone. Se connecter synchronise plutôt avec votre propre serveur openGym — vous pourrez changer cela plus tard dans Réglages.'
|
||||
'Local keeps everything on this phone. Connecting syncs to your own openGym server instead — you can switch later in Settings.': 'Local garde tout sur ce téléphone. Se connecter synchronise plutôt avec votre propre serveur openGym — vous pourrez changer cela plus tard dans Réglages.',
|
||||
|
||||
// --- workout notes and planned warm-ups ---
|
||||
'{0} — done': '{0} — terminé',
|
||||
'Workout done': 'Séance terminée',
|
||||
'reps': 'reps',
|
||||
'Most reps in a set per workout': 'Plus de reps dans une série par séance',
|
||||
'Warm-up sets': 'Séries d’échauffement',
|
||||
'Added before your work sets and left out of volume, records and progression. Each one closes half the gap to the work weight — you can still change any of them mid-session.': 'Ajoutées avant tes séries de travail et exclues du volume, des records et de la progression. Chacune réduit de moitié l’écart avec la charge de travail — tu peux les modifier pendant la séance.',
|
||||
'Ramp-up sets added before the work sets, so you do not have to add them by hand each session.': 'Séries de montée en charge avant les séries de travail, pour ne pas les ajouter à la main chaque fois.',
|
||||
'Note': 'Note',
|
||||
'This session': 'Cette séance',
|
||||
'How it went, what to change — kept with today’s workout.': 'Comment ça s’est passé, ce qu’il faut changer — conservé avec la séance du jour.',
|
||||
'Show this next time': 'Afficher la prochaine fois',
|
||||
'Brings it up again the next time you train this exercise.': 'Réapparaît la prochaine fois que tu travailles cet exercice.',
|
||||
'Always for this exercise': 'Toujours pour cet exercice',
|
||||
'Seat height, pin position, a form cue — shown every session.': 'Hauteur du siège, position de la goupille, un rappel technique — visible à chaque séance.',
|
||||
'From {0}:': 'Du {0} :',
|
||||
'Session note': 'Note de séance',
|
||||
'How the session went as a whole.': 'Comment la séance s’est passée dans l’ensemble.',
|
||||
'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': 'Le rest-pause s’entraîne toujours comme une série d’échauffement à ce nombre de reps, puis une série de travail rest-pause — « Séries » n’est pas utilisé.'
|
||||
}
|
||||
@@ -651,5 +651,25 @@ export default {
|
||||
'Connect': 'कनेक्ट करें',
|
||||
'How do you want to use openGym?': 'आप openGym का उपयोग कैसे करना चाहते हैं?',
|
||||
'Use on this device': 'इस डिवाइस पर उपयोग करें',
|
||||
'Local keeps everything on this phone. Connecting syncs to your own openGym server instead — you can switch later in Settings.': 'लोकल सब कुछ इसी फ़ोन पर रखता है। कनेक्ट करने पर इसके बजाय आपके अपने openGym सर्वर से सिंक होता है — इसे बाद में सेटिंग्स में बदला जा सकता है।'
|
||||
'Local keeps everything on this phone. Connecting syncs to your own openGym server instead — you can switch later in Settings.': 'लोकल सब कुछ इसी फ़ोन पर रखता है। कनेक्ट करने पर इसके बजाय आपके अपने openGym सर्वर से सिंक होता है — इसे बाद में सेटिंग्स में बदला जा सकता है।',
|
||||
|
||||
// --- workout notes and planned warm-ups ---
|
||||
'{0} — done': '{0} — पूरा',
|
||||
'Workout done': 'कसरत पूरी',
|
||||
'reps': 'रेप्स',
|
||||
'Most reps in a set per workout': 'प्रति कसरत एक सेट में सबसे ज़्यादा रेप्स',
|
||||
'Warm-up sets': 'वार्म-अप सेट',
|
||||
'Added before your work sets and left out of volume, records and progression. Each one closes half the gap to the work weight — you can still change any of them mid-session.': 'ये आपके वर्क सेट से पहले जुड़ते हैं और वॉल्यूम, रिकॉर्ड तथा प्रोग्रेशन में नहीं गिने जाते। हर सेट वर्क वज़न तक बची दूरी को आधा कर देता है — कसरत के दौरान आप इन्हें बदल सकते हैं।',
|
||||
'Ramp-up sets added before the work sets, so you do not have to add them by hand each session.': 'वर्क सेट से पहले जुड़ने वाले तैयारी सेट, ताकि हर बार खुद जोड़ना न पड़े।',
|
||||
'Note': 'नोट',
|
||||
'This session': 'यह कसरत',
|
||||
'How it went, what to change — kept with today’s workout.': 'कैसा रहा, क्या बदलना है — आज की कसरत के साथ सहेजा जाता है।',
|
||||
'Show this next time': 'अगली बार दिखाएँ',
|
||||
'Brings it up again the next time you train this exercise.': 'अगली बार यह कसरत करते समय फिर दिखेगा।',
|
||||
'Always for this exercise': 'इस कसरत के लिए हमेशा',
|
||||
'Seat height, pin position, a form cue — shown every session.': 'सीट की ऊँचाई, पिन की जगह, तकनीक का सुझाव — हर कसरत में दिखता है।',
|
||||
'From {0}:': '{0} से:',
|
||||
'Session note': 'सत्र का नोट',
|
||||
'How the session went as a whole.': 'पूरा सत्र कैसा रहा।',
|
||||
'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': 'रेस्ट-पॉज़ हमेशा इसी रेप्स संख्या के एक वार्म-अप सेट और एक रेस्ट-पॉज़ वर्क सेट के रूप में किया जाता है — “सेट” का उपयोग नहीं होता।'
|
||||
}
|
||||
@@ -651,5 +651,25 @@ export default {
|
||||
'Connect': 'Connetti',
|
||||
'How do you want to use openGym?': 'Come vuoi usare openGym?',
|
||||
'Use on this device': 'Usa su questo dispositivo',
|
||||
'Local keeps everything on this phone. Connecting syncs to your own openGym server instead — you can switch later in Settings.': 'Locale mantiene tutto su questo telefono. Connettersi sincronizza invece con il tuo server openGym — potrai cambiarlo più tardi nelle Impostazioni.'
|
||||
'Local keeps everything on this phone. Connecting syncs to your own openGym server instead — you can switch later in Settings.': 'Locale mantiene tutto su questo telefono. Connettersi sincronizza invece con il tuo server openGym — potrai cambiarlo più tardi nelle Impostazioni.',
|
||||
|
||||
// --- workout notes and planned warm-ups ---
|
||||
'{0} — done': '{0} — fatto',
|
||||
'Workout done': 'Allenamento fatto',
|
||||
'reps': 'rip.',
|
||||
'Most reps in a set per workout': 'Più rip. in una serie per allenamento',
|
||||
'Warm-up sets': 'Serie di riscaldamento',
|
||||
'Added before your work sets and left out of volume, records and progression. Each one closes half the gap to the work weight — you can still change any of them mid-session.': 'Vengono aggiunte prima delle serie di lavoro e non contano per volume, record e progressione. Ognuna dimezza la distanza dal peso di lavoro — puoi comunque modificarle durante la sessione.',
|
||||
'Ramp-up sets added before the work sets, so you do not have to add them by hand each session.': 'Serie di avvicinamento prima delle serie di lavoro, così non devi aggiungerle a mano ogni volta.',
|
||||
'Note': 'Nota',
|
||||
'This session': 'Questa sessione',
|
||||
'How it went, what to change — kept with today’s workout.': 'Com’è andata, cosa cambiare — resta con l’allenamento di oggi.',
|
||||
'Show this next time': 'Mostra la prossima volta',
|
||||
'Brings it up again the next time you train this exercise.': 'Ricompare la prossima volta che alleni questo esercizio.',
|
||||
'Always for this exercise': 'Sempre per questo esercizio',
|
||||
'Seat height, pin position, a form cue — shown every session.': 'Altezza del sedile, posizione del pin, un promemoria tecnico — visibile a ogni sessione.',
|
||||
'From {0}:': 'Del {0}:',
|
||||
'Session note': 'Nota della sessione',
|
||||
'How the session went as a whole.': 'Com’è andata la sessione nel complesso.',
|
||||
'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': 'Il rest-pause si allena sempre come una serie di riscaldamento a queste ripetizioni e una serie di lavoro rest-pause — “Serie” non viene usato.'
|
||||
}
|
||||
@@ -651,5 +651,25 @@ export default {
|
||||
'Connect': '연결',
|
||||
'How do you want to use openGym?': 'openGym을 어떻게 사용하시겠어요?',
|
||||
'Use on this device': '이 기기에서 사용',
|
||||
'Local keeps everything on this phone. Connecting syncs to your own openGym server instead — you can switch later in Settings.': '로컬 모드는 모든 것을 이 휴대폰에 보관합니다. 연결하면 대신 자신의 openGym 서버와 동기화됩니다 — 나중에 설정에서 변경할 수 있습니다.'
|
||||
'Local keeps everything on this phone. Connecting syncs to your own openGym server instead — you can switch later in Settings.': '로컬 모드는 모든 것을 이 휴대폰에 보관합니다. 연결하면 대신 자신의 openGym 서버와 동기화됩니다 — 나중에 설정에서 변경할 수 있습니다.',
|
||||
|
||||
// --- workout notes and planned warm-ups ---
|
||||
'{0} — done': '{0} — 완료',
|
||||
'Workout done': '운동 완료',
|
||||
'reps': '회',
|
||||
'Most reps in a set per workout': '운동당 한 세트 최다 횟수',
|
||||
'Warm-up sets': '워밍업 세트',
|
||||
'Added before your work sets and left out of volume, records and progression. Each one closes half the gap to the work weight — you can still change any of them mid-session.': '작업 세트 앞에 추가되며 볼륨, 기록, 진행에는 포함되지 않습니다. 각 세트는 작업 중량까지의 차이를 절반으로 줄이며, 운동 중에 언제든 바꿀 수 있습니다.',
|
||||
'Ramp-up sets added before the work sets, so you do not have to add them by hand each session.': '작업 세트 앞에 넣는 준비 세트로, 매번 직접 추가하지 않아도 됩니다.',
|
||||
'Note': '메모',
|
||||
'This session': '이번 운동',
|
||||
'How it went, what to change — kept with today’s workout.': '어땠는지, 무엇을 바꿀지 — 오늘 운동과 함께 저장됩니다.',
|
||||
'Show this next time': '다음에 다시 보기',
|
||||
'Brings it up again the next time you train this exercise.': '이 운동을 다음에 할 때 다시 표시됩니다.',
|
||||
'Always for this exercise': '이 운동에 항상 표시',
|
||||
'Seat height, pin position, a form cue — shown every session.': '시트 높이, 핀 위치, 자세 팁 — 매 운동마다 표시됩니다.',
|
||||
'From {0}:': '{0}에서:',
|
||||
'Session note': '운동 메모',
|
||||
'How the session went as a whole.': '이번 운동이 전체적으로 어땠는지.',
|
||||
'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': '레스트포즈는 항상 이 횟수의 워밍업 세트 하나와 레스트포즈 작업 세트 하나로 진행됩니다 — ‘세트’는 사용하지 않습니다.'
|
||||
}
|
||||
@@ -651,5 +651,25 @@ export default {
|
||||
'Connect': 'Połącz',
|
||||
'How do you want to use openGym?': 'Jak chcesz korzystać z openGym?',
|
||||
'Use on this device': 'Użyj na tym urządzeniu',
|
||||
'Local keeps everything on this phone. Connecting syncs to your own openGym server instead — you can switch later in Settings.': 'Tryb lokalny zachowuje wszystko na tym telefonie. Połączenie synchronizuje zamiast tego z Twoim własnym serwerem openGym — możesz to później zmienić w Ustawieniach.'
|
||||
'Local keeps everything on this phone. Connecting syncs to your own openGym server instead — you can switch later in Settings.': 'Tryb lokalny zachowuje wszystko na tym telefonie. Połączenie synchronizuje zamiast tego z Twoim własnym serwerem openGym — możesz to później zmienić w Ustawieniach.',
|
||||
|
||||
// --- workout notes and planned warm-ups ---
|
||||
'{0} — done': '{0} — zrobione',
|
||||
'Workout done': 'Trening zrobiony',
|
||||
'reps': 'powt.',
|
||||
'Most reps in a set per workout': 'Najwięcej powt. w serii na trening',
|
||||
'Warm-up sets': 'Serie rozgrzewkowe',
|
||||
'Added before your work sets and left out of volume, records and progression. Each one closes half the gap to the work weight — you can still change any of them mid-session.': 'Dodawane przed seriami roboczymi i pomijane w objętości, rekordach i progresji. Każda zmniejsza o połowę dystans do ciężaru roboczego — w trakcie treningu nadal możesz je zmienić.',
|
||||
'Ramp-up sets added before the work sets, so you do not have to add them by hand each session.': 'Serie wprowadzające przed seriami roboczymi, żeby nie dodawać ich ręcznie za każdym razem.',
|
||||
'Note': 'Notatka',
|
||||
'This session': 'Ta sesja',
|
||||
'How it went, what to change — kept with today’s workout.': 'Jak poszło, co zmienić — zostaje przy dzisiejszym treningu.',
|
||||
'Show this next time': 'Pokaż następnym razem',
|
||||
'Brings it up again the next time you train this exercise.': 'Pojawi się ponownie, gdy następnym razem będziesz robić to ćwiczenie.',
|
||||
'Always for this exercise': 'Zawsze przy tym ćwiczeniu',
|
||||
'Seat height, pin position, a form cue — shown every session.': 'Wysokość siedziska, pozycja bolca, wskazówka techniczna — widoczne w każdej sesji.',
|
||||
'From {0}:': 'Z {0}:',
|
||||
'Session note': 'Notatka do sesji',
|
||||
'How the session went as a whole.': 'Jak przebiegła cała sesja.',
|
||||
'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': 'Rest-pause zawsze trenuje się jako jedna seria rozgrzewkowa o tej liczbie powtórzeń i jedna seria robocza rest-pause — „Serie” nie są używane.'
|
||||
}
|
||||
@@ -292,7 +292,17 @@ export const PT_BR_OVERRIDES = {
|
||||
'How do you want to use openGym?': 'Como você quer usar o openGym?',
|
||||
'Local keeps everything on this phone. Connecting syncs to your own openGym server instead — you can switch later in Settings.': 'Local mantém tudo neste celular. Conectar sincroniza com o seu próprio servidor openGym — você pode mudar depois em Configurações.',
|
||||
'Every set becomes a drop-set: after the main set, {0} drop(s) with no rest, each about {1}% lighter.': 'Cada série vira uma série decrescente: depois da série principal, {0} queda(s) sem descanso, cada uma cerca de {1}% mais leve.',
|
||||
'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.': 'Cada série vira rest-pause: {0} repetições para começar, depois mais {1} divididas em rajadas curtas, com {2}s de descanso antes de cada uma, caindo cerca de metade a cada vez.'
|
||||
'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.': 'Cada série vira rest-pause: {0} repetições para começar, depois mais {1} divididas em rajadas curtas, com {2}s de descanso antes de cada uma, caindo cerca de metade a cada vez.',
|
||||
|
||||
// --- workout notes and planned warm-ups ---
|
||||
'Most reps in a set per workout': 'Mais reps em uma série por treino',
|
||||
'Added before your work sets and left out of volume, records and progression. Each one closes half the gap to the work weight — you can still change any of them mid-session.': 'São adicionadas antes das suas séries de trabalho e ficam de fora do volume, dos recordes e da progressão. Cada uma reduz pela metade a distância até o peso de trabalho — você ainda pode alterá-las durante o treino.',
|
||||
'Ramp-up sets added before the work sets, so you do not have to add them by hand each session.': 'Séries de aproximação antes das séries de trabalho, para você não precisar adicioná-las na mão a cada treino.',
|
||||
'How it went, what to change — kept with today’s workout.': 'Como foi, o que mudar — fica salvo com o treino de hoje.',
|
||||
'Brings it up again the next time you train this exercise.': 'Aparece de novo na próxima vez que você treinar este exercício.',
|
||||
'Seat height, pin position, a form cue — shown every session.': 'Altura do banco, posição do pino, uma dica de execução — aparece em todos os treinos.',
|
||||
'How the session went as a whole.': 'Como foi o treino como um todo.',
|
||||
'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': 'O rest-pause sempre treina como uma série de aquecimento com essas repetições e uma série de trabalho rest-pause — “Séries” não é usado.'
|
||||
}
|
||||
|
||||
export default { ...pt, ...PT_BR_OVERRIDES }
|
||||
@@ -651,5 +651,25 @@ export default {
|
||||
'Connect': 'Ligar',
|
||||
'How do you want to use openGym?': 'Como queres usar o openGym?',
|
||||
'Use on this device': 'Usar neste dispositivo',
|
||||
'Local keeps everything on this phone. Connecting syncs to your own openGym server instead — you can switch later in Settings.': 'Local mantém tudo neste telemóvel. Ligar sincroniza antes com o teu próprio servidor openGym — podes mudar mais tarde em Definições.'
|
||||
'Local keeps everything on this phone. Connecting syncs to your own openGym server instead — you can switch later in Settings.': 'Local mantém tudo neste telemóvel. Ligar sincroniza antes com o teu próprio servidor openGym — podes mudar mais tarde em Definições.',
|
||||
|
||||
// --- workout notes and planned warm-ups ---
|
||||
'{0} — done': '{0} — concluído',
|
||||
'Workout done': 'Treino concluído',
|
||||
'reps': 'reps',
|
||||
'Most reps in a set per workout': 'Mais reps numa série por treino',
|
||||
'Warm-up sets': 'Séries de aquecimento',
|
||||
'Added before your work sets and left out of volume, records and progression. Each one closes half the gap to the work weight — you can still change any of them mid-session.': 'São acrescentadas antes das tuas séries de trabalho e ficam de fora do volume, dos recordes e da progressão. Cada uma reduz a metade a distância até ao peso de trabalho — podes alterá-las durante a sessão.',
|
||||
'Ramp-up sets added before the work sets, so you do not have to add them by hand each session.': 'Séries de aproximação antes das séries de trabalho, para não teres de as acrescentar à mão em cada treino.',
|
||||
'Note': 'Nota',
|
||||
'This session': 'Esta sessão',
|
||||
'How it went, what to change — kept with today’s workout.': 'Como correu, o que mudar — fica guardado com o treino de hoje.',
|
||||
'Show this next time': 'Mostrar da próxima vez',
|
||||
'Brings it up again the next time you train this exercise.': 'Volta a aparecer da próxima vez que treinares este exercício.',
|
||||
'Always for this exercise': 'Sempre neste exercício',
|
||||
'Seat height, pin position, a form cue — shown every session.': 'Altura do banco, posição do pino, uma indicação técnica — visível em todas as sessões.',
|
||||
'From {0}:': 'De {0}:',
|
||||
'Session note': 'Nota da sessão',
|
||||
'How the session went as a whole.': 'Como correu a sessão no seu todo.',
|
||||
'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': 'O rest-pause treina sempre como uma série de aquecimento com estas repetições e uma série de trabalho rest-pause — «Séries» não é usado.'
|
||||
}
|
||||
@@ -651,5 +651,25 @@ export default {
|
||||
'Connect': 'Подключить',
|
||||
'How do you want to use openGym?': 'Как вы хотите использовать openGym?',
|
||||
'Use on this device': 'Использовать на этом устройстве',
|
||||
'Local keeps everything on this phone. Connecting syncs to your own openGym server instead — you can switch later in Settings.': 'Локальный режим хранит всё на этом телефоне. Подключение вместо этого синхронизирует данные с вашим сервером openGym — вы сможете изменить это позже в Настройках.'
|
||||
'Local keeps everything on this phone. Connecting syncs to your own openGym server instead — you can switch later in Settings.': 'Локальный режим хранит всё на этом телефоне. Подключение вместо этого синхронизирует данные с вашим сервером openGym — вы сможете изменить это позже в Настройках.',
|
||||
|
||||
// --- workout notes and planned warm-ups ---
|
||||
'{0} — done': '{0} — сделано',
|
||||
'Workout done': 'Тренировка сделана',
|
||||
'reps': 'повт.',
|
||||
'Most reps in a set per workout': 'Больше всего повт. в подходе за тренировку',
|
||||
'Warm-up sets': 'Разминочные подходы',
|
||||
'Added before your work sets and left out of volume, records and progression. Each one closes half the gap to the work weight — you can still change any of them mid-session.': 'Добавляются перед рабочими подходами и не учитываются в объёме, рекордах и прогрессии. Каждый вдвое сокращает разрыв до рабочего веса — во время тренировки их всё равно можно изменить.',
|
||||
'Ramp-up sets added before the work sets, so you do not have to add them by hand each session.': 'Подводящие подходы перед рабочими, чтобы не добавлять их вручную каждый раз.',
|
||||
'Note': 'Заметка',
|
||||
'This session': 'Эта тренировка',
|
||||
'How it went, what to change — kept with today’s workout.': 'Как прошло, что изменить — останется с сегодняшней тренировкой.',
|
||||
'Show this next time': 'Показать в следующий раз',
|
||||
'Brings it up again the next time you train this exercise.': 'Появится снова, когда вы в следующий раз будете делать это упражнение.',
|
||||
'Always for this exercise': 'Всегда для этого упражнения',
|
||||
'Seat height, pin position, a form cue — shown every session.': 'Высота сиденья, положение фиксатора, подсказка по технике — видно на каждой тренировке.',
|
||||
'From {0}:': 'От {0}:',
|
||||
'Session note': 'Заметка о тренировке',
|
||||
'How the session went as a whole.': 'Как прошла тренировка в целом.',
|
||||
'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': 'Rest-pause всегда выполняется как один разминочный подход с этим числом повторений и один рабочий подход rest-pause — «Подходы» не используются.'
|
||||
}
|
||||
@@ -651,5 +651,25 @@ export default {
|
||||
'Connect': 'Bağlan',
|
||||
'How do you want to use openGym?': "openGym'i nasıl kullanmak istersin?",
|
||||
'Use on this device': 'Bu cihazda kullan',
|
||||
'Local keeps everything on this phone. Connecting syncs to your own openGym server instead — you can switch later in Settings.': "Yerel, her şeyi bu telefonda tutar. Bağlanmak ise bunun yerine kendi openGym sunucunla senkronize eder — bunu daha sonra Ayarlar'dan değiştirebilirsin."
|
||||
'Local keeps everything on this phone. Connecting syncs to your own openGym server instead — you can switch later in Settings.': "Yerel, her şeyi bu telefonda tutar. Bağlanmak ise bunun yerine kendi openGym sunucunla senkronize eder — bunu daha sonra Ayarlar'dan değiştirebilirsin.",
|
||||
|
||||
// --- workout notes and planned warm-ups ---
|
||||
'{0} — done': '{0} — tamamlandı',
|
||||
'Workout done': 'Antrenman tamamlandı',
|
||||
'reps': 'tekrar',
|
||||
'Most reps in a set per workout': 'Antrenman başına bir sette en çok tekrar',
|
||||
'Warm-up sets': 'Isınma setleri',
|
||||
'Added before your work sets and left out of volume, records and progression. Each one closes half the gap to the work weight — you can still change any of them mid-session.': 'Çalışma setlerinden önce eklenir; hacim, rekor ve ilerlemeye sayılmaz. Her biri çalışma ağırlığına kalan farkı yarıya indirir — antrenman sırasında yine de değiştirebilirsin.',
|
||||
'Ramp-up sets added before the work sets, so you do not have to add them by hand each session.': 'Çalışma setlerinden önce eklenen hazırlık setleri, böylece her antrenmanda elle eklemen gerekmez.',
|
||||
'Note': 'Not',
|
||||
'This session': 'Bu antrenman',
|
||||
'How it went, what to change — kept with today’s workout.': 'Nasıl geçti, neyi değiştirmeli — bugünün antrenmanıyla saklanır.',
|
||||
'Show this next time': 'Bir dahaki sefere göster',
|
||||
'Brings it up again the next time you train this exercise.': 'Bu hareketi bir dahaki çalışmanda yeniden karşına çıkar.',
|
||||
'Always for this exercise': 'Bu harekette her zaman',
|
||||
'Seat height, pin position, a form cue — shown every session.': 'Sehpa yüksekliği, pim konumu, bir teknik ipucu — her antrenmanda görünür.',
|
||||
'From {0}:': '{0} tarihinden:',
|
||||
'Session note': 'Antrenman notu',
|
||||
'How the session went as a whole.': 'Antrenmanın genel olarak nasıl geçtiği.',
|
||||
'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': 'Rest-pause her zaman bu tekrar sayısında bir ısınma seti ve bir rest-pause çalışma seti olarak çalışılır — “Setler” kullanılmaz.'
|
||||
}
|
||||
@@ -651,5 +651,25 @@ export default {
|
||||
'Connect': '连接',
|
||||
'How do you want to use openGym?': '你想如何使用 openGym?',
|
||||
'Use on this device': '在此设备上使用',
|
||||
'Local keeps everything on this phone. Connecting syncs to your own openGym server instead — you can switch later in Settings.': '本地模式会把所有内容保留在这部手机上。连接则会改为与你自己的 openGym 服务器同步——之后可以在设置中更改。'
|
||||
'Local keeps everything on this phone. Connecting syncs to your own openGym server instead — you can switch later in Settings.': '本地模式会把所有内容保留在这部手机上。连接则会改为与你自己的 openGym 服务器同步——之后可以在设置中更改。',
|
||||
|
||||
// --- workout notes and planned warm-ups ---
|
||||
'{0} — done': '{0} — 已完成',
|
||||
'Workout done': '训练已完成',
|
||||
'reps': '次',
|
||||
'Most reps in a set per workout': '每次训练单组最多次数',
|
||||
'Warm-up sets': '热身组',
|
||||
'Added before your work sets and left out of volume, records and progression. Each one closes half the gap to the work weight — you can still change any of them mid-session.': '加在正式组之前,不计入容量、纪录和进阶。每一组都把与正式重量的差距减半 —— 训练中仍可随时调整。',
|
||||
'Ramp-up sets added before the work sets, so you do not have to add them by hand each session.': '在正式组之前加入的爬升组,这样就不用每次手动添加。',
|
||||
'Note': '备注',
|
||||
'This session': '本次训练',
|
||||
'How it went, what to change — kept with today’s workout.': '感觉如何、下次要改什么 —— 随今天的训练一起保存。',
|
||||
'Show this next time': '下次显示',
|
||||
'Brings it up again the next time you train this exercise.': '下次练这个动作时会再次出现。',
|
||||
'Always for this exercise': '这个动作始终显示',
|
||||
'Seat height, pin position, a form cue — shown every session.': '座椅高度、插销位置、动作要点 —— 每次训练都会显示。',
|
||||
'From {0}:': '来自 {0}:',
|
||||
'Session note': '训练备注',
|
||||
'How the session went as a whole.': '这次训练整体感觉如何。',
|
||||
'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': 'Rest-pause 始终按这个次数练一个热身组,再加一个 rest-pause 正式组 —— 不使用“组数”。'
|
||||
}
|
||||
+111
-6
@@ -1,10 +1,10 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { useStore } from './store/useStore.js'
|
||||
import { useUI } from './store/useUI.js'
|
||||
import { EXDB, EXIDX, BODYPARTS, isCardio, isBodyweightEq, allExercises, equipmentOf, smOf, matchExercise } from './lib/exercises.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, uid, exCount, DAYN, 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 } from './lib/history.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 { beep, vibrate } from './lib/sound.js'
|
||||
import { t, instrFor, exerciseNameFor, getLang, INSTR_LANGS } from './lib/i18n.js'
|
||||
import { nav } from './lib/nav.js'
|
||||
@@ -602,14 +602,18 @@ function ExConfig({ ex, existing, onSave, onDelete, close, routine, initial }) {
|
||||
// Mode-independent, so it is spread in below rather than folded into `flags`.
|
||||
const note = (c.note || '').trim().slice(0, 500)
|
||||
const withNote = note ? { note } : {}
|
||||
// Only written when there are any, so a plan that never asked for warm-ups keeps the exact
|
||||
// shape it had — and reads back as 0 either way (buildSets).
|
||||
const warmupSets = Math.max(0, Math.min(MAX_PLANNED_WARMUPS, Math.round(c.warmupSets) || 0))
|
||||
const withWarmups = warmupSets ? { warmupSets } : {}
|
||||
if (cardio) onSave({ sets, min: Math.max(1, Math.round(c.min) || 20), speed: Math.max(0, c.speed || 8), ...withNote })
|
||||
else if (mode === 'time') onSave({ sets, mode: 'time', sec: Math.max(1, Math.round(c.sec) || 45), weight: Math.max(0, c.weight || 0), ...flags, ...prog, ...withNote })
|
||||
else if (mode === 'time') onSave({ sets, mode: 'time', sec: Math.max(1, Math.round(c.sec) || 45), weight: Math.max(0, c.weight || 0), ...flags, ...prog, ...withNote, ...withWarmups })
|
||||
else {
|
||||
// A unilateral target is stored even: the split has to divide, and a typed 15 would
|
||||
// otherwise plan seven reps on one side and eight on the other, every session.
|
||||
const typed = Math.max(1, Math.round(c.reps) || 10)
|
||||
const reps = perSide ? Math.ceil(typed / 2) * 2 : typed
|
||||
const out = { sets, mode: 'reps', reps, weight: Math.max(0, c.weight || 0), ...flags, ...(perSide ? { side: true } : {}), ...prog, ...withNote }
|
||||
const out = { sets, mode: 'reps', reps, weight: Math.max(0, c.weight || 0), ...flags, ...(perSide ? { side: true } : {}), ...prog, ...withNote, ...withWarmups }
|
||||
if (policyFor({ ...c, id: ex.id }, routine, 'reps') === 'double') out.repsMin = Math.min(reps, Math.max(1, Math.round(c.repsMin) || Math.max(1, reps - 2)))
|
||||
// A ceiling below the working reps would tell you to add a set on day one.
|
||||
if (bw && !(out.weight > 0) && c.repsMax > 0) out.repsMax = Math.max(reps, Math.round(c.repsMax))
|
||||
@@ -622,9 +626,14 @@ function ExConfig({ ex, existing, onSave, onDelete, close, routine, initial }) {
|
||||
return <>
|
||||
<h3 className="capitalize">{exerciseNameFor(ex)}</h3>
|
||||
<Media ex={ex} />
|
||||
{/* The same tags the exercise detail sheet shows, secondaries included: choosing what goes
|
||||
into a plan is exactly when "what else does this hit" matters, and until now that was
|
||||
only visible from the Exercises tab, after the fact. */}
|
||||
<div className="row" style={{ gap: 6, flexWrap: 'wrap', margin: '10px 0 14px' }}>
|
||||
{cardio && <span className="tag acc"><Icon name="figureRun" />{t('Cardio')}</span>}
|
||||
<span className="tag">{t(ex.tg || ex.bp)}</span><span className="tag">{t(ex.eq)}</span>
|
||||
{!cardio && (ex.secondaries?.length ? ex.secondaries : smOf(ex)).slice(0, 3)
|
||||
.map((s, i) => <span key={i} className="tag dim">{t(s)}</span>)}
|
||||
</div>
|
||||
{ex.desc && <div className="exnote">{ex.desc}</div>}
|
||||
{!cardio && <div style={{ marginBottom: 14 }}>
|
||||
@@ -654,6 +663,20 @@ function ExConfig({ ex, existing, onSave, onDelete, close, routine, initial }) {
|
||||
{c.intensifier?.type === 'restpause' && <div className="small dim" style={{ marginTop: -10, marginBottom: 18 }}>
|
||||
{t('Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.')}
|
||||
</div>}
|
||||
{/* Planned warm-ups: the session used to start at the work weight and you added every
|
||||
warm-up by hand, every time. Rest-pause is excluded because it builds its own warm-up
|
||||
row, and cardio because an interval plan has no load to ramp. */}
|
||||
{!cardio && c.intensifier?.type !== 'restpause' && <>
|
||||
<div className="row cfgrow" style={{ marginBottom: 6 }}>
|
||||
<Stepper label={t('Warm-up sets')} value={c.warmupSets || 0} step={1} decimal={false}
|
||||
onChange={v => setC(x => ({ ...x, warmupSets: Math.max(0, Math.min(MAX_PLANNED_WARMUPS, Math.round(v) || 0)) }))} />
|
||||
</div>
|
||||
<div className="small dim" style={{ marginBottom: 18 }}>
|
||||
{(c.warmupSets || 0) > 0
|
||||
? t('Added before your work sets and left out of volume, records and progression. Each one closes half the gap to the work weight — you can still change any of them mid-session.')
|
||||
: t('Ramp-up sets added before the work sets, so you do not have to add them by hand each session.')}
|
||||
</div>
|
||||
</>}
|
||||
{mode === 'time' && !bw && <div className="small dim" style={{ marginBottom: 18 }}>
|
||||
{t('A timer runs while you hold the set. Leave the weight at 0 for bodyweight holds.')}
|
||||
</div>}
|
||||
@@ -890,6 +913,16 @@ export const dayAssignSheet = day => ui().openSheet(close => <DayAssign day={day
|
||||
/* ============================ workout detail ============================ */
|
||||
function WorkoutDetail({ w, close }) {
|
||||
const st = useStore(s => s.S)
|
||||
const update = useStore(s => s.update)
|
||||
// The session note is editable here rather than only at the finish sheet: what you want to
|
||||
// record about a session is often clearer once you have looked at what you actually did.
|
||||
const [note, setNote] = useState(w.note || '')
|
||||
const saveNote = () => update(s => {
|
||||
const rec = s.workouts.find(x => x.id === w.id)
|
||||
if (!rec) return
|
||||
const text = note.trim().slice(0, NOTE_MAX)
|
||||
if (text) rec.note = text; else delete rec.note
|
||||
})
|
||||
return <>
|
||||
<h3>{w.name}</h3>
|
||||
<div className="muted small" style={{ marginBottom: 12 }}>{[fmtDate(w.d, true), ...durPart(w.end - w.start), fmtVol(w.vol, st.unit), ...(w.bw ? [fmtNum(w.bw) + ' ' + st.unit] : [])].join(' · ')}</div>
|
||||
@@ -898,9 +931,17 @@ function WorkoutDetail({ w, close }) {
|
||||
return <div key={i} className="row" style={{ marginBottom: 12, alignItems: 'flex-start' }}>
|
||||
{ex && <Thumb ex={ex} />}
|
||||
<div className="grow"><div className="tt capitalize" style={{ fontWeight: 600 }}>{ex ? exerciseNameFor(ex) : (e.n || e.id)} {w.prs && w.prs.includes(e.id) && <span className="pr"><Icon name="trophy" />PR</span>}</div>
|
||||
<div className="ss">{e.sets.filter(s => s.done).map(s => setLabel(e.id, s, e.target)).join(' · ') || t('no sets')}</div></div>
|
||||
<div className="ss">{e.sets.filter(s => s.done).map(s => setLabel(e.id, s, e.target)).join(' · ') || t('no sets')}</div>
|
||||
{e.note && <div className="small dim" style={{ marginTop: 3 }}>
|
||||
{e.notePin && <Icon name="flag" style={{ fontSize: 12, marginRight: 4, verticalAlign: '-1px', color: 'var(--yellow)' }} />}{e.note}
|
||||
</div>}</div>
|
||||
</div>
|
||||
})}
|
||||
<div className="small muted" style={{ margin: '4px 0 6px' }}>{t('Session note')}</div>
|
||||
<textarea className="input" rows={2} maxLength={NOTE_MAX} value={note}
|
||||
placeholder={t('How the session went as a whole.')}
|
||||
onChange={e => setNote(e.target.value)} onBlur={saveNote} />
|
||||
<div style={{ height: 14 }} />
|
||||
<Button variant="danger" onClick={() => confirmSheet({ title: t('Delete workout?'), message: t('This removes it from your history for good.'), confirmText: t('Delete'), danger: true, onConfirm: () => { update(s => { s.workouts = s.workouts.filter(x => x.id !== w.id) }); close(); toast(t('Workout deleted')) } })}>{t('Delete workout')}</Button>
|
||||
</>
|
||||
}
|
||||
@@ -973,7 +1014,7 @@ export function beginWorkout(routineId, bw) {
|
||||
// kept on the entry purely so the workout can explain the number it chose.
|
||||
const entries = (r ? r.ex : []).map(cfg => {
|
||||
const plan = nextPrescription(st, cfg, r)
|
||||
const sets = applyIntensifierPlan(applyPrescription(buildSets(st, cfg), plan), cfg)
|
||||
const sets = applyIntensifierPlan(applyPrescription(buildSets(st, cfg, { step: defaultIncrement(cfg.id, st.unit) }), plan), cfg)
|
||||
return { id: cfg.id, sg: cfg.sg, target: { ...cfg }, plan, sets }
|
||||
})
|
||||
update(s => {
|
||||
@@ -1032,6 +1073,70 @@ function TopWeight({ entryIdx, close }) {
|
||||
}
|
||||
export const topWeightSheet = entryIdx => ui().openSheet(close => <TopWeight entryIdx={entryIdx} close={close} />)
|
||||
|
||||
/* ============================ exercise notes ============================
|
||||
Two notes, one sheet, because from the user's side it is one question — "what do I want to
|
||||
remember about this exercise?" — with two different lifetimes:
|
||||
|
||||
· today's note belongs to this session and is stored on the workout entry. It is history:
|
||||
what happened, how it felt. The PIN is the user saying "this one is for next time", which
|
||||
only they can know at the moment of writing — see pinnedNoteFor.
|
||||
· the standing note belongs to the exercise itself and lives in S.exNotes. Seat height, pin
|
||||
position, a form cue. True every session, so it is shown every session and never expires.
|
||||
|
||||
A routine's own `note` (a plan's instruction for this exercise) is edited in the config sheet
|
||||
and is deliberately not here: it belongs to the plan, not to the day or to the movement. */
|
||||
function ExerciseNote({ entryIdx, close }) {
|
||||
const st = useStore(s => s.S)
|
||||
const update = useStore(s => s.update)
|
||||
const A = st.active
|
||||
const entry = A ? A.entries[entryIdx] : null
|
||||
const ex = entry ? exOr(entry.id) : null
|
||||
const [note, setNote] = useState(entry?.note || '')
|
||||
const [pin, setPin] = useState(!!entry?.notePin)
|
||||
const [standing, setStanding] = useState(entry ? (st.exNotes?.[entry.id] || '') : '')
|
||||
useEffect(() => { if (!entry) close() }, [!entry])
|
||||
if (!entry) return null
|
||||
|
||||
const save = () => {
|
||||
const today = note.trim().slice(0, NOTE_MAX)
|
||||
const always = standing.trim().slice(0, NOTE_MAX)
|
||||
update(s => {
|
||||
const e = s.active?.entries?.[entryIdx]
|
||||
if (e) {
|
||||
if (today) { e.note = today; if (pin) e.notePin = true; else delete e.notePin }
|
||||
else { delete e.note; delete e.notePin }
|
||||
}
|
||||
s.exNotes = s.exNotes || {}
|
||||
if (always) s.exNotes[entry.id] = always
|
||||
else delete s.exNotes[entry.id]
|
||||
})
|
||||
close()
|
||||
}
|
||||
|
||||
return <>
|
||||
<h3 className="capitalize">{exerciseNameFor(ex)}</h3>
|
||||
<div className="small muted" style={{ marginBottom: 6 }}>{t('This session')}</div>
|
||||
<textarea className="input" rows={3} maxLength={NOTE_MAX} value={note}
|
||||
placeholder={t('How it went, what to change — kept with today’s workout.')}
|
||||
onChange={e => setNote(e.target.value)} />
|
||||
<div style={{ height: 10 }} />
|
||||
<div className="sect-b">
|
||||
<Row icon="flag" iconTint="var(--yellow)" title={t('Show this next time')}
|
||||
subtitle={t('Brings it up again the next time you train this exercise.')}>
|
||||
<Switch checked={pin} onChange={setPin} disabled={!note.trim()} />
|
||||
</Row>
|
||||
</div>
|
||||
<div style={{ height: 18 }} />
|
||||
<div className="small muted" style={{ marginBottom: 6 }}>{t('Always for this exercise')}</div>
|
||||
<textarea className="input" rows={2} maxLength={NOTE_MAX} value={standing}
|
||||
placeholder={t('Seat height, pin position, a form cue — shown every session.')}
|
||||
onChange={e => setStanding(e.target.value)} />
|
||||
<div style={{ height: 18 }} />
|
||||
<Button variant="primary" onClick={save}>{t('Save')}</Button>
|
||||
</>
|
||||
}
|
||||
export const exerciseNoteSheet = entryIdx => ui().openSheet(close => <ExerciseNote entryIdx={entryIdx} close={close} />)
|
||||
|
||||
/* Drop-set drops and rest-pause bursts are edited inline on the set row itself (Workout.jsx) —
|
||||
no sheet, no timer. A planned exercise (see the "Intensifier" config below) arrives with them
|
||||
already computed via applyIntensifierPlan; an unplanned straight set can still grow one live
|
||||
|
||||
@@ -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,
|
||||
// Standing per-exercise notes, keyed by exercise id: the gym-specific facts that are true
|
||||
// every time you do the movement ("seat 4, pin 7"). Distinct from a routine's `note`, which
|
||||
// belongs to one exercise in one plan, and from a session note, which belongs to one day.
|
||||
exNotes: {},
|
||||
}
|
||||
const clone = o => JSON.parse(JSON.stringify(o))
|
||||
|
||||
|
||||
@@ -26,6 +26,9 @@ export default function Home() {
|
||||
|
||||
const monday = new Date(today); monday.setDate(today.getDate() - ((today.getDay() + 6) % 7) + 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)
|
||||
@@ -58,17 +61,26 @@ export default function Home() {
|
||||
<button className="iconbtn" style={{ width: 30, height: 30, fontSize: 15 }} onClick={() => setWeekOffset(w => w + 1)} aria-label="Next week"><Icon name="chevronRight" /></button>
|
||||
</div>
|
||||
<div className="week">{strip}</div>
|
||||
{/* Once today's session is logged the row stops asking for it. The week strip already
|
||||
knew (its dot goes 'done'); this row did not, so a finished day kept showing the
|
||||
routine name behind a green Start tag and read as still outstanding (issue #4).
|
||||
An in-progress session still wins — that one is happening right now. Tapping the
|
||||
row keeps working, so a second session in one day is a tap away, just not urged. */}
|
||||
<div className="today-row" onClick={onToday}>
|
||||
<div className="row" style={{ gap: 9, minWidth: 0 }}>
|
||||
<span className="lrow-i" style={{ background: S.active ? 'var(--orange)' : routine ? 'var(--acc)' : 'var(--surface-3)' }}>
|
||||
<Icon name={S.active ? 'timer' : routine ? glyphOf(routine.emoji) : 'moon'} />
|
||||
<span className="lrow-i" style={{ background: S.active ? 'var(--orange)' : doneToday ? 'var(--surface-3)' : routine ? 'var(--acc)' : 'var(--surface-3)' }}>
|
||||
<Icon name={S.active ? 'timer' : doneToday ? 'checkCircle' : routine ? glyphOf(routine.emoji) : 'moon'}
|
||||
style={doneToday && !S.active ? { color: 'var(--green)' } : undefined} />
|
||||
</span>
|
||||
<div style={{ minWidth: 0 }}>
|
||||
<div className="lbl2">{t('Today')}</div>
|
||||
<div className="ttl">{S.active ? t('{0} — in progress', S.active.name) : routine ? routine.name : t('Rest day')}{todayOvr && routine ? ' · ' + t('rescheduled') : ''}</div>
|
||||
<div className="ttl">{S.active ? t('{0} — in progress', S.active.name)
|
||||
: doneToday ? (doneToday.name ? t('{0} — done', doneToday.name) : t('Workout done'))
|
||||
: routine ? routine.name : t('Rest day')}{todayOvr && routine && !doneToday ? ' · ' + t('rescheduled') : ''}</div>
|
||||
</div>
|
||||
</div>
|
||||
{S.active ? <span className="tag" style={{ color: 'var(--orange)', background: 'color-mix(in srgb,var(--orange) 16%,transparent)' }}>{t('Resume')}</span>
|
||||
: doneToday ? <span className="tag" style={{ color: 'var(--green)', background: 'color-mix(in srgb,var(--green) 16%,transparent)' }}>{t('Done')}</span>
|
||||
: routine ? <span className="tag acc">{t('Start')}</span>
|
||||
: <Icon name="plus" className="chev" />}
|
||||
</div>
|
||||
|
||||
@@ -300,6 +300,12 @@ export default function Stats() {
|
||||
const rows = metricRowsForEntry(en, mode)
|
||||
const mx = mode === 'reps' ? bestWeightForEntry(en) : Math.max(0, ...rows.map(s => mode === 'cardio' ? (s.speed || 0) : mode === 'time' ? (s.sec || 0) : (s.w || 0)))
|
||||
if (mx > 0) return { mx, unit: mode === 'cardio' ? 'km/h' : mode === 'time' ? 's' : S.unit }
|
||||
// Unloaded reps work still has a current figure — its rep count. Without this the whole
|
||||
// picker label went blank and the exercise sorted to the bottom as if it had no history.
|
||||
if (mode === 'reps') {
|
||||
const reps = Math.max(0, ...rows.map(s => Number(s.r) || 0))
|
||||
if (reps > 0) return { mx: reps, unit: t('reps') }
|
||||
}
|
||||
}
|
||||
return { mx: 0, unit: S.unit }
|
||||
}
|
||||
@@ -321,8 +327,18 @@ export default function Stats() {
|
||||
})() : 'reps'
|
||||
const curCardio = curMode === 'cardio'
|
||||
const curTimed = curMode === 'time'
|
||||
// A pull-up or a push-up carries no weight, so its "best weight" is 0 — and dropping every
|
||||
// zero point left the card reading "No data yet" for exercises with a full history behind
|
||||
// them (issue #5). When nothing in an exercise's history was ever loaded, the progress IS
|
||||
// the rep count, so plot that. Add a weighted set later and it switches back to weight on
|
||||
// its own, which is also the honest reading: that is when load became the thing improving.
|
||||
const repsOnly = curEx && curMode === 'reps' && !workouts.some(w => {
|
||||
const en = w.entries.find(e => e.id === curEx)
|
||||
return en && bestWeightForEntry(en) > 0
|
||||
})
|
||||
const bestRepsOf = en => Math.max(0, ...metricRowsForEntry(en, 'reps').map(s => Number(s.r) || 0))
|
||||
const metric = s => curCardio ? (s.speed || 0) : curTimed ? (s.sec || 0) : (s.w || 0)
|
||||
const exUnit = curCardio ? 'km/h' : curTimed ? 's' : S.unit
|
||||
const exUnit = curCardio ? 'km/h' : curTimed ? 's' : repsOnly ? t('reps') : S.unit
|
||||
let exPts = [], exList = [], exBest = 0
|
||||
if (curEx) {
|
||||
workouts.forEach(w => {
|
||||
@@ -331,7 +347,9 @@ export default function Stats() {
|
||||
const loggedMode = metricModeForEntry(en)
|
||||
if (loggedMode !== curMode) return
|
||||
const doneSets = metricRowsForEntry(en, curMode)
|
||||
const mx = curMode === 'reps' ? bestWeightForEntry(en) : Math.max(0, ...doneSets.map(metric))
|
||||
const mx = curMode === 'reps'
|
||||
? (repsOnly ? bestRepsOf(en) : bestWeightForEntry(en))
|
||||
: Math.max(0, ...doneSets.map(metric))
|
||||
if (mx > 0) {
|
||||
exPts.push({ t: w.start, y: mx, d: w.d, sets: doneSets, target: en.target })
|
||||
if (mx > exBest) exBest = mx
|
||||
@@ -413,7 +431,7 @@ export default function Stats() {
|
||||
<div style={{ marginTop: 8 }}>{exList.map((p, i) => <div key={i} className="row between small" style={{ padding: '6px 0', borderBottom: 'var(--hair) solid var(--sep)' }}>
|
||||
<span className="muted">{fmtDate(p.d, true)}</span><span>{p.sets.map(s => setLabel(curEx, s, p.target)).join(' ')}</span></div>)}</div>
|
||||
<div className="small dim" style={{ marginTop: 8 }}>
|
||||
{onEff ? t('Average effort per workout') : onE1 ? t('Estimated 1RM per workout') : curCardio ? t('Top speed per workout') : curTimed ? t('Longest hold per workout') : t('Best set weight per workout')}
|
||||
{onEff ? t('Average effort per workout') : onE1 ? t('Estimated 1RM per workout') : curCardio ? t('Top speed per workout') : curTimed ? t('Longest hold per workout') : repsOnly ? t('Most reps in a set per workout') : t('Best set weight per workout')}
|
||||
{onEff ? '' : <> · {t('Best:')}{' '}<b className="accent">{fmtNum(onE1 ? e1Best.est : exBest)} {onE1 ? S.unit : exUnit}</b></>}
|
||||
</div>
|
||||
{onE1 && <div className="small dim" style={{ marginTop: 4 }}>
|
||||
|
||||
@@ -3,17 +3,17 @@ import { useNavigate } from 'react-router-dom'
|
||||
import { useStore } from '../store/useStore.js'
|
||||
import { useUI } from '../store/useUI.js'
|
||||
import { exOr } from '../lib/exercises.js'
|
||||
import { effectiveRoutine, lastEntryFor, bestWeightFor, buildSets, freestyleConfig, defaultConfig, setsDoneActive, supersetUnits, unitOf, setLabel, modeOf, isBw, isPerSide, sideReps, repStep, EFFORT, effortOf, stepEffort, capEffort, cascadeWeight, insertWarmupRow, removeRowAt, pairAdjacent, unpairSuperset, cleanupSg, applyIntensifierPlan } from '../lib/history.js'
|
||||
import { effectiveRoutine, lastEntryFor, bestWeightFor, buildSets, freestyleConfig, defaultConfig, setsDoneActive, supersetUnits, unitOf, setLabel, modeOf, isBw, isPerSide, sideReps, repStep, EFFORT, effortOf, stepEffort, capEffort, cascadeWeight, insertWarmupRow, removeRowAt, pairAdjacent, unpairSuperset, cleanupSg, applyIntensifierPlan, pinnedNoteFor, exNoteFor } from '../lib/history.js'
|
||||
import { fmtNum, fmtDate, todayISO, exCount, DAYN } from '../lib/format.js'
|
||||
import { beep, vibrate } from '../lib/sound.js'
|
||||
import { t, exerciseNameFor } from '../lib/i18n.js'
|
||||
import { api } from '../lib/api.js'
|
||||
import { setProgressHighWater, supersetFlowStep } from '../lib/supersetFlow.js'
|
||||
import { setProgressHighWater, supersetFlowStep, restAfterSet, restOnRecheck } from '../lib/supersetFlow.js'
|
||||
import Media from '../components/Media.jsx'
|
||||
import { startFlow, exercisePicker, exConfigSheet, exerciseDetailSheet, topWeightSheet, finishWorkout, workoutCompleteSheet, confirmSheet } from '../sheets.jsx'
|
||||
import { startFlow, exercisePicker, exConfigSheet, exerciseDetailSheet, topWeightSheet, finishWorkout, workoutCompleteSheet, confirmSheet, exerciseNoteSheet } from '../sheets.jsx'
|
||||
import Icon from '../components/Icon.jsx'
|
||||
import { Button, Check, NumberField } from '../components/ui.jsx'
|
||||
import { nextPrescription, applyPrescription } from '../lib/progression.js'
|
||||
import { nextPrescription, applyPrescription, defaultIncrement } from '../lib/progression.js'
|
||||
import { glyphOf } from '../lib/glyphs.js'
|
||||
import { isWarmupRow, isDropSet, isRestPauseSet, dropsOf, clustersOf, addDrop, addCluster, removeDropAt, removeClusterAt, setDropAt, setClusterAt, nextDropWeight, nextBurstReps } from '../lib/workout-model.js'
|
||||
|
||||
@@ -96,6 +96,10 @@ function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemov
|
||||
const cardio = mode === 'cardio'
|
||||
const timed = mode === 'time'
|
||||
const last = lastEntryFor(S, entry.id)
|
||||
const standingNote = exNoteFor(S, entry.id)
|
||||
// Only worth surfacing while there is still work left: once the exercise is finished, a note
|
||||
// telling you what to do in it is behind you, and the block is already long.
|
||||
const pinnedNote = entry.sets.some(s => !s.done) ? pinnedNoteFor(S, entry.id) : null
|
||||
// The same number the "confirm your working weight" sheet calls your best, so the two
|
||||
// never disagree inside one session: heaviest logged set, or the working weight you kept.
|
||||
const best = cardio ? 0 : Math.max(bestWeightFor(S, entry.id), (S.exWeights[entry.id] || {}).w || 0)
|
||||
@@ -154,7 +158,12 @@ function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemov
|
||||
<Media ex={ex} key={entry.id} compact={compact} minimizable />
|
||||
<div className="row between" style={{ marginBottom: 6 }}>
|
||||
<div style={{ fontSize: compact ? 17 : 20, fontWeight: 600, letterSpacing: '-.02em', textTransform: 'capitalize', lineHeight: 1.2 }}>{exerciseNameFor(ex)}</div>
|
||||
<button className="iconbtn" aria-label={t('Details')} onClick={() => exerciseDetailSheet(ex)}><Icon name="info" /></button>
|
||||
<div className="row" style={{ gap: 2, flex: 'none' }}>
|
||||
<button className="iconbtn" aria-label={t('Note')} title={t('Note')}
|
||||
style={entry.note ? { color: 'var(--acc)' } : undefined}
|
||||
onClick={() => exerciseNoteSheet(entryIdx)}><Icon name="pencil" /></button>
|
||||
<button className="iconbtn" aria-label={t('Details')} onClick={() => exerciseDetailSheet(ex)}><Icon name="info" /></button>
|
||||
</div>
|
||||
</div>
|
||||
{!compact && (onPairPrev || onPairNext) && <div className="row" style={{ gap: 6, flexWrap: 'wrap', marginBottom: 8 }}>
|
||||
{onPairPrev && <Button size="xs" variant="tinted" icon="link" title={t('Make superset with previous')} onClick={onPairPrev}>{t('Make superset with previous')}</Button>}
|
||||
@@ -169,7 +178,17 @@ function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemov
|
||||
{ex.eq && <span className="tag">{t(ex.eq)}</span>}
|
||||
{best > 0 && <span className="tag nocap">{t('Best:')} {fmtNum(best)} {S.unit}</span>}
|
||||
</div>
|
||||
{/* Three notes can apply to one exercise and they are not interchangeable, so each keeps its
|
||||
own line and its own icon: the plan's instruction (cfg.note, from the routine), the
|
||||
standing fact about the movement (exNotes), and the message you pinned to yourself last
|
||||
session. Today's own note is edited through the button in the header and shown last. */}
|
||||
{cfg.note && <div className="exnote">{cfg.note}</div>}
|
||||
{standingNote && <div className="exnote"><Icon name="info" style={{ fontSize: 13, marginRight: 5, verticalAlign: '-2px' }} />{standingNote}</div>}
|
||||
{pinnedNote && <div className="exnote" style={{ color: 'var(--yellow)' }}>
|
||||
<Icon name="flag" style={{ fontSize: 13, marginRight: 5, verticalAlign: '-2px' }} />
|
||||
{t('From {0}:', fmtDate(pinnedNote.d, true))} {pinnedNote.note}
|
||||
</div>}
|
||||
{entry.note && <div className="exnote">{entry.note}</div>}
|
||||
{last && <div className="small dim" style={{ marginBottom: 4 }}>{t('Last time')} ({fmtDate(last.d)}): {last.sets.map(s => setLabel(entry.id, s, last.target)).join(', ')}</div>}
|
||||
{plan && plan.why && plan.kind !== 'off' && <div className={'progline' + (plan.kind === 'deload' ? ' warn' : '')}>
|
||||
<Icon name={plan.kind === 'up' ? 'arrowUp' : plan.kind === 'deload' ? 'arrowDown' : 'lightbulb'} />
|
||||
@@ -304,7 +323,7 @@ function ActiveWorkout() {
|
||||
const removeSet = idx => mutEntry(idx, e => { if (e.sets.length > 1) e.sets.pop() })
|
||||
const addWarmup = idx => mutEntry(idx, e => {
|
||||
const m = modeOf({ ...(e.target || {}), id: e.id })
|
||||
e.sets = insertWarmupRow(e.sets, m, e.target || {})
|
||||
e.sets = insertWarmupRow(e.sets, m, e.target || {}, defaultIncrement(e.id, S.unit))
|
||||
})
|
||||
const removeSetAt = (idx, i) => mutEntry(idx, e => { e.sets = removeRowAt(e.sets, i) })
|
||||
const pairAt = (first, second) => update(s => {
|
||||
@@ -392,7 +411,6 @@ function ActiveWorkout() {
|
||||
if (fresh && checked && fresh.entries[idx]) {
|
||||
const progress = setProgressHighWater(fresh.entries[idx], progressHighWater.current[idx] || 0)
|
||||
progressHighWater.current[idx] = progress.highWater
|
||||
if (!progress.isNew) return
|
||||
|
||||
const freshUnits = supersetUnits(fresh.entries)
|
||||
const freshUnit = freshUnits.find(u => u.includes(idx))
|
||||
@@ -400,11 +418,19 @@ function ActiveWorkout() {
|
||||
const freshLastUnit = freshUnitIdx >= freshUnits.length - 1
|
||||
const freshUnitDone = freshUnit?.every(ui => fresh.entries[ui].sets.every(x => x.done))
|
||||
|
||||
// Singleton units are ordinary exercises: preserve their historical between-set rest,
|
||||
// while final sets finish quietly and never enter superset navigation.
|
||||
// A re-check of finished work must not navigate or reopen a sheet, but it may still owe
|
||||
// you a rest — see restOnRecheck, and the other half of issue #3.
|
||||
if (!progress.isNew) {
|
||||
if (restOnRecheck({ timerRunning: !!useUI.getState().timer, unitDone: freshUnitDone, lastUnit: freshLastUnit })) startRest(S.restSec)
|
||||
return
|
||||
}
|
||||
|
||||
// Singleton units are ordinary exercises: they rest between sets and after the closing
|
||||
// one, and never enter superset navigation. stopRest() first so the rest that belongs
|
||||
// after this set replaces the one that was running, rather than stacking on it.
|
||||
if (freshUnitDone) stopRest()
|
||||
if (!freshUnit || freshUnit.length <= 1) {
|
||||
if (!freshUnitDone) startRest(S.restSec)
|
||||
if (restAfterSet({ unitDone: freshUnitDone, lastUnit: freshLastUnit })) startRest(S.restSec)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -493,7 +519,7 @@ function ActiveWorkout() {
|
||||
exConfigSheet(ex, null, cfg => update(s => {
|
||||
const full = { ...cfg, id: ex.id }
|
||||
const plan = freestyle ? null : nextPrescription(s, full, s.routines.find(r => r.id === s.active.routineId))
|
||||
const sets = buildSets(s, full, freestyle ? { preferLast: true } : undefined)
|
||||
const sets = buildSets(s, full, { step: defaultIncrement(ex.id, s.unit), ...(freestyle ? { preferLast: true } : {}) })
|
||||
const progressed = freestyle ? sets : applyPrescription(sets, plan)
|
||||
s.active.entries.push({ id: ex.id, target: { ...cfg }, plan, sets: applyIntensifierPlan(progressed, full) })
|
||||
s.active.cur = s.active.entries.length - 1
|
||||
|
||||
Reference in new issue
Block a user