Merge main (v1.2.11) into coach: Pairing, Notizen, Aufwaerm-Saetze, GitLab-CI
Der Coach-Zweig stand seit v1.2.7. Konflikte: beide Seiten behalten (Server-Imports, Store-Felder, Home-Titel mit naechster Einheit, history.js), das Dockerfile behaelt seine zwei Targets und kopiert die neuen Server-Module mit, compose zeigt auf die GitLab-Registry. pt-BR: die 139 Coach-Strings in die Sie-Form gebracht, Fingerprint nachgezogen.
This commit is contained in:
commit
4a9e1e3456
148 files changed
+24456
-761
No files matched your search
+25
-2
@@ -3,10 +3,33 @@ export const IS_APPLE = /iPhone|iPad|iPod|Macintosh/.test(navigator.userAgent)
|
||||
export const IS_ANDROID = /Android/.test(navigator.userAgent)
|
||||
export const BIO = IS_APPLE ? 'Face ID / Touch ID' : IS_ANDROID ? 'fingerprint or face unlock' : 'your fingerprint, face or PIN'
|
||||
export const VAULT = IS_APPLE ? 'iCloud Keychain' : IS_ANDROID ? 'Google Password Manager' : 'your password manager'
|
||||
export const webauthnOK = () => !!(window.PublicKeyCredential && navigator.credentials)
|
||||
// PublicKeyCredential is the WebAuthn-specific capability signal. Do not also gate the UI on
|
||||
// navigator.credentials: some browsers expose WebAuthn while that generic Credential Management
|
||||
// API check produces a false negative (notably Chrome on iOS). The real create/get calls still run
|
||||
// only after the user chooses a passkey action and surface any genuine browser error there.
|
||||
export const webauthnOK = () => typeof window.PublicKeyCredential !== 'undefined'
|
||||
|
||||
// The paired mobile app (lib/remote.js) is the only caller of these — everywhere else stays on
|
||||
// same-origin cookies, so remoteBase/remoteToken stay empty and api() behaves exactly as before.
|
||||
let remoteBase = ''
|
||||
let remoteToken = null
|
||||
export function setRemoteAuth(base, token) { remoteBase = base || ''; remoteToken = token || null }
|
||||
|
||||
export async function api(path, opts) {
|
||||
const r = await fetch(path, Object.assign({ headers: { 'Content-Type': 'application/json' } }, opts))
|
||||
const headers = Object.assign({ 'Content-Type': 'application/json' }, opts && opts.headers)
|
||||
if (remoteToken) headers.Authorization = 'Bearer ' + remoteToken
|
||||
const r = await fetch(remoteBase + path, Object.assign({}, opts, { headers }))
|
||||
const data = await r.json().catch(() => ({}))
|
||||
if (!r.ok) { const e = new Error(data.error || ('HTTP ' + r.status)); e.status = r.status; throw e }
|
||||
return data
|
||||
}
|
||||
|
||||
// Bootstraps the connection itself: the base isn't configured yet (that's what this call decides),
|
||||
// so it talks straight to the server the user typed in, no Authorization header.
|
||||
export async function pairRedeem(serverBase, code) {
|
||||
const r = await fetch(serverBase + '/api/pair/redeem', {
|
||||
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ code })
|
||||
})
|
||||
const data = await r.json().catch(() => ({}))
|
||||
if (!r.ok) { const e = new Error(data.error || ('HTTP ' + r.status)); e.status = r.status; throw e }
|
||||
return data
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import { webauthnOK } from './api.js'
|
||||
|
||||
const originalPublicKeyCredential = window.PublicKeyCredential
|
||||
const originalCredentials = navigator.credentials
|
||||
|
||||
function setCapability(target, property, value) {
|
||||
Object.defineProperty(target, property, { configurable: true, value })
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
setCapability(window, 'PublicKeyCredential', originalPublicKeyCredential)
|
||||
setCapability(navigator, 'credentials', originalCredentials)
|
||||
})
|
||||
|
||||
describe('webauthnOK', () => {
|
||||
it('accepts WebAuthn when PublicKeyCredential is exposed', () => {
|
||||
setCapability(window, 'PublicKeyCredential', class PublicKeyCredential {})
|
||||
setCapability(navigator, 'credentials', {})
|
||||
expect(webauthnOK()).toBe(true)
|
||||
})
|
||||
|
||||
it('does not reject WebAuthn when the generic credentials check is unavailable', () => {
|
||||
setCapability(window, 'PublicKeyCredential', class PublicKeyCredential {})
|
||||
setCapability(navigator, 'credentials', undefined)
|
||||
expect(webauthnOK()).toBe(true)
|
||||
})
|
||||
|
||||
it('rejects browsers without the WebAuthn credential type', () => {
|
||||
setCapability(window, 'PublicKeyCredential', undefined)
|
||||
setCapability(navigator, 'credentials', {})
|
||||
expect(webauthnOK()).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,73 @@
|
||||
// Rendering for the admin activity log (GET /api/admin/audit).
|
||||
//
|
||||
// The server stores reason codes, not sentences — `{ ev: 'auth.login.fail', msg: 'unknown-credential' }`
|
||||
// rather than "someone tried a passkey we don't know". Turning those into English
|
||||
// belongs here and not in Admin.jsx: it is the only part of the feature that can be wrong in a way
|
||||
// a person sees, and as a plain module it is testable without mounting the dashboard.
|
||||
//
|
||||
// Like the rest of the admin screen this is English-only — the operator surface deliberately
|
||||
// stays out of the per-language string packs (see the header of views/Admin.jsx). Times still
|
||||
// follow the UI language, the way numbers and dates already do.
|
||||
import { dateLocale } from './i18n-core.js'
|
||||
|
||||
// The first segment of an event name is also the filter chip it belongs to.
|
||||
export const auditCat = ev => String(ev || '').split('.')[0]
|
||||
|
||||
const LABELS = {
|
||||
'auth.login.ok': 'Signed in',
|
||||
'auth.login.fail': 'Sign-in failed',
|
||||
'auth.register.ok': 'Created a profile',
|
||||
'auth.register.fail': 'Profile creation failed',
|
||||
'auth.register.denied': 'Signup refused',
|
||||
'auth.logout': 'Signed out',
|
||||
'auth.logout.all': 'Signed out everywhere',
|
||||
'admin.user.disable': 'Disabled an account',
|
||||
'admin.user.enable': 'Re-enabled an account',
|
||||
'admin.invite.create': 'Created an invite code',
|
||||
'admin.invite.revoke': 'Revoked an invite code',
|
||||
'admin.audit.clear': 'Cleared the activity log',
|
||||
'admin.denied': 'Blocked from the admin dashboard'
|
||||
}
|
||||
// An unknown event is shown raw rather than dropped or rendered as "undefined": a dashboard
|
||||
// that is one version behind the server should still say *something* truthful.
|
||||
export const auditLabel = ev => LABELS[ev] || String(ev || 'Unknown event')
|
||||
|
||||
const REASONS = {
|
||||
'challenge-expired': 'the sign-in took too long and expired',
|
||||
'unknown-credential': 'unknown passkey',
|
||||
'verify-error': 'the passkey could not be verified',
|
||||
'not-verified': 'the passkey was rejected',
|
||||
'user-missing': 'the passkey points at a profile that no longer exists',
|
||||
'account-disabled': 'the account is disabled',
|
||||
'credential-exists': 'that passkey already belongs to a profile',
|
||||
'invite-invalid': 'the invite code was used or revoked in the meantime',
|
||||
'invite-rejected': 'wrong or already-used invite code'
|
||||
}
|
||||
export const auditReason = msg => REASONS[msg] || (msg ? String(msg) : '')
|
||||
|
||||
// → { title, sub }. `sub` is the house "a · b · c" metadata line used by every list row.
|
||||
export function auditLine(e) {
|
||||
if (!e) return { title: '', sub: '' }
|
||||
const parts = []
|
||||
if (e.name) parts.push(e.name)
|
||||
else if (e.uid) parts.push(e.uid)
|
||||
else if (!e.ok) parts.push('unknown caller')
|
||||
if (e.tname) parts.push('→ ' + e.tname)
|
||||
// The reason codes and the invite codes share the msg field; only failures read as a reason.
|
||||
if (e.msg) parts.push(e.ok ? e.msg : auditReason(e.msg))
|
||||
if (e.ip) parts.push(e.ip)
|
||||
return { title: auditLabel(e.ev), sub: parts.join(' · ') }
|
||||
}
|
||||
|
||||
// The activity log is the one place in the app that needs a clock, and fmtDate() renders none —
|
||||
// it is used by every other view and is not worth changing for this.
|
||||
export function fmtWhen(ts, now = Date.now()) {
|
||||
if (!ts) return ''
|
||||
const d = new Date(ts)
|
||||
const time = d.toLocaleTimeString(dateLocale(), { hour: '2-digit', minute: '2-digit' })
|
||||
const n = new Date(now)
|
||||
const sameDay = d.toDateString() === n.toDateString()
|
||||
if (sameDay) return 'today ' + time
|
||||
if (now - ts < 6 * 86400000 && ts <= now) return d.toLocaleDateString(dateLocale(), { weekday: 'short' }) + ' ' + time
|
||||
return d.toLocaleDateString(dateLocale(), { day: 'numeric', month: 'short' }) + ' ' + time
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { auditCat, auditLabel, auditReason, auditLine, fmtWhen } from './audit.js'
|
||||
|
||||
// Every event name and reason code the server can emit (api/server.js, the audit block).
|
||||
// If a new one is added there without a label here, the first test fails rather than the
|
||||
// dashboard quietly printing a dotted identifier at a person.
|
||||
const EVENTS = [
|
||||
'auth.login.ok', 'auth.login.fail', 'auth.register.ok', 'auth.register.fail',
|
||||
'auth.register.denied', 'auth.logout', 'auth.logout.all',
|
||||
'admin.user.disable', 'admin.user.enable', 'admin.invite.create',
|
||||
'admin.invite.revoke', 'admin.audit.clear', 'admin.denied'
|
||||
]
|
||||
const REASONS = [
|
||||
'challenge-expired', 'unknown-credential', 'verify-error', 'not-verified',
|
||||
'user-missing', 'account-disabled', 'credential-exists', 'invite-invalid', 'invite-rejected'
|
||||
]
|
||||
|
||||
describe('auditLabel', () => {
|
||||
it('has a sentence for every event the server emits', () => {
|
||||
for (const ev of EVENTS) {
|
||||
expect(auditLabel(ev), ev).not.toBe(ev)
|
||||
expect(auditLabel(ev)).toMatch(/^[A-Z]/)
|
||||
}
|
||||
})
|
||||
|
||||
it('shows an unknown event raw instead of rendering undefined', () => {
|
||||
// A dashboard one version behind the server must still say something truthful.
|
||||
expect(auditLabel('auth.something.new')).toBe('auth.something.new')
|
||||
expect(auditLabel(undefined)).toBe('Unknown event')
|
||||
expect(auditLabel('')).toBe('Unknown event')
|
||||
})
|
||||
})
|
||||
|
||||
describe('auditCat', () => {
|
||||
it('takes the filter category from the first segment', () => {
|
||||
expect(auditCat('auth.login.ok')).toBe('auth')
|
||||
expect(auditCat('admin.invite.create')).toBe('admin')
|
||||
})
|
||||
it('survives a missing event name', () => {
|
||||
expect(auditCat(undefined)).toBe('')
|
||||
})
|
||||
it('puts every known event in exactly auth or admin', () => {
|
||||
expect([...new Set(EVENTS.map(auditCat))].sort()).toEqual(['admin', 'auth'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('auditReason', () => {
|
||||
it('has plain English for every reason code', () => {
|
||||
for (const m of REASONS) {
|
||||
expect(auditReason(m), m).not.toBe(m)
|
||||
expect(auditReason(m).length).toBeGreaterThan(3)
|
||||
}
|
||||
})
|
||||
it('falls back to the raw code and tolerates none at all', () => {
|
||||
expect(auditReason('brand-new-code')).toBe('brand-new-code')
|
||||
expect(auditReason(undefined)).toBe('')
|
||||
})
|
||||
})
|
||||
|
||||
describe('auditLine', () => {
|
||||
it('names the person who did it', () => {
|
||||
expect(auditLine({ ev: 'auth.login.ok', ok: true, uid: 'u1', name: 'Duarte' }))
|
||||
.toEqual({ title: 'Signed in', sub: 'Duarte' })
|
||||
})
|
||||
|
||||
it('shows both sides of an admin action', () => {
|
||||
const l = auditLine({ ev: 'admin.user.disable', ok: true, uid: 'a', name: 'Duarte', tgt: 'b', tname: 'Ana' })
|
||||
expect(l.title).toBe('Disabled an account')
|
||||
expect(l.sub).toBe('Duarte · → Ana')
|
||||
})
|
||||
|
||||
it('translates the reason on a failure but not the invite code on a success', () => {
|
||||
expect(auditLine({ ev: 'auth.login.fail', ok: false, msg: 'unknown-credential' }).sub)
|
||||
.toBe('unknown caller · unknown passkey')
|
||||
// admin.invite.* put the actual code in msg — that must not be run through auditReason.
|
||||
expect(auditLine({ ev: 'admin.invite.create', ok: true, name: 'Duarte', msg: 'A1B2C3D4' }).sub)
|
||||
.toBe('Duarte · A1B2C3D4')
|
||||
})
|
||||
|
||||
it('says "unknown caller" only when a failure carries no identity', () => {
|
||||
expect(auditLine({ ev: 'auth.login.fail', ok: false }).sub).toBe('unknown caller')
|
||||
// A successful event without a name is not an anonymous attacker, so it stays blank.
|
||||
expect(auditLine({ ev: 'auth.logout', ok: true }).sub).toBe('')
|
||||
})
|
||||
|
||||
it('falls back to the uid when the name was never recorded', () => {
|
||||
expect(auditLine({ ev: 'auth.login.fail', ok: false, uid: 'Xy1', msg: 'user-missing' }).sub)
|
||||
.toBe('Xy1 · the passkey points at a profile that no longer exists')
|
||||
})
|
||||
|
||||
it('appends the network when the operator opted into IPs', () => {
|
||||
expect(auditLine({ ev: 'auth.login.ok', ok: true, name: 'Duarte', ip: '203.0.113.0/24' }).sub)
|
||||
.toBe('Duarte · 203.0.113.0/24')
|
||||
})
|
||||
|
||||
it('renders nothing rather than throwing on a missing record', () => {
|
||||
expect(auditLine(undefined)).toEqual({ title: '', sub: '' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('fmtWhen', () => {
|
||||
const at = (y, m, d, h, min) => new Date(y, m - 1, d, h, min).getTime()
|
||||
const now = at(2026, 8, 23, 15, 0) // Sunday
|
||||
|
||||
it('says "today" for the same calendar day', () => {
|
||||
expect(fmtWhen(at(2026, 8, 23, 9, 5), now)).toMatch(/^today /)
|
||||
expect(fmtWhen(at(2026, 8, 23, 0, 1), now)).toMatch(/^today /)
|
||||
})
|
||||
|
||||
it('uses the weekday inside the last six days', () => {
|
||||
const s = fmtWhen(at(2026, 8, 21, 18, 30), now)
|
||||
expect(s).not.toMatch(/^today/)
|
||||
expect(s).toMatch(/^[A-Za-zÀ-ÿ.]+ \d/)
|
||||
})
|
||||
|
||||
it('falls back to a date once it is older', () => {
|
||||
expect(fmtWhen(at(2026, 8, 12, 14, 32), now)).toMatch(/\d/)
|
||||
expect(fmtWhen(at(2026, 8, 12, 14, 32), now)).not.toMatch(/^today/)
|
||||
})
|
||||
|
||||
it('always carries a time of day — that is the whole point of not reusing fmtDate', () => {
|
||||
for (const ts of [at(2026, 8, 23, 9, 5), at(2026, 8, 21, 18, 30), at(2026, 8, 12, 14, 32)]) {
|
||||
expect(fmtWhen(ts, now)).toMatch(/\d{1,2}[:.]\d{2}/)
|
||||
}
|
||||
})
|
||||
|
||||
it('does not call a future timestamp "3 days ago"', () => {
|
||||
// Clock skew between server and browser is real; a tomorrow must not read as a weekday.
|
||||
expect(fmtWhen(at(2026, 8, 30, 10, 0), now)).not.toMatch(/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)/)
|
||||
})
|
||||
|
||||
it('returns an empty string for a missing timestamp', () => {
|
||||
expect(fmtWhen(0)).toBe('')
|
||||
expect(fmtWhen(undefined)).toBe('')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,62 @@
|
||||
// Android system back (the gesture and the hardware/nav button are the same event).
|
||||
//
|
||||
// Capacitor's BridgeActivity does not handle back at all — without a JS listener the
|
||||
// activity simply finishes, so a back swipe quit the app from anywhere, whatever the
|
||||
// WebView history said. That made the sheet history entries from #63 dead weight in the
|
||||
// packaged app: they only ever worked in a browser tab, where the browser walks history
|
||||
// itself.
|
||||
//
|
||||
// Once a `backButton` listener exists, the plugin stops falling through to finish() —
|
||||
// back can then ONLY leave the app through App.exitApp(), which is why the last step is
|
||||
// an explicit press-again-to-exit rather than a silent no-op.
|
||||
import { MOBILE } from './mobile.js'
|
||||
import { useUI } from '../store/useUI.js'
|
||||
import { t } from './i18n.js'
|
||||
|
||||
// How long a first back press stays armed as "press again to exit" (the toast shows 2.2s).
|
||||
export const EXIT_WINDOW = 2000
|
||||
|
||||
// What a back press means, given what is on screen. Pure, so the table below is testable.
|
||||
export function decideBack({ top, canGoBack, exitArmed }) {
|
||||
if (top) return top.locked ? 'ignore' : 'sheet' // a locked sheet swallows back on purpose
|
||||
if (canGoBack) return 'history' // a page/tab we pushed ourselves
|
||||
return exitArmed ? 'exit' : 'arm-exit'
|
||||
}
|
||||
|
||||
export function makeBackHandler({ getSheets, closeSheet, toast, goBack, exit, now = Date.now }) {
|
||||
let armedAt = -Infinity
|
||||
return (ev = {}) => {
|
||||
const sheets = getSheets()
|
||||
const action = decideBack({
|
||||
top: sheets[sheets.length - 1],
|
||||
canGoBack: !!ev.canGoBack,
|
||||
exitArmed: now() - armedAt < EXIT_WINDOW,
|
||||
})
|
||||
if (action !== 'arm-exit') armedAt = -Infinity
|
||||
if (action === 'sheet') closeSheet(sheets[sheets.length - 1].id)
|
||||
else if (action === 'history') goBack()
|
||||
else if (action === 'arm-exit') { armedAt = now(); toast(t('Press back again to exit')) }
|
||||
else if (action === 'exit') exit()
|
||||
return action
|
||||
}
|
||||
}
|
||||
|
||||
// Registers the listener for the native shell. No-op in web builds, where the browser
|
||||
// (or the PWA shell) walks history on its own and there is no plugin to talk to.
|
||||
export async function initBackButton() {
|
||||
if (!MOBILE) return () => {}
|
||||
try {
|
||||
const { App } = await import('@capacitor/app')
|
||||
const handler = makeBackHandler({
|
||||
getSheets: () => useUI.getState().sheets,
|
||||
closeSheet: id => useUI.getState().closeSheet(id),
|
||||
toast: msg => useUI.getState().toast(msg),
|
||||
goBack: () => window.history.back(),
|
||||
exit: () => App.exitApp(),
|
||||
})
|
||||
const sub = await App.addListener('backButton', handler)
|
||||
return () => sub.remove()
|
||||
} catch (e) {
|
||||
return () => {} // no plugin (older install): leave back to the default behaviour
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { decideBack, makeBackHandler, EXIT_WINDOW } from './back.js'
|
||||
|
||||
// Back on Android has to serve three layers with one event: the sheet stack on top, the
|
||||
// page history under it, and — because a registered listener stops the plugin from ever
|
||||
// finishing the activity itself — a deliberate way out of the app at the bottom.
|
||||
describe('decideBack', () => {
|
||||
it('dismisses the top sheet before touching history', () => {
|
||||
expect(decideBack({ top: { id: 's1' }, canGoBack: true, exitArmed: false })).toBe('sheet')
|
||||
})
|
||||
|
||||
it('lets a locked sheet swallow the press', () => {
|
||||
expect(decideBack({ top: { id: 's1', locked: true }, canGoBack: true, exitArmed: true })).toBe('ignore')
|
||||
})
|
||||
|
||||
it('walks history when nothing is open', () => {
|
||||
expect(decideBack({ top: undefined, canGoBack: true, exitArmed: false })).toBe('history')
|
||||
})
|
||||
|
||||
it('arms the exit at the bottom of the stack, and exits on the second press', () => {
|
||||
expect(decideBack({ top: undefined, canGoBack: false, exitArmed: false })).toBe('arm-exit')
|
||||
expect(decideBack({ top: undefined, canGoBack: false, exitArmed: true })).toBe('exit')
|
||||
})
|
||||
})
|
||||
|
||||
function harness() {
|
||||
const calls = { closed: [], toasts: [], back: 0, exit: 0 }
|
||||
let sheets = []
|
||||
let now = 1000
|
||||
const handler = makeBackHandler({
|
||||
getSheets: () => sheets,
|
||||
closeSheet: id => { calls.closed.push(id); sheets = sheets.filter(s => s.id !== id) },
|
||||
toast: m => calls.toasts.push(m),
|
||||
goBack: () => { calls.back++ },
|
||||
exit: () => { calls.exit++ },
|
||||
now: () => now,
|
||||
})
|
||||
return { calls, handler, setSheets: s => { sheets = s }, tick: ms => { now += ms } }
|
||||
}
|
||||
|
||||
describe('makeBackHandler', () => {
|
||||
it('closes stacked sheets one press at a time', () => {
|
||||
const h = harness()
|
||||
h.setSheets([{ id: 'a' }, { id: 'b' }])
|
||||
expect(h.handler({ canGoBack: true })).toBe('sheet')
|
||||
expect(h.handler({ canGoBack: true })).toBe('sheet')
|
||||
expect(h.calls.closed).toEqual(['b', 'a'])
|
||||
expect(h.calls.back).toBe(0)
|
||||
})
|
||||
|
||||
it('does not close a locked sheet, and does not arm the exit behind it', () => {
|
||||
const h = harness()
|
||||
h.setSheets([{ id: 'a', locked: true }])
|
||||
expect(h.handler({ canGoBack: false })).toBe('ignore')
|
||||
expect(h.calls.closed).toEqual([])
|
||||
expect(h.calls.toasts).toEqual([])
|
||||
expect(h.calls.exit).toBe(0)
|
||||
})
|
||||
|
||||
it('goes back a page while the WebView still has app history', () => {
|
||||
const h = harness()
|
||||
expect(h.handler({ canGoBack: true })).toBe('history')
|
||||
expect(h.calls.back).toBe(1)
|
||||
expect(h.calls.exit).toBe(0)
|
||||
})
|
||||
|
||||
// The whole point of the fix: one press at the root must never be the end of the app.
|
||||
it('warns once, then exits on a second press inside the window', () => {
|
||||
const h = harness()
|
||||
expect(h.handler({ canGoBack: false })).toBe('arm-exit')
|
||||
expect(h.calls.toasts).toHaveLength(1)
|
||||
expect(h.calls.exit).toBe(0)
|
||||
h.tick(EXIT_WINDOW - 1)
|
||||
expect(h.handler({ canGoBack: false })).toBe('exit')
|
||||
expect(h.calls.exit).toBe(1)
|
||||
})
|
||||
|
||||
it('re-arms rather than exiting once the window has passed', () => {
|
||||
const h = harness()
|
||||
h.handler({ canGoBack: false })
|
||||
h.tick(EXIT_WINDOW + 1)
|
||||
expect(h.handler({ canGoBack: false })).toBe('arm-exit')
|
||||
expect(h.calls.exit).toBe(0)
|
||||
expect(h.calls.toasts).toHaveLength(2)
|
||||
})
|
||||
|
||||
// A sheet opened (or a page pushed) after the warning means the user is still using the
|
||||
// app — the next back belongs to that sheet, and the one after must warn again.
|
||||
it('disarms the exit as soon as another press does real work', () => {
|
||||
const h = harness()
|
||||
h.handler({ canGoBack: false })
|
||||
h.setSheets([{ id: 'a' }])
|
||||
expect(h.handler({ canGoBack: true })).toBe('sheet')
|
||||
expect(h.handler({ canGoBack: false })).toBe('arm-exit')
|
||||
expect(h.calls.exit).toBe(0)
|
||||
})
|
||||
|
||||
it('treats a missing event payload as no history', () => {
|
||||
const h = harness()
|
||||
expect(h.handler()).toBe('arm-exit')
|
||||
})
|
||||
})
|
||||
@@ -11,4 +11,4 @@
|
||||
// lands in a self-hosted bundle.
|
||||
export const DEMO = import.meta.env.VITE_DEMO === '1'
|
||||
export const DEMO_SEEDED = 'gym_demo_seeded_v1'
|
||||
export const REPO = 'https://github.com/DuarteSantos8/openGym'
|
||||
export const REPO = 'https://gitlab.com/DuarteSantos8/opengym'
|
||||
@@ -0,0 +1,34 @@
|
||||
import { t } from './i18n.js'
|
||||
import { EXDB } from './exercises-data.js'
|
||||
|
||||
// Every equipment value present in the catalogue, most common first — this becomes the
|
||||
// checklist Settings shows when you build a profile.
|
||||
export const ALL_EQUIPMENT = (() => {
|
||||
const c = {}
|
||||
EXDB.forEach(e => { if (e.eq) c[e.eq] = (c[e.eq] || 0) + 1 })
|
||||
return Object.keys(c).sort((a, b) => c[b] - c[a] || (a < b ? -1 : 1))
|
||||
})()
|
||||
|
||||
// Body weight is never gated by a profile — no gym or home setup can take it away from you,
|
||||
// and every profile should be able to see bodyweight exercises regardless of what's checked.
|
||||
const ALWAYS_AVAILABLE = 'body weight'
|
||||
|
||||
export function activeProfile(S) {
|
||||
if (!S.equipFilterOn) return null
|
||||
const profiles = S.equipProfiles || []
|
||||
return profiles.find(p => p.id === S.activeEquipId) || null
|
||||
}
|
||||
|
||||
// Whether an exercise is usable under the active profile. With filtering off, or no profile
|
||||
// selected, everything is available — this is purely additive, never a trap that hides your
|
||||
// whole library because you haven't set anything up yet.
|
||||
export function exAvailable(S, ex) {
|
||||
const p = activeProfile(S)
|
||||
if (!p) return true
|
||||
if (!ex.eq || ex.eq === ALWAYS_AVAILABLE) return true
|
||||
return (p.equipment || []).includes(ex.eq)
|
||||
}
|
||||
|
||||
export function newProfile(name) {
|
||||
return { id: 'eq' + Date.now().toString(36) + Math.random().toString(36).slice(2, 6), name, equipment: [] }
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import batch from './exercise-muscle-batch-1.json' with { type: 'json' }
|
||||
import { MACHINE_BATCH_2 } from './exercise-muscle-batch-2.js'
|
||||
|
||||
/**
|
||||
* ExRx-informed metadata for the first compound-lift batch. The raw generated catalogue remains
|
||||
* untouched; exercises.js applies this layer to the runtime index.
|
||||
*/
|
||||
export const COMPOUND_LIFT_BATCH_1 = Object.freeze(batch)
|
||||
|
||||
// Keep the phase-2 artifact in its own module for auditing while preserving the phase-1 resolver
|
||||
// interface consumed by exercises.js and downstream muscle helpers.
|
||||
export { MACHINE_BATCH_2 }
|
||||
|
||||
/**
|
||||
* Reserved for owner-approved corrections. This layer is intentionally separate from the
|
||||
* generated batch so a correction can replace a generated body part or muscle list without
|
||||
* editing generated data. Explicit metadata on a user/custom exercise wins as well.
|
||||
*/
|
||||
export const USER_EXERCISE_MUSCLE_OVERRIDES = Object.freeze({})
|
||||
|
||||
export function exerciseMuscleMetadataFor(id) {
|
||||
return {
|
||||
...(COMPOUND_LIFT_BATCH_1[id] || {}),
|
||||
...(MACHINE_BATCH_2[id] || {}),
|
||||
...(USER_EXERCISE_MUSCLE_OVERRIDES[id] || {})
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,85 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { BODYPARTS, EXDB, EXIDX, registerCustom } from './exercises.js'
|
||||
import { COMPOUND_LIFT_BATCH_1 } from './exercise-muscle-batch-1.js'
|
||||
import { MUSCLES, musclesOf } from './muscles.js'
|
||||
|
||||
const ids = Object.keys(COMPOUND_LIFT_BATCH_1)
|
||||
const catalogueIds = new Set(EXDB.map(ex => ex.id))
|
||||
|
||||
const duplicateFree = values => values.length === new Set(values).size
|
||||
|
||||
describe('compound-lift muscle metadata batch 1', () => {
|
||||
it('contains a bounded first batch of compound-lift catalogue entries', () => {
|
||||
expect(ids.length).toBeGreaterThanOrEqual(60)
|
||||
expect(ids.length).toBeLessThanOrEqual(120)
|
||||
expect(ids.every(id => catalogueIds.has(id))).toBe(true)
|
||||
})
|
||||
|
||||
it('stores canonical primary and secondary arrays for every batch entry', () => {
|
||||
for (const [id, metadata] of Object.entries(COMPOUND_LIFT_BATCH_1)) {
|
||||
expect(metadata.primaries.length, id).toBeGreaterThan(0)
|
||||
expect(duplicateFree(metadata.primaries), id).toBe(true)
|
||||
expect(duplicateFree(metadata.secondaries), id).toBe(true)
|
||||
expect(metadata.primaries.some(muscle => metadata.secondaries.includes(muscle)), id).toBe(false)
|
||||
expect(metadata.primaries.every(muscle => MUSCLES.includes(muscle)), id).toBe(true)
|
||||
expect(metadata.secondaries.every(muscle => MUSCLES.includes(muscle)), id).toBe(true)
|
||||
expect(EXIDX[id]).toMatchObject(metadata)
|
||||
}
|
||||
})
|
||||
|
||||
it('follows the documented ExRx family templates and preserves source-known muscles', () => {
|
||||
expect(COMPOUND_LIFT_BATCH_1['0043']).toEqual({
|
||||
bp: 'upper legs',
|
||||
primaries: ['quadriceps', 'gluteal', 'adductors'],
|
||||
secondaries: ['hamstring', 'calves', 'lower-back', 'abs', 'obliques']
|
||||
})
|
||||
expect(COMPOUND_LIFT_BATCH_1['0032']).toEqual({
|
||||
bp: 'full body',
|
||||
primaries: ['gluteal', 'hamstring', 'lower-back'],
|
||||
secondaries: ['quadriceps', 'adductors', 'calves', 'abs', 'obliques']
|
||||
})
|
||||
expect(COMPOUND_LIFT_BATCH_1['0025']).toEqual({
|
||||
bp: 'chest', primaries: ['chest'], secondaries: ['triceps', 'deltoids', 'biceps']
|
||||
})
|
||||
expect(COMPOUND_LIFT_BATCH_1['0091']).toEqual({
|
||||
bp: 'shoulders', primaries: ['deltoids'],
|
||||
secondaries: ['chest', 'triceps', 'trapezius', 'serratus']
|
||||
})
|
||||
expect(COMPOUND_LIFT_BATCH_1['0027']).toEqual({
|
||||
bp: 'back', primaries: ['upper-back'],
|
||||
secondaries: ['biceps', 'deltoids', 'forearm']
|
||||
})
|
||||
expect(COMPOUND_LIFT_BATCH_1['0652']).toEqual({
|
||||
bp: 'back', primaries: ['upper-back'], secondaries: ['biceps', 'deltoids', 'forearm']
|
||||
})
|
||||
expect(musclesOf(EXDB.find(exercise => exercise.id === '0587'))).toMatchObject({ chest: 0.4 })
|
||||
expect(musclesOf(EXIDX['0587'])).toMatchObject({ chest: 0.4 })
|
||||
})
|
||||
|
||||
it('keeps torso bracing secondary and does not label the twisting press full body', () => {
|
||||
expect(COMPOUND_LIFT_BATCH_1['0414']).toEqual({
|
||||
bp: 'shoulders', primaries: ['deltoids'], secondaries: ['triceps', 'trapezius', 'abs']
|
||||
})
|
||||
expect(COMPOUND_LIFT_BATCH_1['1012']).toEqual({
|
||||
bp: 'shoulders', primaries: ['deltoids'],
|
||||
secondaries: ['triceps', 'trapezius', 'abs', 'obliques']
|
||||
})
|
||||
expect(COMPOUND_LIFT_BATCH_1['1012'].primaries).not.toContain('abs')
|
||||
expect(COMPOUND_LIFT_BATCH_1['1012'].secondaries).toContain('obliques')
|
||||
})
|
||||
|
||||
it('marks the cross-region lifts as Full body while keeping classic areas available', () => {
|
||||
expect(EXIDX['0069']).toMatchObject({ bp: 'full body', primaries: ['quadriceps', 'gluteal', 'adductors'] })
|
||||
expect(EXIDX['0032'].bp).toBe('full body')
|
||||
expect(BODYPARTS).toContain('full body')
|
||||
expect(EXIDX['0025'].bp).toBe('chest')
|
||||
expect(EXIDX['0652'].bp).toBe('back')
|
||||
})
|
||||
|
||||
it('lets an explicit user exercise override the batch and restores the catalogue afterward', () => {
|
||||
registerCustom([{ id: '0025', n: 'Owner bench correction', bp: 'chest', primaries: ['triceps'], secondaries: [] }])
|
||||
expect(EXIDX['0025']).toMatchObject({ primaries: ['triceps'], secondaries: [] })
|
||||
registerCustom([])
|
||||
expect(EXIDX['0025']).toMatchObject(COMPOUND_LIFT_BATCH_1['0025'])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,8 @@
|
||||
import batch from './exercise-muscle-batch-2.json' with { type: 'json' }
|
||||
|
||||
/**
|
||||
* ExRx-informed metadata for machine, cable, sled, and Smith-machine catalogue entries.
|
||||
* `exercises.js` applies this as a runtime overlay so the raw generated catalogue remains
|
||||
* compatible with imports and historical records.
|
||||
*/
|
||||
export const MACHINE_BATCH_2 = Object.freeze(batch)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,135 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { BODYPARTS, EXDB, EXIDX, registerCustom } from './exercises.js'
|
||||
import { MACHINE_BATCH_2 } from './exercise-muscle-batch-2.js'
|
||||
import { MUSCLES, musclesOf } from './muscles.js'
|
||||
|
||||
const ids = Object.keys(MACHINE_BATCH_2)
|
||||
const catalogue = new Map(EXDB.map(exercise => [exercise.id, exercise]))
|
||||
const duplicateFree = values => values.length === new Set(values).size
|
||||
|
||||
const expectMapping = (id, expected) => {
|
||||
expect(MACHINE_BATCH_2[id], id).toEqual(expected)
|
||||
expect(EXIDX[id], id).toMatchObject(expected)
|
||||
}
|
||||
|
||||
describe('machine muscle metadata batch 2', () => {
|
||||
it('contains a bounded batch of machine and cable catalogue entries', () => {
|
||||
expect(ids.length).toBeGreaterThanOrEqual(60)
|
||||
expect(ids.length).toBeLessThanOrEqual(120)
|
||||
expect(ids.length).toBe(119)
|
||||
expect(ids.every(id => catalogue.has(id))).toBe(true)
|
||||
expect(ids.every(id => /machine|cable/.test(catalogue.get(id).eq))).toBe(true)
|
||||
})
|
||||
|
||||
it('uses only existing body-part keys and canonical drawable muscle slugs', () => {
|
||||
for (const [id, metadata] of Object.entries(MACHINE_BATCH_2)) {
|
||||
expect(BODYPARTS, id).toContain(metadata.bp)
|
||||
expect(metadata.primaries.length, id).toBeGreaterThan(0)
|
||||
expect(duplicateFree(metadata.primaries), id).toBe(true)
|
||||
expect(duplicateFree(metadata.secondaries), id).toBe(true)
|
||||
expect(metadata.primaries.some(muscle => metadata.secondaries.includes(muscle)), id).toBe(false)
|
||||
expect(metadata.primaries.every(muscle => MUSCLES.includes(muscle)), id).toBe(true)
|
||||
expect(metadata.secondaries.every(muscle => MUSCLES.includes(muscle)), id).toBe(true)
|
||||
expect(EXIDX[id]).toMatchObject(metadata)
|
||||
}
|
||||
})
|
||||
|
||||
it('maps the pec-deck family from the lever seated-fly template', () => {
|
||||
expectMapping('0596', {
|
||||
bp: 'chest', primaries: ['chest'], secondaries: ['deltoids', 'biceps', 'serratus']
|
||||
})
|
||||
})
|
||||
|
||||
it('maps chest-press machines to chest with pressing assistants', () => {
|
||||
expectMapping('0577', {
|
||||
bp: 'chest', primaries: ['chest'], secondaries: ['deltoids', 'triceps', 'biceps']
|
||||
})
|
||||
})
|
||||
|
||||
it('maps cable crossovers to drawing-ready upper-back support', () => {
|
||||
expectMapping('0155', {
|
||||
bp: 'chest', primaries: ['chest'], secondaries: ['upper-back', 'trapezius']
|
||||
})
|
||||
})
|
||||
|
||||
it('maps machine/cable lat pulldowns to upper back with arm-and-shoulder synergy', () => {
|
||||
expectMapping('0579', {
|
||||
bp: 'back',
|
||||
primaries: ['upper-back'],
|
||||
secondaries: ['biceps', 'deltoids', 'forearm', 'trapezius', 'triceps']
|
||||
})
|
||||
})
|
||||
|
||||
it('maps seated rows to upper back with the phase-1 pull template', () => {
|
||||
expectMapping('1350', {
|
||||
bp: 'back',
|
||||
primaries: ['upper-back'],
|
||||
secondaries: ['biceps', 'deltoids', 'forearm', 'trapezius', 'chest', 'triceps']
|
||||
})
|
||||
})
|
||||
|
||||
it('maps assisted triceps dip variants to full synergist support', () => {
|
||||
expectMapping('0019', {
|
||||
bp: 'upper arms',
|
||||
primaries: ['triceps'],
|
||||
secondaries: ['deltoids', 'chest', 'upper-back', 'trapezius', 'biceps']
|
||||
})
|
||||
expectMapping('1451', {
|
||||
bp: 'upper arms',
|
||||
primaries: ['triceps'],
|
||||
secondaries: ['deltoids', 'chest', 'upper-back', 'trapezius', 'biceps']
|
||||
})
|
||||
})
|
||||
|
||||
it('maps lever triceps extension without ExRx synergist secondaries', () => {
|
||||
expectMapping('0607', {
|
||||
bp: 'upper arms', primaries: ['triceps'], secondaries: []
|
||||
})
|
||||
})
|
||||
|
||||
it('maps sled leg presses to the multi-primary lower-body template', () => {
|
||||
expectMapping('0739', {
|
||||
bp: 'upper legs', primaries: ['quadriceps', 'gluteal', 'adductors'], secondaries: ['hamstring', 'calves']
|
||||
})
|
||||
})
|
||||
|
||||
it('maps leg extensions as quadriceps isolation', () => {
|
||||
expectMapping('0585', {
|
||||
bp: 'upper legs', primaries: ['quadriceps'], secondaries: []
|
||||
})
|
||||
})
|
||||
|
||||
it('maps seated leg curls to hamstrings with calf assistance', () => {
|
||||
expectMapping('0599', {
|
||||
bp: 'upper legs', primaries: ['hamstring'], secondaries: ['calves', 'adductors']
|
||||
})
|
||||
})
|
||||
|
||||
it('maps machine shoulder presses to deltoids with direct press support', () => {
|
||||
expectMapping('0603', {
|
||||
bp: 'shoulders', primaries: ['deltoids'],
|
||||
secondaries: ['chest', 'triceps', 'trapezius', 'serratus', 'biceps']
|
||||
})
|
||||
})
|
||||
|
||||
it('preserves raw dataset metadata while enriching only the runtime catalogue', () => {
|
||||
const raw = catalogue.get('0577')
|
||||
expect(raw).toMatchObject({ id: '0577', n: 'lever chest press', tg: 'pectorals', mg: 'triceps' })
|
||||
expect(raw).not.toHaveProperty('primaries')
|
||||
expect(raw).not.toHaveProperty('secondaries')
|
||||
expect(musclesOf(raw)).toEqual({ chest: 1, deltoids: 0.4, triceps: 0.4 })
|
||||
expect(musclesOf(EXIDX['0577'])).toEqual({ chest: 1, deltoids: 0.4, triceps: 0.4, biceps: 0.4 })
|
||||
})
|
||||
|
||||
it('gives an explicit custom collision precedence and restores the machine overlay', () => {
|
||||
registerCustom([{
|
||||
id: '0577', n: 'Owner machine press correction', bp: 'chest',
|
||||
primaries: ['triceps'], secondaries: []
|
||||
}])
|
||||
expect(EXIDX['0577']).toMatchObject({ primaries: ['triceps'], secondaries: [] })
|
||||
expect(musclesOf(EXIDX['0577'])).toEqual({ triceps: 1 })
|
||||
registerCustom([])
|
||||
expect(EXIDX['0577']).toMatchObject(MACHINE_BATCH_2['0577'])
|
||||
expect(musclesOf(EXIDX['0577'])).toEqual({ chest: 1, deltoids: 0.4, triceps: 0.4, biceps: 0.4 })
|
||||
})
|
||||
})
|
||||
+130
-12
@@ -1,8 +1,29 @@
|
||||
import { EXDB } from './exercises-data.js'
|
||||
import { t } from './i18n-core.js'
|
||||
import { USER_EXERCISE_MUSCLE_OVERRIDES, exerciseMuscleMetadataFor } from './exercise-muscle-batch-1.js'
|
||||
import { t, getVersion, exerciseNameSearchText } from './i18n-core.js'
|
||||
|
||||
export { EXDB }
|
||||
|
||||
// The generated dataset remains the compatibility/raw export. The runtime catalogue applies
|
||||
// owner-approved muscle metadata as a narrow overlay, so imports and historical tests that rely
|
||||
// on the upstream shape keep working while EXIDX and pickers see the corrected model.
|
||||
const catalogueExercise = ex => {
|
||||
const metadata = exerciseMuscleMetadataFor(ex?.id)
|
||||
if (!Object.keys(metadata).length) return ex
|
||||
const out = { ...ex, ...metadata }
|
||||
const user = USER_EXERCISE_MUSCLE_OVERRIDES[ex?.id] || {}
|
||||
// A future dataset row may carry explicit arrays of its own; preserve those over generated
|
||||
// defaults unless the owner has deliberately supplied a correction for the same field.
|
||||
for (const key of ['primaries', 'secondaries']) {
|
||||
if (Object.prototype.hasOwnProperty.call(ex, key) && !Object.prototype.hasOwnProperty.call(user, key)) out[key] = ex[key]
|
||||
}
|
||||
if (Array.isArray(out.primaries)) out.primaries = [...out.primaries]
|
||||
if (Array.isArray(out.secondaries)) out.secondaries = [...out.secondaries]
|
||||
return out
|
||||
}
|
||||
|
||||
export const CATALOGUE = EXDB.map(catalogueExercise)
|
||||
|
||||
// The generated dataset already supplies secondary muscles for most exercises. Keep the
|
||||
// handful of conservative catalogue additions that are useful to the muscle map here so a
|
||||
// dataset refresh does not erase them. Values follow the dataset's existing alias vocabulary.
|
||||
@@ -23,8 +44,8 @@ export const smOf = ex => {
|
||||
}
|
||||
|
||||
export const EXIDX = {}
|
||||
EXDB.forEach(e => { EXIDX[e.id] = e })
|
||||
export const BODYPARTS = [...new Set(EXDB.map(e => e.bp))].sort()
|
||||
CATALOGUE.forEach(e => { EXIDX[e.id] = e })
|
||||
export const BODYPARTS = [...new Set(CATALOGUE.map(e => e.bp))].sort()
|
||||
|
||||
// Equipment options present in a given list of exercises, most common first (issue #6).
|
||||
// Deriving them from the *already filtered* list keeps the chip row short and means
|
||||
@@ -39,25 +60,78 @@ export function equipmentOf(list) {
|
||||
// merged into the id index here so every EXIDX[id] lookup keeps working unchanged.
|
||||
let customIds = []
|
||||
export function registerCustom(list) {
|
||||
customIds.forEach(id => delete EXIDX[id])
|
||||
customIds.forEach(id => {
|
||||
delete EXIDX[id]
|
||||
const builtIn = CATALOGUE.find(ex => ex.id === id)
|
||||
if (builtIn) EXIDX[id] = builtIn
|
||||
})
|
||||
customIds = (list || []).map(e => e.id)
|
||||
;(list || []).forEach(e => { EXIDX[e.id] = e })
|
||||
}
|
||||
// Full searchable catalogue — customs first so your own exercises are easy to find.
|
||||
export const allExercises = st => [...(st.customEx || []), ...EXDB]
|
||||
export const allExercises = st => [...(st.customEx || []), ...CATALOGUE]
|
||||
|
||||
function searchableText(value) {
|
||||
if (Array.isArray(value)) return value.map(searchableText).join(' ')
|
||||
if (value == null) return ''
|
||||
try { return String(value) } catch { return '' }
|
||||
}
|
||||
|
||||
/** Case-insensitive search over built-in and legacy custom exercise metadata. */
|
||||
function isSubsequence(needle, hay) {
|
||||
let i = 0
|
||||
for (const ch of hay) {
|
||||
if (ch === needle[i]) i++
|
||||
if (i === needle.length) return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Fuzzy match score for one exercise against a query. Best hits: exact field match, then
|
||||
// field prefix, then word-boundary starts, then substrings (closer to the start scores
|
||||
// better), and finally typo-tolerant ordered subsequences. Fields are weighted - the name
|
||||
// dominates, target/equipment matter, muscles and description are supporting evidence.
|
||||
// 0 means no match, so matchesExerciseSearch stays a boolean filter while the picker can
|
||||
// rank results by score.
|
||||
export function searchScore(exercise, query) {
|
||||
const needle = searchableText(query).toLowerCase().trim()
|
||||
if (!needle) return 1
|
||||
const source = exercise && typeof exercise === 'object' ? exercise : {}
|
||||
const fields = [['n', 100], ['tg', 40], ['eq', 40], ['sm', 30], ['muscleGroups', 30], ['primaries', 30], ['secondaries', 30], ['desc', 10], ['cues', 10]]
|
||||
// Token-level matching: every query word must match somewhere (any order), so
|
||||
// "press bench" finds "Bench Press". The score sums each token's best hit.
|
||||
const tokens = needle.split(/[^a-z0-9]+/).filter(Boolean)
|
||||
if (!tokens.length) return 0
|
||||
let total = 0
|
||||
for (const token of tokens) {
|
||||
let best = 0
|
||||
for (const [field, weight] of fields) {
|
||||
const hay = searchableText(source[field]).toLowerCase()
|
||||
if (!hay) continue
|
||||
if (hay === token) best = Math.max(best, weight * 4)
|
||||
else if (hay.startsWith(token)) best = Math.max(best, weight * 3)
|
||||
const idx = hay.indexOf(token)
|
||||
if (idx > 0) best = Math.max(best, weight * 2 - Math.min(idx, 20) * 0.5)
|
||||
if (hay.split(/[^a-z0-9]+/).some(w => w.startsWith(token))) best = Math.max(best, weight * 2.5)
|
||||
if (isSubsequence(token, hay)) best = Math.max(best, weight + Math.max(0, 10 - (hay.length - token.length)))
|
||||
}
|
||||
if (!best) return 0 // every token must match
|
||||
total += best
|
||||
}
|
||||
return total
|
||||
}
|
||||
|
||||
export function matchesExerciseSearch(exercise, query) {
|
||||
return searchScore(exercise, query) > 0
|
||||
}
|
||||
|
||||
// Media normally sits next to the app (img/ and gif/, mounted into the web container).
|
||||
// A build can point them somewhere else — the demo build pulls them off a CDN instead of
|
||||
// shipping ~140 MB of images into the deployment. `import.meta.env` is undefined in plain
|
||||
// Node; the guard keeps this module loadable without Vite.
|
||||
// The defaults are absolute on purpose (issue #79). A bare 'img/' resolves against the
|
||||
// current document's directory, so on the one two-segment route in the app, /plan/r/:id,
|
||||
// every request went to /plan/r/img/… and 404'd — and nginx's extension block has no
|
||||
// try_files, so it 404s rather than falling through to index.html, leaving a blank image
|
||||
// and nothing in the console.
|
||||
const ENV = import.meta.env || {}
|
||||
const IMG_BASE = ENV.VITE_IMG_BASE || '/img/'
|
||||
const GIF_BASE = ENV.VITE_GIF_BASE || '/gif/'
|
||||
const IMG_BASE = ENV.VITE_IMG_BASE || 'img/'
|
||||
const GIF_BASE = ENV.VITE_GIF_BASE || 'gif/'
|
||||
export const imgSrc = ex => IMG_BASE + ex.img
|
||||
export const gifSrc = ex => GIF_BASE + ex.gif
|
||||
|
||||
@@ -77,3 +151,47 @@ export const isBodyweightEq = idOrEx =>
|
||||
// down on the first `ex.n`.
|
||||
export const exOr = id => EXIDX[id] ||
|
||||
{ id, n: t('Unknown exercise'), bp: '', tg: '', eq: '', sm: [], st: [], missing: true }
|
||||
|
||||
// Normalizes text by lowercasing and stripping diacritics/accents (e.g. "elevação" -> "elevacao")
|
||||
export const normalizeStr = s => (s || '')
|
||||
.normalize('NFD')
|
||||
.replace(/[\u0300-\u036f]/g, '')
|
||||
.toLowerCase()
|
||||
|
||||
// Multi-token, accent-insensitive and multilingual exercise search.
|
||||
// Matches when all whitespace-separated words in the query appear anywhere in the exercise's
|
||||
// name, equipment, target muscle, body part (both in English and translated to active language),
|
||||
// secondary muscles or description.
|
||||
//
|
||||
// The haystack is built once per exercise and cached: NFD-normalising ~1300 catalogue entries
|
||||
// on every keystroke costs ~8ms on a desktop and several times that on a phone. The cache key
|
||||
// is the i18n version (bumped by every setLang), so switching language rebuilds the translated
|
||||
// terms. Custom exercises are re-cached automatically — the store clones state on update, so an
|
||||
// edited exercise arrives as a new object the WeakMap has never seen.
|
||||
const corpusCache = new WeakMap()
|
||||
|
||||
function corpusOf(e) {
|
||||
const v = getVersion()
|
||||
const hit = corpusCache.get(e)
|
||||
if (hit && hit.v === v) return hit.s
|
||||
const sm = Array.isArray(e?.sm) ? e.sm : []
|
||||
const s = normalizeStr([
|
||||
exerciseNameSearchText(e),
|
||||
e?.tg || '', t(e?.tg || ''),
|
||||
e?.eq || '', t(e?.eq || ''),
|
||||
e?.bp || '', t(e?.bp || ''),
|
||||
...sm, ...sm.map(m => t(m)),
|
||||
e?.desc || ''
|
||||
].join(' '))
|
||||
corpusCache.set(e, { v, s })
|
||||
return s
|
||||
}
|
||||
|
||||
export function matchExercise(e, query) {
|
||||
if (!query) return true
|
||||
const tokens = normalizeStr(query).split(/\s+/).filter(Boolean)
|
||||
if (!tokens.length) return true
|
||||
if (!e || typeof e !== 'object') return false
|
||||
const corpus = corpusOf(e)
|
||||
return tokens.every(tok => corpus.includes(tok))
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { matchExercise, normalizeStr } from './exercises.js'
|
||||
import { _setLangState } from './i18n-core.js'
|
||||
|
||||
describe('normalizeStr', () => {
|
||||
it('handles null, undefined and empty strings', () => {
|
||||
expect(normalizeStr(null)).toBe('')
|
||||
expect(normalizeStr(undefined)).toBe('')
|
||||
expect(normalizeStr('')).toBe('')
|
||||
})
|
||||
|
||||
it('lowercases text and removes diacritics / accents', () => {
|
||||
expect(normalizeStr('Elevação Lateral')).toBe('elevacao lateral')
|
||||
expect(normalizeStr('SUPINO INCLINADO COM HALTERES')).toBe('supino inclinado com halteres')
|
||||
expect(normalizeStr('Tríceps & Panturrilhas')).toBe('triceps & panturrilhas')
|
||||
expect(normalizeStr('Quadríceps / Glúteos')).toBe('quadriceps / gluteos')
|
||||
})
|
||||
})
|
||||
|
||||
describe('matchExercise', () => {
|
||||
const benchPress = {
|
||||
id: '0025',
|
||||
n: 'barbell bench press',
|
||||
bp: 'chest',
|
||||
tg: 'pectorals',
|
||||
eq: 'barbell',
|
||||
sm: ['triceps', 'deltoids'],
|
||||
desc: 'Classic chest exercise using a barbell on a flat bench.'
|
||||
}
|
||||
|
||||
const lateralRaise = {
|
||||
id: '0283',
|
||||
n: 'dumbbell lateral raise',
|
||||
bp: 'shoulders',
|
||||
tg: 'delts',
|
||||
eq: 'dumbbell',
|
||||
sm: ['traps'],
|
||||
desc: 'Shoulder isolation movement.'
|
||||
}
|
||||
|
||||
it('returns true for empty or whitespace-only query', () => {
|
||||
expect(matchExercise(benchPress, '')).toBe(true)
|
||||
expect(matchExercise(benchPress, ' ')).toBe(true)
|
||||
expect(matchExercise(benchPress, null)).toBe(true)
|
||||
})
|
||||
|
||||
it('matches exact and partial words in exercise name regardless of case', () => {
|
||||
expect(matchExercise(benchPress, 'bench')).toBe(true)
|
||||
expect(matchExercise(benchPress, 'BENCH')).toBe(true)
|
||||
expect(matchExercise(benchPress, 'barbell')).toBe(true)
|
||||
expect(matchExercise(benchPress, 'press')).toBe(true)
|
||||
expect(matchExercise(benchPress, 'squat')).toBe(false)
|
||||
})
|
||||
|
||||
it('matches multiple tokens in ANY order (not just sequential)', () => {
|
||||
// "bench barbell" is reversed order compared to "barbell bench press"
|
||||
expect(matchExercise(benchPress, 'bench barbell')).toBe(true)
|
||||
expect(matchExercise(benchPress, 'press bench barbell')).toBe(true)
|
||||
expect(matchExercise(benchPress, 'barbell press chest')).toBe(true)
|
||||
expect(matchExercise(benchPress, 'bench squat')).toBe(false)
|
||||
})
|
||||
|
||||
it('matches target muscle, equipment, secondary muscles and description', () => {
|
||||
expect(matchExercise(benchPress, 'pectorals')).toBe(true)
|
||||
expect(matchExercise(benchPress, 'triceps barbell')).toBe(true)
|
||||
expect(matchExercise(benchPress, 'flat bench')).toBe(true)
|
||||
expect(matchExercise(lateralRaise, 'dumbbell shoulder')).toBe(true)
|
||||
})
|
||||
|
||||
it('matches accent-insensitively', () => {
|
||||
const customEx = {
|
||||
id: 'custom-1',
|
||||
n: 'Elevação de Panturrilha',
|
||||
bp: 'lower legs',
|
||||
tg: 'calves',
|
||||
eq: 'body weight',
|
||||
desc: 'Exercício para panturrilhas em pé.'
|
||||
}
|
||||
|
||||
expect(matchExercise(customEx, 'elevacao')).toBe(true)
|
||||
expect(matchExercise(customEx, 'elevação')).toBe(true)
|
||||
expect(matchExercise(customEx, 'panturrilha elevacao')).toBe(true)
|
||||
expect(matchExercise(customEx, 'ELEVACAO PE')).toBe(true)
|
||||
})
|
||||
|
||||
it('matches translated UI terms when a language is active', () => {
|
||||
_setLangState('pt', {
|
||||
chest: 'peito',
|
||||
barbell: 'barra',
|
||||
dumbbell: 'halteres',
|
||||
shoulders: 'ombros'
|
||||
}, null)
|
||||
|
||||
// "peito" is the translated bp, "barra" is the translated eq
|
||||
expect(matchExercise(benchPress, 'peito')).toBe(true)
|
||||
expect(matchExercise(benchPress, 'barra')).toBe(true)
|
||||
expect(matchExercise(benchPress, 'peito barra bench')).toBe(true)
|
||||
expect(matchExercise(lateralRaise, 'halteres ombros')).toBe(true)
|
||||
})
|
||||
|
||||
// The pt-BR exercise-name pack (!16) renames the catalogue in the UI. Searching has to reach
|
||||
// that name as well as the canonical English one, or the library goes dark for pt-BR profiles
|
||||
// the moment they type what they see on screen.
|
||||
it('matches the localized exercise name as well as the English one', () => {
|
||||
_setLangState('pt-BR', {}, null, { '0025': 'supino reto com barra' })
|
||||
|
||||
expect(matchExercise(benchPress, 'supino')).toBe(true)
|
||||
expect(matchExercise(benchPress, 'supino barra')).toBe(true)
|
||||
expect(matchExercise(benchPress, 'bench press')).toBe(true) // English still reaches it
|
||||
expect(matchExercise(lateralRaise, 'supino')).toBe(false) // untranslated entry unaffected
|
||||
})
|
||||
|
||||
it('rebuilds the cached haystack when the language changes', () => {
|
||||
_setLangState('pt-BR', {}, null, { '0025': 'supino reto com barra' })
|
||||
expect(matchExercise(benchPress, 'supino')).toBe(true)
|
||||
|
||||
_setLangState('en', null, null, null)
|
||||
expect(matchExercise(benchPress, 'supino')).toBe(false)
|
||||
expect(matchExercise(benchPress, 'bench')).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -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' }
|
||||
+183
-10
@@ -1,7 +1,7 @@
|
||||
// Pure helpers over the state object S (ported 1:1 from the vanilla app).
|
||||
import { todayISO, isoOf, weekKey, fmtNum } from './format.js'
|
||||
import { isCardio, isBodyweightEq } from './exercises.js'
|
||||
import { phaseForSet, modeForSet, modeForEntry, isWarmupRow, normalizeMode } from './workout-model.js'
|
||||
import { phaseForSet, modeForSet, modeForEntry, isWarmupRow, normalizeMode, extraVolumeOf, nextDropWeight, splitBurstReps } from './workout-model.js'
|
||||
const objectOf = value => value && typeof value === 'object' && !Array.isArray(value) ? value : {}
|
||||
// Completed-state-independent work rows whose authoritative mode matches the requested mode.
|
||||
const workRowsForMode = (entry = {}, mode = 'reps') => {
|
||||
@@ -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
|
||||
@@ -268,7 +303,30 @@ export function nextTrainingDay(S, iso) {
|
||||
}
|
||||
return null
|
||||
}
|
||||
/**
|
||||
* Build the rows a planned exercise starts a session with: its work sets, preceded by however
|
||||
* many warm-up sets the routine asks for (`cfg.warmupSets`, 0 by default so an existing plan
|
||||
* 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)
|
||||
@@ -305,11 +363,58 @@ export function buildSets(S, cfg, options = {}) {
|
||||
}
|
||||
return sets
|
||||
}
|
||||
|
||||
/**
|
||||
* Stamp every work row with the exercise's planned intensifier and pre-fill its drops/clusters,
|
||||
* already computed and editable — the plan designs the set, not a button pressed mid-workout.
|
||||
*
|
||||
* Must run AFTER applyPrescription: a drop-set's chain of drops is a percentage of each row's
|
||||
* own `w`, so it has to be computed from the final prescribed weight, not the pre-progression
|
||||
* one buildSets started from — otherwise a bumped working weight would leave stale, cheaper
|
||||
* drops sitting underneath it.
|
||||
*/
|
||||
export function applyIntensifierPlan(sets, cfg) {
|
||||
const kind = cfg && cfg.intensifier && cfg.intensifier.type
|
||||
if (kind !== 'dropset' && kind !== 'restpause') return sets
|
||||
if (kind === 'dropset') {
|
||||
const count = Math.max(1, Math.round(cfg.intensifier.count) || 1)
|
||||
const pct = cfg.intensifier.pct
|
||||
return sets.map(s => {
|
||||
if (isWarmupRow(s)) return s
|
||||
const drops = []
|
||||
let w = s.w || 0
|
||||
for (let k = 0; k < count; k++) { w = nextDropWeight(w, pct); drops.push({ w, r: s.r }) }
|
||||
return { ...s, type: 'dropset', drops }
|
||||
})
|
||||
}
|
||||
// Rest-pause trains as exactly two sets, not one per configured `sets` count: a warm-up at
|
||||
// the exercise's own configured reps, then a single rest-pause work set. Doing the full
|
||||
// activation+bursts protocol several times over isn't how rest-pause is actually trained, so
|
||||
// planning it replaces whatever buildSets built rather than stamping each of those rows.
|
||||
// The work row's own reps are the total — not "the total minus what the bursts carry" — and
|
||||
// the bursts are the full breakdown of that same total, down to the last one. See
|
||||
// extraVolumeOf/setTonnage: a rest-pause row's `clusters` are read-only display of how `r`
|
||||
// breaks down, not extra volume on top of it, precisely so this doesn't double-count.
|
||||
const restSec = Math.max(5, cfg.intensifier.restSec || 15)
|
||||
const totalReps = Math.max(1, Math.round(cfg.intensifier.totalReps) || 1)
|
||||
const w = (sets.find(s => !isWarmupRow(s)) || sets[0] || {}).w || 0
|
||||
const warmup = { w, r: Math.max(1, Math.round(cfg.reps) || 1), done: false, phase: 'warmup' }
|
||||
const work = { w, r: totalReps, done: false, type: 'restpause', clusters: splitBurstReps(totalReps).map(r => ({ r, restSec })) }
|
||||
return [warmup, work]
|
||||
}
|
||||
export function workoutVolume(w) {
|
||||
let v = 0
|
||||
// No special case for unilateral work: a per-side set logs its total, so both sides are
|
||||
// already in the rep count that arrives here.
|
||||
w.entries.forEach(e => e.sets.forEach(s => { if (s.done) v += (s.w || 0) * (s.r || 0) }))
|
||||
// already in the rep count that arrives here. Drop-set drops and rest-pause bursts add their
|
||||
// own weight x reps on top of the row's main/activation set (see extraVolumeOf).
|
||||
// Warm-ups are excluded here as everywhere else. The config sheet promises it in so many
|
||||
// words ("left out of volume, records and progression") and every other consumer already
|
||||
// does it; this line was the one that did not, which only stopped being harmless when a
|
||||
// routine started planning warm-ups by default. The number is written into the saved
|
||||
// workout, so an inflated one would stay wrong forever.
|
||||
w.entries.forEach(e => e.sets.forEach(s => {
|
||||
if (s.done && !isWarmupRow(s)) v += (s.w || 0) * (s.r || 0) + extraVolumeOf(s)
|
||||
}))
|
||||
return v
|
||||
}
|
||||
export function setsDone(w) {
|
||||
@@ -367,16 +472,84 @@ 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.
|
||||
*/
|
||||
/**
|
||||
* Recompute the warm-up block so it ramps toward the weight the work rows ACTUALLY carry.
|
||||
*
|
||||
* buildSets prepends the warm-ups before a prescription is applied, and applyPrescription
|
||||
* deliberately rewrites work rows only — so without this the ramp still aims at last
|
||||
* session's weight. On a deload that put the last warm-up above every work set, which is
|
||||
* the exact opposite of what a warm-up is for.
|
||||
*
|
||||
* A warm-up already logged keeps its weight and becomes what the next one ramps from: it
|
||||
* happened, and rewriting performed work is data loss. Entries with nothing to ramp toward
|
||||
* — cardio, bodyweight, an unloaded hold — are returned untouched.
|
||||
*/
|
||||
export function rerampWarmups(rows, step = 2.5) {
|
||||
const firstWork = rows.findIndex(x => !isWarmupRow(x))
|
||||
if (firstWork <= 0) return rows
|
||||
const target = rows[firstWork].w || 0
|
||||
if (!(target > 0)) return rows
|
||||
const out = rows.slice()
|
||||
let from = 0
|
||||
for (let i = 0; i < firstWork; i++) {
|
||||
if (out[i].done) { from = out[i].w || 0; continue }
|
||||
const w = target > from
|
||||
? Math.max(0, Math.min(target, Math.floor((from + (target - from) / 2) / step) * step))
|
||||
: target
|
||||
out[i] = { ...out[i], w }
|
||||
from = w
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
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
|
||||
// Nothing to ramp toward: bodyweight, cardio, a timed hold with no load.
|
||||
if (!(to > 0)) return 0
|
||||
// Already at or past the work weight — which happens when a warm-up was edited by hand
|
||||
// above it. Returning `from` here handed the next warm-up that same too-heavy number and
|
||||
// let it propagate down the block. A warm-up is never heavier than the set it warms up for.
|
||||
if (to <= from) return to
|
||||
// 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 { nextTrainingDay, modeOf, isTimed, fmtSec, setLabel, defaultConfig, buildSets, freestyleConfig, exLine, workoutVolume, bestWeightFor, bestWeightForEntry, effortOf, stepEffort, capEffort, isBw, isPerSide, sideReps, repStep, cascadeWeight, insertWarmupRow, removeRowAt, workSetsDone, pairAdjacent, unpairSuperset, supersetUnits } from './history.js'
|
||||
import { nextTrainingDay, modeOf, isTimed, fmtSec, setLabel, defaultConfig, buildSets, freestyleConfig, exLine, workoutVolume, bestWeightFor, bestWeightForEntry, effortOf, stepEffort, capEffort, isBw, isPerSide, sideReps, repStep, cascadeWeight, insertWarmupRow, removeRowAt, workSetsDone, pairAdjacent, unpairSuperset, supersetUnits, applyIntensifierPlan, pinnedNoteFor, exNoteFor } from './history.js'
|
||||
import { EXDB } from './exercises.js'
|
||||
|
||||
// Real ids out of the shipped catalogue, so the body-part fallback is exercised for real.
|
||||
@@ -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: {},
|
||||
@@ -456,6 +492,55 @@ describe('buildSets', () => {
|
||||
expect(buildSets(S, { id: LIFT, sets: 2, reps: 8, weight: 50 }, { preferLast: true }))
|
||||
.toEqual([{ w: 60, r: 10, done: false }, { w: 62.5, r: 8, done: false }])
|
||||
})
|
||||
|
||||
})
|
||||
|
||||
describe('applyIntensifierPlan', () => {
|
||||
it('pre-fills every work row with a chain of drops, each pct% lighter than the one before', () => {
|
||||
const sets = [{ w: 100, r: 8, done: false }, { w: 100, r: 8, done: false }]
|
||||
const out = applyIntensifierPlan(sets, { intensifier: { type: 'dropset', count: 2, pct: 20 } })
|
||||
expect(out).toEqual([
|
||||
{ w: 100, r: 8, done: false, type: 'dropset', drops: [{ w: 80, r: 8 }, { w: 64, r: 8 }] },
|
||||
{ w: 100, r: 8, done: false, type: 'dropset', drops: [{ w: 80, r: 8 }, { w: 64, r: 8 }] },
|
||||
])
|
||||
})
|
||||
|
||||
it('collapses rest-pause to exactly two rows regardless of how many sets were configured: a warm-up at the exercise\'s own reps, then one work set whose own reps ARE the total', () => {
|
||||
const sets = [{ w: 60, r: 8, done: false }, { w: 60, r: 8, done: false }, { w: 60, r: 8, done: false }]
|
||||
const out = applyIntensifierPlan(sets, { reps: 8, intensifier: { type: 'restpause', totalReps: 12, restSec: 15 } })
|
||||
expect(out).toEqual([
|
||||
{ w: 60, r: 8, done: false, phase: 'warmup' },
|
||||
{ w: 60, r: 12, done: false, type: 'restpause', clusters: [{ r: 6, restSec: 15 }, { r: 3, restSec: 15 }, { r: 2, restSec: 15 }, { r: 1, restSec: 15 }] },
|
||||
])
|
||||
// the full breakdown always sums back to the row's own r — no reps missing, none double-counted
|
||||
expect(out[1].clusters.reduce((sum, c) => sum + c.r, 0)).toBe(out[1].r)
|
||||
})
|
||||
|
||||
it('the warm-up reps come from the exercise\'s own configured reps, not the rest-pause total', () => {
|
||||
const sets = [{ w: 60, r: 8, done: false }]
|
||||
const out = applyIntensifierPlan(sets, { reps: 5, intensifier: { type: 'restpause', totalReps: 20, restSec: 15 } })
|
||||
expect(out[0]).toEqual({ w: 60, r: 5, done: false, phase: 'warmup' })
|
||||
})
|
||||
|
||||
it('carries the prescribed weight from the built sets onto both new rows', () => {
|
||||
const sets = [{ w: 82.5, r: 8, done: false }]
|
||||
const out = applyIntensifierPlan(sets, { reps: 8, intensifier: { type: 'restpause', totalReps: 4, restSec: 15 } })
|
||||
expect(out[0].w).toBe(82.5)
|
||||
expect(out[1].w).toBe(82.5)
|
||||
})
|
||||
|
||||
it('never touches a warm-up row', () => {
|
||||
const sets = [{ w: 20, r: 8, done: false, phase: 'warmup' }, { w: 100, r: 8, done: false }]
|
||||
const out = applyIntensifierPlan(sets, { intensifier: { type: 'dropset', count: 1, pct: 20 } })
|
||||
expect(out[0]).toEqual({ w: 20, r: 8, done: false, phase: 'warmup' })
|
||||
expect(out[1].type).toBe('dropset')
|
||||
})
|
||||
|
||||
it('leaves sets untouched with no intensifier configured', () => {
|
||||
const sets = [{ w: 100, r: 8, done: false }]
|
||||
expect(applyIntensifierPlan(sets, {})).toBe(sets)
|
||||
expect(applyIntensifierPlan(sets, { intensifier: { type: 'nonsense' } })).toBe(sets)
|
||||
})
|
||||
})
|
||||
|
||||
describe('workoutVolume', () => {
|
||||
@@ -473,6 +558,21 @@ describe('workoutVolume', () => {
|
||||
expect(workoutVolume(w)).toBe(320)
|
||||
})
|
||||
|
||||
it('adds drop-set drops on top of the row\'s main set', () => {
|
||||
const dropRow = { type: 'dropset', w: 100, r: 5, done: true, drops: [{ w: 80, r: 5 }, { w: 60, r: 5 }] }
|
||||
expect(workoutVolume({ entries: [{ id: LIFT, sets: [dropRow] }] })).toBe(100 * 5 + 80 * 5 + 60 * 5)
|
||||
})
|
||||
|
||||
it('counts a rest-pause row once — its own r is already the total across every burst', () => {
|
||||
const burstRow = { type: 'restpause', w: 60, r: 20, done: true, clusters: [{ r: 10, restSec: 15 }, { r: 5, restSec: 15 }, { r: 3, restSec: 15 }, { r: 1, restSec: 15 }, { r: 1, restSec: 15 }] }
|
||||
expect(workoutVolume({ entries: [{ id: LIFT, sets: [burstRow] }] })).toBe(60 * 20)
|
||||
})
|
||||
|
||||
it('ignores drops/bursts on a row that was never checked off', () => {
|
||||
const dropRow = { type: 'dropset', w: 100, r: 5, done: false, drops: [{ w: 80, r: 5 }] }
|
||||
expect(workoutVolume({ entries: [{ id: LIFT, sets: [dropRow] }] })).toBe(0)
|
||||
})
|
||||
|
||||
it('leaves an unloaded bodyweight set at zero volume rather than inventing a number', () => {
|
||||
const w = { entries: [{ id: BW, target: { bodyweight: true }, sets: [{ w: 0, r: 20, done: true }] }] }
|
||||
expect(workoutVolume(w)).toBe(0)
|
||||
@@ -641,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 }]
|
||||
@@ -734,3 +863,35 @@ describe('nextTrainingDay', () => {
|
||||
expect(nextTrainingDay(off, TUE)).toMatchObject({ weekday: 5 })
|
||||
})
|
||||
})
|
||||
|
||||
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()
|
||||
})
|
||||
})
|
||||
@@ -1,21 +1,25 @@
|
||||
// Runtime-agnostic core of the i18n module: state, constants and readers (t, dateLocale,
|
||||
// instrFor, getLang). Plain Node-loadable — the browser-only pieces (import.meta.glob lazy
|
||||
// instrFor, exerciseNameFor, getLang). Plain Node-loadable — the browser-only pieces
|
||||
// (import.meta.glob lazy
|
||||
// loads, the React subscription hook) live in i18n.js and re-export from here.
|
||||
|
||||
export const LANGS = {
|
||||
en: 'English', de: 'Deutsch', es: 'Español', fr: 'Français', it: 'Italiano',
|
||||
pt: 'Português', pl: 'Polski', tr: 'Türkçe', ru: 'Русский', zh: '中文',
|
||||
pt: 'Português (Portugal)', 'pt-BR': 'Português (Brasil)', pl: 'Polski',
|
||||
tr: 'Türkçe', ru: 'Русский', zh: '中文',
|
||||
ko: '한국어', hi: 'हिन्दी'
|
||||
}
|
||||
export const INSTR_LANGS = ['en', 'es', 'fr', 'it', 'tr', 'ru', 'zh', 'hi', 'pl', 'ko']
|
||||
export const INSTR_LANGS = ['en', 'es', 'fr', 'it', 'tr', 'ru', 'zh', 'hi', 'pl', 'ko', 'pt-BR']
|
||||
export const EXERCISE_NAME_LANGS = ['pt-BR']
|
||||
export const DATE_LOCALES = {
|
||||
en: 'en-GB', de: 'de-DE', es: 'es-ES', fr: 'fr-FR', it: 'it-IT', pt: 'pt-PT',
|
||||
en: 'en-GB', de: 'de-DE', es: 'es-ES', fr: 'fr-FR', it: 'it-IT', pt: 'pt-PT', 'pt-BR': 'pt-BR',
|
||||
pl: 'pl-PL', tr: 'tr-TR', ru: 'ru-RU', zh: 'zh-CN', ko: 'ko-KR', hi: 'hi-IN'
|
||||
}
|
||||
|
||||
let lang = 'en' // set only by _setLangState, called from i18n.js setLang
|
||||
let dict = {} // current locale pack (empty = English fallback)
|
||||
let instr = null // { exId: [steps] } for the current language, null = English
|
||||
let exerciseNames = null // { exId: translated name }, null = original catalogue name
|
||||
let version = 0 // bumped on every setLang; drives the React subscription selector
|
||||
|
||||
export const getLang = () => lang
|
||||
@@ -32,13 +36,32 @@ export function t(s, ...args) {
|
||||
// Instructions for an exercise in the current language (English steps as fallback).
|
||||
export const instrFor = ex => (instr && instr[ex.id]) || ex.st || []
|
||||
|
||||
// Built-in catalogue names are bilingual when a complete translated name pack is active.
|
||||
// User-created exercises have no entry in the pack and keep their exact chosen name.
|
||||
export const exerciseNameFor = ex => {
|
||||
const translated = exerciseNames && ex && exerciseNames[ex.id]
|
||||
if (!translated) return ex?.n || ''
|
||||
// Some names (Burpee, Pilates, brand/model terms) are the established pt-BR term too.
|
||||
// Repeating an identical loanword in parentheses adds noise rather than context.
|
||||
return translated.toLocaleLowerCase('pt-BR') === ex.n.toLocaleLowerCase('en')
|
||||
? translated
|
||||
: `${translated} (${ex.n})`
|
||||
}
|
||||
|
||||
// Search both the localized and canonical English title without changing persisted data.
|
||||
export const exerciseNameSearchText = ex => {
|
||||
const translated = exerciseNames && ex && exerciseNames[ex.id]
|
||||
return translated ? `${translated} ${ex.n}` : (ex?.n || '')
|
||||
}
|
||||
|
||||
// Called by i18n.js's setLang once the locale pack has been loaded — kept here rather than
|
||||
// exported as setLang because loading packs requires import.meta.glob, which is Vite-only.
|
||||
// Both `dict` and `instr` may be null to reset to English.
|
||||
export function _setLangState(newLang, newDict, newInstr) {
|
||||
// `dict`, `instr` and `exerciseNames` may be null to reset to their English fallbacks.
|
||||
export function _setLangState(newLang, newDict, newInstr, newExerciseNames) {
|
||||
lang = LANGS[newLang] ? newLang : 'en'
|
||||
dict = lang === 'en' ? {} : (newDict || {})
|
||||
instr = lang === 'en' || !INSTR_LANGS.includes(lang) ? null : (newInstr || null)
|
||||
exerciseNames = lang === 'en' || !EXERCISE_NAME_LANGS.includes(lang) ? null : (newExerciseNames || null)
|
||||
version++
|
||||
return version
|
||||
}
|
||||
+17
-10
@@ -5,16 +5,20 @@
|
||||
|
||||
import { useSyncExternalStore } from 'react'
|
||||
import {
|
||||
LANGS, INSTR_LANGS, DATE_LOCALES,
|
||||
getLang, dateLocale, t, instrFor, getVersion, _setLangState
|
||||
LANGS, INSTR_LANGS, EXERCISE_NAME_LANGS, DATE_LOCALES,
|
||||
getLang, dateLocale, t, instrFor, exerciseNameFor, exerciseNameSearchText, getVersion, _setLangState
|
||||
} from './i18n-core.js'
|
||||
|
||||
export { LANGS, INSTR_LANGS, DATE_LOCALES, getLang, dateLocale, t, instrFor }
|
||||
export {
|
||||
LANGS, INSTR_LANGS, EXERCISE_NAME_LANGS, DATE_LOCALES,
|
||||
getLang, dateLocale, t, instrFor, exerciseNameFor, exerciseNameSearchText
|
||||
}
|
||||
|
||||
// Vite code-splits each locale pack into its own chunk via import.meta.glob; instructions use
|
||||
// the same mechanism in src/instr/. Both are lazy, so the production bundle ships English only.
|
||||
// Vite code-splits locale, instruction and exercise-name packs via import.meta.glob. They are
|
||||
// lazy, so the production bundle ships English only until another language is selected.
|
||||
const localePacks = import.meta.glob('../locales/*.js')
|
||||
const instrPacks = import.meta.glob('../instr/*.js')
|
||||
const exerciseNamePacks = import.meta.glob('../exercise-names/*.js')
|
||||
|
||||
// React subscription bookkeeping — kept here, not in core, so core has zero React coupling.
|
||||
const subs = new Set()
|
||||
@@ -23,12 +27,15 @@ const notify = () => { subs.forEach(f => f()) }
|
||||
export async function setLang(l) {
|
||||
if (!LANGS[l]) l = 'en'
|
||||
if (l === getLang() && getVersion() > 0) return
|
||||
let dict = {}, instr = null
|
||||
let dict = {}, instr = null, exerciseNames = null
|
||||
try { dict = l === 'en' ? {} : (await localePacks['../locales/' + l + '.js']()).default } catch (e) { dict = {} }
|
||||
try { instr = l === 'en' || !INSTR_LANGS.includes(l) ? null : (await instrPacks['../instr/' + l + '.js']()).default } catch (e) { instr = null }
|
||||
try {
|
||||
dict = l === 'en' ? {} : (await localePacks['../locales/' + l + '.js']()).default
|
||||
instr = l === 'en' || !INSTR_LANGS.includes(l) ? null : (await instrPacks['../instr/' + l + '.js']()).default
|
||||
} catch (e) { dict = {}; instr = null }
|
||||
_setLangState(l, dict, instr)
|
||||
exerciseNames = l === 'en' || !EXERCISE_NAME_LANGS.includes(l)
|
||||
? null
|
||||
: (await exerciseNamePacks['../exercise-names/' + l + '.js']()).default
|
||||
} catch (e) { exerciseNames = null }
|
||||
_setLangState(l, dict, instr, exerciseNames)
|
||||
notify()
|
||||
}
|
||||
|
||||
|
||||
@@ -58,9 +58,9 @@ const norm = h => h.toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim()
|
||||
const COLUMNS = [
|
||||
['exercise', ['exercise', 'exercise name', 'exercise title']],
|
||||
['date', ['date', 'workout date']],
|
||||
['startTime', ['start time']],
|
||||
['startTime', ['start time', 'start date']],
|
||||
['endTime', ['end time']],
|
||||
['workoutName', ['workout name', 'title']],
|
||||
['workoutName', ['workout name', 'title', 'workout']],
|
||||
['category', ['category', 'body part', 'muscle group']],
|
||||
['weightKg', ['weight kg']],
|
||||
['weightLb', ['weight lbs', 'weight lb']],
|
||||
@@ -74,10 +74,10 @@ const COLUMNS = [
|
||||
['distanceKm', ['distance km']],
|
||||
['distance', ['distance']],
|
||||
['distanceUnit', ['distance unit']],
|
||||
['seconds', ['seconds', 'duration seconds']],
|
||||
['seconds', ['seconds', 'duration seconds', 'set duration sec']],
|
||||
['time', ['time', 'duration']],
|
||||
['setType', ['set type']],
|
||||
['note', ['comment', 'comments', 'notes', 'note']],
|
||||
['note', ['comment', 'comments', 'notes', 'note', 'workout notes']],
|
||||
]
|
||||
|
||||
function mapHeader(header) {
|
||||
@@ -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',
|
||||
@@ -258,10 +296,10 @@ const LB_TO_KG = 0.45359237
|
||||
const p2 = n => String(n).padStart(2, '0')
|
||||
const MON = { jan: 1, feb: 2, mar: 3, apr: 4, may: 5, jun: 6, jul: 7, aug: 8, sep: 9, oct: 10, nov: 11, dec: 12 }
|
||||
|
||||
/** "2020-12-30 18:51:52" · "2024-03-07" · "22 Dec 2025, 08:00" · "07/03/2024" -> { d, t } */
|
||||
/** "2020-12-30 18:51:52" · "2024-03-07" · "2024/03/07" · "2024.03.07" · "22 Dec 2025, 08:00" · "07/03/2024" -> { d, t } */
|
||||
export function parseWhen(s) {
|
||||
const v = String(s || '').trim()
|
||||
let m = v.match(/^(\d{4})-(\d{1,2})-(\d{1,2})(?:[T ](\d{1,2}):(\d{2}))?/)
|
||||
let m = v.match(/^(\d{4})[-/.](\d{1,2})[-/.](\d{1,2})(?:[T ](\d{1,2}):(\d{2}))?/)
|
||||
if (m) return { d: `${m[1]}-${p2(m[2])}-${p2(m[3])}`, t: hm(m[4], m[5]) }
|
||||
m = v.match(/^(\d{1,2})\s+([A-Za-z]{3})[a-z]*\.?\s+(\d{4})(?:,?\s+(\d{1,2}):(\d{2}))?/)
|
||||
if (m && MON[m[2].toLowerCase()]) return { d: `${m[3]}-${p2(MON[m[2].toLowerCase()])}-${p2(m[1])}`, t: hm(m[4], m[5]) }
|
||||
@@ -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)
|
||||
|
||||
@@ -4,7 +4,9 @@ import { parseWorkoutCSV } from './import-csv.js'
|
||||
const CSV = [
|
||||
'Date,Exercise,Weight,Reps,Set Type',
|
||||
'2026-08-08,Bench Press,100,5,Warm-up',
|
||||
'2026-08-08,Bench Press,80,5,Working',
|
||||
'2026.08.08,Bench Press,80,5,Working',
|
||||
'8 Aug 2026,Bench Press,80,5,Working',
|
||||
'2026/08/08,Bench Press,85,3,Working',
|
||||
].join('\n')
|
||||
|
||||
describe('CSV warm-up provenance', () => {
|
||||
@@ -16,7 +18,35 @@ describe('CSV warm-up provenance', () => {
|
||||
expect(entry.sets).toEqual([
|
||||
{ w: 100, r: 5, done: true, phase: 'warmup' },
|
||||
{ w: 80, r: 5, done: true },
|
||||
{ w: 80, r: 5, done: true },
|
||||
{ w: 85, r: 3, done: true },
|
||||
])
|
||||
expect(entry.topW).toBe(80)
|
||||
expect(entry.topW).toBe(85)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
// gravl writes its units in parentheses ("Weight (kg)", "Set Duration (sec)"). Header text is
|
||||
// normalised before it is matched, so the alias table has to hold the normalised form — an alias
|
||||
// written with the parentheses can never match. Sample rows are from the gravl export in !21.
|
||||
const GRAVL = [
|
||||
'Date,Start Date,Workout,Source,Workout Duration (min),Energy,Exercise,Superset,Set,Set Type,Reps,Weight (kg),Distance (km),Set Duration (sec),Incline,Steps,Effort,Workout Notes',
|
||||
'2026/01/01,1:11 PM,Push Day,,11,11,Chin Up,No,1,Normal,11,11,0,,,,Ideal,felt strong',
|
||||
'2026/01/22,2:22 PM,External Something,APP,21,22,Walking,No,0,Normal,0,0,0,22,,,,',
|
||||
].join('\n')
|
||||
|
||||
describe('gravl export', () => {
|
||||
it('reads slash dates, parenthesised weight and per-set duration', () => {
|
||||
const parsed = parseWorkoutCSV(GRAVL, { unit: 'kg' })
|
||||
|
||||
expect(parsed.skipped).toBe(0)
|
||||
expect(parsed.from).toBe('2026-01-01')
|
||||
expect(parsed.to).toBe('2026-01-22')
|
||||
|
||||
const [lift, cardio] = parsed.workouts
|
||||
expect(lift.name).toBe('Push Day')
|
||||
expect(lift.entries[0].sets).toEqual([{ w: 11, r: 11, done: true }])
|
||||
|
||||
// "Set Duration (sec)" is seconds, not minutes: read as `time` it would land as 22 minutes.
|
||||
expect(cardio.entries[0].sets).toEqual([{ min: 0.4, speed: 0, done: true }])
|
||||
})
|
||||
})
|
||||
@@ -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')
|
||||
})
|
||||
})
|
||||
@@ -10,6 +10,7 @@
|
||||
// Like the demo build, MOBILE is replaced at build time, so all of this folds away in
|
||||
// web bundles; the Capacitor plugins are only ever imported behind it.
|
||||
import { t } from './i18n-core.js'
|
||||
import { todayISO } from './format.js'
|
||||
|
||||
export const MOBILE = import.meta.env.VITE_MOBILE === '1'
|
||||
|
||||
@@ -30,6 +31,27 @@ export async function nativeSave(state) {
|
||||
} catch (e) { /* keep the localStorage copy */ }
|
||||
}
|
||||
|
||||
// "Connect to my server" mode (lib/remote.js): which of local-only / a paired remote account this
|
||||
// device chose, kept in its own file — never inside opengym-state.json, since that file's content
|
||||
// is exactly what pushState() PUTs to a server, and a device's own connection secret must never
|
||||
// travel as if it were training data.
|
||||
const REMOTE_FILE = 'opengym-remote.json'
|
||||
|
||||
export async function loadRemoteFile() {
|
||||
try {
|
||||
const { Filesystem, Directory, Encoding } = await import('@capacitor/filesystem')
|
||||
const r = await Filesystem.readFile({ path: REMOTE_FILE, directory: Directory.Data, encoding: Encoding.UTF8 })
|
||||
return JSON.parse(r.data)
|
||||
} catch (e) { return null } // never decided yet
|
||||
}
|
||||
|
||||
export async function saveRemoteFile(data) {
|
||||
try {
|
||||
const { Filesystem, Directory, Encoding } = await import('@capacitor/filesystem')
|
||||
await Filesystem.writeFile({ path: REMOTE_FILE, directory: Directory.Data, data: JSON.stringify(data), encoding: Encoding.UTF8 })
|
||||
} catch (e) { /* worst case: onboarding asks again next launch */ }
|
||||
}
|
||||
|
||||
// (Re)schedule the workout-day reminder: one repeating notification per weekday that has a
|
||||
// routine in the weekly plan. Cheap enough to run after any state change — the plan or the
|
||||
// reminder time may just have been edited. `interactive` gates the OS permission prompt to
|
||||
@@ -66,3 +88,20 @@ export async function shareExport(json, filename) {
|
||||
const w = await Filesystem.writeFile({ path: filename, directory: Directory.Cache, data: json, encoding: Encoding.UTF8 })
|
||||
await Share.share({ title: filename, url: w.uri })
|
||||
}
|
||||
|
||||
// "Auto-backup on changes" (Settings): a dated snapshot dropped into the Documents folder —
|
||||
// visible in Files (iOS) / a file manager (Android), unlike the private mirror nativeSave keeps
|
||||
// — so whatever the user points at that folder (a sync app, a manual copy) always has something
|
||||
// recent. One file per day; later triggers the same day just overwrite it.
|
||||
export async function writeAutoBackup(state) {
|
||||
try {
|
||||
const { Filesystem, Directory, Encoding } = await import('@capacitor/filesystem')
|
||||
await Filesystem.writeFile({
|
||||
path: `opengym-backup-${todayISO()}.json`,
|
||||
directory: Directory.Documents,
|
||||
data: JSON.stringify(state),
|
||||
encoding: Encoding.UTF8,
|
||||
recursive: true,
|
||||
})
|
||||
} catch (e) { /* best effort — the private mirror in Directory.Data still has the data */ }
|
||||
}
|
||||
+63
-15
@@ -65,6 +65,7 @@ const BY_BODYPART = {
|
||||
'upper legs': { quadriceps: 0.4, hamstring: 0.35, gluteal: 0.25 },
|
||||
'lower legs': { calves: 0.8, tibialis: 0.2 },
|
||||
neck: { trapezius: 1 },
|
||||
'full body': { chest: 0.2, 'upper-back': 0.2, gluteal: 0.2, quadriceps: 0.2, hamstring: 0.1, abs: 0.1 },
|
||||
cardio: {},
|
||||
}
|
||||
|
||||
@@ -72,18 +73,40 @@ const SECONDARY = 0.4 // a supporting muscle counts this much against a primar
|
||||
|
||||
const arrayOf = value => Array.isArray(value) ? value : value == null || value === '' ? [] : [value]
|
||||
|
||||
function firstPresent(object, keys) {
|
||||
if (!object || typeof object !== 'object') return null
|
||||
for (const key of keys) {
|
||||
if (Object.prototype.hasOwnProperty.call(object, key)) return object[key]
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
// Completed history entries may retain a nested snapshot after their custom exercise is
|
||||
// deleted from the profile catalogue. Prefer that snapshot when the outer entry has no muscle
|
||||
// metadata of its own, while keeping direct/legacy entry fields authoritative when present.
|
||||
function metadataOf(ex) {
|
||||
if (!ex || typeof ex !== 'object') return ex
|
||||
const hasDirect = ['muscleGroups', 'muscles', 'targetMuscles'].some(key => Object.prototype.hasOwnProperty.call(ex, key))
|
||||
const DIRECT_KEYS = [
|
||||
'muscleGroups', 'muscles', 'targetMuscles', 'muscleWeights',
|
||||
'primaries', 'primaryMuscles', 'primary', 'secondaries', 'secondaryMuscles', 'secondary',
|
||||
]
|
||||
const hasDirect = DIRECT_KEYS.some(key => Object.prototype.hasOwnProperty.call(ex, key))
|
||||
|| [ex.tg, ex.mg, ...arrayOf(ex.sm)].some(value => value != null && value !== '')
|
||||
return !hasDirect && ex.muscleSnapshot && typeof ex.muscleSnapshot === 'object' && !Array.isArray(ex.muscleSnapshot)
|
||||
? ex.muscleSnapshot
|
||||
: ex
|
||||
}
|
||||
|
||||
function explicitPartsOf(ex) {
|
||||
if (!ex || typeof ex !== 'object') return null
|
||||
const primary = firstPresent(ex, ['primaries', 'primaryMuscles', 'primary'])
|
||||
const secondary = firstPresent(ex, ['secondaries', 'secondaryMuscles', 'secondary'])
|
||||
if (primary !== null || secondary !== null) return {
|
||||
primary: arrayOf(primary), secondary: arrayOf(secondary)
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function explicitGroupsOf(ex) {
|
||||
if (!ex || typeof ex !== 'object') return null
|
||||
if (Object.prototype.hasOwnProperty.call(ex, 'muscleGroups')) {
|
||||
@@ -102,12 +125,14 @@ function explicitGroupsOf(ex) {
|
||||
}
|
||||
|
||||
/** True only when the catalogue explicitly supplied muscle groups, not a body-part fallback. */
|
||||
export function hasExplicitMuscleMetadata(ex) {
|
||||
const source = metadataOf(ex)
|
||||
if (!source || typeof source !== 'object') return false
|
||||
const groups = explicitGroupsOf(source)
|
||||
export function hasExplicitMuscleMetadata(entry) {
|
||||
const ex = metadataOf(entry)
|
||||
if (!ex || typeof ex !== 'object') return false
|
||||
const parts = explicitPartsOf(ex)
|
||||
if (parts && [...parts.primary, ...parts.secondary].some(value => canonicalMuscle(value))) return true
|
||||
const groups = explicitGroupsOf(ex)
|
||||
if (groups && groups.some(value => canonicalMuscle(value))) return true
|
||||
return [source.tg, source.mg, ...arrayOf(source.sm)].some(value => canonicalMuscle(value))
|
||||
return [ex.tg, ex.mg, ...arrayOf(smOf(ex))].some(value => canonicalMuscle(value))
|
||||
}
|
||||
|
||||
function canonicalMuscle(value) {
|
||||
@@ -116,17 +141,28 @@ function canonicalMuscle(value) {
|
||||
return ALIAS[name] || null
|
||||
}
|
||||
|
||||
/** Canonical unique muscle groups, accepting both new arrays and legacy single fields. */
|
||||
export function muscleGroupsOf(ex) {
|
||||
const sourceEx = metadataOf(ex)
|
||||
const explicit = explicitGroupsOf(sourceEx)
|
||||
const source = explicit || [sourceEx?.tg, sourceEx?.mg, ...arrayOf(smOf(sourceEx))]
|
||||
function canonicalUnique(values) {
|
||||
const out = []
|
||||
source.forEach(value => {
|
||||
for (const value of values || []) {
|
||||
const slug = canonicalMuscle(value)
|
||||
if (slug && !out.includes(slug)) out.push(slug)
|
||||
})
|
||||
if (!out.length && explicit == null) Object.keys(BY_BODYPART[sourceEx?.bp] || {}).forEach(slug => { if (!out.includes(slug)) out.push(slug) })
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** Canonical unique muscle groups, accepting new primary/secondary arrays and legacy fields. */
|
||||
export function muscleGroupsOf(entry) {
|
||||
const ex = metadataOf(entry)
|
||||
const parts = explicitPartsOf(ex)
|
||||
const explicit = explicitGroupsOf(ex)
|
||||
const useParts = parts && [...parts.primary, ...parts.secondary].some(value => canonicalMuscle(value))
|
||||
const source = useParts
|
||||
? [...parts.primary, ...parts.secondary]
|
||||
: explicit || [ex?.tg, ex?.mg, ...arrayOf(smOf(ex))]
|
||||
const out = canonicalUnique(source)
|
||||
if (!out.length && !useParts && explicit == null) {
|
||||
canonicalUnique(Object.keys(BY_BODYPART[ex?.bp] || {})).forEach(slug => out.push(slug))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
@@ -158,8 +194,13 @@ export function musclesOf(ex) {
|
||||
const slug = canonicalMuscle(name)
|
||||
if (slug) out[slug] = Math.max(out[slug] || 0, w)
|
||||
}
|
||||
const parts = explicitPartsOf(ex)
|
||||
const explicit = explicitGroupsOf(ex)
|
||||
if (explicit) explicit.forEach(m => add(m, 1))
|
||||
const useParts = parts && [...parts.primary, ...parts.secondary].some(value => canonicalMuscle(value))
|
||||
if (useParts) {
|
||||
parts.primary.forEach(m => add(m, 1))
|
||||
parts.secondary.forEach(m => add(m, SECONDARY))
|
||||
} else if (explicit) explicit.forEach(m => add(m, 1))
|
||||
else {
|
||||
add(ex.tg, 1)
|
||||
add(ex.mg, SECONDARY)
|
||||
@@ -178,6 +219,13 @@ export function exerciseMuscleSnapshot(ex) {
|
||||
if (ex.bp != null) out.bp = ex.bp
|
||||
const weights = musclesOf(ex)
|
||||
if (Object.keys(weights).length) out.muscleWeights = { ...weights }
|
||||
const parts = explicitPartsOf(ex)
|
||||
if (parts) {
|
||||
const primaries = canonicalUnique(parts.primary)
|
||||
const secondaries = canonicalUnique(parts.secondary).filter(slug => !primaries.includes(slug))
|
||||
if (primaries.length) out.primaries = primaries
|
||||
if (secondaries.length) out.secondaries = secondaries
|
||||
}
|
||||
if (hasExplicitMuscleMetadata(ex)) out.muscleGroups = [...muscleGroupsOf(ex)]
|
||||
return out
|
||||
}
|
||||
|
||||
@@ -1,9 +1,45 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { EXIDX, EXDB, smOf } from './exercises.js'
|
||||
import { loadOfWorkouts, musclesOf } from './muscles.js'
|
||||
import { MUSCLE_NAME, exerciseMuscleSnapshot, hasExplicitMuscleMetadata, loadOf, loadOfWorkouts, matchesMuscleGroups, muscleGroupsOf, musclesOf } from './muscles.js'
|
||||
|
||||
describe('multi-muscle exercise metadata', () => {
|
||||
it('normalizes legacy primary/secondary fields and removes duplicate groups', () => {
|
||||
const ex = { tg: 'pectorals', mg: 'triceps', sm: ['triceps', 'chest'] }
|
||||
expect(muscleGroupsOf(ex)).toEqual(['chest', 'triceps'])
|
||||
expect(musclesOf(ex)).toEqual({ chest: 1, triceps: 0.4 })
|
||||
})
|
||||
|
||||
it('uses explicit multi-group metadata when present and supports legacy single groups', () => {
|
||||
expect(muscleGroupsOf({ muscleGroups: ['chest', 'pectorals', 'triceps'] })).toEqual(['chest', 'triceps'])
|
||||
expect(muscleGroupsOf({ tg: 'chest' })).toEqual(['chest'])
|
||||
expect(MUSCLE_NAME.chest).toBe('Chest')
|
||||
})
|
||||
|
||||
it('falls back to the legacy body-part map when an optional multi-group field is empty', () => {
|
||||
expect(muscleGroupsOf({ bp: 'back', muscleGroups: [] })).toEqual(['upper-back', 'lower-back'])
|
||||
expect(matchesMuscleGroups({ bp: 'back', muscleGroups: [] }, ['lower-back'])).toBe(true)
|
||||
})
|
||||
|
||||
it('matches an exercise when any requested muscle group matches', () => {
|
||||
const ex = { muscleGroups: ['chest', 'triceps'] }
|
||||
expect(matchesMuscleGroups(ex, ['hamstring', 'triceps'])).toBe(true)
|
||||
expect(matchesMuscleGroups(ex, ['hamstring', 'gluteal'])).toBe(false)
|
||||
expect(matchesMuscleGroups(ex, [])).toBe(true)
|
||||
})
|
||||
|
||||
it('counts one effective set per unique group instead of double counting duplicates', () => {
|
||||
expect(loadOf([{ id: 'inline', ex: { tg: 'chest', sm: ['chest', 'triceps'] }, sets: 2 }]))
|
||||
.toEqual({ chest: 2, triceps: 0.8 })
|
||||
})
|
||||
|
||||
it('uses multi-muscle metadata carried by a history entry when its catalogue id is unavailable', () => {
|
||||
expect(loadOfWorkouts([{ entries: [{
|
||||
id: 'deleted-custom', muscleGroups: ['chest', 'chest', 'triceps'],
|
||||
sets: [{ done: true }]
|
||||
}] }])).toEqual({ chest: 1, triceps: 1 })
|
||||
})
|
||||
})
|
||||
|
||||
// The catalogue keeps the source dataset's secondary-muscle spellings; musclesOf maps
|
||||
// those aliases to the canonical body-map slugs and applies the 0.4 support weight.
|
||||
describe('catalogue secondary muscles', () => {
|
||||
it('maps a bench press to chest, triceps and deltoids', () => {
|
||||
expect(musclesOf(EXIDX['0025'])).toMatchObject({
|
||||
@@ -16,7 +52,7 @@ describe('catalogue secondary muscles', () => {
|
||||
it('maps a squat to glutes, quads and hamstrings', () => {
|
||||
expect(musclesOf(EXIDX['0043'])).toMatchObject({
|
||||
gluteal: 1,
|
||||
quadriceps: 0.4,
|
||||
quadriceps: 1,
|
||||
hamstring: 0.4,
|
||||
})
|
||||
})
|
||||
@@ -44,6 +80,46 @@ describe('catalogue secondary additions', () => {
|
||||
})
|
||||
|
||||
|
||||
describe('explicit multi-primary metadata', () => {
|
||||
it('gives every primary full weight and secondaries supporting weight', () => {
|
||||
const ex = {
|
||||
bp: 'chest', tg: 'abs', mg: 'triceps', sm: ['lower back'],
|
||||
primaries: ['chest', 'triceps', 'chest'], secondaries: ['deltoids', 'triceps']
|
||||
}
|
||||
expect(muscleGroupsOf(ex)).toEqual(['chest', 'triceps', 'deltoids'])
|
||||
expect(musclesOf(ex)).toEqual({ chest: 1, triceps: 1, deltoids: 0.4 })
|
||||
})
|
||||
|
||||
it('keeps the body-part fallback when primaries are absent or explicitly empty', () => {
|
||||
const expected = { 'upper-back': 0.75, 'lower-back': 0.25 }
|
||||
expect(musclesOf({ bp: 'back' })).toEqual(expected)
|
||||
expect(musclesOf({ bp: 'back', primaries: [] })).toEqual(expected)
|
||||
})
|
||||
|
||||
it('keeps legacy metadata when a new array field is present but empty', () => {
|
||||
expect(exerciseMuscleSnapshot({ bp: 'chest', tg: 'abs', primaries: [] })).toMatchObject({
|
||||
muscleGroups: ['abs']
|
||||
})
|
||||
})
|
||||
|
||||
it('provides a conservative Full body fallback for legacy custom exercises', () => {
|
||||
expect(muscleGroupsOf({ bp: 'full body' })).toEqual(['chest', 'upper-back', 'gluteal', 'quadriceps', 'hamstring', 'abs'])
|
||||
expect(musclesOf({ bp: 'full body' })).toEqual({
|
||||
chest: 0.2, 'upper-back': 0.2, gluteal: 0.2, quadriceps: 0.2, hamstring: 0.1, abs: 0.1
|
||||
})
|
||||
})
|
||||
|
||||
it('preserves explicit primary and secondary arrays in history snapshots', () => {
|
||||
expect(exerciseMuscleSnapshot({
|
||||
n: 'Deadlift', bp: 'full body', primaries: ['gluteal', 'lower-back'], secondaries: ['hamstring']
|
||||
})).toMatchObject({
|
||||
n: 'Deadlift', bp: 'full body', primaries: ['gluteal', 'lower-back'], secondaries: ['hamstring'],
|
||||
muscleGroups: ['gluteal', 'lower-back', 'hamstring']
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
describe('map load with warm-up phases', () => {
|
||||
it('excludes warm-up sets from the by-sets-worked map', () => {
|
||||
const w = {
|
||||
@@ -60,3 +136,39 @@ describe('map load with warm-up phases', () => {
|
||||
expect(load.chest).toBe(1)
|
||||
})
|
||||
})
|
||||
|
||||
// A custom exercise that was deleted from the catalogue survives in history only as the
|
||||
// muscleSnapshot finish-workout wrote. Reading it back is what keeps those sessions in the
|
||||
// body map and in Stats instead of silently contributing nothing.
|
||||
describe('deleted custom exercises', () => {
|
||||
const snapshotEntry = {
|
||||
id: 'gone-custom-1',
|
||||
sets: [{ w: 60, r: 8, done: true }],
|
||||
muscleSnapshot: { n: 'Deleted custom', bp: 'chest', muscleGroups: ['chest'], muscleWeights: { chest: 1 } },
|
||||
}
|
||||
|
||||
it('reads muscle load back out of the snapshot', () => {
|
||||
expect(loadOfWorkouts([{ d: '2026-08-01', entries: [snapshotEntry] }])).toEqual({ chest: 1 })
|
||||
})
|
||||
|
||||
it('reports the snapshot groups as explicit metadata', () => {
|
||||
expect(hasExplicitMuscleMetadata(snapshotEntry)).toBe(true)
|
||||
expect(muscleGroupsOf(snapshotEntry)).toEqual(['chest'])
|
||||
})
|
||||
|
||||
it('still prefers the entry\'s own metadata when it has any', () => {
|
||||
const withOwn = { ...snapshotEntry, tg: 'quadriceps' }
|
||||
expect(muscleGroupsOf(withOwn)).toEqual(['quadriceps'])
|
||||
})
|
||||
})
|
||||
|
||||
// muscles.js counts completed work, so its warm-up boundary has to agree with the one the
|
||||
// session runtime uses — including the legacy spellings phaseForSet normalises.
|
||||
describe('warm-up boundary', () => {
|
||||
it('excludes every phase spelling the workout model treats as a warm-up', () => {
|
||||
const entries = spelling => [{ id: '0025', sets: [{ w: 100, r: 5, done: true, phase: spelling }] }]
|
||||
for (const spelling of ['warmup', 'warm-up', 'warm_up', 'Warmup', ' warmup ']) {
|
||||
expect(loadOfWorkouts([{ d: '2026-08-01', entries: entries(spelling) }]), spelling).toEqual({})
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -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()
|
||||
})
|
||||
})
|
||||
@@ -148,6 +148,32 @@ describe('is1RMRecord', () => {
|
||||
})
|
||||
|
||||
|
||||
describe('drop-sets, rest-pause sets and 1RM', () => {
|
||||
it('estimates only from the main/activation weight×reps, ignoring lighter drops', () => {
|
||||
const entry = { id: 'x', sets: [
|
||||
{ type: 'dropset', w: 100, r: 5, done: true, drops: [{ w: 80, r: 5 }, { w: 60, r: 5 }] },
|
||||
] }
|
||||
expect(bestSetOf(entry)).toEqual(bestSetOf({ id: 'x', sets: [{ w: 100, r: 5, done: true }] }))
|
||||
})
|
||||
|
||||
it('estimates only from the row\'s own w/r, ignoring rest-pause bursts', () => {
|
||||
const entry = { id: 'x', sets: [
|
||||
{ type: 'restpause', w: 60, r: 8, done: true, clusters: [{ r: 4, restSec: 15 }, { r: 3, restSec: 15 }] },
|
||||
] }
|
||||
expect(bestSetOf(entry)).toEqual(bestSetOf({ id: 'x', sets: [{ w: 60, r: 8, done: true }] }))
|
||||
})
|
||||
|
||||
it('refuses to estimate a planned rest-pause row once its total reps exceed REP_CAP, same as any other high-rep set', () => {
|
||||
// A planned rest-pause row's own r is the total across every burst (see
|
||||
// applyIntensifierPlan/history.js), so it commonly lands above REP_CAP — the row is real
|
||||
// work, but "estimate a max from 20 broken-up reps" is exactly the fantasy REP_CAP refuses.
|
||||
const entry = { id: 'x', sets: [
|
||||
{ type: 'restpause', w: 60, r: 20, done: true, clusters: [{ r: 10, restSec: 15 }, { r: 5, restSec: 15 }, { r: 3, restSec: 15 }, { r: 1, restSec: 15 }, { r: 1, restSec: 15 }] },
|
||||
] }
|
||||
expect(bestSetOf(entry)).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('warm-up sets and 1RM', () => {
|
||||
const ENTRY = { id: 'warm-test', sets: [
|
||||
{ w: 20, r: 8, done: true, warmup: true },
|
||||
|
||||
@@ -9,9 +9,9 @@
|
||||
// a page break — each exercise, and each routine that fits, stays in one place.
|
||||
|
||||
import { EXIDX, isBodyweightEq } from './exercises.js'
|
||||
import { modeOf, fmtSec, isBw, isPerSide, sideReps } from './history.js'
|
||||
import { modeOf, fmtSec, isBw, isPerSide, sideReps, MAX_PLANNED_WARMUPS } from './history.js'
|
||||
import { uid, todayISO, DAYN, fmtNum, exCount } from './format.js'
|
||||
import { t } from './i18n-core.js'
|
||||
import { t, exerciseNameFor } from './i18n-core.js'
|
||||
|
||||
const PLAN_FMT = 1
|
||||
const WEEK_ORDER = [1, 2, 3, 4, 5, 6, 0] // Mon-first, matching the Plan screen
|
||||
@@ -45,9 +45,37 @@ function cleanEx(e) {
|
||||
if (e.repsMin != null) o.repsMin = e.repsMin
|
||||
if (e.repsMax != null) o.repsMax = e.repsMax
|
||||
if (e.sg) o.sg = e.sg
|
||||
if (e.note) o.note = e.note
|
||||
const warm = cleanWarmupSets(e.warmupSets)
|
||||
if (warm) o.warmupSets = warm
|
||||
// Drop-sets and rest-pause are part of how the exercise is prescribed, not a logging detail.
|
||||
// Without this a shared "3x5 with a double drop" arrived at the other end as a plain 3x5,
|
||||
// silently — parsePlan's `dropped` counter only tracks exercises it cannot resolve at all.
|
||||
const intens = cleanIntensifier(e.intensifier)
|
||||
if (intens) o.intensifier = intens
|
||||
return o
|
||||
}
|
||||
|
||||
/** Clamped the same way buildSets clamps it on the way out — the stepper showed a hand-edited
|
||||
* plan file's "999" verbatim, because the clamp only happened when the rows were built. */
|
||||
function cleanWarmupSets(v) {
|
||||
const n = Math.round(Number(v)) || 0
|
||||
return n > 0 ? Math.min(MAX_PLANNED_WARMUPS, n) : 0
|
||||
}
|
||||
|
||||
/** Keep the floors the config sheet and applyIntensifierPlan already enforce, and nothing else:
|
||||
* a plan file is someone else's data, so anything unrecognised is dropped rather than trusted. */
|
||||
function cleanIntensifier(x) {
|
||||
const type = x && x.type
|
||||
if (type === 'dropset') {
|
||||
return { type, count: Math.max(1, Math.round(Number(x.count)) || 1), pct: Math.max(5, Math.round(Number(x.pct)) || 20) }
|
||||
}
|
||||
if (type === 'restpause') {
|
||||
return { type, totalReps: Math.max(1, Math.round(Number(x.totalReps)) || 1), restSec: Math.max(5, Math.round(Number(x.restSec)) || 15) }
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** Build the shareable bundle: every routine, the week schedule, referenced customs. */
|
||||
export function buildPlanBundle(S, name) {
|
||||
const routines = (S.routines || []).map(r => ({
|
||||
@@ -85,6 +113,13 @@ export function parsePlan(raw) {
|
||||
const ok = !!e && (known.has(e.id) || !!EXIDX[e.id])
|
||||
if (!ok) dropped++
|
||||
return ok
|
||||
}).map(e => {
|
||||
// The exercises pass through as written, so the two fields that carry numbers into the
|
||||
// planner get the same clamps on the way in that they get on the way out.
|
||||
const warm = cleanWarmupSets(e.warmupSets)
|
||||
const intens = cleanIntensifier(e.intensifier)
|
||||
const { warmupSets, intensifier, ...rest } = e
|
||||
return { ...rest, ...(warm ? { warmupSets: warm } : {}), ...(intens ? { intensifier: intens } : {}) }
|
||||
})
|
||||
}))
|
||||
return {
|
||||
@@ -172,9 +207,10 @@ function routineHTML(r, unit) {
|
||||
const rows = units(r.ex).map(u => {
|
||||
const items = u.map(e => {
|
||||
const ex = EXIDX[e.id]
|
||||
const name = ex ? ex.n : t('Unknown exercise')
|
||||
const name = ex ? exerciseNameFor(ex) : t('Unknown exercise')
|
||||
const part = ex && ex.bp && ex.bp !== 'cardio' ? `<span class="part">${esc(ex.bp)}</span>` : ''
|
||||
return `<div class="ex"><div class="ex-n">${esc(name)}${part}</div><div class="ex-s">${esc(scheme(e, unit))}</div></div>`
|
||||
const note = e.note ? `<div class="ex-note">${esc(e.note)}</div>` : ''
|
||||
return `<div class="ex"><div class="ex-row"><div class="ex-n">${esc(name)}${part}</div><div class="ex-s">${esc(scheme(e, unit))}</div></div>${note}</div>`
|
||||
}).join('')
|
||||
return u.length > 1
|
||||
? `<div class="ss"><div class="ss-tag">${esc(t('Superset'))}</div><div class="ss-items">${items}</div></div>`
|
||||
@@ -236,11 +272,13 @@ export function planPrintHTML(S, owner) {
|
||||
.r-count { font-size: 12px; color: #8a90a0; white-space: nowrap; }
|
||||
|
||||
.ex-list { display: flex; flex-direction: column; }
|
||||
.ex { display: flex; align-items: baseline; justify-content: space-between; gap: 14px; padding: 6px 0; break-inside: avoid; page-break-inside: avoid; }
|
||||
.ex { display: flex; flex-direction: column; padding: 6px 0; break-inside: avoid; page-break-inside: avoid; }
|
||||
.ex + .ex, .ss + .ex, .ex + .ss { border-top: 1px solid #f2f3f6; }
|
||||
.ex-row { display: flex; align-items: baseline; justify-content: space-between; gap: 14px; }
|
||||
.ex-n { text-transform: capitalize; font-weight: 500; }
|
||||
.ex-n .part { text-transform: capitalize; color: #9aa0ae; font-weight: 400; font-size: 12px; margin-left: 8px; }
|
||||
.ex-s { color: #3d424e; white-space: nowrap; font-variant-numeric: tabular-nums; }
|
||||
.ex-note { color: #6a7080; font-size: 12px; margin-top: 2px; }
|
||||
.ex.empty, .none { color: #a2a8b6; }
|
||||
|
||||
.ss { break-inside: avoid; page-break-inside: avoid; border-left: 3px solid #cfe08a; padding-left: 12px; margin: 4px 0; }
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { buildPlanBundle, parsePlan } from './plan-share.js'
|
||||
|
||||
// There was no test file for plan sharing at all, which is how a whole prescription field
|
||||
// went missing without anyone noticing.
|
||||
const stateWith = ex => ({
|
||||
routines: [{ id: 'r1', name: 'Push', ex: [{ id: '0025', sets: 3, reps: 5, weight: 100, ...ex }] }],
|
||||
week: {}, customEx: [],
|
||||
})
|
||||
const roundTrip = ex => parsePlan(JSON.stringify(buildPlanBundle(stateWith(ex), 'Plan'))).routines[0].ex[0]
|
||||
|
||||
describe('what survives a shared plan', () => {
|
||||
it('carries a drop-set prescription', () => {
|
||||
expect(roundTrip({ intensifier: { type: 'dropset', count: 2, pct: 20 } }).intensifier)
|
||||
.toEqual({ type: 'dropset', count: 2, pct: 20 })
|
||||
})
|
||||
|
||||
it('carries a rest-pause prescription', () => {
|
||||
expect(roundTrip({ intensifier: { type: 'restpause', totalReps: 12, restSec: 15 } }).intensifier)
|
||||
.toEqual({ type: 'restpause', totalReps: 12, restSec: 15 })
|
||||
})
|
||||
|
||||
it('carries planned warm-ups', () => {
|
||||
expect(roundTrip({ warmupSets: 3 }).warmupSets).toBe(3)
|
||||
})
|
||||
|
||||
it('drops an intensifier it does not recognise rather than passing it on', () => {
|
||||
expect(roundTrip({ intensifier: { type: 'nonsense', count: 3 } }).intensifier).toBeUndefined()
|
||||
})
|
||||
|
||||
it('clamps a hand-edited warm-up count instead of showing it verbatim', () => {
|
||||
const bundle = { opengym_plan: 1, name: 'x', routines: [{ id: 'r', name: 'R', ex: [{ id: '0025', sets: 3, reps: 5, warmupSets: 999 }] }], week: {}, customEx: [] }
|
||||
expect(parsePlan(bundle).routines[0].ex[0].warmupSets).toBe(5)
|
||||
})
|
||||
|
||||
// The floors are the config sheet's own (count >= 1, pct >= 5); a value that is present but
|
||||
// out of range is pulled up to the floor, while a missing one falls back to the default.
|
||||
it('clamps out-of-range intensifier numbers to the floors the app enforces', () => {
|
||||
const bundle = { opengym_plan: 1, name: 'x', routines: [{ id: 'r', name: 'R', ex: [{ id: '0025', sets: 3, reps: 5, intensifier: { type: 'dropset', count: 0, pct: -5 } }] }], week: {}, customEx: [] }
|
||||
expect(parsePlan(bundle).routines[0].ex[0].intensifier).toEqual({ type: 'dropset', count: 1, pct: 5 })
|
||||
})
|
||||
|
||||
it('falls back to the default drop percentage when the file omits it', () => {
|
||||
const bundle = { opengym_plan: 1, name: 'x', routines: [{ id: 'r', name: 'R', ex: [{ id: '0025', sets: 3, reps: 5, intensifier: { type: 'dropset' } }] }], week: {}, customEx: [] }
|
||||
expect(parsePlan(bundle).routines[0].ex[0].intensifier).toEqual({ type: 'dropset', count: 1, pct: 20 })
|
||||
})
|
||||
})
|
||||
@@ -16,7 +16,7 @@
|
||||
// · fewer sets than prescribed → miss
|
||||
// So a session that fell apart can never advance the load as though it had succeeded.
|
||||
|
||||
import { modeOf, repStep } from './history.js'
|
||||
import { modeOf, repStep, rerampWarmups } from './history.js'
|
||||
import { EXIDX } from './exercises.js'
|
||||
import { isWarmupRow } from './workout-model.js'
|
||||
|
||||
@@ -250,7 +250,7 @@ export function nextPrescription(S, cfg, routine) {
|
||||
* Apply a prescription to freshly built sets. Only the fields the policy actually decided
|
||||
* are touched, and only on sets that have not been logged yet.
|
||||
*/
|
||||
export function applyPrescription(sets, p) {
|
||||
export function applyPrescription(sets, p, step = 2.5) {
|
||||
if (!p || p.kind === 'off' || p.kind === 'first') return sets
|
||||
const out = sets.map(s => {
|
||||
// Never rewrite a logged set, and never rewrite a warm-up: the prescription speaks to
|
||||
@@ -270,9 +270,16 @@ export function applyPrescription(sets, p) {
|
||||
if (p.sets > workRows.length) {
|
||||
// An all-warm-up entry has no work row to seed growth from - growing warm-up copies
|
||||
// would both invent work and never terminate the loop. Leave the entry untouched.
|
||||
if (!workRows.length) return out
|
||||
if (!workRows.length) return rerampWarmups(out, step)
|
||||
const seed = workRows[workRows.length - 1]
|
||||
while (out.filter(s => !isWarmupRow(s)).length < p.sets) out.push({ ...seed, done: false })
|
||||
// A freshly appended row hasn't been performed, so it never inherits a seed's already-
|
||||
// logged drops/clusters — that would invent extra work the row never actually did. Its
|
||||
// `type` is kept: that's the exercise's plan (every set is a drop-set/rest-pause), not
|
||||
// something this particular row logged.
|
||||
const { drops, clusters, ...plainSeed } = seed
|
||||
while (out.filter(s => !isWarmupRow(s)).length < p.sets) out.push({ ...plainSeed, done: false })
|
||||
}
|
||||
return out
|
||||
// Last, because the work rows now carry their final weight: the warm-up block ramps toward
|
||||
// what you are actually about to lift, not toward what you lifted last time.
|
||||
return rerampWarmups(out, step)
|
||||
}
|
||||
@@ -523,3 +523,34 @@ describe('applyPrescription never touches warm-up rows (round 3)', () => {
|
||||
expect(out).toEqual(sets) // no work row to seed growth from - nothing grows, no loop
|
||||
})
|
||||
})
|
||||
|
||||
describe('drop-sets and rest-pause sets in progression', () => {
|
||||
it('readSession judges a drop-set row on its own main weight/reps, ignoring the drops', () => {
|
||||
const withDrops = readSession({ id: LIFT, target: { sets: 1, reps: 5 }, sets: [
|
||||
{ type: 'dropset', w: 60, r: 5, done: true, drops: [{ w: 40, r: 8 }, { w: 20, r: 10 }] },
|
||||
] })
|
||||
const plain = readSession({ id: LIFT, target: { sets: 1, reps: 5 }, sets: [{ w: 60, r: 5, done: true }] })
|
||||
expect(withDrops).toEqual(plain)
|
||||
})
|
||||
|
||||
it('readSession judges a rest-pause row on its activation weight/reps, ignoring the bursts', () => {
|
||||
const withBursts = readSession({ id: LIFT, target: { sets: 1, reps: 8 }, sets: [
|
||||
{ type: 'restpause', w: 60, r: 8, done: true, clusters: [{ r: 4, restSec: 15 }, { r: 3, restSec: 15 }] },
|
||||
] })
|
||||
const plain = readSession({ id: LIFT, target: { sets: 1, reps: 8 }, sets: [{ w: 60, r: 8, done: true }] })
|
||||
expect(withBursts).toEqual(plain)
|
||||
})
|
||||
|
||||
it('applyPrescription still rewrites a drop-set/rest-pause row\'s own weight, leaving its drops/clusters untouched', () => {
|
||||
const sets = [{ type: 'dropset', w: 60, r: 5, done: false, drops: [{ w: 40, r: 8 }] }]
|
||||
const out = applyPrescription(sets, { kind: 'up', weight: 62.5 })
|
||||
expect(out[0]).toEqual({ type: 'dropset', w: 62.5, r: 5, done: false, drops: [{ w: 40, r: 8 }] })
|
||||
})
|
||||
|
||||
it('a newly grown row keeps the seed\'s planned type but not its already-logged drops/clusters', () => {
|
||||
const sets = [{ type: 'dropset', w: 0, r: 10, done: false, drops: [{ w: 0, r: 12 }] }]
|
||||
const out = applyPrescription(sets, { kind: 'up', weight: 0, reps: 10, sets: 2 })
|
||||
expect(out).toHaveLength(2)
|
||||
expect(out[1]).toEqual({ type: 'dropset', w: 0, r: 10, done: false })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,61 @@
|
||||
import { afterEach, describe, expect, test } from 'vitest'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import ptBR from '../exercise-names/pt-BR.js'
|
||||
import { EXDB } from './exercises-data.js'
|
||||
import {
|
||||
EXERCISE_NAME_LANGS, _setLangState, exerciseNameFor, exerciseNameSearchText
|
||||
} from './i18n-core.js'
|
||||
|
||||
describe('Brazilian Portuguese exercise names', () => {
|
||||
const source = JSON.parse(readFileSync(new URL('../../../scripts/exercise-name-sources/pt-BR.json', import.meta.url), 'utf8'))
|
||||
afterEach(() => _setLangState('en', {}, null, null))
|
||||
|
||||
test('matches the curated source and covers the complete built-in catalogue', () => {
|
||||
expect(Object.keys(ptBR)).toHaveLength(EXDB.length)
|
||||
expect(ptBR).toEqual(source)
|
||||
expect(EXERCISE_NAME_LANGS).toContain('pt-BR')
|
||||
})
|
||||
|
||||
test('contains a non-empty translation for every known exercise', () => {
|
||||
for (const exercise of EXDB) {
|
||||
expect(ptBR[exercise.id]?.trim(), exercise.id).toBeTruthy()
|
||||
expect(ptBR[exercise.id], exercise.id).not.toMatch(/(?:^|[^\p{L}])(?:abdómen|anca|gémeos|ecrã|ginásio|banda|piso|omoplata|pegada inversa|pegada invertida)(?=$|[^\p{L}])/iu)
|
||||
}
|
||||
})
|
||||
|
||||
test('preserves identity-changing qualifiers and equipment', () => {
|
||||
const rules = [
|
||||
[/assisted/iu, /assistid/iu],
|
||||
[/weighted/iu, /(?:peso|carga|lastro|ponderad)/iu],
|
||||
[/(?:^|[^\p{L}])male(?=$|[^\p{L}])/iu, /masculin/iu],
|
||||
[/(?:^|[^\p{L}])female(?=$|[^\p{L}])/iu, /feminin/iu],
|
||||
[/barbell/iu, /barra/iu],
|
||||
[/dumbbell/iu, /halter/iu],
|
||||
[/kettlebell/iu, /kettlebell/iu],
|
||||
[/smith/iu, /smith/iu],
|
||||
[/stability ball/iu, /bola de estabilidade/iu],
|
||||
[/medicine ball/iu, /bola medicinal/iu],
|
||||
]
|
||||
for (const exercise of EXDB) {
|
||||
for (const [english, portuguese] of rules) {
|
||||
if (english.test(exercise.n)) expect(ptBR[exercise.id], `${exercise.id}: ${english}`).toMatch(portuguese)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
test('shows Portuguese first and preserves the canonical English title', () => {
|
||||
const exercise = EXDB[0]
|
||||
_setLangState('pt-BR', {}, null, ptBR)
|
||||
expect(exerciseNameFor(exercise)).toBe(`${ptBR[exercise.id]} (${exercise.n})`)
|
||||
expect(exerciseNameSearchText(exercise)).toContain(ptBR[exercise.id])
|
||||
expect(exerciseNameSearchText(exercise)).toContain(exercise.n)
|
||||
})
|
||||
|
||||
test('never translates custom exercises or changes other languages', () => {
|
||||
const custom = { id: 'custom-1', n: 'Meu exercício' }
|
||||
_setLangState('pt-BR', {}, null, ptBR)
|
||||
expect(exerciseNameFor(custom)).toBe('Meu exercício')
|
||||
_setLangState('en', {}, null, null)
|
||||
expect(exerciseNameFor(EXDB[0])).toBe(EXDB[0].n)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,55 @@
|
||||
import { describe, expect, test } from 'vitest'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import ptBR from '../instr/pt-BR.js'
|
||||
import { EXDB } from './exercises-data.js'
|
||||
import { INSTR_LANGS } from './i18n-core.js'
|
||||
|
||||
describe('Brazilian Portuguese exercise instructions', () => {
|
||||
const exercises = new Map(EXDB.map(exercise => [exercise.id, exercise]))
|
||||
const source = JSON.parse(readFileSync(new URL('../../../scripts/instruction-sources/pt-BR.json', import.meta.url), 'utf8'))
|
||||
|
||||
test('matches the curated source and covers the complete exercise corpus', () => {
|
||||
expect(Object.keys(ptBR)).toHaveLength(EXDB.length)
|
||||
expect(ptBR).toEqual(source)
|
||||
})
|
||||
|
||||
test('only enables pt-BR instructions when the pack is complete', () => {
|
||||
expect(INSTR_LANGS.includes('pt-BR')).toBe(Object.keys(ptBR).length === EXDB.length)
|
||||
})
|
||||
|
||||
test('completes Stage 1 waist and core coverage', () => {
|
||||
const stage = EXDB.filter(exercise => exercise.bp === 'waist')
|
||||
expect(stage).toHaveLength(169)
|
||||
stage.forEach(exercise => expect(ptBR, exercise.id).toHaveProperty(exercise.id))
|
||||
})
|
||||
|
||||
test('contains only known exercises with complete, non-empty step lists', () => {
|
||||
for (const [id, steps] of Object.entries(ptBR)) {
|
||||
const exercise = exercises.get(id)
|
||||
expect(exercise, `unknown exercise ${id}`).toBeDefined()
|
||||
expect(steps, id).toHaveLength(exercise.st.length)
|
||||
steps.forEach((step, index) => {
|
||||
expect(step.trim(), `${id} step ${index + 1}`).not.toBe('')
|
||||
expect(step, `${id} step ${index + 1}`).not.toBe(exercise.st[index])
|
||||
expect(step, `${id} step ${index + 1}`).not.toMatch(/(?:^|[^\p{L}])(?:the|your|with|from|towards?|repeat|desired|starting|slowly|hold|while|then|back|straight|ground|feet|hands|body|legs|arms|knees|shoulders)(?=$|[^\p{L}])/iu)
|
||||
expect(step, `${id} step ${index + 1}`).not.toMatch(/(?:^|[^\p{L}])(?:ginásio|anca|abdómen|gémeos|ecrã|core|banda|piso|omoplata|peso de mão|barra de elevações|pegada por cima|pegada invertida|pegada inversa|bola suíça)(?=$|[^\p{L}])/iu)
|
||||
expect(step, `${id} step ${index + 1}`).not.toMatch(/flexion\p{L}*\s+(?:a\s+|o\s+|os\s+|um\s+|uma\s+)?(?:barra|pesos?|halter(?:es)?|mão)(?=$|[^\p{L}])/iu)
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
test('does not replace kettlebells with dumbbells', () => {
|
||||
for (const exercise of EXDB) {
|
||||
exercise.st.forEach((step, index) => {
|
||||
if (/kettlebells?/iu.test(step)) {
|
||||
expect(ptBR[exercise.id][index], `${exercise.id} step ${index + 1}`).toMatch(/kettlebells?/iu)
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
test('uses wrist extension for reverse wrist curls', () => {
|
||||
const reverseWristCurlIds = ['0079', '0082', '0104', '0210', '0224', '0358', '0367', '0368', '0385', '0771', '0994', '1441']
|
||||
reverseWristCurlIds.forEach(id => expect(ptBR[id].join(' '), id).toMatch(/estend\p{L}*(?: lentamente)? (?:o |os )?punhos?/iu))
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,54 @@
|
||||
import { describe, expect, test } from 'vitest'
|
||||
import { createHash } from 'node:crypto'
|
||||
import pt from '../locales/pt.js'
|
||||
import ptBR, { PT_BR_OVERRIDES } from '../locales/pt-BR.js'
|
||||
import { DATE_LOCALES, LANGS } from './i18n-core.js'
|
||||
|
||||
const placeholders = value => [...String(value).matchAll(/\{\d+\}/g)].map(match => match[0]).sort()
|
||||
const byCodeUnit = ([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)
|
||||
|
||||
describe('Brazilian Portuguese locale', () => {
|
||||
test('is a separately selectable locale with Brazilian date formatting', () => {
|
||||
expect(LANGS.pt).toBe('Português (Portugal)')
|
||||
expect(LANGS['pt-BR']).toBe('Português (Brasil)')
|
||||
expect(DATE_LOCALES['pt-BR']).toBe('pt-BR')
|
||||
})
|
||||
|
||||
test('matches the source key set and preserves interpolation placeholders', () => {
|
||||
expect(Object.keys(ptBR).sort()).toEqual(Object.keys(pt).sort())
|
||||
for (const [source, translated] of Object.entries(ptBR)) {
|
||||
expect(placeholders(translated), source).toEqual(placeholders(source))
|
||||
}
|
||||
})
|
||||
|
||||
test('makes every inherited pt-PT value an explicit reviewed snapshot', () => {
|
||||
const inherited = Object.entries(pt)
|
||||
.filter(([key]) => !(key in PT_BR_OVERRIDES))
|
||||
.sort(byCodeUnit)
|
||||
const fingerprint = createHash('sha256').update(JSON.stringify(inherited)).digest('hex')
|
||||
|
||||
expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(362)
|
||||
expect(inherited).toHaveLength(517)
|
||||
// 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('56fd46aefb32a69e0bd6ed0c9f263d521113d3db6f44cfdcefb66d88d26312e5')
|
||||
})
|
||||
|
||||
test('does not leak European Portuguese UI terms', () => {
|
||||
const text = Object.values(ptBR).join('\n')
|
||||
const europeanPortuguese = /(?:^|[^\p{L}])(?:ficheiro\p{L}*|telemóvel\p{L}*|ecrã\p{L}*|regist(?:o|am|ado|ada|ados|adas)|eliminad\p{L}*|definições|cronómetro|detetad\p{L}*|gémeos|abdómen|anca|coifa dos rotadores|escadora|completaste|acabaste|aguentas|definires|completares|aguenta|aguentaste|ficaste|viajares)(?=$|[^\p{L}])/iu
|
||||
expect(text).not.toMatch(europeanPortuguese)
|
||||
expect(text).not.toMatch(/[«»]/u)
|
||||
expect(ptBR.Save).toBe('Salvar')
|
||||
expect(ptBR.Settings).toBe('Configurações')
|
||||
expect(ptBR['Delete workout']).toBe('Excluir treino')
|
||||
expect(ptBR.Superset).toBe('Superset')
|
||||
expect(ptBR['Guest mode — data lives only in this browser.']).toContain('visitante')
|
||||
expect(ptBR['Sign in with passkey']).toContain('chave de acesso')
|
||||
expect(ptBR.band).toBe('elástico')
|
||||
expect(ptBR['resistance band']).toBe('faixa elástica')
|
||||
expect(ptBR.soleus).toBe('sóleo')
|
||||
expect(ptBR.Unpair).toBe('Desvincular')
|
||||
expect(ptBR['Starter plan loaded — Mon Push · Wed Pull · Fri Legs']).toContain('Seg Push · Qua Pull')
|
||||
})
|
||||
})
|
||||
@@ -1,6 +1,6 @@
|
||||
import { EXIDX } from './exercises.js'
|
||||
import { MUSCLES, musclesOf } from './muscles.js'
|
||||
import { isWarmupRow } from './workout-model.js'
|
||||
import { isWarmupRow, dropsOf } from './workout-model.js'
|
||||
|
||||
// A "normal" hard session for one muscle, in primary-set equivalents. The saturation curve
|
||||
// 1 - exp(-stimulus / REF) maps any session size onto [0,1) so volume raises the starting
|
||||
@@ -172,6 +172,25 @@ function session1RMs(workout, opts = {}) {
|
||||
return best
|
||||
}
|
||||
|
||||
// Extra tonnage from a drop-set's drops, weighted the same way as the row's own main set — a
|
||||
// drop taken near failure counts the same as any other hard rep for fatigue purposes, it just
|
||||
// carries its own (usually lighter) load.
|
||||
//
|
||||
// A rest-pause row's `clusters` are NOT extra here: the row's own `r` already is the total reps
|
||||
// across every burst (see applyIntensifierPlan/history.js), so the main tonnage term below
|
||||
// already covers it — adding clusters on top would double-count the same reps.
|
||||
function extraTonnage(ex, entry, set, workout, oneRm, opts = {}) {
|
||||
const drops = dropsOf(set)
|
||||
if (!drops.length) return 0
|
||||
const isBwEx = bodyweightConfigured(ex, entry, set, workout, opts)
|
||||
const weigh = (load, reps) => {
|
||||
if (!(load > 0) || !(reps > 0)) return 0
|
||||
const raw = load * reps
|
||||
return isBwEx || !(oneRm > 0) ? raw : raw * Math.min(1, load / oneRm) ** 1.5
|
||||
}
|
||||
return drops.reduce((sum, d) => sum + weigh(loadKgFor(ex, entry, d, workout, opts), Number(d?.r) || 0), 0)
|
||||
}
|
||||
|
||||
// Intensity-weighted tonnage for one completed set: load x reps x (load / exercise 1RM)^1.5.
|
||||
// The exponent saturates the "hard set" effect - a set at 90% of your 1RM counts ~0.81 of its
|
||||
// raw tonnage, one at 50% only ~0.35. Cardio, timed holds, and sets whose exercise has no
|
||||
@@ -186,13 +205,14 @@ function setTonnage(ex, entry, set, workout, oneRm, opts = {}) {
|
||||
const reps = set?.r || 1
|
||||
const load = loadKgFor(ex, entry, set, workout, opts)
|
||||
const raw = load * reps
|
||||
const extra = extraTonnage(ex, entry, set, workout, oneRm, opts)
|
||||
// A bodyweight target is already an external-load-normalised total (body mass + any added
|
||||
// load). It has no meaningful barbell-style 1RM intensity ratio in the legacy data model, so
|
||||
// retain the monotonic total-load stimulus instead of letting a newly created low 1RM shrink
|
||||
// a weighted bodyweight set below the unloaded version.
|
||||
if (bodyweightConfigured(ex, entry, set, workout, opts)) return raw
|
||||
if (!(oneRm > 0) || !(load > 0)) return raw
|
||||
return raw * Math.min(1, load / oneRm) ** 1.5
|
||||
if (bodyweightConfigured(ex, entry, set, workout, opts)) return raw + extra
|
||||
if (!(oneRm > 0) || !(load > 0)) return raw + extra
|
||||
return raw * Math.min(1, load / oneRm) ** 1.5 + extra
|
||||
}
|
||||
|
||||
// One session's per-muscle stimulus, calculated only from that session. A completed zero-load
|
||||
|
||||
@@ -403,6 +403,47 @@ describe('warm-up flag in strength and fatigue', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('drop-set drops add fatigue tonnage on top of the main set', () => {
|
||||
// Same within-session Epley baseline setTonnage derives from the row's own w/r (8 reps,
|
||||
// under REP_CAP), so a drop is weighted against the same 1RM as the main set.
|
||||
const oneRm = 80 * (1 + 8 / 30)
|
||||
|
||||
it('a drop-set drop adds its own intensity-weighted tonnage', () => {
|
||||
const dropRow = { done: true, type: 'dropset', w: 80, r: 8, drops: [{ w: 60, r: 6 }] }
|
||||
const dropTonnage = 60 * 6 * Math.min(1, 60 / oneRm) ** 1.5
|
||||
const expected = expectedFatigue([{ stimulus: V + dropTonnage }])
|
||||
|
||||
expect(fatigueOf([workoutAt(SINGLE.id, NOW, [dropRow])], NOW)[SINGLE_SLUG]).toBeCloseTo(expected, 8)
|
||||
// strictly more than the plain 80x8 set alone — the drop is real extra work
|
||||
expect(fatigueOf([workoutAt(SINGLE.id, NOW, [dropRow])], NOW)[SINGLE_SLUG])
|
||||
.toBeGreaterThan(fatigueOf([doneWorkoutAt(SINGLE.id, NOW)], NOW)[SINGLE_SLUG])
|
||||
})
|
||||
|
||||
it('leaves fatigue unchanged for a straight set with no drops', () => {
|
||||
const plain = { done: true, w: 80, r: 8 }
|
||||
expect(fatigueOf([workoutAt(SINGLE.id, NOW, [plain])], NOW)[SINGLE_SLUG])
|
||||
.toBeCloseTo(expectedFatigue([{ stimulus: V }]), 8)
|
||||
})
|
||||
})
|
||||
|
||||
describe('a rest-pause row\'s clusters add no extra fatigue tonnage', () => {
|
||||
// Its own r is already the total across every burst (see applyIntensifierPlan/history.js),
|
||||
// so setTonnage's main w x r term already covers all of it — clusters are a breakdown only.
|
||||
it('matches a plain set of the same w/r exactly, regardless of how the clusters break it down', () => {
|
||||
const burstRow = { done: true, type: 'restpause', w: 80, r: 8, clusters: [{ r: 4, restSec: 15 }] }
|
||||
const plainRow = { done: true, w: 80, r: 8 }
|
||||
expect(fatigueOf([workoutAt(SINGLE.id, NOW, [burstRow])], NOW)[SINGLE_SLUG])
|
||||
.toBeCloseTo(fatigueOf([workoutAt(SINGLE.id, NOW, [plainRow])], NOW)[SINGLE_SLUG], 10)
|
||||
})
|
||||
|
||||
it('holds for a realistic planned total too — a full descending split adds nothing beyond the row\'s own r', () => {
|
||||
const burstRow = { done: true, type: 'restpause', w: 80, r: 20, clusters: [{ r: 10, restSec: 15 }, { r: 5, restSec: 15 }, { r: 3, restSec: 15 }, { r: 1, restSec: 15 }, { r: 1, restSec: 15 }] }
|
||||
const plainRow = { done: true, w: 80, r: 20 }
|
||||
expect(fatigueOf([workoutAt(SINGLE.id, NOW, [burstRow])], NOW)[SINGLE_SLUG])
|
||||
.toBeCloseTo(fatigueOf([workoutAt(SINGLE.id, NOW, [plainRow])], NOW)[SINGLE_SLUG], 10)
|
||||
})
|
||||
})
|
||||
|
||||
describe('canonical loads and configured bodyweight', () => {
|
||||
const loaded = EXDB.find(ex => {
|
||||
const weights = musclesOf(ex)
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
// Mobile build only: "connect to my server" mode (see mobile.js's header comment for why the
|
||||
// mobile flavor has no backend at all by default). This is the alternative — pairing the app to
|
||||
// an already self-hosted openGym server instead of keeping data device-local.
|
||||
//
|
||||
// Passkeys can't be used from inside the app's own WebView (its origin never matches the
|
||||
// server's RP_ID), so auth here is a short one-time code redeemed from an already signed-in
|
||||
// browser tab (Settings → "Pair the mobile app") for a bearer token — see api/server.js's
|
||||
// /api/pair/create + /api/pair/redeem.
|
||||
import { pairRedeem, setRemoteAuth } from './api.js'
|
||||
import { loadRemoteFile, saveRemoteFile } from './mobile.js'
|
||||
|
||||
// Accepts what someone actually types: bare host, no scheme, trailing slash, stray whitespace.
|
||||
// Defaults to https:// (self-hosting docs already push for HTTPS; the one exception, localhost,
|
||||
// still parses fine without a scheme). Returns null for anything that isn't a usable URL at all.
|
||||
export function normalizeServerUrl(raw) {
|
||||
const s = String(raw || '').trim()
|
||||
if (!s) return null
|
||||
const withScheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(s) ? s : 'https://' + s
|
||||
try {
|
||||
const u = new URL(withScheme)
|
||||
if (!u.hostname) return null
|
||||
return u.origin
|
||||
} catch (e) { return null }
|
||||
}
|
||||
|
||||
export async function loadRemote() {
|
||||
return loadRemoteFile()
|
||||
}
|
||||
|
||||
export async function chooseLocal() {
|
||||
await saveRemoteFile({ mode: 'local' })
|
||||
}
|
||||
|
||||
export async function forgetRemote() {
|
||||
await saveRemoteFile({ mode: 'local' })
|
||||
setRemoteAuth('', null)
|
||||
}
|
||||
|
||||
// Redeems the pairing code, wires api.js at the resolved base, and persists the connection so
|
||||
// boot() can restore it on the next launch.
|
||||
export async function connect(rawUrl, code) {
|
||||
const base = normalizeServerUrl(rawUrl)
|
||||
if (!base) throw new Error('Enter a valid server address')
|
||||
const { token, user } = await pairRedeem(base, String(code || '').trim())
|
||||
setRemoteAuth(base, token)
|
||||
await saveRemoteFile({ mode: 'remote', base, token, user })
|
||||
return user
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { normalizeServerUrl } from './remote.js'
|
||||
|
||||
// The pairing flow lives or dies on this being forgiving about what someone types on a phone
|
||||
// keyboard, while still refusing input that can't possibly be a server address.
|
||||
describe('normalizeServerUrl', () => {
|
||||
it('accepts a bare host and adds https://', () => {
|
||||
expect(normalizeServerUrl('gym.example.com')).toBe('https://gym.example.com')
|
||||
})
|
||||
|
||||
it('keeps an explicit scheme, including http for LAN testing', () => {
|
||||
expect(normalizeServerUrl('http://192.168.1.20:8080')).toBe('http://192.168.1.20:8080')
|
||||
expect(normalizeServerUrl('https://gym.example.com')).toBe('https://gym.example.com')
|
||||
})
|
||||
|
||||
it('trims whitespace and a trailing path/slash down to the origin', () => {
|
||||
expect(normalizeServerUrl(' gym.example.com/ ')).toBe('https://gym.example.com')
|
||||
expect(normalizeServerUrl('https://gym.example.com/some/path')).toBe('https://gym.example.com')
|
||||
})
|
||||
|
||||
it('rejects empty or unusable input', () => {
|
||||
for (const v of ['', ' ', null, undefined, 'not a url at all!!']) {
|
||||
expect(normalizeServerUrl(v)).toBe(null)
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,73 @@
|
||||
// @vitest-environment happy-dom
|
||||
// The session note shipped with a hole in it: buildCompletedWorkout read `active.note` and
|
||||
// nothing in the app ever wrote it, so the only way to get one was after the fact — and that
|
||||
// path threw the text away unless you happened to tab out of the field first.
|
||||
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 { sessionNoteSheet, workoutDetailSheet } from '../sheets.jsx'
|
||||
import { buildCompletedWorkout } from './finish-workout.js'
|
||||
|
||||
const mounted = []
|
||||
function render(open) {
|
||||
open()
|
||||
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(() => useUI.getState().closeSheet(sheet.id))))
|
||||
return host
|
||||
}
|
||||
const type = (el, value) => {
|
||||
Object.getOwnPropertyDescriptor(el.constructor.prototype, 'value').set.call(el, value)
|
||||
el.dispatchEvent(new Event('input', { bubbles: true }))
|
||||
}
|
||||
const unmountAll = () => act(() => { mounted.splice(0).forEach(r => r.unmount()) })
|
||||
|
||||
const workout = () => ({
|
||||
id: 'w1', d: '2026-08-25', start: 1, end: 2, name: 'Push', vol: 100,
|
||||
entries: [{ id: 'bench', sets: [{ w: 100, r: 5, done: true }] }], prs: [],
|
||||
})
|
||||
|
||||
describe('session note', () => {
|
||||
beforeEach(() => {
|
||||
globalThis.IS_REACT_ACT_ENVIRONMENT = true
|
||||
useUI.setState({ sheets: [] })
|
||||
document.body.innerHTML = ''
|
||||
})
|
||||
afterEach(unmountAll)
|
||||
|
||||
it('can be written during the workout and survives finishing', () => {
|
||||
useStore.setState(s => ({
|
||||
S: { ...s.S, active: { id: 'w1', d: '2026-08-25', start: 1, name: 'Push', entries: [{ id: 'bench', sets: [] }] } },
|
||||
}))
|
||||
const host = render(() => sessionNoteSheet())
|
||||
act(() => { type(host.querySelector('textarea'), 'slept badly, still hit it') })
|
||||
act(() => { [...host.querySelectorAll('button')].find(b => /save/i.test(b.textContent)).click() })
|
||||
|
||||
const A = useStore.getState().S.active
|
||||
expect(A.note).toBe('slept badly, still hit it')
|
||||
// The path buildCompletedWorkout already had a test for is now actually reachable.
|
||||
expect(buildCompletedWorkout(A, { end: 2 }).note).toBe('slept badly, still hit it')
|
||||
})
|
||||
|
||||
it('is kept when the history sheet is dismissed without blurring the field', () => {
|
||||
useStore.setState(s => ({ S: { ...s.S, workouts: [workout()] } }))
|
||||
const host = render(() => workoutDetailSheet(useStore.getState().S.workouts[0]))
|
||||
act(() => { type(host.querySelector('textarea'), 'good session') })
|
||||
// Escape / Android back / swipe all unmount without a blur.
|
||||
unmountAll()
|
||||
expect(useStore.getState().S.workouts[0].note).toBe('good session')
|
||||
})
|
||||
|
||||
it('clearing it removes the note rather than storing an empty string', () => {
|
||||
useStore.setState(s => ({ S: { ...s.S, workouts: [{ ...workout(), note: 'old' }] } }))
|
||||
const host = render(() => workoutDetailSheet(useStore.getState().S.workouts[0]))
|
||||
act(() => { type(host.querySelector('textarea'), ' ') })
|
||||
unmountAll()
|
||||
expect(useStore.getState().S.workouts[0].note).toBeUndefined()
|
||||
})
|
||||
})
|
||||
@@ -11,6 +11,7 @@ import { STRENGTH_FULL_MS, STRENGTH_HALF_LIFE_MS, STRENGTH_FLOOR, halfLifeDecay
|
||||
import { musclesOf } from './muscles.js'
|
||||
import { EXIDX } from './exercises.js'
|
||||
import { isWarmupRow } from './workout-model.js'
|
||||
import { exerciseNameFor } from './i18n-core.js'
|
||||
|
||||
const round1 = value => Math.round(value * 10) / 10
|
||||
|
||||
@@ -61,11 +62,11 @@ export function primaryMuscleOf(entry) {
|
||||
return best
|
||||
}
|
||||
|
||||
function exerciseName(entry) {
|
||||
function resolvedExerciseName(entry) {
|
||||
// Imported history often has no name snapshot (entries are { id, sets, topW }) - the
|
||||
// catalogue (or the registered custom) is the canonical name source.
|
||||
const ex = entry && typeof entry === 'object' ? EXIDX[entry.id] : null
|
||||
if (ex?.n) return ex.n
|
||||
if (ex?.n) return exerciseNameFor(ex)
|
||||
if (entry?.muscleSnapshot?.n) return entry.muscleSnapshot.n
|
||||
return entry && typeof entry === 'object' && entry.n ? entry.n : null
|
||||
}
|
||||
@@ -97,7 +98,7 @@ export function strengthExerciseRows(S, now) {
|
||||
const decay = lastAt == null ? STRENGTH_FLOOR : strengthFromAge(Number(now) - lastAt)
|
||||
rows.push({
|
||||
id,
|
||||
name: exerciseName(entry) || id,
|
||||
name: resolvedExerciseName(entry) || id,
|
||||
est: best.est,
|
||||
estDate: best.d,
|
||||
primary: primaryMuscleOf(entry) ? primaryMuscleOf(entry).slug : null,
|
||||
@@ -129,7 +130,7 @@ export function strengthExerciseRowsForMuscle(S, now, slug) {
|
||||
const primary = primaryMuscleOf(entry)
|
||||
seen.set(entry.id, {
|
||||
id: entry.id,
|
||||
name: exerciseName(entry) || entry.id,
|
||||
name: resolvedExerciseName(entry) || entry.id,
|
||||
weight,
|
||||
primary: primary ? primary.slug : null,
|
||||
est: best.est,
|
||||
|
||||
@@ -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,76 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { workoutVolume, insertWarmupRow, buildSets } from './history.js'
|
||||
import { applyPrescription } from './progression.js'
|
||||
|
||||
// The config sheet tells users warm-ups are "left out of volume, records and progression",
|
||||
// and history.js repeats that as an invariant in a comment. Volume was the one place it
|
||||
// was false — harmless while warm-ups were hand-added and rare, wrong now that a routine
|
||||
// plans them by default and the number is written into the saved workout for good.
|
||||
describe('warm-ups and volume', () => {
|
||||
const w = {
|
||||
entries: [{
|
||||
id: 'bench',
|
||||
sets: [
|
||||
{ w: 50, r: 5, done: true, phase: 'warmup', warmup: true },
|
||||
{ w: 75, r: 5, done: true, phase: 'warmup', warmup: true },
|
||||
{ w: 87.5, 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 },
|
||||
],
|
||||
}],
|
||||
}
|
||||
|
||||
it('counts only the work sets', () => {
|
||||
expect(workoutVolume(w)).toBe(1500)
|
||||
})
|
||||
|
||||
it('a warm-up adds nothing, whatever it weighs', () => {
|
||||
const heavy = { entries: [{ id: 'b', sets: [{ w: 200, r: 10, done: true, phase: 'warmup', warmup: true }] }] }
|
||||
expect(workoutVolume(heavy)).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
// A warm-up must never be heavier than the set it warms you up for. The ramp branch clamps
|
||||
// to the work weight; the early-return branch did not, so a hand-edited warm-up above the
|
||||
// work weight propagated into every warm-up added after it.
|
||||
describe('a warm-up never outweighs the work set', () => {
|
||||
// The 120 is something the user typed, and it stays: silently rewriting their own edit
|
||||
// would be worse than leaving it. What must not happen is the NEW row inheriting it, which
|
||||
// is how one bad number used to spread through the whole warm-up block.
|
||||
it('does not copy a hand-edited warm-up that sits above the work weight', () => {
|
||||
const rows = [{ warmup: true, phase: 'warmup', w: 120, r: 5 }, { w: 100, r: 5 }]
|
||||
const out = insertWarmupRow(rows, 'reps', { reps: 5 }, 2.5)
|
||||
expect(out.map(r => r.w)).toEqual([120, 100, 100])
|
||||
expect(out[1].phase).toBe('warmup')
|
||||
})
|
||||
|
||||
it('still ramps normally when the previous warm-up is below the work weight', () => {
|
||||
const rows = [{ warmup: true, phase: 'warmup', w: 50, r: 5 }, { w: 100, r: 5 }]
|
||||
const out = insertWarmupRow(rows, 'reps', { reps: 5 }, 2.5)
|
||||
expect(out.filter(r => r.phase === 'warmup').map(r => r.w)).toEqual([50, 75])
|
||||
})
|
||||
})
|
||||
|
||||
// buildSets prepends the warm-ups, then applyPrescription rewrites the WORK rows only — so a
|
||||
// ramp built against last session's weight is stale the moment progression moves. On a deload
|
||||
// that put the last warm-up above every work set.
|
||||
describe('the ramp follows the prescribed weight', () => {
|
||||
const S = { workouts: [], exWeights: {}, routines: [] }
|
||||
const cfg = { id: 'bench', sets: 3, reps: 5, weight: 100, warmupSets: 2 }
|
||||
|
||||
it('re-ramps after a deload instead of aiming at the old weight', () => {
|
||||
const rows = applyPrescription(buildSets(S, cfg, { step: 2.5 }), { kind: 'deload', weight: 50 })
|
||||
const warm = rows.filter(r => r.phase === 'warmup').map(r => r.w)
|
||||
const work = rows.filter(r => r.phase !== 'warmup').map(r => r.w)
|
||||
expect(work).toEqual([50, 50, 50])
|
||||
for (const x of warm) expect(x).toBeLessThanOrEqual(50)
|
||||
expect(warm).toEqual([25, 37.5])
|
||||
})
|
||||
|
||||
it('re-ramps after a bump', () => {
|
||||
const rows = applyPrescription(buildSets(S, cfg, { step: 2.5 }), { kind: 'up', weight: 150 })
|
||||
expect(rows.filter(r => r.phase !== 'warmup').map(r => r.w)).toEqual([150, 150, 150])
|
||||
expect(rows.filter(r => r.phase === 'warmup').map(r => r.w)).toEqual([75, 112.5])
|
||||
})
|
||||
})
|
||||
@@ -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])
|
||||
})
|
||||
})
|
||||
@@ -22,6 +22,112 @@ export function isWarmupRow(set) {
|
||||
return phaseForSet(set) === 'warmup'
|
||||
}
|
||||
|
||||
// A row's shape beyond warm-up/work: 'straight' (default), 'dropset' (a main set followed by
|
||||
// weight drops logged with no rest) or 'restpause' (an activation set followed by short-rest
|
||||
// bursts). Both extras ride on the row itself — same card, not a new set in the array — the
|
||||
// same trick `phase` uses for warm-ups, so the rest of the app can keep reading a row's own
|
||||
// `w`/`r` and stay correct without knowing this field exists.
|
||||
export function setType(set) {
|
||||
const source = objectOf(set)
|
||||
return source.type === 'dropset' || source.type === 'restpause' ? source.type : 'straight'
|
||||
}
|
||||
export const isDropSet = set => setType(set) === 'dropset'
|
||||
export const isRestPauseSet = set => setType(set) === 'restpause'
|
||||
|
||||
/** A drop-set's weight drops, oldest first; empty for anything else. */
|
||||
export function dropsOf(set) {
|
||||
const source = objectOf(set)
|
||||
return isDropSet(source) && Array.isArray(source.drops) ? source.drops : []
|
||||
}
|
||||
|
||||
/** A rest-pause set's short-rest bursts, oldest first; empty for anything else. */
|
||||
export function clustersOf(set) {
|
||||
const source = objectOf(set)
|
||||
return isRestPauseSet(source) && Array.isArray(source.clusters) ? source.clusters : []
|
||||
}
|
||||
|
||||
/**
|
||||
* Weight x reps from a drop-set's drops, on top of its own main set. The 1RM estimate and the
|
||||
* progression engine deliberately read only a row's own `w`/`r` (the heaviest effort), so this
|
||||
* is the one place a drop-set's extra volume gets added back in for totals.
|
||||
*
|
||||
* A rest-pause row is different: its own `r` IS the total (every burst's reps included), and
|
||||
* `clusters` is only how that total breaks down — not extra volume on top of it. Adding
|
||||
* `clustersOf(set)` here as well would double-count the same reps twice.
|
||||
*/
|
||||
export function extraVolumeOf(set) {
|
||||
const drops = dropsOf(set)
|
||||
return drops.reduce((v, d) => v + (Number(d?.w) || 0) * (Number(d?.r) || 0), 0)
|
||||
}
|
||||
|
||||
/** Append a weight drop to a row, marking it a drop-set. */
|
||||
export function addDrop(set, drop) {
|
||||
const prev = Array.isArray(objectOf(set).drops) ? objectOf(set).drops : []
|
||||
return { ...objectOf(set), type: 'dropset', drops: [...prev, { w: Number(drop?.w) || 0, r: Number(drop?.r) || 0 }] }
|
||||
}
|
||||
|
||||
/** Append a short-rest burst to a row, marking it a rest-pause set. */
|
||||
export function addCluster(set, cluster) {
|
||||
const prev = Array.isArray(objectOf(set).clusters) ? objectOf(set).clusters : []
|
||||
return { ...objectOf(set), type: 'restpause', clusters: [...prev, { r: Number(cluster?.r) || 0, restSec: Number(cluster?.restSec) || 0 }] }
|
||||
}
|
||||
|
||||
/** Remove one drop by index. Clearing the last one reverts the row to a straight set. */
|
||||
export function removeDropAt(set, i) {
|
||||
const drops = (objectOf(set).drops || []).filter((_, idx) => idx !== i)
|
||||
return drops.length ? { ...objectOf(set), drops } : { ...objectOf(set), type: 'straight', drops }
|
||||
}
|
||||
|
||||
/** Remove one burst by index. Clearing the last one reverts the row to a straight set. */
|
||||
export function removeClusterAt(set, i) {
|
||||
const clusters = (objectOf(set).clusters || []).filter((_, idx) => idx !== i)
|
||||
return clusters.length ? { ...objectOf(set), clusters } : { ...objectOf(set), type: 'straight', clusters }
|
||||
}
|
||||
|
||||
/** Patch one drop's fields in place (weight/reps steppers edit an existing drop). */
|
||||
export function setDropAt(set, i, patch) {
|
||||
const drops = (objectOf(set).drops || []).slice()
|
||||
if (!drops[i]) return set
|
||||
drops[i] = { ...drops[i], ...patch }
|
||||
return { ...objectOf(set), drops }
|
||||
}
|
||||
|
||||
/** Patch one burst's fields in place (a reps stepper edits an existing burst). */
|
||||
export function setClusterAt(set, i, patch) {
|
||||
const clusters = (objectOf(set).clusters || []).slice()
|
||||
if (!clusters[i]) return set
|
||||
clusters[i] = { ...clusters[i], ...patch }
|
||||
return { ...objectOf(set), clusters }
|
||||
}
|
||||
|
||||
/** Suggested weight for the next drop: pct% lighter than the previous weight, rounded to .5. */
|
||||
export function nextDropWeight(prevWeight, pct = 20) {
|
||||
const p = Math.min(90, Math.max(1, Number(pct) || 20))
|
||||
return Math.round(Math.max(0, (Number(prevWeight) || 0) * (1 - p / 100)) * 2) / 2
|
||||
}
|
||||
|
||||
/** Suggested reps for the next rest-pause burst: roughly half the previous rep count. */
|
||||
export function nextBurstReps(prevReps) {
|
||||
return Math.max(1, Math.round((Number(prevReps) || 0) / 2))
|
||||
}
|
||||
|
||||
/**
|
||||
* Split a rest-pause total (the extra reps you want past the activation set) into a descending,
|
||||
* roughly-halving sequence of bursts that adds back up to it — e.g. 12 -> [6, 3, 2, 1]. This is
|
||||
* what a planned rest-pause exercise configures directly, rather than a burst count picked by
|
||||
* hand: you say how many reps you want out of the whole rest-pause portion, not how many rests.
|
||||
*/
|
||||
export function splitBurstReps(total) {
|
||||
const bursts = []
|
||||
let remaining = Math.max(0, Math.round(Number(total) || 0))
|
||||
while (remaining > 0) {
|
||||
const burst = Math.min(remaining, nextBurstReps(remaining))
|
||||
bursts.push(burst)
|
||||
remaining -= burst
|
||||
}
|
||||
return bursts
|
||||
}
|
||||
|
||||
export function normalizeMode(value, fallback = 'reps') {
|
||||
const token = typeof value === 'string' ? value.trim().toLowerCase() : ''
|
||||
if (MODES.includes(token)) return token
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import {
|
||||
phaseForSet, isWarmupRow, modeForSet, modeForEntry,
|
||||
setType, isDropSet, isRestPauseSet, dropsOf, clustersOf, extraVolumeOf,
|
||||
addDrop, addCluster, removeDropAt, removeClusterAt, setDropAt, setClusterAt,
|
||||
nextDropWeight, nextBurstReps, splitBurstReps,
|
||||
} from './workout-model.js'
|
||||
|
||||
describe('phaseForSet / isWarmupRow', () => {
|
||||
it('reads both the explicit phase and the legacy boolean', () => {
|
||||
expect(isWarmupRow({ phase: 'warmup' })).toBe(true)
|
||||
expect(isWarmupRow({ warmup: true })).toBe(true)
|
||||
expect(isWarmupRow({ phase: 'work' })).toBe(false)
|
||||
expect(isWarmupRow({})).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('setType / isDropSet / isRestPauseSet', () => {
|
||||
it('defaults to straight for anything without a recognised type', () => {
|
||||
expect(setType({})).toBe('straight')
|
||||
expect(setType({ type: 'nonsense' })).toBe('straight')
|
||||
expect(setType(null)).toBe('straight')
|
||||
expect(isDropSet({})).toBe(false)
|
||||
expect(isRestPauseSet({})).toBe(false)
|
||||
})
|
||||
|
||||
it('recognises drop-set and rest-pause rows', () => {
|
||||
expect(setType({ type: 'dropset' })).toBe('dropset')
|
||||
expect(isDropSet({ type: 'dropset' })).toBe(true)
|
||||
expect(setType({ type: 'restpause' })).toBe('restpause')
|
||||
expect(isRestPauseSet({ type: 'restpause' })).toBe(true)
|
||||
})
|
||||
|
||||
it('is a separate axis from warm-up — a row is not both at once by construction, but phase never leaks into type', () => {
|
||||
expect(setType({ phase: 'warmup', type: 'dropset' })).toBe('dropset')
|
||||
expect(isWarmupRow({ phase: 'warmup', type: 'dropset' })).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('dropsOf / clustersOf', () => {
|
||||
it('only return rows for their own type', () => {
|
||||
const drop = { type: 'dropset', drops: [{ w: 80, r: 5 }] }
|
||||
const burst = { type: 'restpause', clusters: [{ r: 4, restSec: 15 }] }
|
||||
expect(dropsOf(drop)).toEqual([{ w: 80, r: 5 }])
|
||||
expect(clustersOf(drop)).toEqual([])
|
||||
expect(clustersOf(burst)).toEqual([{ r: 4, restSec: 15 }])
|
||||
expect(dropsOf(burst)).toEqual([])
|
||||
})
|
||||
|
||||
it('is defensive about missing/malformed arrays', () => {
|
||||
expect(dropsOf({ type: 'dropset' })).toEqual([])
|
||||
expect(dropsOf({ type: 'dropset', drops: 'nope' })).toEqual([])
|
||||
expect(clustersOf(null)).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('extraVolumeOf', () => {
|
||||
it('sums weight x reps across a drop-set\'s own drops', () => {
|
||||
const set = { type: 'dropset', w: 100, r: 5, drops: [{ w: 80, r: 5 }, { w: 60, r: 6 }] }
|
||||
expect(extraVolumeOf(set)).toBe(80 * 5 + 60 * 6)
|
||||
})
|
||||
|
||||
it('is zero for rest-pause — its own r is already the total across every burst, so clusters are a breakdown, not extra volume', () => {
|
||||
const set = { type: 'restpause', w: 60, r: 20, clusters: [{ r: 10, restSec: 15 }, { r: 5, restSec: 15 }, { r: 3, restSec: 15 }, { r: 1, restSec: 15 }, { r: 1, restSec: 15 } ] }
|
||||
expect(extraVolumeOf(set)).toBe(0)
|
||||
})
|
||||
|
||||
it('is zero for a straight or warm-up set', () => {
|
||||
expect(extraVolumeOf({ w: 100, r: 5 })).toBe(0)
|
||||
expect(extraVolumeOf({ phase: 'warmup', w: 20, r: 8 })).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('addDrop / addCluster', () => {
|
||||
it('appends a drop and stamps the row as a drop-set', () => {
|
||||
const set = { w: 100, r: 5, done: true }
|
||||
const next = addDrop(set, { w: 80, r: 5 })
|
||||
expect(next.type).toBe('dropset')
|
||||
expect(next.drops).toEqual([{ w: 80, r: 5 }])
|
||||
expect(set.drops).toBeUndefined() // pure — the original row is untouched
|
||||
expect(addDrop(next, { w: 60, r: 4 }).drops).toEqual([{ w: 80, r: 5 }, { w: 60, r: 4 }])
|
||||
})
|
||||
|
||||
it('appends a burst and stamps the row as a rest-pause set', () => {
|
||||
const set = { w: 60, r: 8, done: true }
|
||||
const next = addCluster(set, { r: 4, restSec: 15 })
|
||||
expect(next.type).toBe('restpause')
|
||||
expect(next.clusters).toEqual([{ r: 4, restSec: 15 }])
|
||||
})
|
||||
})
|
||||
|
||||
describe('removeDropAt / removeClusterAt', () => {
|
||||
it('removes one entry by index, leaving the rest in place', () => {
|
||||
const set = { type: 'dropset', w: 100, r: 5, drops: [{ w: 80, r: 5 }, { w: 60, r: 5 }] }
|
||||
expect(removeDropAt(set, 0).drops).toEqual([{ w: 60, r: 5 }])
|
||||
})
|
||||
|
||||
it('removes one burst by index', () => {
|
||||
const set = { type: 'restpause', w: 60, r: 8, clusters: [{ r: 4, restSec: 15 }, { r: 3, restSec: 15 }] }
|
||||
expect(removeClusterAt(set, 1).clusters).toEqual([{ r: 4, restSec: 15 }])
|
||||
})
|
||||
|
||||
it('reverts the row to a straight set once its last drop/burst is removed', () => {
|
||||
const drop = { type: 'dropset', w: 100, r: 5, drops: [{ w: 80, r: 5 }] }
|
||||
expect(removeDropAt(drop, 0)).toEqual({ type: 'straight', w: 100, r: 5, drops: [] })
|
||||
expect(isDropSet(removeDropAt(drop, 0))).toBe(false)
|
||||
|
||||
const burst = { type: 'restpause', w: 60, r: 8, clusters: [{ r: 4, restSec: 15 }] }
|
||||
expect(removeClusterAt(burst, 0)).toEqual({ type: 'straight', w: 60, r: 8, clusters: [] })
|
||||
expect(isRestPauseSet(removeClusterAt(burst, 0))).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('setDropAt / setClusterAt', () => {
|
||||
it('patches one drop\'s fields, leaving the others untouched', () => {
|
||||
const set = { type: 'dropset', w: 100, r: 5, drops: [{ w: 80, r: 5 }, { w: 60, r: 5 }] }
|
||||
expect(setDropAt(set, 0, { w: 82.5 }).drops).toEqual([{ w: 82.5, r: 5 }, { w: 60, r: 5 }])
|
||||
expect(setDropAt(set, 1, { r: 6 }).drops).toEqual([{ w: 80, r: 5 }, { w: 60, r: 6 }])
|
||||
})
|
||||
|
||||
it('patches one burst\'s reps', () => {
|
||||
const set = { type: 'restpause', w: 60, r: 8, clusters: [{ r: 4, restSec: 15 }] }
|
||||
expect(setClusterAt(set, 0, { r: 5 }).clusters).toEqual([{ r: 5, restSec: 15 }])
|
||||
})
|
||||
|
||||
it('is a no-op for an index that does not exist', () => {
|
||||
const set = { type: 'dropset', w: 100, r: 5, drops: [{ w: 80, r: 5 }] }
|
||||
expect(setDropAt(set, 3, { w: 1 })).toBe(set)
|
||||
})
|
||||
})
|
||||
|
||||
describe('nextDropWeight / nextBurstReps', () => {
|
||||
it('drops by the given percentage, rounded to the nearest .5', () => {
|
||||
expect(nextDropWeight(100, 20)).toBe(80)
|
||||
expect(nextDropWeight(80, 20)).toBe(64)
|
||||
expect(nextDropWeight(61, 10)).toBe(55)
|
||||
})
|
||||
|
||||
it('defaults to 20% and never goes negative', () => {
|
||||
expect(nextDropWeight(100)).toBe(80)
|
||||
expect(nextDropWeight(0, 20)).toBe(0)
|
||||
})
|
||||
|
||||
it('roughly halves the previous rep count, floored at 1', () => {
|
||||
expect(nextBurstReps(8)).toBe(4)
|
||||
expect(nextBurstReps(1)).toBe(1)
|
||||
expect(nextBurstReps(0)).toBe(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('splitBurstReps', () => {
|
||||
it('splits a total into a descending, roughly-halving sequence that adds back up to it', () => {
|
||||
expect(splitBurstReps(12)).toEqual([6, 3, 2, 1])
|
||||
expect(splitBurstReps(6)).toEqual([3, 2, 1])
|
||||
expect(splitBurstReps(1)).toEqual([1])
|
||||
})
|
||||
|
||||
it('every split sums exactly to the requested total', () => {
|
||||
for (const total of [1, 2, 3, 5, 7, 10, 15, 20, 33]) {
|
||||
expect(splitBurstReps(total).reduce((a, b) => a + b, 0)).toBe(total)
|
||||
}
|
||||
})
|
||||
|
||||
it('is empty for zero or invalid input', () => {
|
||||
expect(splitBurstReps(0)).toEqual([])
|
||||
expect(splitBurstReps(-5)).toEqual([])
|
||||
expect(splitBurstReps(undefined)).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('modeForSet / modeForEntry stay reps-mode for drop-sets and rest-pause sets', () => {
|
||||
it('infers reps mode from the row\'s own r field regardless of type', () => {
|
||||
expect(modeForSet({ type: 'dropset', w: 100, r: 5 })).toBe('reps')
|
||||
expect(modeForSet({ type: 'restpause', w: 60, r: 8 })).toBe('reps')
|
||||
})
|
||||
|
||||
it('an entry mixing straight and drop-set rows still reads as one reps-mode entry', () => {
|
||||
const entry = { sets: [{ w: 100, r: 5 }, { type: 'dropset', w: 100, r: 5, drops: [{ w: 80, r: 5 }] }] }
|
||||
expect(modeForEntry(entry)).toBe('reps')
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user