Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
274a0276e0 | ||
|
|
528cb70a79 | ||
|
|
a7d7f5c24b | ||
|
|
fe585097c8 | ||
|
|
d8c734a2b6 | ||
|
|
087ce34674 | ||
|
|
157ca90f3b | ||
|
|
15c29029c1 | ||
|
|
030a609427 | ||
|
|
8bbf59c001 | ||
|
|
b29a3f6bb0 | ||
|
|
bee9b64b78 | ||
|
|
35181af2aa | ||
|
|
01072ef5e3 | ||
|
|
86ac937d5d | ||
|
|
9cc645c755 | ||
|
|
cbb3630423 | ||
|
|
0109857249 | ||
|
|
edb3e42c43 | ||
|
|
577c86b487 | ||
|
|
13ed730a0c | ||
|
|
7e60ac20f2 | ||
|
|
06a1e0a709 | ||
|
|
d99f0ef2f1 | ||
|
|
d0075eeddf | ||
|
|
86f3476f5f | ||
|
|
9daf637044 | ||
|
|
b2b3577744 | ||
|
|
84e98425cc | ||
|
|
941d911fa9 | ||
|
|
5b5d65b63e | ||
|
|
6c91adefcd | ||
|
|
d1cede21d3 | ||
|
|
9af028bde3 | ||
|
|
eeee4b461c | ||
|
|
551b072c54 | ||
|
|
e007f76d43 | ||
|
|
e28345dd13 | ||
|
|
ba412cb36d | ||
|
|
f554b6b004 | ||
|
|
09949686c2 | ||
|
|
7c69e57b4f | ||
|
|
6aaf2a3eea | ||
|
|
4143ab8676 | ||
|
|
92914dea43 | ||
|
|
fadeb17b6c |
No files matched your search
@@ -33,6 +33,14 @@ RP_NAME=openGym
|
||||
# generate the codes from the admin dashboard):
|
||||
#
|
||||
# INVITE_ONLY=1
|
||||
#
|
||||
# Remove the "Continue without account" button, so a profile is the only way in.
|
||||
# Guest mode keeps everything in the browser and never touches this server, but
|
||||
# on an instance meant for a known set of people it is still the wrong front
|
||||
# door. Anyone already inside as a guest is signed out on their next visit; the
|
||||
# data they made stays in that browser. Defaults to on (guests allowed):
|
||||
#
|
||||
# ALLOW_GUEST=0
|
||||
|
||||
# ── Session length (optional) ──────────────────────────────────────────────
|
||||
# How long a sign-in lasts, in days. Default 90 — long enough that people who
|
||||
|
||||
@@ -6,11 +6,13 @@ on:
|
||||
pull_request:
|
||||
paths:
|
||||
- 'frontend/**'
|
||||
- 'mcp/**'
|
||||
- '.github/workflows/test.yml'
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- 'frontend/**'
|
||||
- 'mcp/**'
|
||||
- '.github/workflows/test.yml'
|
||||
workflow_dispatch:
|
||||
|
||||
@@ -41,3 +43,23 @@ jobs:
|
||||
working-directory: frontend
|
||||
- run: node scripts/check-locales.mjs
|
||||
working-directory: frontend
|
||||
|
||||
mcp:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
- uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version: 22
|
||||
cache: npm
|
||||
cache-dependency-path: mcp/package-lock.json
|
||||
- run: npm ci
|
||||
working-directory: mcp
|
||||
- run: npm test
|
||||
working-directory: mcp
|
||||
# The one check the vitest suite structurally cannot make. The MCP server is a bare node
|
||||
# process, but vitest runs its tests through Vite — import.meta.glob, .jsx imports and
|
||||
# ?raw all resolve happily there. That is how a Vite-only import reached a shared lib
|
||||
# module with 33 green tests standing over a server that died on startup.
|
||||
- run: npm run check:node-loadable
|
||||
working-directory: mcp
|
||||
@@ -13,3 +13,4 @@ frontend/dist/
|
||||
node_modules/
|
||||
*.log
|
||||
.DS_Store
|
||||
node_modules
|
||||
+166
@@ -1,5 +1,171 @@
|
||||
# Changelog
|
||||
|
||||
## v1.2.6 — 2026-08-11
|
||||
|
||||
The muscle map learned to answer a second question — not just where the volume went, but what is
|
||||
still recovering from it. Plus: a freestyle session no longer starts from blanks, the rest timer
|
||||
can reach you in another app, and a self-hosted instance can insist that everyone using it has an
|
||||
account.
|
||||
|
||||
### The muscle map, read as recovery (#44)
|
||||
|
||||
- 🔥 **A `Balance | Fatigue | Strength` switch on the Stats muscle card.** Balance is the map you
|
||||
already had and is untouched. Fatigue shades each muscle by how much of the recent training it
|
||||
is still carrying; Strength shades it by how long it has been since you trained it at all, with
|
||||
the weeks-since count spelled out underneath.
|
||||
- **Fatigue is volume-sensitive and fades smoothly.** A hard twelve-set chest day starts near the
|
||||
top and takes about six days to read ready again; a single set barely registers and is gone in
|
||||
two. It decays continuously on a 36-hour half-life rather than expiring at a window edge, so the
|
||||
map never flips from "fatigued" to "ready" between one look and the next.
|
||||
- **Strength holds for two weeks, then decays toward a floor.** A muscle you have not trained in
|
||||
months reads detrained rather than absent, which is the state that actually tells you something.
|
||||
- Both views are pure functions over your existing history — no new stored data, no schema change,
|
||||
nothing sent anywhere.
|
||||
|
||||
### The rest timer can reach you in another app (#49)
|
||||
|
||||
- ⏰ **A system notification when rest is over**, on top of the beep, for when you have switched to
|
||||
another tab or app mid-session. Permission is asked the first time a rest starts, and everything
|
||||
degrades quietly where notifications are unsupported or refused.
|
||||
- It goes through the service worker where the browser requires that — which is most phones — and
|
||||
falls back to the direct API elsewhere. No new dependencies; the existing server push path is
|
||||
untouched.
|
||||
|
||||
### Rows now strain the rear delts (#51)
|
||||
|
||||
- **Four row variations gained rear-deltoid secondaries** — barbell, dumbbell, inverted and cable
|
||||
seated rows — so the muscle map spreads their load the way the lift actually does. The overrides
|
||||
live in a small table that survives a regeneration of the exercise dataset rather than being
|
||||
edited into the generated data.
|
||||
|
||||
### An instance can require an account (#42)
|
||||
|
||||
- 🔒 **`ALLOW_GUEST=0` removes the "Continue without account" button.** Guest mode keeps everything
|
||||
in the browser and never touches the server — no account, no sync, nothing the admin dashboard
|
||||
can see — so on an instance meant for a known set of people it was a door leading nowhere
|
||||
useful, and until now there was no way to close it.
|
||||
- **It also ends guest sessions that already exist.** Guests never authenticate, so there is no
|
||||
request for the server to start refusing; the switch reaches someone already inside on their
|
||||
next visit, when the app checks the config and returns them to the login screen. Their data is
|
||||
not deleted — it stays in that browser, and moves into a real profile if they create one on the
|
||||
same device.
|
||||
- **A server it cannot reach is not a server that said no.** The button is only withdrawn on an
|
||||
explicit `allow_guest: false`; a failed config request, or a server too old to send the flag at
|
||||
all, leaves guest mode exactly as it was. An instance that is merely offline for a moment does
|
||||
not lock out everyone who never made an account.
|
||||
- **Default is on, so nothing changes for existing instances.** Set it alongside `INVITE_ONLY=1`:
|
||||
invite-only governs who may *create a profile* and says nothing about the guest button, which
|
||||
never creates one.
|
||||
|
||||
### Freestyle sessions start where you left off
|
||||
|
||||
- 🏋️ **Adding an exercise to an empty workout now prefills it from the last time you trained
|
||||
it** — the same number of sets, with each row's reps and weight carried across by position.
|
||||
Cardio brings its duration and speed, a hold brings its seconds. Until now every row opened on
|
||||
the config-sheet defaults, so the first thing a freestyle session asked of you was to retype
|
||||
what you already did last week.
|
||||
- **The config sheet agrees with the rows it is about to create.** It opens on the last target you
|
||||
actually trained rather than the generic default, so the set count you confirm is the set count
|
||||
you get.
|
||||
- **Planned sessions are untouched.** A routine-driven workout still runs the progression logic and
|
||||
still applies its prescription; only the freestyle path — which has no prescription to apply —
|
||||
reads from history instead.
|
||||
|
||||
Contributed by [@Space-Hermes](https://github.com/Space-Hermes) in
|
||||
[#50](https://github.com/DuarteSantos8/openGym/pull/50).
|
||||
|
||||
### Pair exercises into a superset mid-session (#64)
|
||||
|
||||
- 🔗 **"Make superset with previous / next" on each exercise card.** Two exercises paired in the
|
||||
session collapse into a single *Superset* card — do them back-to-back, rest once at the end —
|
||||
with an **Unpair** button in the header. No planning ahead required; pair them when you decide
|
||||
to, in the workout.
|
||||
- **Groups are any size.** Pairing the end of one group to the start of another merges them, and
|
||||
the header wording stays correct past two exercises.
|
||||
- **Unpairing cleans up after itself.** A group reduced to one exercise is dissolved rather than
|
||||
left as a superset of one, and the pairing helpers never mutate the running session.
|
||||
- Session-only by design: pairings drive the workout, and history stores the sets.
|
||||
|
||||
Contributed by [@Space-Hermes](https://github.com/Space-Hermes) in
|
||||
[#64](https://github.com/DuarteSantos8/openGym/pull/64).
|
||||
|
||||
### The muscle map stops rewriting the catalogue (#67)
|
||||
|
||||
- **The curated secondary-muscle additions are now an overlay, not a mutation.** The four row
|
||||
exercises that strain the rear delts used to get that written into the shared exercise dataset
|
||||
at import time, which meant export, print and import saw a catalogue that had been edited
|
||||
underneath them. They are derived at the read points instead, so the dataset stays pristine.
|
||||
- The detail sheet's tag row reads through the same overlay, so those muscles still show where
|
||||
they always did.
|
||||
|
||||
Contributed by [@Space-Hermes](https://github.com/Space-Hermes) in
|
||||
[#67](https://github.com/DuarteSantos8/openGym/pull/67).
|
||||
|
||||
### Fixes
|
||||
|
||||
- 🖼️ **Exercise images and animations were blank on the routine screen** ([#79]). The media paths
|
||||
were relative, and `/plan/r/:id` is the app's only two-segment route — so the browser asked for
|
||||
`/plan/r/img/…` and got a 404 with nothing in the console to say why. Every other screen was
|
||||
fine, which is what made it look like a one-screen mystery. Reported with the root cause already
|
||||
found, by [@lemi1000](https://github.com/lemi1000).
|
||||
- 📥 **Imports mapped more of what other apps export** ([#74]). Treadmill, Goblet Squat, Cycling and
|
||||
Cable Core Pallof Press arrived as *custom* exercises rather than catalogue ones — no word
|
||||
overlap could reach the names openGym stores them under. Those and their neighbours are now in
|
||||
the alias table. Already-imported history stays custom; new imports resolve. Reported by
|
||||
[@KiloOscarSix](https://github.com/KiloOscarSix).
|
||||
- **A progression edge case that could loop forever** ([#60]). An entry left with nothing but
|
||||
warm-up rows seeded the set-growth loop from a warm-up, which could never satisfy its own exit
|
||||
condition. It leaves the entry alone instead. Contributed by
|
||||
[@Space-Hermes](https://github.com/Space-Hermes).
|
||||
- Documented that `VITE_IMG_BASE` / `VITE_GIF_BASE` are build-time values, so setting them next to
|
||||
`docker compose` does nothing on a prebuilt image.
|
||||
|
||||
[#79]: https://github.com/DuarteSantos8/openGym/issues/79
|
||||
[#74]: https://github.com/DuarteSantos8/openGym/issues/74
|
||||
[#60]: https://github.com/DuarteSantos8/openGym/pull/60
|
||||
|
||||
## v1.2.5 — 2026-08-04
|
||||
|
||||
Nothing in the app itself changed. This release adds an optional side door: a small server that
|
||||
lets an AI assistant you already run — Claude Desktop, Cursor, Cline — answer questions about
|
||||
your own training, off the same files your instance already writes. If you don't use one, this
|
||||
release is invisible to you.
|
||||
|
||||
### Ask an AI about your training, without the data leaving your box (#19)
|
||||
|
||||
- 🤖 **An MCP server (`mcp/`)** — opt-in, read-only, and not part of the Docker build. Your LLM
|
||||
client spawns it as a local process, it reads `./data` directly, and it exits when the client
|
||||
disconnects. No new container, no extra auth on the api, no third-party service, nothing over
|
||||
the network. *"What did I bench last week?", "what's my estimated 1RM on deadlift?", "which
|
||||
muscles have I been neglecting?"*
|
||||
- **The answers match the Stats screen because they are the same numbers.** The server calls the
|
||||
very functions in `frontend/src/lib/` the app already computes with, rather than reimplementing
|
||||
them. Eight tools: routines, the week plan, workouts, one session in detail, body weight,
|
||||
estimated 1RM and muscle balance.
|
||||
- **Read-only on purpose.** Logging a workout from an assistant needs a long-lived token the api
|
||||
does not have yet, plus a lock against the web UI's read-modify-write. Until both exist, the
|
||||
server answers questions and does nothing else. It never reads passkey material, VAPID keys or
|
||||
session state — only the profile it was pointed at.
|
||||
- `docker-compose.yml` is untouched and nothing new enters the image, so an instance that ignores
|
||||
this ships exactly what it shipped before. Setup is in [mcp/README.md](mcp/README.md).
|
||||
|
||||
### Under the hood
|
||||
|
||||
- The pure half of `i18n.js` — the language state, the constants, the readers — moved into
|
||||
`i18n-core.js`, so the helpers under `frontend/src/lib/` can be loaded by a plain Node process
|
||||
and not only by Vite. `i18n.js` keeps the Vite-only parts (the locale-pack loader, the React
|
||||
hook) and re-exports the rest, so nothing that imports it had to change.
|
||||
- The shared lib modules that only need `t` now take it from the core directly. A Vite-only
|
||||
import inside a shared module is invisible under vitest, which transforms it, and fatal to the
|
||||
MCP server, which does not — so the shared half stays clear of the bundler half by
|
||||
construction rather than by remembering to.
|
||||
- `npm run check:node-loadable` in `mcp/` walks the server's import graph under a bare `node`,
|
||||
which is the one thing the test suite cannot do from inside Vite. CI runs it, alongside the
|
||||
MCP tests — neither had ever run there before.
|
||||
|
||||
The MCP server was contributed by [@Pengboi](https://github.com/Pengboi) — the first feature in
|
||||
openGym written by someone other than me. Thank you.
|
||||
|
||||
## v1.2.4 — 2026-08-01
|
||||
|
||||
The effort ratings you have been recording since v1.2.3 now answer questions, and bodyweight
|
||||
|
||||
@@ -12,6 +12,9 @@ api/ backend — server.js (Node, no framework), one dependency (@simplewe
|
||||
web/ multi-stage Dockerfile (builds frontend → nginx) + nginx.conf (serves app, proxies /api).
|
||||
media/ exercise img/gif (gitignored, fetched at runtime).
|
||||
docs/ self-hosting guide.
|
||||
mcp/ optional Model Context Protocol server — read-only stdio bridge for LLM apps
|
||||
(Claude Desktop, Cursor, …) to query a user's workouts/1RM/muscle balance. Not in
|
||||
the Docker build; only runs when an LLM client spawns it. See mcp/README.md.
|
||||
```
|
||||
|
||||
## Running for development
|
||||
|
||||
@@ -81,6 +81,7 @@ as a home-screen app, passkey sign-in, offline support, sync across your phone a
|
||||
- 🌍 **12 languages** — full UI translation (EN, DE, ES, FR, IT, PT, PL, TR, RU, ZH, KO, HI); exercise instructions localized in 10 of them, loaded on demand so the app stays fast
|
||||
- 📥 **Bring your history with you** — import from **FitNotes** (Android and iOS), **Strong** and **Hevy**, or body weight straight out of an **Apple Health** export. Exercise names are matched against the library and anything unrecognised becomes one of your own exercises, so nothing in the file is dropped
|
||||
- 📦 **Yours to keep** — one-tap JSON export/import, guest mode, **no telemetry**
|
||||
- 🤖 **Ask an AI about your training** (optional) — an [MCP server](mcp/README.md) lets a client like Claude Desktop or Cursor read your history in your own words: *"what did I bench last week?"*. Read-only, spawned locally by the client, nothing leaves your box. Not in the Docker build — if you don't use an AI assistant, it isn't there
|
||||
- 📱 **Standalone Android app** — the whole tracker as a sideloadable APK: no account, no server, data on the phone, native workout reminders ([download](https://opengym.duarte-santos.ch))
|
||||
|
||||
## Quick start (self-host)
|
||||
@@ -154,6 +155,7 @@ All via `.env` (see `.env.example`):
|
||||
| `RP_NAME` | Name shown in the passkey prompt | `openGym` |
|
||||
| `ADMIN_UIDS` | User ids that get the admin dashboard (comma-separated) | *(none)* |
|
||||
| `INVITE_ONLY` | Require an invite code to create a profile | *(off)* |
|
||||
| `ALLOW_GUEST` | Offer "Continue without account" — set `0` to require a profile | *(on)* |
|
||||
|
||||
Push notification keys are generated on first run and saved to `./data/vapid.json` — nothing to set.
|
||||
|
||||
@@ -184,6 +186,10 @@ lives in pure functions under `frontend/src/lib/` with tests next to them: `npm
|
||||
`frontend/`. Vitest is a dev dependency; the app itself ships no runtime dependencies beyond
|
||||
React, the router and Zustand.
|
||||
|
||||
The same pure helpers power an optional MCP server (`mcp/`) that lets an LLM client like
|
||||
Claude Desktop read your data over stdio — see [mcp/README.md](mcp/README.md). Opt-in, not
|
||||
in the Docker build.
|
||||
|
||||
## Community
|
||||
|
||||
- **[Q&A](https://github.com/DuarteSantos8/openGym/discussions/categories/q-a)** — self-hosting
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "gym-api",
|
||||
"version": "1.2.4",
|
||||
"version": "1.2.6",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "server.js",
|
||||
|
||||
+6
-1
@@ -19,6 +19,11 @@ const RP_NAME = process.env.RP_NAME || 'openGym';
|
||||
// code the admin generates. Both default off so a fresh self-hosted instance stays open.
|
||||
const ADMIN_UIDS = (process.env.ADMIN_UIDS || '').split(',').map(s => s.trim()).filter(Boolean);
|
||||
const INVITE_ONLY = /^(1|true|yes|on)$/i.test(process.env.INVITE_ONLY || '');
|
||||
// Guest mode ("Continue without account") keeps everything in the browser and never touches this
|
||||
// server — but on an instance meant for a known set of people, an entrance nobody can walk back
|
||||
// out of is still the wrong front door (#42). Default ON, so existing instances are unchanged;
|
||||
// the polarity is inverted from INVITE_ONLY because the safe default here is the permissive one.
|
||||
const ALLOW_GUEST = !/^(0|false|no|off)$/i.test(process.env.ALLOW_GUEST || '');
|
||||
// 90 days keeps someone who trains a few times a week permanently signed in without a stolen
|
||||
// cookie staying good for a year. Overridable because a family instance and one on the open
|
||||
// internet don't want the same number. Only affects cookies minted from now on — the expiry is
|
||||
@@ -256,7 +261,7 @@ const routes = {
|
||||
'GET /api/health': async (req, res) => json(res, 200, { ok: true, users: db.users.length }),
|
||||
|
||||
// Public config the login screen needs before anyone is signed in.
|
||||
'GET /api/config': async (req, res) => json(res, 200, { invite_only: INVITE_ONLY }),
|
||||
'GET /api/config': async (req, res) => json(res, 200, { invite_only: INVITE_ONLY, allow_guest: ALLOW_GUEST }),
|
||||
|
||||
'GET /api/me': async (req, res) => {
|
||||
const user = readSession(req);
|
||||
|
||||
+23
-1
@@ -90,11 +90,12 @@ Visit `https://gym.example.com`, create your profile, and add it to your home sc
|
||||
Anyone who can reach the URL can create their own profile — each gets isolated data. That's the
|
||||
default: open signup, no admin.
|
||||
|
||||
If you'd rather control who gets in, two optional settings in `.env` turn that around:
|
||||
If you'd rather control who gets in, three optional settings in `.env` turn that around:
|
||||
|
||||
```bash
|
||||
ADMIN_UIDS=youruserid # comma-separated; these users get the admin dashboard
|
||||
INVITE_ONLY=1 # new profiles need an invite code
|
||||
ALLOW_GUEST=0 # remove "Continue without account"
|
||||
```
|
||||
|
||||
Register your own passkey profile first, then find your id in `./data/db.json` under `users[].id`
|
||||
@@ -104,6 +105,16 @@ out and locked out everywhere until you re-enable it), and — with `INVITE_ONLY
|
||||
revoking invite codes. Existing accounts keep working when you switch invite-only on. Admin access
|
||||
is gated by your passkey and enforced server-side, so it needs no separate login.
|
||||
|
||||
`INVITE_ONLY=1` and `ALLOW_GUEST=0` answer different questions and are usually set together.
|
||||
Invite-only controls who may *create a profile*; it says nothing about the **Continue without
|
||||
account** button, which never creates one. Guest mode keeps everything in that browser and never
|
||||
talks to the server — there is no account, no sync and nothing for the admin dashboard to show —
|
||||
so on an instance meant for a known set of people it is a door that leads nowhere useful. With
|
||||
`ALLOW_GUEST=0` the button is gone, and anyone already using the app as a guest is returned to the
|
||||
login screen on their next visit. Their data is not deleted: it stays in that browser and comes
|
||||
back if you ever switch guests on again, or moves into a real profile if they create one on the
|
||||
same device.
|
||||
|
||||
Prefer to keep the whole thing off the open internet? A VPN or an auth proxy (Authelia, Cloudflare
|
||||
Access…) in front still works, and composes with the above.
|
||||
|
||||
@@ -167,3 +178,14 @@ downloaded media are untouched.
|
||||
| Day reminder fires at the wrong time | Toggle it off and on in Settings so it re-detects your browser's timezone (also happens automatically on every app load — see section 6). |
|
||||
| Want to reset a stuck login | Delete the cookie in your browser; sessions are just signed cookies. |
|
||||
| `docker compose pull` fails with "denied" / "unauthorized" | The prebuilt images aren't published yet, or need to be, or the GHCR package is still private — build from source instead (`docker compose up -d --build`). |
|
||||
| Exercise images/GIFs blank when a routine is open | Fixed in current images (issue #79). On an older build, see the note below. |
|
||||
|
||||
### `VITE_IMG_BASE` / `VITE_GIF_BASE` are build-time, not run-time
|
||||
|
||||
These two are read by Vite when the frontend is **compiled**, so their values are baked into
|
||||
the shipped JavaScript bundle. Setting them in the `.env` next to `docker compose` has no
|
||||
effect on an already-built image — the bundle has already made up its mind.
|
||||
|
||||
They are only useful if you build the frontend yourself (`docker compose up -d --build`, or a
|
||||
`npm run build` with the variables exported). If you need to redirect media on a prebuilt
|
||||
image, do it in your reverse proxy instead.
|
||||
@@ -7,8 +7,8 @@ android {
|
||||
applicationId "ch.duartesantos.opengym"
|
||||
minSdkVersion rootProject.ext.minSdkVersion
|
||||
targetSdkVersion rootProject.ext.targetSdkVersion
|
||||
versionCode 5
|
||||
versionName "1.2.4"
|
||||
versionCode 7
|
||||
versionName "1.2.6"
|
||||
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
||||
aaptOptions {
|
||||
// Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps.
|
||||
|
||||
Generated
+291
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "opengym-frontend",
|
||||
"version": "1.2.4",
|
||||
"version": "1.2.5",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "opengym-frontend",
|
||||
"version": "1.2.4",
|
||||
"version": "1.2.5",
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"dependencies": {
|
||||
"@capacitor/core": "^7.6.8",
|
||||
@@ -24,6 +24,7 @@
|
||||
"@capacitor/cli": "^7.6.8",
|
||||
"@capacitor/ios": "^7.6.8",
|
||||
"@vitejs/plugin-react": "^6.0.3",
|
||||
"linkedom": "^0.18.13",
|
||||
"vite": "^8.1.5",
|
||||
"vitest": "^4.1.10"
|
||||
}
|
||||
@@ -2594,6 +2595,13 @@
|
||||
"url": "https://github.com/sponsors/fb55"
|
||||
}
|
||||
},
|
||||
"node_modules/cssom": {
|
||||
"version": "0.5.0",
|
||||
"resolved": "https://registry.npmjs.org/cssom/-/cssom-0.5.0.tgz",
|
||||
"integrity": "sha512-iKuQcq+NdHqlAcwUY0o/HL69XQrUaQdMjmStJ8JFmUaiiQErlhrmuigkg/CU4E2J0IyUKUrMAgl36TvN67MqTw==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/dargs": {
|
||||
"version": "7.0.0",
|
||||
"resolved": "https://registry.npmjs.org/dargs/-/dargs-7.0.0.tgz",
|
||||
@@ -3337,6 +3345,105 @@
|
||||
"integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==",
|
||||
"dev": true
|
||||
},
|
||||
"node_modules/html-escaper": {
|
||||
"version": "3.0.3",
|
||||
"resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-3.0.3.tgz",
|
||||
"integrity": "sha512-RuMffC89BOWQoY0WKGpIhn5gX3iI54O6nRA0yC124NYVtzjmFWBIiFd8M0x+ZdX0P9R4lADg1mgP8C7PxGOWuQ==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/htmlparser2": {
|
||||
"version": "10.1.0",
|
||||
"resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-10.1.0.tgz",
|
||||
"integrity": "sha512-VTZkM9GWRAtEpveh7MSF6SjjrpNVNNVJfFup7xTY3UpFtm67foy9HDVXneLtFVt4pMz5kZtgNcvCniNFb1hlEQ==",
|
||||
"dev": true,
|
||||
"funding": [
|
||||
"https://github.com/fb55/htmlparser2?sponsor=1",
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/fb55"
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"domelementtype": "^2.3.0",
|
||||
"domhandler": "^5.0.3",
|
||||
"domutils": "^3.2.2",
|
||||
"entities": "^7.0.1"
|
||||
}
|
||||
},
|
||||
"node_modules/htmlparser2/node_modules/dom-serializer": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-2.0.0.tgz",
|
||||
"integrity": "sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"domelementtype": "^2.3.0",
|
||||
"domhandler": "^5.0.2",
|
||||
"entities": "^4.2.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/cheeriojs/dom-serializer?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/htmlparser2/node_modules/dom-serializer/node_modules/entities": {
|
||||
"version": "4.5.0",
|
||||
"resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz",
|
||||
"integrity": "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==",
|
||||
"dev": true,
|
||||
"license": "BSD-2-Clause",
|
||||
"engines": {
|
||||
"node": ">=0.12"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/fb55/entities?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/htmlparser2/node_modules/domhandler": {
|
||||
"version": "5.0.3",
|
||||
"resolved": "https://registry.npmjs.org/domhandler/-/domhandler-5.0.3.tgz",
|
||||
"integrity": "sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w==",
|
||||
"dev": true,
|
||||
"license": "BSD-2-Clause",
|
||||
"dependencies": {
|
||||
"domelementtype": "^2.3.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 4"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/fb55/domhandler?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/htmlparser2/node_modules/domutils": {
|
||||
"version": "3.2.2",
|
||||
"resolved": "https://registry.npmjs.org/domutils/-/domutils-3.2.2.tgz",
|
||||
"integrity": "sha512-6kZKyUajlDuqlHKVX1w7gyslj9MPIXzIFiz/rGu35uC1wMi+kMhQwGhl4lt9unC9Vb9INnY9Z3/ZA3+FhASLaw==",
|
||||
"dev": true,
|
||||
"license": "BSD-2-Clause",
|
||||
"dependencies": {
|
||||
"dom-serializer": "^2.0.0",
|
||||
"domelementtype": "^2.3.0",
|
||||
"domhandler": "^5.0.3"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/fb55/domutils?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/htmlparser2/node_modules/entities": {
|
||||
"version": "7.0.1",
|
||||
"resolved": "https://registry.npmjs.org/entities/-/entities-7.0.1.tgz",
|
||||
"integrity": "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==",
|
||||
"dev": true,
|
||||
"license": "BSD-2-Clause",
|
||||
"engines": {
|
||||
"node": ">=0.12"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/fb55/entities?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/ieee754": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz",
|
||||
@@ -3826,6 +3933,181 @@
|
||||
"integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==",
|
||||
"dev": true
|
||||
},
|
||||
"node_modules/linkedom": {
|
||||
"version": "0.18.13",
|
||||
"resolved": "https://registry.npmjs.org/linkedom/-/linkedom-0.18.13.tgz",
|
||||
"integrity": "sha512-ES/o9qotMpzpN2MHs+Iq/JcVoOj8Fa5wiQYrTdFpvAnwXL0g66XHHUc9WUMk6nAlBtGsFQ24ne+SYnvnaQ2FSw==",
|
||||
"dev": true,
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"css-select": "^7.0.0",
|
||||
"cssom": "^0.5.0",
|
||||
"html-escaper": "^3.0.3",
|
||||
"htmlparser2": "^10.1.0",
|
||||
"uhyphen": "^0.2.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=16"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"canvas": ">= 2"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"canvas": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/linkedom/node_modules/boolbase": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/boolbase/-/boolbase-2.0.0.tgz",
|
||||
"integrity": "sha512-DkVaaQHymRhpYEYo9x1oo7Q7B0Y6KJUsjm3c9eTyFDby4MHLBTwZ6ZDWBel5zrYxj1WsZgC5oLpiz+93MluXeA==",
|
||||
"dev": true,
|
||||
"license": "ISC",
|
||||
"engines": {
|
||||
"node": ">=20.19.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/fb55"
|
||||
}
|
||||
},
|
||||
"node_modules/linkedom/node_modules/css-select": {
|
||||
"version": "7.0.0",
|
||||
"resolved": "https://registry.npmjs.org/css-select/-/css-select-7.0.0.tgz",
|
||||
"integrity": "sha512-snmjEVXy+1LnwXdxhYvTMj1d9tOh4HxkA1YmoayVBeeyR2C14Pum7fcxJIm4SswYspVy866eYNwlH6xC3/VH5g==",
|
||||
"dev": true,
|
||||
"license": "BSD-2-Clause",
|
||||
"dependencies": {
|
||||
"boolbase": "^2.0.0",
|
||||
"css-what": "^8.0.0",
|
||||
"domhandler": "^6.0.1",
|
||||
"domutils": "^4.0.2",
|
||||
"nth-check": "^3.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.19.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/fb55"
|
||||
}
|
||||
},
|
||||
"node_modules/linkedom/node_modules/css-what": {
|
||||
"version": "8.0.0",
|
||||
"resolved": "https://registry.npmjs.org/css-what/-/css-what-8.0.0.tgz",
|
||||
"integrity": "sha512-DH0Bqq3DNp5tdOReuNyAA+Ev4Y2GS5FMbZpeTLP6C4CDi0h5nL0BmUPChXw3o/qbHLDWHl49sbNqQVY7bMSDdw==",
|
||||
"dev": true,
|
||||
"license": "BSD-2-Clause",
|
||||
"engines": {
|
||||
"node": ">=20.19.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/fb55"
|
||||
}
|
||||
},
|
||||
"node_modules/linkedom/node_modules/dom-serializer": {
|
||||
"version": "3.1.1",
|
||||
"resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-3.1.1.tgz",
|
||||
"integrity": "sha512-4MEa38/QexBob6gFNwu+EGdWvhJ1OKuNwdYY3Y3NyeWDQfnGeDYQUDfIRzWu5B5gsv03so2Uxd28YC6zrsx3Lw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"domelementtype": "^3.0.0",
|
||||
"domhandler": "^6.0.0",
|
||||
"entities": "^8.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.19.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/cheeriojs/dom-serializer?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/linkedom/node_modules/domelementtype": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-3.0.0.tgz",
|
||||
"integrity": "sha512-umCQid3jKbDmVjx8jGaW7uUykm4DEUeyV21hPxNMo2nV955DhUThwqyOIDtreepP31hl84X7G5U9ZfsWvIB3Pg==",
|
||||
"dev": true,
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/fb55"
|
||||
}
|
||||
],
|
||||
"license": "BSD-2-Clause",
|
||||
"engines": {
|
||||
"node": ">=20.19.0"
|
||||
}
|
||||
},
|
||||
"node_modules/linkedom/node_modules/domhandler": {
|
||||
"version": "6.0.1",
|
||||
"resolved": "https://registry.npmjs.org/domhandler/-/domhandler-6.0.1.tgz",
|
||||
"integrity": "sha512-gYzvtM72ZtxQO0T048kd6HWSbbGCNOUwcnfQ01cqIJ4X2IYKFFHZ5mKvrQETcFXxsRObZulDaKmy//R7TPtsBg==",
|
||||
"dev": true,
|
||||
"license": "BSD-2-Clause",
|
||||
"dependencies": {
|
||||
"domelementtype": "^3.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.19.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/fb55/domhandler?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/linkedom/node_modules/domutils": {
|
||||
"version": "4.0.2",
|
||||
"resolved": "https://registry.npmjs.org/domutils/-/domutils-4.0.2.tgz",
|
||||
"integrity": "sha512-qI4JLRKnSzqFqr7hAlS5xQDusBCjKSEG4t4+7aNrIQMHBcsC2TGEhuyABJdYkgSewL57PNLYEiibY2iPKhKpaA==",
|
||||
"dev": true,
|
||||
"license": "BSD-2-Clause",
|
||||
"dependencies": {
|
||||
"dom-serializer": "^3.0.0",
|
||||
"domelementtype": "^3.0.0",
|
||||
"domhandler": "^6.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.19.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/fb55/domutils?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/linkedom/node_modules/entities": {
|
||||
"version": "8.0.0",
|
||||
"resolved": "https://registry.npmjs.org/entities/-/entities-8.0.0.tgz",
|
||||
"integrity": "sha512-zwfzJecQ/Uej6tusMqwAqU/6KL2XaB2VZ2Jg54Je6ahNBGNH6Ek6g3jjNCF0fG9EWQKGZNddNjU5F1ZQn/sBnA==",
|
||||
"dev": true,
|
||||
"license": "BSD-2-Clause",
|
||||
"engines": {
|
||||
"node": ">=20.19.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/fb55/entities?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/linkedom/node_modules/nth-check": {
|
||||
"version": "3.0.1",
|
||||
"resolved": "https://registry.npmjs.org/nth-check/-/nth-check-3.0.1.tgz",
|
||||
"integrity": "sha512-GX0gsdbGVCgnRgbeGaubfjpBXyYRWOOCVeYh08bSQvDZqxz5ndXs1OTfAt/h36G1xvI94YIspsI0sVFqAV9+RQ==",
|
||||
"dev": true,
|
||||
"license": "BSD-2-Clause",
|
||||
"dependencies": {
|
||||
"boolbase": "^2.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.19.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/fb55/nth-check?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/load-json-file": {
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmjs.org/load-json-file/-/load-json-file-4.0.0.tgz",
|
||||
@@ -5886,6 +6168,13 @@
|
||||
"node": ">=0.8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/uhyphen": {
|
||||
"version": "0.2.0",
|
||||
"resolved": "https://registry.npmjs.org/uhyphen/-/uhyphen-0.2.0.tgz",
|
||||
"integrity": "sha512-qz3o9CHXmJJPGBdqzab7qAYuW8kQGKNEuoHFYrBwV6hWIMcpAmxDLXojcHfFr9US1Pe6zUswEIJIbLI610fuqA==",
|
||||
"dev": true,
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/undici-types": {
|
||||
"version": "8.3.0",
|
||||
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.3.0.tgz",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "opengym-frontend",
|
||||
"private": true,
|
||||
"version": "1.2.4",
|
||||
"version": "1.2.6",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
@@ -28,6 +28,7 @@
|
||||
"@capacitor/cli": "^7.6.8",
|
||||
"@capacitor/ios": "^7.6.8",
|
||||
"@vitejs/plugin-react": "^6.0.3",
|
||||
"linkedom": "^0.18.13",
|
||||
"vite": "^8.1.5",
|
||||
"vitest": "^4.1.10"
|
||||
}
|
||||
|
||||
@@ -47,11 +47,13 @@ function View({ view, levels, onMuscle, selected }) {
|
||||
/**
|
||||
* <BodyMap load={{ chest: 12, … }} body="male" />
|
||||
* `load` is effective sets per muscle (see lib/muscles.js); shading is relative to
|
||||
* the hardest-worked muscle in that same load, so it always reads as a balance.
|
||||
* the hardest-worked muscle in that same load, so it always reads as a balance. Pass ordered
|
||||
* `{ at, level, exclusive? }` `thresholds` for a fixed absolute scale (recovery views use this
|
||||
* to keep their semantic bands stable); omitting it preserves the balance behavior.
|
||||
*/
|
||||
export default function BodyMap({ load = {}, body = 'male', onMuscle, selected, className = '' }) {
|
||||
export default function BodyMap({ load = {}, thresholds, body = 'male', onMuscle, selected, className = '' }) {
|
||||
const paths = useBodyPaths()
|
||||
const levels = levelsOf(load)
|
||||
const levels = levelsOf(load, thresholds)
|
||||
const g = paths && (paths[body] || paths.male)
|
||||
return (
|
||||
<div className={'bodymap ' + className}>
|
||||
|
||||
@@ -559,6 +559,9 @@ h4.sec{
|
||||
.setrow+.setrow::before{
|
||||
content:'';position:absolute;left:32px;right:0;top:0;height:var(--hair);background:var(--sep);
|
||||
}
|
||||
.setph{margin:8px 0 2px;font-size:11px;letter-spacing:.08em;text-transform:uppercase;color:var(--dim);display:flex;align-items:center;gap:10px}
|
||||
.setph::after{content:'';flex:1;height:1px;background:var(--sep)}
|
||||
.setsep{height:1px;background:var(--sep);margin:9px 0}
|
||||
.setrow .n{
|
||||
width:24px;height:24px;border-radius:50%;background:var(--surface-2);color:var(--label-2);
|
||||
display:flex;align-items:center;justify-content:center;font-size:12px;font-weight:500;flex:none;
|
||||
@@ -777,6 +780,18 @@ h4.sec{
|
||||
.bm-m.l2{fill:color-mix(in srgb,var(--acc) 56%,var(--bm-base))}
|
||||
.bm-m.l3{fill:color-mix(in srgb,var(--acc) 78%,var(--bm-base))}
|
||||
.bm-m.l4{fill:var(--acc)}
|
||||
/* Fatigue view: attention ramp - fatigued muscles highlighted (owner tweak 2026-08-06) */
|
||||
.hm-fatigue .bm-m.l4{fill:var(--red)}
|
||||
.hm-fatigue .bm-m.l3{fill:var(--orange)}
|
||||
.hm-fatigue .bm-m.l2{fill:var(--yellow)}
|
||||
.hm-fatigue .bm-m.l1{fill:color-mix(in srgb,var(--yellow) 32%,var(--bm-base))}
|
||||
.hm-fatigue .hm-c.l4{background:var(--red)}
|
||||
.hm-fatigue .hm-c.l3{background:var(--orange)}
|
||||
.hm-fatigue .hm-c.l2{background:var(--yellow)}
|
||||
/* Strength view: top band pops gold (owner tweak 2026-08-06) */
|
||||
.hm-strength .bm-m.l4{fill:var(--yellow);filter:drop-shadow(0 0 1.5px var(--yellow))}
|
||||
.hm-strength .hm-c.l4{background:var(--yellow)}
|
||||
|
||||
.bm-m.sel{stroke:var(--label);stroke-width:7}
|
||||
.bodymap.tappable .bm-m{cursor:pointer}
|
||||
/* A hairline in the surface colour separates neighbouring muscles; the artwork has no
|
||||
|
||||
@@ -44,7 +44,7 @@ export const scaleName = kind => EFFORT[kind].hd
|
||||
function eachDoneSet(S, fn) {
|
||||
;(S.workouts || []).forEach(w =>
|
||||
(w.entries || []).forEach(e =>
|
||||
(e.sets || []).forEach(s => { if (s.done) fn(s, w, e) })))
|
||||
(e.sets || []).forEach(s => { if (s.done && !s.warmup) fn(s, w, e) })))
|
||||
}
|
||||
|
||||
// A window in days, counted back from now. 0 = everything, which is also what an empty
|
||||
|
||||
@@ -1,7 +1,27 @@
|
||||
import { EXDB } from './exercises-data.js'
|
||||
import { t } from './i18n.js'
|
||||
import { t } from './i18n-core.js'
|
||||
|
||||
export { EXDB }
|
||||
|
||||
// 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.
|
||||
const SECONDARY_ADDITIONS = {
|
||||
'0027': ['rear deltoids'], // barbell bent over row
|
||||
'0293': ['rear deltoids'], // dumbbell bent over row
|
||||
'0499': ['rear deltoids'], // inverted row
|
||||
'0861': ['rear deltoids'], // cable seated row
|
||||
}
|
||||
|
||||
// Secondary muscles for an exercise, with the small conservative additions applied as an
|
||||
// overlay. The raw dataset is never mutated - consumers that want the pristine catalogue
|
||||
// (export, print, import) keep reading EXDB untouched, while the muscle map sees the
|
||||
// enriched list. Values follow the dataset's existing alias vocabulary.
|
||||
export const smOf = ex => {
|
||||
const base = Array.isArray(ex?.sm) ? ex.sm : (ex?.sm ? [ex.sm] : [])
|
||||
return [...new Set([...base, ...(SECONDARY_ADDITIONS[ex?.id] || [])])]
|
||||
}
|
||||
|
||||
export const EXIDX = {}
|
||||
EXDB.forEach(e => { EXIDX[e.id] = e })
|
||||
export const BODYPARTS = [...new Set(EXDB.map(e => e.bp))].sort()
|
||||
@@ -28,9 +48,16 @@ export const allExercises = st => [...(st.customEx || []), ...EXDB]
|
||||
|
||||
// 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.
|
||||
const IMG_BASE = import.meta.env.VITE_IMG_BASE || 'img/'
|
||||
const GIF_BASE = import.meta.env.VITE_GIF_BASE || 'gif/'
|
||||
// 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/'
|
||||
export const imgSrc = ex => IMG_BASE + ex.img
|
||||
export const gifSrc = ex => GIF_BASE + ex.gif
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// Formatting + date helpers (ported from the vanilla app, unit taken from the store where needed).
|
||||
import { dateLocale, t } from './i18n.js'
|
||||
import { dateLocale, t } from './i18n-core.js'
|
||||
export const todayISO = () => {
|
||||
const d = new Date()
|
||||
return d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0')
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
/**
|
||||
* Whether "Continue without account" may be offered, given the public config from /api/config.
|
||||
*
|
||||
* Guest mode is allowed unless the server has *positively* said otherwise. That asymmetry is the
|
||||
* whole point: a config we could not fetch — offline, server restarting, request failed — is not
|
||||
* the same answer as `allow_guest: false`, and treating it as one would lock people out of an
|
||||
* instance whose admin never disabled anything. An instance that really did disable guests says
|
||||
* so on the next successful boot, and the session is ended then (see useStore.boot).
|
||||
*
|
||||
* Older servers predate the flag and send no `allow_guest` at all; they mean "allowed".
|
||||
*
|
||||
* @param {{allow_guest?: boolean}|null|undefined} config Parsed /api/config body, or null.
|
||||
* @returns {boolean} true when the guest entrance may be shown and used.
|
||||
*/
|
||||
export const guestAllowed = config => !(config && config.allow_guest === false)
|
||||
@@ -0,0 +1,36 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { guestAllowed } from './guest.js'
|
||||
|
||||
// The flag is the easy half. The half worth pinning down is what happens when the server did not
|
||||
// answer: a failed config fetch must not be read as "guests are disabled", or an instance that is
|
||||
// merely unreachable locks out everyone who never made an account (#42).
|
||||
describe('guestAllowed', () => {
|
||||
it('allows guests when the server says so', () => {
|
||||
expect(guestAllowed({ allow_guest: true })).toBe(true)
|
||||
})
|
||||
|
||||
it('refuses guests only on an explicit false', () => {
|
||||
expect(guestAllowed({ allow_guest: false })).toBe(false)
|
||||
})
|
||||
|
||||
it('allows guests when the config could not be fetched', () => {
|
||||
expect(guestAllowed(null)).toBe(true)
|
||||
expect(guestAllowed(undefined)).toBe(true)
|
||||
})
|
||||
|
||||
it('allows guests against a server too old to send the flag', () => {
|
||||
expect(guestAllowed({ invite_only: true })).toBe(true)
|
||||
})
|
||||
|
||||
// A missing key and a falsy-but-not-false value are different things. Only `false` — what the
|
||||
// server actually serialises — closes the door; anything else stays open rather than guessing.
|
||||
it('does not treat other falsy values as a refusal', () => {
|
||||
for (const v of [0, '', null, undefined, NaN]) {
|
||||
expect(guestAllowed({ allow_guest: v })).toBe(true)
|
||||
}
|
||||
})
|
||||
|
||||
it('treats the string "false" as the misconfiguration it is, not as a refusal', () => {
|
||||
expect(guestAllowed({ allow_guest: 'false' })).toBe(true)
|
||||
})
|
||||
})
|
||||
+125
-3
@@ -1,7 +1,11 @@
|
||||
// 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 { t } from './i18n.js'
|
||||
// i18n-core, not i18n: this file is imported by mcp/, which is plain Node with no Vite and no
|
||||
// React. i18n.js is the Vite half — import.meta.glob over the locale packs, useSyncExternalStore
|
||||
// for the hook — and it re-exports this very `t` from core, so nothing changes here except what
|
||||
// gets dragged along behind it.
|
||||
import { t } from './i18n-core.js'
|
||||
|
||||
// How an exercise is logged (issue #16). This used to be derived from the body part alone,
|
||||
// which meant a plank or a farmer's carry could only be timed by filing it under cardio.
|
||||
@@ -138,6 +142,60 @@ export function cleanupSg(ex) {
|
||||
})
|
||||
}
|
||||
|
||||
// Return the contiguous run around an entry that shares its superset id. A repeated id in a
|
||||
// separated part of the list is deliberately not included: the display semantics are adjacent
|
||||
// entries sharing one id, not every entry that happens to carry that id.
|
||||
function contiguousSgGroup(items, idx) {
|
||||
const sg = items[idx]?.sg
|
||||
if (!sg) return [idx]
|
||||
let first = idx
|
||||
let last = idx
|
||||
while (first > 0 && items[first - 1]?.sg === sg) first--
|
||||
while (last + 1 < items.length && items[last + 1]?.sg === sg) last++
|
||||
return Array.from({ length: last - first + 1 }, (_, i) => first + i)
|
||||
}
|
||||
|
||||
function freshSg(items, first, second) {
|
||||
const base = `sg-${Math.min(first, second)}-${Math.max(first, second)}`
|
||||
let sg = base
|
||||
let n = 2
|
||||
while (items.some(e => e.sg === sg)) sg = `${base}-${n++}`
|
||||
return sg
|
||||
}
|
||||
|
||||
// Purely pair two adjacent entries. Existing contiguous groups on either side are merged, so
|
||||
// pairing the end of one group with the start of another produces one display unit. A caller can
|
||||
// provide a group id (useful when restoring a known id); otherwise an existing id is preferred,
|
||||
// with a deterministic unused id for two previously ungrouped entries.
|
||||
export function pairAdjacent(items, first, second, groupId) {
|
||||
if (!Array.isArray(items)) throw new TypeError('Superset entries must be an array')
|
||||
if (!Number.isInteger(first) || !Number.isInteger(second) || !items[first] || !items[second]) {
|
||||
throw new RangeError('Superset entry indexes are invalid')
|
||||
}
|
||||
if (Math.abs(first - second) !== 1) throw new RangeError('Superset entries must be adjacent')
|
||||
|
||||
const next = items.map(e => ({ ...e }))
|
||||
const left = Math.min(first, second)
|
||||
const right = Math.max(first, second)
|
||||
const group = groupId || next[left].sg || next[right].sg || freshSg(next, left, right)
|
||||
const members = new Set([...contiguousSgGroup(next, left), ...contiguousSgGroup(next, right)])
|
||||
members.forEach(i => { next[i].sg = group })
|
||||
return next
|
||||
}
|
||||
|
||||
// Remove one entry from its superset and clean any ids that no longer have an adjacent partner.
|
||||
// This is pure so the active workout can replace its entries atomically through the store.
|
||||
export function unpairSuperset(items, idx) {
|
||||
if (!Array.isArray(items)) throw new TypeError('Superset entries must be an array')
|
||||
if (!Number.isInteger(idx) || !items[idx]) throw new RangeError('Superset entry index is invalid')
|
||||
const next = items.map(e => ({ ...e }))
|
||||
delete next[idx].sg
|
||||
next.forEach((e, i) => {
|
||||
if (e.sg && !(next[i - 1]?.sg === e.sg || next[i + 1]?.sg === e.sg)) delete e.sg
|
||||
})
|
||||
return next
|
||||
}
|
||||
|
||||
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)
|
||||
@@ -148,6 +206,21 @@ export function lastEntryFor(S, exId) {
|
||||
}
|
||||
return 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
|
||||
// number of rows need to be seeded here so the config sheet and the rows agree.
|
||||
export function freestyleConfig(S, cfg) {
|
||||
const last = lastEntryFor(S, cfg.id)
|
||||
if (!last) return { ...cfg }
|
||||
return {
|
||||
...cfg,
|
||||
...(last.target || {}),
|
||||
id: cfg.id,
|
||||
sets: Math.max(1, last.sets.length)
|
||||
}
|
||||
}
|
||||
export function bestWeightFor(S, exId) {
|
||||
let best = 0
|
||||
S.workouts.forEach(w => w.entries.forEach(e => {
|
||||
@@ -169,10 +242,11 @@ export function effectiveRoutine(S, iso) {
|
||||
const id = effectiveRoutineId(S, iso)
|
||||
return id ? S.routines.find(r => r.id === id) || null : null
|
||||
}
|
||||
export function buildSets(S, cfg) {
|
||||
export function buildSets(S, cfg, options = {}) {
|
||||
const last = lastEntryFor(S, cfg.id)
|
||||
const n = Math.max(1, cfg.sets || 1)
|
||||
const mode = modeOf(cfg)
|
||||
const preferLast = !!options.preferLast
|
||||
const sets = []
|
||||
// Last time's set at the same position, falling back to its final set when the plan grew.
|
||||
const prevAt = i => (last ? (last.sets[i] || last.sets[last.sets.length - 1]) : null)
|
||||
@@ -198,7 +272,9 @@ export function buildSets(S, cfg) {
|
||||
for (let i = 0; i < n; i++) {
|
||||
const prev = prevAt(i)
|
||||
const usable = prev && prev.r > 0 ? prev : null
|
||||
const w = conf && conf.w > 0 ? conf.w : (usable ? usable.w : cfg.weight)
|
||||
// Planned sessions may use the confirmed working weight, while freestyle should reproduce
|
||||
// the load of each matching set when that option is requested.
|
||||
const w = preferLast && usable ? usable.w : (conf && conf.w > 0 ? conf.w : (usable ? usable.w : cfg.weight))
|
||||
sets.push({ w, r: usable ? usable.r : cfg.reps, done: false })
|
||||
}
|
||||
return sets
|
||||
@@ -248,3 +324,49 @@ export function streakWeeks(S) {
|
||||
}
|
||||
return streak
|
||||
}
|
||||
|
||||
/**
|
||||
* Cascade a weight change forward: following sets of the same warm-up flag that are still
|
||||
* undone take the new value (null deletes the key). Done sets are never rewritten.
|
||||
*/
|
||||
export function cascadeWeight(rows, from, value) {
|
||||
const warm = !!rows[from]?.warmup
|
||||
const next = rows.slice()
|
||||
for (let j = from + 1; j < next.length; j++) {
|
||||
if (!!next[j].warmup === warm && !next[j].done) {
|
||||
if (value == null) delete next[j].w
|
||||
else next[j].w = 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) {
|
||||
const firstWork = rows.findIndex(x => !x.warmup)
|
||||
const at = firstWork === -1 ? rows.length : firstWork
|
||||
const l = rows[at - 1] || rows[rows.length - 1]
|
||||
const warm = mode === 'cardio'
|
||||
? { min: l ? l.min : (target.min || 20), speed: l ? l.speed : (target.speed || 8), done: false, warmup: true }
|
||||
: mode === 'time'
|
||||
? { sec: l ? l.sec : (target.sec || 45), w: l ? (l.w || 0) : (target.weight || 0), done: false, warmup: true }
|
||||
: { w: l ? l.w : 0, r: l ? l.r : target.reps, done: false, warmup: true }
|
||||
const next = rows.slice()
|
||||
next.splice(at, 0, warm)
|
||||
return next
|
||||
}
|
||||
|
||||
/** Remove the row at `i`, never emptying the entry below one row. */
|
||||
export function removeRowAt(rows, i) {
|
||||
if (rows.length <= 1) return rows.slice()
|
||||
const next = rows.slice()
|
||||
next.splice(i, 1)
|
||||
return next
|
||||
}
|
||||
|
||||
/** Completed non-warm-up sets across a workout's entries. */
|
||||
export function workSetsDone(w) {
|
||||
return (w?.entries || []).reduce(
|
||||
(n, e) => n + (e.sets || []).filter(s => s.done && !s.warmup).length, 0,
|
||||
)
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { modeOf, isTimed, fmtSec, setLabel, defaultConfig, buildSets, exLine, workoutVolume, effortOf, stepEffort, capEffort, isBw, isPerSide, sideReps, repStep } from './history.js'
|
||||
import { modeOf, isTimed, fmtSec, setLabel, defaultConfig, buildSets, freestyleConfig, exLine, workoutVolume, effortOf, stepEffort, capEffort, isBw, isPerSide, sideReps, repStep, cascadeWeight, insertWarmupRow, removeRowAt, pairAdjacent, unpairSuperset, supersetUnits } from './history.js'
|
||||
import { EXDB } from './exercises.js'
|
||||
|
||||
// Real ids out of the shipped catalogue, so the body-part fallback is exercised for real.
|
||||
@@ -9,6 +9,49 @@ const CARDIO = EXDB.find(e => e.bp === 'cardio').id
|
||||
const LIFT = EXDB.find(e => e.bp !== 'cardio' && e.eq !== 'body weight').id
|
||||
const BW = EXDB.find(e => e.eq === 'body weight').id
|
||||
|
||||
describe('superset editing', () => {
|
||||
it('pairs adjacent entries without mutating the source and keeps the display units contiguous', () => {
|
||||
const entries = [{ id: 'a' }, { id: 'b' }, { id: 'c' }]
|
||||
|
||||
const paired = pairAdjacent(entries, 1, 2, 'sg-new')
|
||||
|
||||
expect(paired).toEqual([{ id: 'a' }, { id: 'b', sg: 'sg-new' }, { id: 'c', sg: 'sg-new' }])
|
||||
expect(entries).toEqual([{ id: 'a' }, { id: 'b' }, { id: 'c' }])
|
||||
expect(supersetUnits(paired)).toEqual([[0], [1, 2]])
|
||||
})
|
||||
|
||||
it('merges both contiguous groups when their boundary entries are paired', () => {
|
||||
const entries = [
|
||||
{ id: 'a', sg: 'left' }, { id: 'b', sg: 'left' },
|
||||
{ id: 'c', sg: 'right' }, { id: 'd', sg: 'right' }
|
||||
]
|
||||
|
||||
const merged = pairAdjacent(entries, 1, 2)
|
||||
|
||||
expect(merged.map(e => e.sg)).toEqual(['left', 'left', 'left', 'left'])
|
||||
expect(entries.map(e => e.sg)).toEqual(['left', 'left', 'right', 'right'])
|
||||
})
|
||||
|
||||
it('unpairs one entry and removes sg values left without an adjacent partner', () => {
|
||||
const entries = [
|
||||
{ id: 'a', sg: 'group' }, { id: 'b', sg: 'group' }, { id: 'c', sg: 'group' },
|
||||
{ id: 'd', sg: 'orphan' }
|
||||
]
|
||||
|
||||
const unpaired = unpairSuperset(entries, 1)
|
||||
|
||||
expect(unpaired).toEqual([{ id: 'a' }, { id: 'b' }, { id: 'c' }, { id: 'd' }])
|
||||
expect(entries.map(e => e.sg)).toEqual(['group', 'group', 'group', 'orphan'])
|
||||
})
|
||||
|
||||
it('rejects a non-adjacent pairing request', () => {
|
||||
const entries = [{ id: 'a' }, { id: 'b' }, { id: 'c' }]
|
||||
|
||||
expect(() => pairAdjacent(entries, 0, 2, 'sg-invalid')).toThrow(/adjacent/)
|
||||
expect(entries).toEqual([{ id: 'a' }, { id: 'b' }, { id: 'c' }])
|
||||
})
|
||||
})
|
||||
|
||||
describe('modeOf', () => {
|
||||
it('falls back to the body part when a plan has no mode — every existing plan keeps working', () => {
|
||||
expect(modeOf({ id: CARDIO })).toBe('cardio')
|
||||
@@ -336,6 +379,80 @@ describe('exLine', () => {
|
||||
|
||||
const emptyS = { workouts: [], exWeights: {} }
|
||||
|
||||
describe('freestyleConfig', () => {
|
||||
it('inherits the last target and completed set count for a newly added exercise', () => {
|
||||
const S = {
|
||||
exWeights: {},
|
||||
workouts: [{
|
||||
d: '2026-01-01',
|
||||
entries: [{
|
||||
id: LIFT,
|
||||
target: { mode: 'reps', sets: 4, reps: 8, weight: 60, prog: 'linear' },
|
||||
sets: [
|
||||
{ w: 60, r: 8, done: true },
|
||||
{ w: 62.5, r: 7, done: true },
|
||||
{ w: 62.5, r: 6, done: true },
|
||||
{ w: 62.5, r: 5, done: true }
|
||||
]
|
||||
}]
|
||||
}]
|
||||
}
|
||||
const cfg = freestyleConfig(S, { id: LIFT, mode: 'reps', sets: 3, reps: 10, weight: 0 })
|
||||
|
||||
expect(cfg).toEqual({ id: LIFT, mode: 'reps', sets: 4, reps: 8, weight: 60, prog: 'linear' })
|
||||
expect(buildSets(S, cfg)).toEqual([
|
||||
{ w: 60, r: 8, done: false },
|
||||
{ w: 62.5, r: 7, done: false },
|
||||
{ w: 62.5, r: 6, done: false },
|
||||
{ w: 62.5, r: 5, done: false }
|
||||
])
|
||||
})
|
||||
|
||||
it('inherits the target for timed and cardio exercises too', () => {
|
||||
const timed = {
|
||||
exWeights: {},
|
||||
workouts: [{
|
||||
d: '2026-01-02',
|
||||
entries: [{
|
||||
id: LIFT,
|
||||
target: { mode: 'time', sets: 2, sec: 60, weight: 15 },
|
||||
sets: [{ sec: 55, w: 15, done: true }, { sec: 60, w: 17.5, done: true }]
|
||||
}]
|
||||
}]
|
||||
}
|
||||
const cardio = {
|
||||
exWeights: {},
|
||||
workouts: [{
|
||||
d: '2026-01-03',
|
||||
entries: [{
|
||||
id: CARDIO,
|
||||
target: { sets: 2, min: 30, speed: 7 },
|
||||
sets: [{ min: 28, speed: 7, done: true }, { min: 30, speed: 7.5, done: true }]
|
||||
}]
|
||||
}]
|
||||
}
|
||||
|
||||
const timedCfg = freestyleConfig(timed, { id: LIFT, mode: 'time', sets: 3, sec: 45, weight: 0 })
|
||||
expect(timedCfg).toEqual({ id: LIFT, mode: 'time', sets: 2, sec: 60, weight: 15 })
|
||||
expect(buildSets(timed, timedCfg)).toEqual([
|
||||
{ sec: 55, w: 15, done: false },
|
||||
{ sec: 60, w: 17.5, done: false }
|
||||
])
|
||||
|
||||
const cardioCfg = freestyleConfig(cardio, { id: CARDIO, sets: 1, min: 20, speed: 8 })
|
||||
expect(cardioCfg).toEqual({ id: CARDIO, sets: 2, min: 30, speed: 7 })
|
||||
expect(buildSets(cardio, cardioCfg)).toEqual([
|
||||
{ min: 28, speed: 7, done: false },
|
||||
{ min: 30, speed: 7.5, done: false }
|
||||
])
|
||||
})
|
||||
|
||||
it('keeps the supplied defaults when there is no completed matching workout', () => {
|
||||
const cfg = freestyleConfig(emptyS, { id: LIFT, mode: 'reps', sets: 3, reps: 10, weight: 50 })
|
||||
expect(cfg).toEqual({ id: LIFT, mode: 'reps', sets: 3, reps: 10, weight: 50 })
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildSets', () => {
|
||||
it('builds reps sets from the plan when there is no history', () => {
|
||||
expect(buildSets(emptyS, { id: LIFT, sets: 3, reps: 8, weight: 50 }))
|
||||
@@ -374,6 +491,14 @@ describe('buildSets', () => {
|
||||
const S = { exWeights: { [LIFT]: { w: 75 } }, workouts: [{ d: '2026-01-01', entries: [{ id: LIFT, sets: [{ w: 60, r: 10, done: true }] }] }] }
|
||||
expect(buildSets(S, { id: LIFT, sets: 1, reps: 8, weight: 50 })).toEqual([{ w: 75, r: 10, done: false }])
|
||||
})
|
||||
|
||||
it('can preserve each last set weight for freestyle instead of using the working-weight hint', () => {
|
||||
const S = { exWeights: { [LIFT]: { w: 75 } }, workouts: [{ d: '2026-01-01', entries: [{ id: LIFT, sets: [
|
||||
{ w: 60, r: 10, done: true }, { w: 62.5, r: 8, done: true }
|
||||
] }] }] }
|
||||
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('workoutVolume', () => {
|
||||
@@ -396,3 +521,54 @@ describe('workoutVolume', () => {
|
||||
expect(workoutVolume(w)).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
describe('session row helpers', () => {
|
||||
it('cascadeWeight propagates to same-flag undone rows and never rewrites done sets', () => {
|
||||
const rows = [
|
||||
{ warmup: true, w: 20, done: true },
|
||||
{ warmup: true, w: 20, done: false },
|
||||
{ w: 60, done: true },
|
||||
{ w: 60, done: false },
|
||||
{ w: 60, done: false },
|
||||
]
|
||||
const next = cascadeWeight(rows, 2, 62.5)
|
||||
expect(next[2].w).toBe(60) // done set untouched
|
||||
expect(next[3].w).toBe(62.5) // same flag (work), undone
|
||||
expect(next[4].w).toBe(62.5) // same flag (work), undone
|
||||
expect(next[1].w).toBe(20) // different flag (warm-up) untouched
|
||||
})
|
||||
|
||||
it('cascadeWeight deleting the weight removes the key from following undone rows only', () => {
|
||||
const rows = [
|
||||
{ w: 60, done: true },
|
||||
{ w: 60, done: false },
|
||||
{ w: 60, done: false },
|
||||
]
|
||||
const next = cascadeWeight(rows, 0, null)
|
||||
expect(next[0].w).toBe(60) // done set untouched
|
||||
expect('w' in next[1]).toBe(false)
|
||||
expect('w' in next[2]).toBe(false)
|
||||
})
|
||||
|
||||
it('insertWarmupRow inserts before the first work row and copies the last warm-up values', () => {
|
||||
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 })
|
||||
expect(next.length).toBe(4)
|
||||
expect(next[2].warmup).toBe(true)
|
||||
expect(next[2].w).toBe(30) // copies the preceding warm-up
|
||||
expect(next[3].w).toBe(60) // work row still after the warm-up block
|
||||
})
|
||||
|
||||
it('removeRowAt never empties an entry below one row', () => {
|
||||
expect(removeRowAt([{ w: 60 }], 0).length).toBe(1)
|
||||
const rows = [{ w: 60 }, { w: 70 }]
|
||||
const next = removeRowAt(rows, 0)
|
||||
expect(next.length).toBe(1)
|
||||
expect(next[0].w).toBe(70)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,44 @@
|
||||
// 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
|
||||
// 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: '中文',
|
||||
ko: '한국어', hi: 'हिन्दी'
|
||||
}
|
||||
export const INSTR_LANGS = ['en', 'es', 'fr', 'it', 'tr', 'ru', 'zh', 'hi', 'pl', 'ko']
|
||||
export const DATE_LOCALES = {
|
||||
en: 'en-GB', de: 'de-DE', es: 'es-ES', fr: 'fr-FR', it: 'it-IT', pt: 'pt-PT',
|
||||
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 version = 0 // bumped on every setLang; drives the React subscription selector
|
||||
|
||||
export const getLang = () => lang
|
||||
export const dateLocale = () => DATE_LOCALES[lang] || 'en-GB'
|
||||
export const getVersion = () => version
|
||||
|
||||
// Translate a source string; {0},{1}… are replaced with args (also on the English fallback).
|
||||
export function t(s, ...args) {
|
||||
let v = dict[s] || s
|
||||
for (let i = 0; i < args.length; i++) v = v.replaceAll('{' + i + '}', args[i])
|
||||
return v
|
||||
}
|
||||
|
||||
// Instructions for an exercise in the current language (English steps as fallback).
|
||||
export const instrFor = ex => (instr && instr[ex.id]) || ex.st || []
|
||||
|
||||
// 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) {
|
||||
lang = LANGS[newLang] ? newLang : 'en'
|
||||
dict = lang === 'en' ? {} : (newDict || {})
|
||||
instr = lang === 'en' || !INSTR_LANGS.includes(lang) ? null : (newInstr || null)
|
||||
version++
|
||||
return version
|
||||
}
|
||||
+18
-36
@@ -1,56 +1,38 @@
|
||||
// Tiny dependency-free i18n. English source strings are the keys; locale files in
|
||||
// src/locales/ map them to translations and are lazy-loaded (Vite code-splits each
|
||||
// import.meta.glob entry), so the initial bundle stays English-only.
|
||||
// Exercise instructions come from separately generated packs in src/instr/ (one per
|
||||
// language, from the upstream dataset) — also lazy-loaded on language switch.
|
||||
// Browser-only shell of the i18n module. The runtime-agnostic state and readers live
|
||||
// in i18n-core.js (plain Node-loadable); this file adds the two pieces that genuinely need
|
||||
// the browser: `setLang` (which lazy-loads locale packs via import.meta.glob) and the React
|
||||
// subscription hook `useLang`.
|
||||
|
||||
import { useSyncExternalStore } from 'react'
|
||||
import {
|
||||
LANGS, INSTR_LANGS, DATE_LOCALES,
|
||||
getLang, dateLocale, t, instrFor, getVersion, _setLangState
|
||||
} from './i18n-core.js'
|
||||
|
||||
// UI languages. de/pt have no instruction pack upstream — instructions fall back to English.
|
||||
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: '中文',
|
||||
ko: '한국어', hi: 'हिन्दी'
|
||||
}
|
||||
export const INSTR_LANGS = ['en', 'es', 'fr', 'it', 'tr', 'ru', 'zh', 'hi', 'pl', 'ko']
|
||||
const DATE_LOCALES = {
|
||||
en: 'en-GB', de: 'de-DE', es: 'es-ES', fr: 'fr-FR', it: 'it-IT', pt: 'pt-PT',
|
||||
pl: 'pl-PL', tr: 'tr-TR', ru: 'ru-RU', zh: 'zh-CN', ko: 'ko-KR', hi: 'hi-IN'
|
||||
}
|
||||
export { LANGS, INSTR_LANGS, DATE_LOCALES, getLang, dateLocale, t, instrFor }
|
||||
|
||||
// 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.
|
||||
const localePacks = import.meta.glob('../locales/*.js')
|
||||
const instrPacks = import.meta.glob('../instr/*.js')
|
||||
|
||||
let lang = 'en'
|
||||
let dict = {}
|
||||
let instr = null // { exId: [steps] } for the current language, null = English
|
||||
let version = 0
|
||||
// React subscription bookkeeping — kept here, not in core, so core has zero React coupling.
|
||||
const subs = new Set()
|
||||
const notify = () => { version++; subs.forEach(f => f()) }
|
||||
|
||||
export const getLang = () => lang
|
||||
export const dateLocale = () => DATE_LOCALES[lang] || 'en-GB'
|
||||
|
||||
// Translate a source string; {0},{1}… are replaced with args (also on the English fallback).
|
||||
export function t(s, ...args) {
|
||||
let v = dict[s] || s
|
||||
for (let i = 0; i < args.length; i++) v = v.replaceAll('{' + i + '}', args[i])
|
||||
return v
|
||||
}
|
||||
// Instructions for an exercise in the current language (English steps as fallback).
|
||||
export const instrFor = ex => (instr && instr[ex.id]) || ex.st || []
|
||||
const notify = () => { subs.forEach(f => f()) }
|
||||
|
||||
export async function setLang(l) {
|
||||
if (!LANGS[l]) l = 'en'
|
||||
if (l === lang && version > 0) return
|
||||
lang = l
|
||||
if (l === getLang() && getVersion() > 0) return
|
||||
let dict = {}, 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)
|
||||
notify()
|
||||
}
|
||||
|
||||
// Re-renders the subscribing component (and its children) whenever the language changes.
|
||||
export function useLang() {
|
||||
return useSyncExternalStore(fn => { subs.add(fn); return () => subs.delete(fn) }, () => version)
|
||||
return useSyncExternalStore(fn => { subs.add(fn); return () => subs.delete(fn) }, getVersion)
|
||||
}
|
||||
@@ -173,6 +173,17 @@ const ALIAS_EX = {
|
||||
'tricep pushdown': '0241', 'triceps pushdown': '0241', pushdown: '0241',
|
||||
skullcrusher: '0060', 'skull crusher': '0060', 'lying triceps extension': '0061',
|
||||
lunge: '0054', lunges: '0054', 'cable crossover': '1269', 'cable cross over': '1269',
|
||||
'goblet squat': '1760', 'dumbbell goblet squat': '1760', 'kettlebell goblet squat': '0534',
|
||||
// Reported in issue #74: these come out of Hevy under names no word-overlap can reach, so
|
||||
// they landed as custom exercises. The catalogue's cardio vocabulary is thin (29 of 1,324
|
||||
// entries), so each of these is the *only* candidate rather than the best of several.
|
||||
treadmill: '3666', 'treadmill walk': '3666', 'treadmill run': '3666',
|
||||
cycling: '2331', 'cross trainer': '2331', elliptical: '2141',
|
||||
'stationary bike': '2138', 'exercise bike': '2138', 'stepmill': '2311',
|
||||
// The catalogue has only band Pallof presses, so a cable one resolves to the band entry:
|
||||
// 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',
|
||||
}
|
||||
|
||||
let ALIAS_IDX = null
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { matchExercise } from './import-csv.js'
|
||||
import { EXIDX } from './exercises.js'
|
||||
|
||||
// The names other apps actually export, and the catalogue entry each has to land on.
|
||||
// Everything here was reported as arriving in the app as a *custom* exercise (issue #74):
|
||||
// the alias table is the intended place to fix that, so these pin it.
|
||||
const MAPS = {
|
||||
Treadmill: '3666',
|
||||
'Goblet Squat': '1760',
|
||||
Cycling: '2331',
|
||||
'Cable Core Pallof Press': '0979',
|
||||
Elliptical: '2141',
|
||||
'Stationary Bike': '2138',
|
||||
}
|
||||
|
||||
describe('foreign exercise names resolve to the catalogue', () => {
|
||||
for (const [name, id] of Object.entries(MAPS)) {
|
||||
it(`maps "${name}" to ${id}`, () => {
|
||||
expect(matchExercise(name)).toBe(id)
|
||||
expect(EXIDX[id]).toBeTruthy() // an alias pointing at a dropped id is worse than no alias
|
||||
})
|
||||
}
|
||||
|
||||
// Equipment qualifiers must still beat the bare alias, or an import files years of
|
||||
// dumbbell work under the barbell lift.
|
||||
it('keeps the qualified variants distinct', () => {
|
||||
expect(matchExercise('Kettlebell Goblet Squat')).toBe('0534')
|
||||
expect(matchExercise('Dumbbell Goblet Squat')).toBe('1760')
|
||||
})
|
||||
|
||||
// The word-bag is order-insensitive, which is what lets one alias cover the two ways
|
||||
// exporters write the same movement.
|
||||
it('ignores word order and case', () => {
|
||||
expect(matchExercise('Squat (Barbell)')).toBe(matchExercise('Barbell Squat'))
|
||||
})
|
||||
|
||||
// Regression guard for the aliases added above: the common lifts must not have moved.
|
||||
it('leaves the established aliases alone', () => {
|
||||
expect(matchExercise('Bench Press')).toBe('0025')
|
||||
expect(matchExercise('Squat')).toBe('0043')
|
||||
expect(matchExercise('Barbell Row')).toBe('0027')
|
||||
expect(matchExercise('Deadlift')).toBe('0032')
|
||||
})
|
||||
|
||||
it('still refuses to guess', () => {
|
||||
expect(matchExercise('Some Movement I Invented')).toBe(null)
|
||||
expect(matchExercise('')).toBe(null)
|
||||
})
|
||||
})
|
||||
@@ -9,7 +9,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.js'
|
||||
import { t } from './i18n-core.js'
|
||||
|
||||
export const MOBILE = import.meta.env.VITE_MOBILE === '1'
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
// map can actually draw, via ALIAS below. Anything genuinely undrawable (hands,
|
||||
// ankles, "cardiovascular system") maps to null and is dropped rather than guessed at.
|
||||
|
||||
import { EXIDX } from './exercises.js'
|
||||
import { EXIDX , smOf } from './exercises.js'
|
||||
|
||||
// The muscles a map can shade, in head-to-toe order — also the order of any list
|
||||
// built from them, so "what am I neglecting" reads top-down like a body.
|
||||
@@ -78,7 +78,7 @@ export function musclesOf(ex) {
|
||||
if (slug) out[slug] = Math.max(out[slug] || 0, w)
|
||||
}
|
||||
add(ex.tg, 1)
|
||||
;(ex.sm || []).forEach(m => add(m, SECONDARY))
|
||||
;smOf(ex).forEach(m => add(m, SECONDARY))
|
||||
// Nothing recognised (custom exercises, or a target we don't draw) — use the body part.
|
||||
if (!Object.keys(out).length) Object.assign(out, BY_BODYPART[ex.bp] || {})
|
||||
return out
|
||||
@@ -108,7 +108,7 @@ export function loadOf(items) {
|
||||
*/
|
||||
export const loadOfWorkouts = (workouts, pick) =>
|
||||
loadOf((workouts || []).flatMap(w =>
|
||||
(w.entries || []).map(e => ({ id: e.id, sets: (e.sets || []).filter(s => s.done && (!pick || pick(s))).length }))))
|
||||
(w.entries || []).map(e => ({ id: e.id, sets: (e.sets || []).filter(s => s.done && !s.warmup && (!pick || pick(s))).length }))))
|
||||
|
||||
/** Load a routine *would* produce, from its planned set counts. */
|
||||
export const loadOfRoutine = routine =>
|
||||
@@ -116,14 +116,34 @@ export const loadOfRoutine = routine =>
|
||||
|
||||
/** Load for a workout still in progress — the sets ticked so far. */
|
||||
export const loadOfActive = active =>
|
||||
loadOf((active?.entries || []).map(e => ({ id: e.id, sets: (e.sets || []).filter(s => s.done).length })))
|
||||
loadOf((active?.entries || []).map(e => ({ id: e.id, sets: (e.sets || []).filter(s => s.done && !s.warmup).length })))
|
||||
|
||||
/**
|
||||
* Shade buckets 0–4 per muscle, relative to the hardest-worked muscle in the same
|
||||
* window. Relative rather than absolute on purpose: the map answers "is my training
|
||||
* balanced", which only means anything as a comparison within one period.
|
||||
* Shade buckets 0–4 per muscle.
|
||||
*
|
||||
* With no `thresholds`, levels remain relative to the hardest-worked muscle in the same
|
||||
* window. This is the original balance-map behavior. When `thresholds` is supplied, levels
|
||||
* use an absolute scale instead: it is an ordered array of `{ at, level, exclusive? }` rules,
|
||||
* and the last matching rule wins. An exclusive rule matches values strictly greater than
|
||||
* `at`; otherwise the boundary is inclusive. Values below the first matching rule are l0.
|
||||
* Absolute rules let recovery views keep fixed semantic bands instead of renormalizing to the
|
||||
* strongest muscle on screen.
|
||||
*/
|
||||
export function levelsOf(load) {
|
||||
export function levelsOf(load, thresholds) {
|
||||
if (thresholds) {
|
||||
const lv = {}
|
||||
MUSCLES.forEach(m => {
|
||||
const value = Number(load[m] || 0)
|
||||
let level = 0
|
||||
for (const rule of thresholds) {
|
||||
const matches = rule.exclusive ? value > rule.at : value >= rule.at
|
||||
if (matches) level = Math.max(0, Math.min(4, rule.level))
|
||||
}
|
||||
lv[m] = level
|
||||
})
|
||||
return lv
|
||||
}
|
||||
|
||||
const max = Math.max(0, ...MUSCLES.map(m => load[m] || 0))
|
||||
const lv = {}
|
||||
MUSCLES.forEach(m => {
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { EXIDX, EXDB, smOf } from './exercises.js'
|
||||
import { musclesOf } from './muscles.js'
|
||||
|
||||
// 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({
|
||||
chest: 1,
|
||||
triceps: 0.4,
|
||||
deltoids: 0.4,
|
||||
})
|
||||
})
|
||||
|
||||
it('maps a squat to glutes, quads and hamstrings', () => {
|
||||
expect(musclesOf(EXIDX['0043'])).toMatchObject({
|
||||
gluteal: 1,
|
||||
quadriceps: 0.4,
|
||||
hamstring: 0.4,
|
||||
})
|
||||
})
|
||||
|
||||
it('maps common row variations to the upper back, biceps and rear deltoids', () => {
|
||||
for (const id of ['0027', '0293', '0499', '0861']) {
|
||||
expect(musclesOf(EXIDX[id])).toMatchObject({
|
||||
'upper-back': 1,
|
||||
biceps: 0.4,
|
||||
deltoids: 0.4,
|
||||
})
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
describe('catalogue secondary additions', () => {
|
||||
it('enriches the muscle map without mutating the raw dataset', () => {
|
||||
const raw = EXDB.find(e => e.id === '0027')
|
||||
expect(raw.sm).not.toContain('rear deltoids')
|
||||
expect(smOf(raw)).toContain('rear deltoids')
|
||||
// the alias collapses onto the deltoids slug in the canonical muscle map
|
||||
expect(musclesOf(raw)).toHaveProperty('deltoids')
|
||||
})
|
||||
})
|
||||
@@ -44,7 +44,7 @@ export function estimate1RM(w, r, formula = DEFAULT_FORMULA) {
|
||||
export function bestSetOf(entry, formula = DEFAULT_FORMULA) {
|
||||
let best = null
|
||||
;(entry?.sets || []).forEach(s => {
|
||||
if (!s.done) return
|
||||
if (!s.done || s.warmup) return
|
||||
const est = estimate1RM(s.w, s.r, formula)
|
||||
if (est !== null && (!best || est > best.est)) best = { est, w: Number(s.w), r: Math.round(Number(s.r)) }
|
||||
})
|
||||
|
||||
@@ -146,3 +146,19 @@ describe('is1RMRecord', () => {
|
||||
expect(is1RMRecord(S, 'bench', { id: 'bench', sets: [{ w: 200, r: 5, done: false }] })).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
describe('warm-up sets and 1RM', () => {
|
||||
const ENTRY = { id: 'warm-test', sets: [
|
||||
{ w: 20, r: 8, done: true, warmup: true },
|
||||
{ w: 80, r: 5, done: true },
|
||||
] }
|
||||
|
||||
it('does not let a ticked-off warm-up set set or raise the estimated 1RM', () => {
|
||||
const working = { id: 'warm-test', sets: [{ w: 80, r: 5, done: true }] }
|
||||
expect(bestSetOf(ENTRY)).toEqual(bestSetOf(working))
|
||||
expect(best1RM({ workouts: [{ entries: [ENTRY] }] }, 'warm-test')).toEqual(
|
||||
best1RM({ workouts: [{ entries: [working] }] }, 'warm-test'),
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -11,7 +11,7 @@
|
||||
import { EXIDX, isBodyweightEq } from './exercises.js'
|
||||
import { modeOf, fmtSec, isBw, isPerSide, sideReps } from './history.js'
|
||||
import { uid, todayISO, DAYN, fmtNum, exCount } from './format.js'
|
||||
import { t } from './i18n.js'
|
||||
import { t } from './i18n-core.js'
|
||||
|
||||
const PLAN_FMT = 1
|
||||
const WEEK_ORDER = [1, 2, 3, 4, 5, 6, 0] // Mon-first, matching the Plan screen
|
||||
|
||||
@@ -101,7 +101,9 @@ function deloadTo(cur, step) {
|
||||
export function readSession(entry, fallback) {
|
||||
const target = (entry && entry.target) || fallback || {}
|
||||
const mode = modeOf({ ...target, id: entry && entry.id })
|
||||
const sets = (entry && entry.sets) || []
|
||||
// Warm-up rows are prep, not the session: one filtered read beats guarding every consumer
|
||||
// below (an undone warm-up otherwise poisons `ok` forever and its reps drag `low`/`count`).
|
||||
const sets = ((entry && entry.sets) || []).filter(s => !s.warmup)
|
||||
const planned = target.sets || sets.length
|
||||
const enough = sets.length >= planned
|
||||
|
||||
@@ -132,7 +134,7 @@ export function sessionsFor(S, exId, fallback) {
|
||||
const out = []
|
||||
;(S.workouts || []).forEach(w => {
|
||||
const entry = w.entries.find(e => e.id === exId)
|
||||
if (entry && entry.sets.some(s => s.done)) out.push({ d: w.d, ...readSession(entry, fallback) })
|
||||
if (entry && entry.sets.some(s => s.done && !s.warmup)) out.push({ d: w.d, ...readSession(entry, fallback) })
|
||||
})
|
||||
return out
|
||||
}
|
||||
@@ -250,7 +252,10 @@ export function nextPrescription(S, cfg, routine) {
|
||||
export function applyPrescription(sets, p) {
|
||||
if (!p || p.kind === 'off' || p.kind === 'first') return sets
|
||||
const out = sets.map(s => {
|
||||
if (s.done) return s
|
||||
// Never rewrite a logged set, and never rewrite a warm-up: the prescription speaks to
|
||||
// the work rows only (a ticked warm-up falling through here would be the data-loss the
|
||||
// cascade fix removed, two files over).
|
||||
if (s.done || s.warmup) return s
|
||||
const o = { ...s }
|
||||
if (p.weight != null) o.w = p.weight
|
||||
if (p.reps != null) o.r = p.reps
|
||||
@@ -260,9 +265,13 @@ export function applyPrescription(sets, p) {
|
||||
// A policy that decided on a set count gets to grow the list — bodyweight progression adds
|
||||
// a set where a barbell would have added a plate. Only ever upwards, and only by copying a
|
||||
// row that is already there: a session in progress must not lose a set it has logged.
|
||||
if (p.sets > out.length) {
|
||||
const seed = out[out.length - 1]
|
||||
while (out.length < p.sets) out.push({ ...seed, done: false })
|
||||
const workRows = out.filter(s => !s.warmup)
|
||||
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
|
||||
const seed = workRows[workRows.length - 1]
|
||||
while (out.filter(s => !s.warmup).length < p.sets) out.push({ ...seed, done: false })
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -450,3 +450,65 @@ describe('applyPrescription', () => {
|
||||
expect(applyPrescription(sets, { kind: 'up', weight: 60, sets: 1 })).toHaveLength(sets.length)
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
describe('warm-up rows in session reads (round 3)', () => {
|
||||
it('readSession ignores warm-up rows for reps, count, low and ok', () => {
|
||||
// An undone warm-up (r 0) must not poison `ok` forever; its lighter reps must not
|
||||
// drag `low`/`count` - the warm-up is prep, the session is the work rows.
|
||||
const s = readSession({ id: LIFT, target: { sets: 2, reps: 5, mode: 'reps' }, sets: [
|
||||
{ w: 20, r: 8, done: true, warmup: true },
|
||||
{ w: 60, r: 5, done: true },
|
||||
{ w: 60, r: 6, done: true },
|
||||
] })
|
||||
expect(s.count).toBe(2)
|
||||
expect(s.low).toBe(5)
|
||||
expect(s.reps).toEqual([5, 6])
|
||||
expect(s.ok).toBe(true)
|
||||
})
|
||||
|
||||
it('readSession keeps an undone warm-up out of held/ok in time mode', () => {
|
||||
const s = readSession({ id: LIFT, target: { sets: 2, sec: 45, mode: 'time' }, sets: [
|
||||
{ sec: 45, done: true, warmup: true },
|
||||
{ sec: 45, done: true },
|
||||
{ sec: 30, done: true },
|
||||
] })
|
||||
expect(s.held).toEqual([45, 30])
|
||||
expect(s.ok).toBe(false) // the 30s work row is the miss, not the warm-up
|
||||
})
|
||||
})
|
||||
|
||||
describe('applyPrescription never touches warm-up rows (round 3)', () => {
|
||||
it('leaves a done warm-up exactly as logged', () => {
|
||||
const sets = [
|
||||
{ w: 20, r: 8, done: true, warmup: true },
|
||||
{ w: 60, r: 5, done: true },
|
||||
{ w: 60, r: 5, done: false },
|
||||
]
|
||||
const out = applyPrescription(sets, { kind: 'up', weight: 62.5, reps: 5 })
|
||||
expect(out[0]).toEqual({ w: 20, r: 8, done: true, warmup: true })
|
||||
expect(out[1]).toEqual({ w: 60, r: 5, done: true })
|
||||
expect(out[2]).toEqual({ w: 62.5, r: 5, done: false })
|
||||
})
|
||||
|
||||
it('grows the work rows, not the warm-up rows, when the policy adds sets', () => {
|
||||
const sets = [
|
||||
{ w: 20, r: 8, done: true, warmup: true },
|
||||
{ w: 60, r: 5, done: true },
|
||||
{ w: 60, r: 5, done: false },
|
||||
]
|
||||
const out = applyPrescription(sets, { kind: 'up', weight: 62.5, reps: 5, sets: 4 })
|
||||
expect(out.filter(s => !s.warmup)).toHaveLength(4) // 2 existing + 2 grown
|
||||
expect(out.filter(s => s.warmup)).toHaveLength(1) // warm-up untouched
|
||||
expect(out[0]).toEqual({ w: 20, r: 8, done: true, warmup: true })
|
||||
})
|
||||
|
||||
it('an all-warm-up entry terminates and stays untouched', () => {
|
||||
const sets = [
|
||||
{ w: 20, r: 8, done: true, warmup: true },
|
||||
{ w: 25, r: 6, done: true, warmup: true },
|
||||
]
|
||||
const out = applyPrescription(sets, { kind: 'up', weight: 62.5, reps: 5, sets: 4 })
|
||||
expect(out).toEqual(sets) // no work row to seed growth from - nothing grows, no loop
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,17 @@
|
||||
import { FATIGUE_STATES } from './recovery.js'
|
||||
|
||||
/**
|
||||
* Select the consumer-facing fatigue state for one numeric recovery value.
|
||||
* Values below .25 are ready, .25 through .5 are recovering, and values above .5 are fatigued.
|
||||
* Keeping this boundary selector in production code prevents views and tests from drifting apart.
|
||||
*
|
||||
* @param {number} value Numeric fatigue value from fatigueOf().
|
||||
* @returns {'ready'|'recovering'|'fatigued'} The stable state label for the UI.
|
||||
*/
|
||||
export function fatigueStateOf(value) {
|
||||
return value < 0.25
|
||||
? FATIGUE_STATES.READY
|
||||
: value <= 0.5
|
||||
? FATIGUE_STATES.RECOVERING
|
||||
: FATIGUE_STATES.FATIGUED
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { FATIGUE_STATES, fatigueOf, strengthOf } from './recovery.js'
|
||||
import { fatigueStateOf } from './recovery-view.js'
|
||||
import { MUSCLES, levelsOf } from './muscles.js'
|
||||
|
||||
const FATIGUE_BANDS = [
|
||||
{ at: 0, level: 4 },
|
||||
{ at: 0.25, level: 2 },
|
||||
{ at: 0.5, level: 0, exclusive: true },
|
||||
]
|
||||
const STRENGTH_BANDS = [
|
||||
{ at: 0.5, level: 0 },
|
||||
{ at: 0.625, level: 1 },
|
||||
{ at: 0.75, level: 2 },
|
||||
{ at: 0.875, level: 3 },
|
||||
{ at: 1, level: 4 },
|
||||
]
|
||||
|
||||
describe('production recovery view selectors', () => {
|
||||
it('preserves the relative balance scale when no thresholds are supplied', () => {
|
||||
const levels = levelsOf({ chest: 10, biceps: 5 })
|
||||
expect(levels.chest).toBe(4)
|
||||
expect(levels.biceps).toBe(2)
|
||||
})
|
||||
|
||||
it('uses the production fatigue selector at both approved boundaries', () => {
|
||||
expect(fatigueStateOf(0.2499)).toBe(FATIGUE_STATES.READY)
|
||||
expect(fatigueStateOf(0.25)).toBe(FATIGUE_STATES.RECOVERING)
|
||||
expect(fatigueStateOf(0.5)).toBe(FATIGUE_STATES.RECOVERING)
|
||||
expect(fatigueStateOf(0.5001)).toBe(FATIGUE_STATES.FATIGUED)
|
||||
})
|
||||
|
||||
it('renders fatigue bands on a fixed absolute scale rather than relative to the map maximum', () => {
|
||||
const levels = levelsOf({
|
||||
chest: 0.25,
|
||||
biceps: 0.6,
|
||||
triceps: 0.1,
|
||||
}, FATIGUE_BANDS)
|
||||
expect(levels.chest).toBe(2)
|
||||
expect(levels.biceps).toBe(0)
|
||||
expect(levels.triceps).toBe(4)
|
||||
})
|
||||
|
||||
it('renders strength on fixed .5-to-1 bands with full retention at l4', () => {
|
||||
const levels = levelsOf({ chest: 0.9, biceps: 1, triceps: 0.5 }, STRENGTH_BANDS)
|
||||
expect(levels.chest).toBe(3)
|
||||
expect(levels.biceps).toBe(4)
|
||||
expect(levels.triceps).toBe(0)
|
||||
})
|
||||
|
||||
it('keeps selectors tied to the same render-time clock', () => {
|
||||
const now = Date.UTC(2026, 0, 22)
|
||||
const workout = { start: now - 15 * 86400000, d: '2026-01-07', entries: [] }
|
||||
expect(strengthOf([workout], now).chest).toBe(0.5)
|
||||
expect(fatigueOf([workout], now).chest).toBe(0)
|
||||
expect(strengthOf([workout], now + 7 * 86400000).chest).toBe(0.5)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,197 @@
|
||||
import { EXIDX } from './exercises.js'
|
||||
import { MUSCLES, musclesOf } from './muscles.js'
|
||||
|
||||
/** Completed-workout window used when calculating current fatigue. */
|
||||
// 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
|
||||
// fatigue level without ever pinning it, and the value can then fade asymptotically.
|
||||
export const FATIGUE_REF_VOLUME = 3
|
||||
// Computational bound for the stimulus scan, not a semantic cliff: after 30 days (20
|
||||
// half-lives) a session contributes below 1e-6 to the accumulated value.
|
||||
export const FATIGUE_SCAN_MS = 30 * 24 * 60 * 60 * 1000
|
||||
|
||||
/** Exponential half-life for fatigue stimulus. */
|
||||
export const FATIGUE_HALF_LIFE_MS = 129600000
|
||||
|
||||
/** Period after training during which retained strength remains at full value. */
|
||||
export const STRENGTH_FULL_MS = 1209600000
|
||||
|
||||
/** Exponential half-life for retained strength after the full-retention period. */
|
||||
export const STRENGTH_HALF_LIFE_MS = 2419200000
|
||||
|
||||
/** Minimum retained-strength value for an untrained or fully detrained muscle. */
|
||||
export const STRENGTH_FLOOR = 0.5
|
||||
|
||||
/**
|
||||
* Stable labels for consumer fatigue buckets: values below 0.25 are ready, values from 0.25
|
||||
* through 0.5 are recovering, and values above 0.5 are fatigued.
|
||||
*/
|
||||
export const FATIGUE_STATES = Object.freeze({
|
||||
READY: 'ready',
|
||||
RECOVERING: 'recovering',
|
||||
FATIGUED: 'fatigued',
|
||||
})
|
||||
|
||||
/**
|
||||
* Return exponential decay expressed as a fraction of one half-life.
|
||||
*
|
||||
* @param {number} ageMs Elapsed age of the stimulus in milliseconds.
|
||||
* @param {number} halfLifeMs Duration of one half-life in milliseconds.
|
||||
* @returns {number} Remaining fraction, using the exact `0.5 ** (age / halfLife)` formula.
|
||||
*/
|
||||
export function halfLifeDecay(ageMs, halfLifeMs) {
|
||||
return 0.5 ** (ageMs / halfLifeMs)
|
||||
}
|
||||
|
||||
// The v2 data contract has one timestamp per workout, not per set. Keep this fallback in one
|
||||
// place so fatigue and strength use exactly the same stimulus time as effort.js.
|
||||
function workoutTimestamp(workout) {
|
||||
const timestamp = workout?.start || new Date(workout?.d).getTime()
|
||||
return Number.isFinite(timestamp) ? timestamp : Number(timestamp)
|
||||
}
|
||||
|
||||
function emptyMuscleMap(value) {
|
||||
return Object.fromEntries(MUSCLES.map(slug => [slug, value]))
|
||||
}
|
||||
|
||||
function clamp(value, min, max) {
|
||||
return Math.min(max, Math.max(min, value))
|
||||
}
|
||||
|
||||
// Yield one weighted stimulus per completed set. Repeating the exercise's muscle weights for
|
||||
// every done set is equivalent to multiplying musclesOf(ex) by the completed-set count while
|
||||
// preserving the workout/set shape already used by the app.
|
||||
function completedStimuli(workouts, include) {
|
||||
const stimuli = []
|
||||
for (const workout of workouts || []) {
|
||||
const timestamp = workoutTimestamp(workout)
|
||||
if (!Number.isFinite(timestamp) || !include(timestamp)) continue
|
||||
for (const entry of workout.entries || []) {
|
||||
const weights = musclesOf(EXIDX[entry.id])
|
||||
for (const set of entry.sets || []) {
|
||||
if (set?.done !== true) continue
|
||||
for (const [slug, weight] of Object.entries(weights)) {
|
||||
if (Object.prototype.hasOwnProperty.call(MUSCLES_BY_SLUG, slug)) {
|
||||
stimuli.push({ slug, timestamp, stimulus: weight })
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return stimuli
|
||||
}
|
||||
|
||||
const MUSCLES_BY_SLUG = Object.fromEntries(MUSCLES.map(slug => [slug, true]))
|
||||
|
||||
function fatigueValue(events, now) {
|
||||
if (!events.length) return 0
|
||||
events.sort((a, b) => a.timestamp - b.timestamp)
|
||||
|
||||
let value = 0
|
||||
let lastTimestamp = events[0].timestamp
|
||||
for (const event of events) {
|
||||
value *= halfLifeDecay(event.timestamp - lastTimestamp, FATIGUE_HALF_LIFE_MS)
|
||||
value += event.stimulus
|
||||
lastTimestamp = event.timestamp
|
||||
}
|
||||
value *= halfLifeDecay(now - lastTimestamp, FATIGUE_HALF_LIFE_MS)
|
||||
// Normalise the accumulated stimulus to a saturating fatigue level: more volume starts
|
||||
// higher but never pins, and the value fades asymptotically - no window-edge cliff.
|
||||
return 1 - Math.exp(-value / FATIGUE_REF_VOLUME)
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate current per-muscle fatigue from completed sets in the recent window.
|
||||
*
|
||||
* Stimulus time is `workout.start`, falling back to the workout date `workout.d`. Each completed
|
||||
* set contributes the exercise's `musclesOf` weights; the scan is bounded to FATIGUE_SCAN_MS for
|
||||
* performance, not semantics. Stimuli are accumulated chronologically with a 36-hour half-life,
|
||||
* decayed to `now`, and normalised with the saturation curve 1 - exp(-v / FATIGUE_REF_VOLUME).
|
||||
* The result always contains every drawable muscle slug.
|
||||
*
|
||||
* @param {Array<object>} workouts Workout history with `start`/`d` and entry set arrays.
|
||||
* @param {number} now Current time in milliseconds; injected to keep this function deterministic.
|
||||
* @returns {Record<string, number>} Fatigue values keyed by every drawable muscle slug.
|
||||
*/
|
||||
export function fatigueOf(workouts, now) {
|
||||
const current = Number(now)
|
||||
const cutoff = current - FATIGUE_SCAN_MS
|
||||
const stimuli = completedStimuli(workouts, timestamp => timestamp > cutoff)
|
||||
const byMuscle = Object.fromEntries(MUSCLES.map(slug => [slug, []]))
|
||||
for (const stimulus of stimuli) byMuscle[stimulus.slug].push(stimulus)
|
||||
|
||||
const result = emptyMuscleMap(0)
|
||||
if (!Number.isFinite(current)) return result
|
||||
for (const slug of MUSCLES) result[slug] = fatigueValue(byMuscle[slug], current)
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate retained per-muscle strength from the latest completed stimulus in all history.
|
||||
*
|
||||
* A muscle with no completed set starts at the 0.5 floor. After a completed set, strength is
|
||||
* 1.0 through 14 days old, then decays toward the floor with a 28-day half-life. Any later
|
||||
* completed set becomes the new latest stimulus and resets the 14-day full-retention period.
|
||||
* The result always contains every drawable muscle slug.
|
||||
*
|
||||
* @param {Array<object>} workouts Workout history with `start`/`d` and entry set arrays.
|
||||
* @param {number} now Current time in milliseconds; injected to keep this function deterministic.
|
||||
* @returns {Record<string, number>} Retained-strength values keyed by every drawable muscle slug.
|
||||
*/
|
||||
export function strengthOf(workouts, now) {
|
||||
const current = Number(now)
|
||||
const latest = Object.fromEntries(MUSCLES.map(slug => [slug, -Infinity]))
|
||||
const stimuli = completedStimuli(workouts, () => true)
|
||||
for (const stimulus of stimuli) {
|
||||
if (stimulus.timestamp > latest[stimulus.slug]) latest[stimulus.slug] = stimulus.timestamp
|
||||
}
|
||||
|
||||
const result = emptyMuscleMap(STRENGTH_FLOOR)
|
||||
if (!Number.isFinite(current)) return result
|
||||
for (const slug of MUSCLES) {
|
||||
const lastTimestamp = latest[slug]
|
||||
if (!Number.isFinite(lastTimestamp)) continue
|
||||
const age = current - lastTimestamp
|
||||
if (age <= STRENGTH_FULL_MS) {
|
||||
result[slug] = 1
|
||||
} else {
|
||||
result[slug] = Math.max(
|
||||
STRENGTH_FLOOR,
|
||||
halfLifeDecay(age - STRENGTH_FULL_MS, STRENGTH_HALF_LIFE_MS),
|
||||
)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* List muscles currently above the fatigued threshold.
|
||||
*
|
||||
* @param {Array<object>} workouts Workout history passed to {@link fatigueOf}.
|
||||
* @param {number} now Current time in milliseconds passed to {@link fatigueOf}.
|
||||
* @returns {string[]} Muscle slugs whose fatigue value is greater than 0.5, in `MUSCLES`
|
||||
* head-to-toe order.
|
||||
* @example
|
||||
* const avoid = fatiguedMuscles(workouts, now)
|
||||
*/
|
||||
export function fatiguedMuscles(workouts, now) {
|
||||
return Object.entries(fatigueOf(workouts, now))
|
||||
.filter(([, value]) => value > 0.5)
|
||||
.map(([slug]) => slug)
|
||||
}
|
||||
|
||||
/**
|
||||
* List muscles whose retained strength is below full retention.
|
||||
*
|
||||
* @param {Array<object>} workouts Workout history passed to {@link strengthOf}.
|
||||
* @param {number} now Current time in milliseconds passed to {@link strengthOf}.
|
||||
* @returns {string[]} Muscle slugs whose retained strength is less than 1.0, in `MUSCLES`
|
||||
* head-to-toe order; never-trained muscles are included at the 0.5 floor.
|
||||
* @example
|
||||
* const targets = detrainedMuscles(workouts, now)
|
||||
*/
|
||||
export function detrainedMuscles(workouts, now) {
|
||||
return Object.entries(strengthOf(workouts, now))
|
||||
.filter(([, value]) => value < 1)
|
||||
.map(([slug]) => slug)
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
FATIGUE_HALF_LIFE_MS,
|
||||
FATIGUE_REF_VOLUME,
|
||||
FATIGUE_SCAN_MS,
|
||||
FATIGUE_STATES,
|
||||
STRENGTH_FLOOR,
|
||||
STRENGTH_FULL_MS,
|
||||
STRENGTH_HALF_LIFE_MS,
|
||||
detrainedMuscles,
|
||||
fatiguedMuscles,
|
||||
fatigueOf,
|
||||
halfLifeDecay,
|
||||
strengthOf,
|
||||
} from './recovery.js'
|
||||
import { EXDB } from './exercises.js'
|
||||
import { MUSCLES, musclesOf } from './muscles.js'
|
||||
import { fatigueStateOf } from './recovery-view.js'
|
||||
|
||||
const HOUR = 60 * 60 * 1000
|
||||
const DAY = 24 * HOUR
|
||||
const NOW = Date.UTC(2026, 0, 1, 12)
|
||||
|
||||
// Keep fixtures tied to the shipped catalogue while making the expected stimulus explicit.
|
||||
const SINGLE = EXDB.find(ex => {
|
||||
const weights = musclesOf(ex)
|
||||
return ex.bp !== 'cardio' && Object.keys(weights).length === 1 && Object.values(weights)[0] === 1
|
||||
})
|
||||
const WEIGHTED = EXDB.find(ex => {
|
||||
const weights = musclesOf(ex)
|
||||
return ex.bp !== 'cardio' && Object.values(weights).includes(0.4)
|
||||
})
|
||||
if (!SINGLE || !WEIGHTED) throw new Error('recovery tests require single- and secondary-weight fixtures')
|
||||
|
||||
const SINGLE_WEIGHTS = musclesOf(SINGLE)
|
||||
const WEIGHTED_WEIGHTS = musclesOf(WEIGHTED)
|
||||
const SINGLE_SLUG = Object.keys(SINGLE_WEIGHTS)[0]
|
||||
const WEIGHTED_PRIMARY_SLUG = Object.keys(WEIGHTED_WEIGHTS).find(slug => WEIGHTED_WEIGHTS[slug] === 1)
|
||||
const SECONDARY_SLUG = Object.keys(WEIGHTED_WEIGHTS).find(slug => WEIGHTED_WEIGHTS[slug] === 0.4)
|
||||
if (!WEIGHTED_PRIMARY_SLUG || !SECONDARY_SLUG) throw new Error('recovery tests require weighted primary and secondary fixtures')
|
||||
|
||||
const workoutAt = (id, start, sets = [{ done: true }]) => ({
|
||||
d: new Date(start).toISOString(),
|
||||
start,
|
||||
entries: [{ id, sets: sets.map(set => ({ ...set })) }],
|
||||
})
|
||||
const doneWorkoutAt = (id, start, count = 1) =>
|
||||
workoutAt(id, start, Array.from({ length: count }, () => ({ done: true })))
|
||||
const zeroFatigue = () => Object.fromEntries(MUSCLES.map(slug => [slug, 0]))
|
||||
const floorStrength = () => Object.fromEntries(MUSCLES.map(slug => [slug, STRENGTH_FLOOR]))
|
||||
|
||||
// Numeric fatigue remains the math API; the UI boundary selector is imported from production.
|
||||
const stableFloat = value => Number(value.toFixed(12))
|
||||
|
||||
describe('recovery constants', () => {
|
||||
it('exports the pinned windows, half-lives, floor, and state labels', () => {
|
||||
expect(FATIGUE_REF_VOLUME).toBe(3)
|
||||
expect(FATIGUE_SCAN_MS).toBe(30 * DAY)
|
||||
expect(FATIGUE_HALF_LIFE_MS).toBe(36 * HOUR)
|
||||
expect(STRENGTH_FULL_MS).toBe(14 * DAY)
|
||||
expect(STRENGTH_HALF_LIFE_MS).toBe(28 * DAY)
|
||||
expect(STRENGTH_FLOOR).toBe(0.5)
|
||||
expect(FATIGUE_STATES).toEqual({ READY: 'ready', RECOVERING: 'recovering', FATIGUED: 'fatigued' })
|
||||
expect(halfLifeDecay(FATIGUE_HALF_LIFE_MS, FATIGUE_HALF_LIFE_MS)).toBe(0.5)
|
||||
})
|
||||
})
|
||||
|
||||
describe('fatigueOf and strengthOf', () => {
|
||||
it('returns every muscle, ready/floor defaults, and hook defaults for empty history', () => {
|
||||
const fatigue = fatigueOf([], NOW)
|
||||
const strength = strengthOf([], NOW)
|
||||
|
||||
expect(Object.keys(fatigue)).toEqual(MUSCLES)
|
||||
expect(fatigue).toEqual(zeroFatigue())
|
||||
expect(Object.values(fatigue).map(fatigueStateOf)).toEqual(
|
||||
MUSCLES.map(() => FATIGUE_STATES.READY),
|
||||
)
|
||||
expect(Object.keys(strength)).toEqual(MUSCLES)
|
||||
expect(strength).toEqual(floorStrength())
|
||||
expect(fatiguedMuscles([], NOW)).toEqual([])
|
||||
expect(detrainedMuscles([], NOW)).toEqual(MUSCLES)
|
||||
})
|
||||
|
||||
it('applies one completed set to each of the exercise muscle weights', () => {
|
||||
const workouts = [doneWorkoutAt(WEIGHTED.id, NOW)]
|
||||
const fatigue = fatigueOf(workouts, NOW)
|
||||
const strength = strengthOf(workouts, NOW)
|
||||
|
||||
for (const slug of MUSCLES) {
|
||||
const weight = WEIGHTED_WEIGHTS[slug] || 0
|
||||
expect(fatigue[slug]).toBeCloseTo(1 - Math.exp(-weight / FATIGUE_REF_VOLUME), 10)
|
||||
expect(strength[slug]).toBe(weight ? 1 : STRENGTH_FLOOR)
|
||||
}
|
||||
// one set never crosses the fatigued threshold on the saturating curve
|
||||
expect(fatiguedMuscles(workouts, NOW)).toEqual([])
|
||||
})
|
||||
|
||||
it('raises starting fatigue with volume, never pins, and fades without a cliff', () => {
|
||||
const at0 = count => fatigueOf([doneWorkoutAt(SINGLE.id, NOW, count)], NOW)[SINGLE_SLUG]
|
||||
expect(at0(1)).toBeCloseTo(1 - Math.exp(-1 / FATIGUE_REF_VOLUME), 10)
|
||||
expect(at0(5)).toBeCloseTo(1 - Math.exp(-5 / FATIGUE_REF_VOLUME), 10)
|
||||
expect(at0(12)).toBeCloseTo(1 - Math.exp(-12 / FATIGUE_REF_VOLUME), 10)
|
||||
expect(at0(12)).toBeGreaterThan(at0(5))
|
||||
expect(at0(5)).toBeGreaterThan(at0(1))
|
||||
expect(at0(12)).toBeLessThan(1)
|
||||
// one half-life later the gradient is still visible at any volume
|
||||
const later = fatigueOf([doneWorkoutAt(SINGLE.id, NOW - FATIGUE_HALF_LIFE_MS, 12)], NOW)[SINGLE_SLUG]
|
||||
expect(later).toBeCloseTo(1 - Math.exp(-6 / FATIGUE_REF_VOLUME), 10)
|
||||
expect(later).toBeLessThan(at0(12))
|
||||
// no cliff: 72h keeps decaying instead of snapping to zero
|
||||
const old = fatigueOf([doneWorkoutAt(SINGLE.id, NOW - 72 * HOUR)], NOW)[SINGLE_SLUG]
|
||||
expect(old).toBeGreaterThan(0)
|
||||
expect(old).toBeLessThan(0.25)
|
||||
})
|
||||
|
||||
it('decays each weighted stimulus exactly at 36 hours and by sqrt-half at 18 hours', () => {
|
||||
for (const age of [FATIGUE_HALF_LIFE_MS, FATIGUE_HALF_LIFE_MS / 2]) {
|
||||
const fatigue = fatigueOf([doneWorkoutAt(WEIGHTED.id, NOW - age)], NOW)
|
||||
const expectedDecay = 0.5 ** (age / FATIGUE_HALF_LIFE_MS)
|
||||
for (const [slug, weight] of Object.entries(WEIGHTED_WEIGHTS)) {
|
||||
expect(fatigue[slug]).toBeCloseTo(1 - Math.exp(-weight * expectedDecay / FATIGUE_REF_VOLUME), 10)
|
||||
}
|
||||
if (age === FATIGUE_HALF_LIFE_MS) {
|
||||
expect(fatigue[WEIGHTED_PRIMARY_SLUG]).toBeCloseTo(1 - Math.exp(-0.5 / FATIGUE_REF_VOLUME), 10)
|
||||
}
|
||||
if (age === FATIGUE_HALF_LIFE_MS / 2) {
|
||||
expect(fatigue[WEIGHTED_PRIMARY_SLUG]).toBeCloseTo(1 - Math.exp(-(0.5 ** 0.5) / FATIGUE_REF_VOLUME), 10)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
it('fades a 72-hour-old set below the ready threshold instead of hard-cutting', () => {
|
||||
const workouts = [doneWorkoutAt(SINGLE.id, NOW - 72 * HOUR)]
|
||||
const value = fatigueOf(workouts, NOW)[SINGLE_SLUG]
|
||||
expect(value).toBeGreaterThan(0)
|
||||
expect(value).toBeLessThan(0.25)
|
||||
expect(fatigueStateOf(value)).toBe(FATIGUE_STATES.READY)
|
||||
expect(strengthOf(workouts, NOW)[SINGLE_SLUG]).toBe(1)
|
||||
})
|
||||
|
||||
it('ignores sets whose done flag is false for both axes', () => {
|
||||
const workouts = [workoutAt(WEIGHTED.id, NOW, [{ done: false }])]
|
||||
expect(fatigueOf(workouts, NOW)).toEqual(zeroFatigue())
|
||||
expect(strengthOf(workouts, NOW)).toEqual(floorStrength())
|
||||
expect(fatiguedMuscles(workouts, NOW)).toEqual([])
|
||||
expect(detrainedMuscles(workouts, NOW)).toEqual(MUSCLES)
|
||||
})
|
||||
})
|
||||
|
||||
describe('fatigue state boundaries', () => {
|
||||
// Inverse of the saturation curve: raw stimulus needed to land exactly on a target level.
|
||||
const rawAt = target => -FATIGUE_REF_VOLUME * Math.log(1 - target)
|
||||
|
||||
it('classifies exactly .25 as recovering and .2499 as ready', () => {
|
||||
const weight = WEIGHTED_WEIGHTS[SECONDARY_SLUG]
|
||||
const sets = 3
|
||||
const valueAt = target => {
|
||||
const age = FATIGUE_HALF_LIFE_MS * Math.log2(sets * weight / rawAt(target))
|
||||
const value = fatigueOf([doneWorkoutAt(WEIGHTED.id, NOW - age, sets)], NOW)[SECONDARY_SLUG]
|
||||
expect(value).toBeCloseTo(target, 10)
|
||||
return stableFloat(value)
|
||||
}
|
||||
|
||||
expect(fatigueStateOf(valueAt(0.25))).toBe(FATIGUE_STATES.RECOVERING)
|
||||
expect(fatigueStateOf(valueAt(0.2499))).toBe(FATIGUE_STATES.READY)
|
||||
})
|
||||
|
||||
it('classifies exactly .5 as recovering, .5001 as fatigued, and hooks only fatigued muscles', () => {
|
||||
const sets = 3
|
||||
const atHalf = [doneWorkoutAt(SINGLE.id, NOW - FATIGUE_HALF_LIFE_MS * Math.log2(sets / rawAt(0.4999)), sets)]
|
||||
const aboveHalf = [
|
||||
doneWorkoutAt(SINGLE.id, NOW - FATIGUE_HALF_LIFE_MS * Math.log2(sets / rawAt(0.5001)), sets),
|
||||
]
|
||||
const half = fatigueOf(atHalf, NOW)[SINGLE_SLUG]
|
||||
const above = fatigueOf(aboveHalf, NOW)[SINGLE_SLUG]
|
||||
|
||||
expect(half).toBeCloseTo(0.4999, 10)
|
||||
expect(fatigueStateOf(stableFloat(half))).toBe(FATIGUE_STATES.RECOVERING)
|
||||
expect(fatiguedMuscles(atHalf, NOW)).toEqual([])
|
||||
expect(above).toBeCloseTo(0.5001, 10)
|
||||
expect(fatigueStateOf(stableFloat(above))).toBe(FATIGUE_STATES.FATIGUED)
|
||||
expect(fatiguedMuscles(aboveHalf, NOW)).toEqual([SINGLE_SLUG])
|
||||
})
|
||||
})
|
||||
|
||||
describe('strengthOf', () => {
|
||||
const strengthAt = age => strengthOf([doneWorkoutAt(SINGLE.id, NOW - age)], NOW)[SINGLE_SLUG]
|
||||
|
||||
it('stays at full retention through 14 days and decays from 15 days by the 28-day half-life', () => {
|
||||
expect(strengthAt(STRENGTH_FULL_MS)).toBe(1)
|
||||
expect(strengthAt(15 * DAY)).toBeCloseTo(0.5 ** (1 / 28), 10)
|
||||
})
|
||||
|
||||
it('clamps the 42-day half-life point and later 56-day value at the .5 floor', () => {
|
||||
expect(strengthAt(42 * DAY)).toBe(0.5)
|
||||
expect(strengthAt(56 * DAY)).toBe(STRENGTH_FLOOR)
|
||||
})
|
||||
|
||||
it('resets retained strength when a later completed session retrains the muscle', () => {
|
||||
const workouts = [
|
||||
doneWorkoutAt(SINGLE.id, NOW - 20 * DAY),
|
||||
doneWorkoutAt(SINGLE.id, NOW),
|
||||
]
|
||||
expect(strengthOf(workouts, NOW)[SINGLE_SLUG]).toBe(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('accumulation and purity', () => {
|
||||
it('matches the saturated sum of independently decayed stimuli in chronological order', () => {
|
||||
const ages = [64 * HOUR, 40 * HOUR]
|
||||
const workouts = ages.map(age => doneWorkoutAt(SINGLE.id, NOW - age))
|
||||
const raw = ages.reduce(
|
||||
(sum, age) => sum + 0.5 ** (age / FATIGUE_HALF_LIFE_MS),
|
||||
0,
|
||||
)
|
||||
const expected = 1 - Math.exp(-raw / FATIGUE_REF_VOLUME)
|
||||
|
||||
expect(raw).toBeLessThan(FATIGUE_REF_VOLUME)
|
||||
expect(fatigueOf(workouts, NOW)[SINGLE_SLUG]).toBeCloseTo(expected, 10)
|
||||
expect(fatigueOf([...workouts].reverse(), NOW)[SINGLE_SLUG]).toBeCloseTo(expected, 10)
|
||||
})
|
||||
|
||||
it('saturates without pinning and returns identical results without mutating inputs or sharing state', () => {
|
||||
const saturated = [doneWorkoutAt(SINGLE.id, NOW, 2)]
|
||||
expect(fatigueOf(saturated, NOW)[SINGLE_SLUG]).toBeCloseTo(1 - Math.exp(-2 / FATIGUE_REF_VOLUME), 10)
|
||||
expect(fatigueOf(saturated, NOW)[SINGLE_SLUG]).toBeLessThan(1)
|
||||
|
||||
const workouts = [
|
||||
doneWorkoutAt(SINGLE.id, NOW - 64 * HOUR),
|
||||
doneWorkoutAt(SINGLE.id, NOW - 40 * HOUR),
|
||||
]
|
||||
const before = JSON.parse(JSON.stringify(workouts))
|
||||
const firstFatigue = fatigueOf(workouts, NOW)
|
||||
const firstStrength = strengthOf(workouts, NOW)
|
||||
const secondFatigue = fatigueOf(workouts, NOW)
|
||||
const secondStrength = strengthOf(workouts, NOW)
|
||||
|
||||
expect(secondFatigue).toEqual(firstFatigue)
|
||||
expect(secondStrength).toEqual(firstStrength)
|
||||
expect(workouts).toEqual(before)
|
||||
})
|
||||
})
|
||||
@@ -161,13 +161,15 @@ export default {
|
||||
'Last time you hit all reps — try {0}': 'Letztes Mal alle Wdh. geschafft — versuch {0}',
|
||||
'Weights bumped to {0}': 'Gewichte auf {0} erhöht',
|
||||
'Remove set': 'Satz entfernen',
|
||||
'Warm-up': 'Aufwärmen',
|
||||
'Add warm-up set': 'Aufwärmsatz hinzufügen',
|
||||
'Add set': 'Satz hinzufügen',
|
||||
'Cardio logged': 'Cardio eingetragen',
|
||||
'Discard workout?': 'Training verwerfen?',
|
||||
'The sets you logged in this session will be lost.': 'Die in dieser Einheit eingetragenen Sätze gehen verloren.',
|
||||
'Superset {0} / {1}': 'Supersatz {0} / {1}',
|
||||
'Exercise {0} / {1}': 'Übung {0} / {1}',
|
||||
'Superset · do these back-to-back, rest after both': 'Supersatz · direkt nacheinander, Pause erst danach',
|
||||
'Superset · do these back-to-back, rest when done': 'Supersatz · direkt nacheinander, Pause erst danach',
|
||||
'Freestyle workout — add your first exercise.': 'Freies Training — füge deine erste Übung hinzu.',
|
||||
'Finish workout early · {0} exercises': 'Training vorzeitig beenden · {0} Übungen',
|
||||
'Rest over — next set!': 'Pause vorbei — nächster Satz!',
|
||||
@@ -236,6 +238,7 @@ export default {
|
||||
'Sign in with passkey': 'Mit Passkey anmelden',
|
||||
'Create new profile': 'Neues Profil erstellen',
|
||||
"This browser doesn't support passkeys — you can still use openGym locally on this device.": 'Dieser Browser unterstützt keine Passkeys — du kannst openGym trotzdem lokal auf diesem Gerät nutzen.',
|
||||
"This browser doesn't support passkeys, and this instance requires an account. Try a browser or device with passkey support.": 'Dieser Browser unterstützt keine Passkeys, und dieser Server verlangt ein Konto. Probier einen Browser oder ein Gerät mit Passkey-Unterstützung.',
|
||||
'Continue without account': 'Ohne Konto fortfahren',
|
||||
'Passkeys use {0} — no passwords.': 'Passkeys nutzen {0} — keine Passwörter.',
|
||||
'Each profile keeps its own plan, workouts & body weight.': 'Jedes Profil hat seinen eigenen Plan, Trainings & Körpergewicht.',
|
||||
@@ -378,6 +381,15 @@ export default {
|
||||
'Admin dashboard': 'Admin-Dashboard',
|
||||
// --- muscle map ---
|
||||
'Muscle balance': 'Muskelbalance',
|
||||
'Fatigue': 'Ermüdung',
|
||||
'Ready': 'Bereit',
|
||||
'Recovering': 'In Erholung',
|
||||
'Fatigued': 'Ermüdet',
|
||||
'Fatigue shows how recently each muscle was trained. High means rest.': 'Die Ermüdung zeigt, wie lange das Training jedes Muskels zurückliegt. Ein hoher Wert bedeutet: Pause.',
|
||||
'Strength shows retained muscle strength. Train again to reset it.': 'Die Kraft zeigt, wie viel Muskelkraft erhalten ist. Trainiere erneut, um sie zurückzusetzen.',
|
||||
'full': 'voll',
|
||||
'floor': 'Minimum',
|
||||
'Weeks since training: {0}': 'Zuletzt vor {0} Wo. trainiert',
|
||||
'by sets worked': 'nach Sätzen',
|
||||
'Week': 'Woche',
|
||||
'not trained': 'nicht trainiert',
|
||||
@@ -571,4 +583,8 @@ export default {
|
||||
'{0} sets of {1} — time to add weight or move to a harder variation.': '{0} Sätze mit {1} — Zeit für Zusatzgewicht oder eine schwerere Variante.',
|
||||
'{0} per side': '{0} pro Seite',
|
||||
'You still log the total: {0} is {1} per side.': 'Du trägst weiterhin die Gesamtzahl ein: {0} sind {1} pro Seite.',
|
||||
'{0} sets · {1} work': '{0} Sätze · {1} Arbeit',
|
||||
'Make superset with previous': 'Mit vorheriger Übung kombinieren',
|
||||
'Make superset with next': 'Mit nächster Übung kombinieren',
|
||||
'Unpair': 'Trennen'
|
||||
}
|
||||
@@ -154,13 +154,15 @@ export default {
|
||||
'Last time you hit all reps — try {0}': 'La última vez completaste todas las reps — prueba {0}',
|
||||
'Weights bumped to {0}': 'Pesos subidos a {0}',
|
||||
'Remove set': 'Quitar serie',
|
||||
'Warm-up': 'Calentamiento',
|
||||
'Add warm-up set': 'Añadir serie de calentamiento',
|
||||
'Add set': 'Añadir serie',
|
||||
'Cardio logged': 'Cardio registrado',
|
||||
'Discard workout?': '¿Descartar entrenamiento?',
|
||||
'The sets you logged in this session will be lost.': 'Las series registradas en esta sesión se perderán.',
|
||||
'Superset {0} / {1}': 'Superserie {0} / {1}',
|
||||
'Exercise {0} / {1}': 'Ejercicio {0} / {1}',
|
||||
'Superset · do these back-to-back, rest after both': 'Superserie · hazlos seguidos, descansa después de ambos',
|
||||
'Superset · do these back-to-back, rest when done': 'Superserie · hazlos seguidos, descansa al final',
|
||||
'Freestyle workout — add your first exercise.': 'Entrenamiento libre — añade tu primer ejercicio.',
|
||||
'Finish workout early · {0} exercises': 'Terminar antes · {0} ejercicios',
|
||||
'Rest over — next set!': '¡Descanso terminado — siguiente serie!',
|
||||
@@ -223,6 +225,7 @@ export default {
|
||||
'Sign in with passkey': 'Iniciar sesión con passkey',
|
||||
'Create new profile': 'Crear perfil nuevo',
|
||||
"This browser doesn't support passkeys — you can still use openGym locally on this device.": 'Este navegador no admite passkeys — aun así puedes usar openGym localmente en este dispositivo.',
|
||||
"This browser doesn't support passkeys, and this instance requires an account. Try a browser or device with passkey support.": 'Este navegador no admite passkeys y este servidor requiere una cuenta. Prueba con un navegador o dispositivo compatible con passkeys.',
|
||||
'Continue without account': 'Continuar sin cuenta',
|
||||
'Passkeys use {0} — no passwords.': 'Las passkeys usan {0} — sin contraseñas.',
|
||||
'Each profile keeps its own plan, workouts & body weight.': 'Cada perfil guarda su propio plan, entrenamientos y peso corporal.',
|
||||
@@ -360,6 +363,15 @@ export default {
|
||||
'Admin dashboard': 'Panel de administración',
|
||||
// --- muscle map ---
|
||||
'Muscle balance': 'Equilibrio muscular',
|
||||
'Fatigue': 'Fatiga',
|
||||
'Ready': 'Listo',
|
||||
'Recovering': 'En recuperación',
|
||||
'Fatigued': 'Fatigado',
|
||||
'Fatigue shows how recently each muscle was trained. High means rest.': 'La fatiga indica cuánto tiempo ha pasado desde el último entrenamiento de cada músculo. Un valor alto indica que toca descansar.',
|
||||
'Strength shows retained muscle strength. Train again to reset it.': 'La fuerza muestra cuánta fuerza muscular se conserva. Vuelve a entrenar para restablecerla.',
|
||||
'full': 'completo',
|
||||
'floor': 'mínimo',
|
||||
'Weeks since training: {0}': 'Último entrenamiento: hace {0} sem.',
|
||||
'by sets worked': 'por series trabajadas',
|
||||
'Week': 'Semana',
|
||||
'not trained': 'sin entrenar',
|
||||
@@ -554,4 +566,8 @@ export default {
|
||||
'{0} sets of {1} — time to add weight or move to a harder variation.': '{0} series de {1}: toca añadir peso o pasar a una variante más difícil.',
|
||||
'{0} per side': '{0} por lado',
|
||||
'You still log the total: {0} is {1} per side.': 'Sigues registrando el total: {0} son {1} por lado.',
|
||||
'{0} sets · {1} work': '{0} series · {1} trabajo',
|
||||
'Make superset with previous': 'Hacer superserie con anterior',
|
||||
'Make superset with next': 'Hacer superserie con siguiente',
|
||||
'Unpair': 'Desvincular'
|
||||
}
|
||||
@@ -154,13 +154,15 @@ export default {
|
||||
'Last time you hit all reps — try {0}': 'Toutes les reps réussies la dernière fois — essaie {0}',
|
||||
'Weights bumped to {0}': 'Poids montés à {0}',
|
||||
'Remove set': 'Retirer une série',
|
||||
'Warm-up': 'Échauffement',
|
||||
'Add warm-up set': 'Ajouter une série d’échauffement',
|
||||
'Add set': 'Ajouter une série',
|
||||
'Cardio logged': 'Cardio noté',
|
||||
'Discard workout?': 'Abandonner la séance ?',
|
||||
'The sets you logged in this session will be lost.': 'Les séries notées dans cette session seront perdues.',
|
||||
'Superset {0} / {1}': 'Superset {0} / {1}',
|
||||
'Exercise {0} / {1}': 'Exercice {0} / {1}',
|
||||
'Superset · do these back-to-back, rest after both': 'Superset · enchaîne-les, repos après les deux',
|
||||
'Superset · do these back-to-back, rest when done': 'Superset · enchaîne-les, repos à la fin',
|
||||
'Freestyle workout — add your first exercise.': 'Séance libre — ajoute ton premier exercice.',
|
||||
'Finish workout early · {0} exercises': 'Terminer plus tôt · {0} exercices',
|
||||
'Rest over — next set!': 'Repos fini — série suivante !',
|
||||
@@ -223,6 +225,7 @@ export default {
|
||||
'Sign in with passkey': 'Se connecter avec une passkey',
|
||||
'Create new profile': 'Créer un nouveau profil',
|
||||
"This browser doesn't support passkeys — you can still use openGym locally on this device.": 'Ce navigateur ne prend pas en charge les passkeys — tu peux quand même utiliser openGym localement sur cet appareil.',
|
||||
"This browser doesn't support passkeys, and this instance requires an account. Try a browser or device with passkey support.": 'Ce navigateur ne prend pas en charge les passkeys, et ce serveur exige un compte. Essaie un navigateur ou un appareil compatible avec les passkeys.',
|
||||
'Continue without account': 'Continuer sans compte',
|
||||
'Passkeys use {0} — no passwords.': 'Les passkeys utilisent {0} — pas de mots de passe.',
|
||||
'Each profile keeps its own plan, workouts & body weight.': 'Chaque profil garde son plan, ses séances et son poids corporel.',
|
||||
@@ -360,6 +363,15 @@ export default {
|
||||
'Admin dashboard': 'Tableau d’administration',
|
||||
// --- muscle map ---
|
||||
'Muscle balance': 'Équilibre musculaire',
|
||||
'Fatigue': 'Fatigue',
|
||||
'Ready': 'Prêt',
|
||||
'Recovering': 'En récupération',
|
||||
'Fatigued': 'Fatigué',
|
||||
'Fatigue shows how recently each muscle was trained. High means rest.': 'La fatigue indique à quand remonte le dernier entraînement de chaque muscle. Un niveau élevé signifie qu’il est temps de se reposer.',
|
||||
'Strength shows retained muscle strength. Train again to reset it.': 'La force indique combien de force musculaire est conservée. Entraîne-toi à nouveau pour la réinitialiser.',
|
||||
'full': 'complet',
|
||||
'floor': 'plancher',
|
||||
'Weeks since training: {0}': 'Dernier entraînement : il y a {0} sem.',
|
||||
'by sets worked': 'par séries effectuées',
|
||||
'Week': 'Semaine',
|
||||
'not trained': 'non travaillé',
|
||||
@@ -554,4 +566,8 @@ export default {
|
||||
'{0} sets of {1} — time to add weight or move to a harder variation.': '{0} séries de {1} — il est temps d’ajouter du poids ou de passer à une variante plus dure.',
|
||||
'{0} per side': '{0} par côté',
|
||||
'You still log the total: {0} is {1} per side.': 'Tu notes toujours le total : {0}, c’est {1} par côté.',
|
||||
'{0} sets · {1} work': '{0} séries · {1} travail',
|
||||
'Make superset with previous': 'Faire un superset avec le précédent',
|
||||
'Make superset with next': 'Faire un superset avec le suivant',
|
||||
'Unpair': 'Dissocier'
|
||||
}
|
||||
@@ -154,13 +154,15 @@ export default {
|
||||
'Last time you hit all reps — try {0}': 'पिछली बार सारे रेप्स पूरे किए — {0} आज़माएँ',
|
||||
'Weights bumped to {0}': 'वज़न बढ़ाकर {0} किया',
|
||||
'Remove set': 'सेट हटाएँ',
|
||||
'Warm-up': 'वार्म-अप',
|
||||
'Add warm-up set': 'वार्म-अप सेट जोड़ें',
|
||||
'Add set': 'सेट जोड़ें',
|
||||
'Cardio logged': 'कार्डियो दर्ज हुआ',
|
||||
'Discard workout?': 'वर्कआउट छोड़ें?',
|
||||
'The sets you logged in this session will be lost.': 'इस सत्र में दर्ज किए सेट खो जाएँगे।',
|
||||
'Superset {0} / {1}': 'सुपरसेट {0} / {1}',
|
||||
'Exercise {0} / {1}': 'व्यायाम {0} / {1}',
|
||||
'Superset · do these back-to-back, rest after both': 'सुपरसेट · इन्हें लगातार करें, दोनों के बाद आराम',
|
||||
'Superset · do these back-to-back, rest when done': 'सुपरसेट · इन्हें लगातार करें, अंत में आराम',
|
||||
'Freestyle workout — add your first exercise.': 'फ्रीस्टाइल वर्कआउट — पहला व्यायाम जोड़ें।',
|
||||
'Finish workout early · {0} exercises': 'जल्दी समाप्त करें · {0} व्यायाम',
|
||||
'Rest over — next set!': 'आराम खत्म — अगला सेट!',
|
||||
@@ -223,6 +225,7 @@ export default {
|
||||
'Sign in with passkey': 'पासकी से साइन इन करें',
|
||||
'Create new profile': 'नई प्रोफ़ाइल बनाएँ',
|
||||
"This browser doesn't support passkeys — you can still use openGym locally on this device.": 'यह ब्राउज़र पासकी सपोर्ट नहीं करता — फिर भी आप इस डिवाइस पर openGym लोकली इस्तेमाल कर सकते हैं।',
|
||||
"This browser doesn't support passkeys, and this instance requires an account. Try a browser or device with passkey support.": 'यह ब्राउज़र पासकी सपोर्ट नहीं करता, और इस सर्वर के लिए खाता ज़रूरी है। पासकी सपोर्ट वाला ब्राउज़र या डिवाइस आज़माएँ।',
|
||||
'Continue without account': 'बिना खाते के जारी रखें',
|
||||
'Passkeys use {0} — no passwords.': 'पासकी {0} का उपयोग करती हैं — कोई पासवर्ड नहीं।',
|
||||
'Each profile keeps its own plan, workouts & body weight.': 'हर प्रोफ़ाइल की अपनी योजना, वर्कआउट और वज़न होते हैं।',
|
||||
@@ -360,6 +363,15 @@ export default {
|
||||
'Admin dashboard': 'एडमिन डैशबोर्ड',
|
||||
// --- muscle map ---
|
||||
'Muscle balance': 'मांसपेशी संतुलन',
|
||||
'Fatigue': 'थकान',
|
||||
'Ready': 'तैयार',
|
||||
'Recovering': 'पुनर्प्राप्ति में',
|
||||
'Fatigued': 'थकी हुई',
|
||||
'Fatigue shows how recently each muscle was trained. High means rest.': 'थकान बताती है कि हर मांसपेशी की ट्रेनिंग कितनी हाल की है। अधिक थकान होने पर आराम करें।',
|
||||
'Strength shows retained muscle strength. Train again to reset it.': 'शक्ति बताती है कि मांसपेशियों की कितनी ताकत बनी हुई है। इसे रीसेट करने के लिए फिर से ट्रेन करें।',
|
||||
'full': 'पूर्ण',
|
||||
'floor': 'न्यूनतम',
|
||||
'Weeks since training: {0}': 'पिछला व्यायाम: {0} सप्ताह पहले',
|
||||
'by sets worked': 'सेट के अनुसार',
|
||||
'Week': 'सप्ताह',
|
||||
'not trained': 'प्रशिक्षित नहीं',
|
||||
@@ -554,4 +566,8 @@ export default {
|
||||
'{0} sets of {1} — time to add weight or move to a harder variation.': '{1} रेप्स के {0} सेट — अब वज़न बढ़ाने या किसी कठिन वैरिएशन पर जाने का समय।',
|
||||
'{0} per side': 'प्रति तरफ़ {0}',
|
||||
'You still log the total: {0} is {1} per side.': 'आप कुल ही दर्ज करते हैं: {0} यानी प्रति तरफ़ {1}।',
|
||||
'{0} sets · {1} work': '{0} सेट · {1} काम',
|
||||
'Make superset with previous': 'पिछले के साथ सुपरसेट',
|
||||
'Make superset with next': 'अगले के साथ सुपरसेट',
|
||||
'Unpair': 'अलग करें'
|
||||
}
|
||||
@@ -154,13 +154,15 @@ export default {
|
||||
'Last time you hit all reps — try {0}': "L'ultima volta hai completato tutte le rip. — prova {0}",
|
||||
'Weights bumped to {0}': 'Pesi aumentati a {0}',
|
||||
'Remove set': 'Rimuovi serie',
|
||||
'Warm-up': 'Riscaldamento',
|
||||
'Add warm-up set': 'Aggiungi serie di riscaldamento',
|
||||
'Add set': 'Aggiungi serie',
|
||||
'Cardio logged': 'Cardio registrato',
|
||||
'Discard workout?': 'Scartare allenamento?',
|
||||
'The sets you logged in this session will be lost.': 'Le serie registrate in questa sessione andranno perse.',
|
||||
'Superset {0} / {1}': 'Superset {0} / {1}',
|
||||
'Exercise {0} / {1}': 'Esercizio {0} / {1}',
|
||||
'Superset · do these back-to-back, rest after both': 'Superset · falli uno dopo l’altro, riposo dopo entrambi',
|
||||
'Superset · do these back-to-back, rest when done': 'Superset · falli uno dopo l’altro, riposo alla fine',
|
||||
'Freestyle workout — add your first exercise.': 'Allenamento libero — aggiungi il primo esercizio.',
|
||||
'Finish workout early · {0} exercises': 'Termina in anticipo · {0} esercizi',
|
||||
'Rest over — next set!': 'Riposo finito — prossima serie!',
|
||||
@@ -223,6 +225,7 @@ export default {
|
||||
'Sign in with passkey': 'Accedi con passkey',
|
||||
'Create new profile': 'Crea nuovo profilo',
|
||||
"This browser doesn't support passkeys — you can still use openGym locally on this device.": 'Questo browser non supporta le passkey — puoi comunque usare openGym localmente su questo dispositivo.',
|
||||
"This browser doesn't support passkeys, and this instance requires an account. Try a browser or device with passkey support.": 'Questo browser non supporta le passkey e questo server richiede un account. Prova un browser o un dispositivo che supporti le passkey.',
|
||||
'Continue without account': 'Continua senza account',
|
||||
'Passkeys use {0} — no passwords.': 'Le passkey usano {0} — niente password.',
|
||||
'Each profile keeps its own plan, workouts & body weight.': 'Ogni profilo ha il proprio piano, allenamenti e peso corporeo.',
|
||||
@@ -360,6 +363,15 @@ export default {
|
||||
'Admin dashboard': 'Pannello di amministrazione',
|
||||
// --- muscle map ---
|
||||
'Muscle balance': 'Equilibrio muscolare',
|
||||
'Fatigue': 'Fatica',
|
||||
'Ready': 'Pronto',
|
||||
'Recovering': 'In recupero',
|
||||
'Fatigued': 'Affaticato',
|
||||
'Fatigue shows how recently each muscle was trained. High means rest.': 'La fatica mostra quanto è recente l’allenamento di ogni muscolo. Un valore alto significa che serve riposo.',
|
||||
'Strength shows retained muscle strength. Train again to reset it.': 'La forza mostra quanta forza muscolare hai mantenuto. Allenati di nuovo per reimpostarla.',
|
||||
'full': 'pieno',
|
||||
'floor': 'minimo',
|
||||
'Weeks since training: {0}': 'Ultimo allenamento: {0} sett. fa',
|
||||
'by sets worked': 'per serie svolte',
|
||||
'Week': 'Settimana',
|
||||
'not trained': 'non allenato',
|
||||
@@ -554,4 +566,8 @@ export default {
|
||||
'{0} sets of {1} — time to add weight or move to a harder variation.': '{0} serie da {1} — è ora di aggiungere peso o passare a una variante più difficile.',
|
||||
'{0} per side': '{0} per lato',
|
||||
'You still log the total: {0} is {1} per side.': 'Registri sempre il totale: {0} sono {1} per lato.',
|
||||
'{0} sets · {1} work': '{0} serie · {1} lavoro',
|
||||
'Make superset with previous': 'Superset con il precedente',
|
||||
'Make superset with next': 'Superset con il successivo',
|
||||
'Unpair': 'Separa'
|
||||
}
|
||||
@@ -154,13 +154,15 @@ export default {
|
||||
'Last time you hit all reps — try {0}': '지난번에 모든 횟수를 채웠어요 — {0}에 도전해 보세요',
|
||||
'Weights bumped to {0}': '무게를 {0}(으)로 올렸어요',
|
||||
'Remove set': '세트 빼기',
|
||||
'Warm-up': '워밍업',
|
||||
'Add warm-up set': '워밍업 세트 추가',
|
||||
'Add set': '세트 추가',
|
||||
'Cardio logged': '유산소 기록됨',
|
||||
'Discard workout?': '운동을 버릴까요?',
|
||||
'The sets you logged in this session will be lost.': '이 세션에서 기록한 세트가 사라집니다.',
|
||||
'Superset {0} / {1}': '슈퍼세트 {0} / {1}',
|
||||
'Exercise {0} / {1}': '운동 {0} / {1}',
|
||||
'Superset · do these back-to-back, rest after both': '슈퍼세트 · 연달아 수행하고, 둘 다 끝난 뒤 휴식',
|
||||
'Superset · do these back-to-back, rest when done': '슈퍼세트 · 연달아 수행하고, 전부 끝난 뒤 휴식',
|
||||
'Freestyle workout — add your first exercise.': '자유 운동 — 첫 운동을 추가하세요.',
|
||||
'Finish workout early · {0} exercises': '일찍 마치기 · 운동 {0}개',
|
||||
'Rest over — next set!': '휴식 끝 — 다음 세트!',
|
||||
@@ -223,6 +225,7 @@ export default {
|
||||
'Sign in with passkey': '패스키로 로그인',
|
||||
'Create new profile': '새 프로필 만들기',
|
||||
"This browser doesn't support passkeys — you can still use openGym locally on this device.": '이 브라우저는 패스키를 지원하지 않아요 — 그래도 이 기기에서 openGym을 로컬로 사용할 수 있습니다.',
|
||||
"This browser doesn't support passkeys, and this instance requires an account. Try a browser or device with passkey support.": '이 브라우저는 패스키를 지원하지 않고, 이 서버는 계정이 필요합니다. 패스키를 지원하는 브라우저나 기기를 사용해 보세요.',
|
||||
'Continue without account': '계정 없이 계속',
|
||||
'Passkeys use {0} — no passwords.': '패스키는 {0}을(를) 사용합니다 — 비밀번호 없음.',
|
||||
'Each profile keeps its own plan, workouts & body weight.': '프로필마다 자신의 계획, 운동, 체중을 보관합니다.',
|
||||
@@ -360,6 +363,15 @@ export default {
|
||||
'Admin dashboard': '관리자 대시보드',
|
||||
// --- muscle map ---
|
||||
'Muscle balance': '근육 균형',
|
||||
'Fatigue': '피로',
|
||||
'Ready': '준비됨',
|
||||
'Recovering': '회복 중',
|
||||
'Fatigued': '피로함',
|
||||
'Fatigue shows how recently each muscle was trained. High means rest.': '피로도는 각 근육을 얼마나 최근에 운동했는지 보여줍니다. 높을수록 휴식이 필요합니다.',
|
||||
'Strength shows retained muscle strength. Train again to reset it.': '근력은 근육에 남아 있는 힘을 보여줍니다. 다시 운동하면 값이 초기화됩니다.',
|
||||
'full': '완전',
|
||||
'floor': '최소',
|
||||
'Weeks since training: {0}': '마지막 운동: {0}주 전',
|
||||
'by sets worked': '세트 수 기준',
|
||||
'Week': '이번 주',
|
||||
'not trained': '훈련 안 함',
|
||||
@@ -554,4 +566,8 @@ export default {
|
||||
'{0} sets of {1} — time to add weight or move to a harder variation.': '{1}회 {0}세트 — 이제 무게를 올리거나 더 어려운 동작으로 넘어가세요.',
|
||||
'{0} per side': '한쪽당 {0}회',
|
||||
'You still log the total: {0} is {1} per side.': '기록은 그대로 합계로 합니다: {0}회는 한쪽당 {1}회입니다.',
|
||||
'{0} sets · {1} work': '{0} 세트 · {1} 작업',
|
||||
'Make superset with previous': '이전 운동과 슈퍼셋',
|
||||
'Make superset with next': '다음 운동과 슈퍼셋',
|
||||
'Unpair': '분리'
|
||||
}
|
||||
@@ -154,13 +154,15 @@ export default {
|
||||
'Last time you hit all reps — try {0}': 'Ostatnio zrobiłeś wszystkie powtórzenia — spróbuj {0}',
|
||||
'Weights bumped to {0}': 'Ciężary podniesione do {0}',
|
||||
'Remove set': 'Usuń serię',
|
||||
'Warm-up': 'Rozgrzewka',
|
||||
'Add warm-up set': 'Dodaj serię rozgrzewkową',
|
||||
'Add set': 'Dodaj serię',
|
||||
'Cardio logged': 'Cardio zapisane',
|
||||
'Discard workout?': 'Odrzucić trening?',
|
||||
'The sets you logged in this session will be lost.': 'Serie zapisane w tej sesji zostaną utracone.',
|
||||
'Superset {0} / {1}': 'Superseria {0} / {1}',
|
||||
'Exercise {0} / {1}': 'Ćwiczenie {0} / {1}',
|
||||
'Superset · do these back-to-back, rest after both': 'Superseria · rób jedno po drugim, odpocznij po obu',
|
||||
'Superset · do these back-to-back, rest when done': 'Superseria · rób jedno po drugim, odpocznij na końcu',
|
||||
'Freestyle workout — add your first exercise.': 'Trening dowolny — dodaj pierwsze ćwiczenie.',
|
||||
'Finish workout early · {0} exercises': 'Zakończ wcześniej · {0} ćwiczeń',
|
||||
'Rest over — next set!': 'Koniec przerwy — następna seria!',
|
||||
@@ -223,6 +225,7 @@ export default {
|
||||
'Sign in with passkey': 'Zaloguj się passkey',
|
||||
'Create new profile': 'Utwórz nowy profil',
|
||||
"This browser doesn't support passkeys — you can still use openGym locally on this device.": 'Ta przeglądarka nie obsługuje passkey — mimo to możesz używać openGym lokalnie na tym urządzeniu.',
|
||||
"This browser doesn't support passkeys, and this instance requires an account. Try a browser or device with passkey support.": 'Ta przeglądarka nie obsługuje passkey, a ten serwer wymaga konta. Spróbuj przeglądarki lub urządzenia z obsługą passkey.',
|
||||
'Continue without account': 'Kontynuuj bez konta',
|
||||
'Passkeys use {0} — no passwords.': 'Passkey używa: {0} — bez haseł.',
|
||||
'Each profile keeps its own plan, workouts & body weight.': 'Każdy profil ma własny plan, treningi i masę ciała.',
|
||||
@@ -360,6 +363,15 @@ export default {
|
||||
'Admin dashboard': 'Panel administratora',
|
||||
// --- muscle map ---
|
||||
'Muscle balance': 'Równowaga mięśniowa',
|
||||
'Fatigue': 'Zmęczenie',
|
||||
'Ready': 'Gotowe',
|
||||
'Recovering': 'W regeneracji',
|
||||
'Fatigued': 'Zmęczony',
|
||||
'Fatigue shows how recently each muscle was trained. High means rest.': 'Zmęczenie pokazuje, jak niedawno trenowano każdą partię mięśni. Wysoki poziom oznacza potrzebę odpoczynku.',
|
||||
'Strength shows retained muscle strength. Train again to reset it.': 'Siła pokazuje, ile siły mięśniowej pozostało. Ponowny trening przywraca jej poziom wyjściowy.',
|
||||
'full': 'pełna',
|
||||
'floor': 'minimum',
|
||||
'Weeks since training: {0}': 'Trening: {0} tyg. temu',
|
||||
'by sets worked': 'wg serii',
|
||||
'Week': 'Tydzień',
|
||||
'not trained': 'nietrenowane',
|
||||
@@ -554,4 +566,8 @@ export default {
|
||||
'{0} sets of {1} — time to add weight or move to a harder variation.': '{0} × {1} powt. — czas dodać ciężar albo przejść na trudniejszy wariant.',
|
||||
'{0} per side': '{0} na stronę',
|
||||
'You still log the total: {0} is {1} per side.': 'Nadal zapisujesz łączną liczbę: {0} to {1} na stronę.',
|
||||
'{0} sets · {1} work': '{0} serii · {1} praca',
|
||||
'Make superset with previous': 'Połącz z poprzednim',
|
||||
'Make superset with next': 'Połącz z następnym',
|
||||
'Unpair': 'Rozłącz'
|
||||
}
|
||||
@@ -154,13 +154,15 @@ export default {
|
||||
'Last time you hit all reps — try {0}': 'Da última vez completaste todas as reps — tenta {0}',
|
||||
'Weights bumped to {0}': 'Pesos aumentados para {0}',
|
||||
'Remove set': 'Remover série',
|
||||
'Warm-up': 'Aquecimento',
|
||||
'Add warm-up set': 'Adicionar série de aquecimento',
|
||||
'Add set': 'Adicionar série',
|
||||
'Cardio logged': 'Cardio registado',
|
||||
'Discard workout?': 'Descartar treino?',
|
||||
'The sets you logged in this session will be lost.': 'As séries registadas nesta sessão vão perder-se.',
|
||||
'Superset {0} / {1}': 'Supersérie {0} / {1}',
|
||||
'Exercise {0} / {1}': 'Exercício {0} / {1}',
|
||||
'Superset · do these back-to-back, rest after both': 'Supersérie · faz seguidos, descansa depois de ambos',
|
||||
'Superset · do these back-to-back, rest when done': 'Supersérie · faz seguidos, descansa no final',
|
||||
'Freestyle workout — add your first exercise.': 'Treino livre — adiciona o teu primeiro exercício.',
|
||||
'Finish workout early · {0} exercises': 'Terminar mais cedo · {0} exercícios',
|
||||
'Rest over — next set!': 'Descanso terminado — próxima série!',
|
||||
@@ -223,6 +225,7 @@ export default {
|
||||
'Sign in with passkey': 'Entrar com passkey',
|
||||
'Create new profile': 'Criar novo perfil',
|
||||
"This browser doesn't support passkeys — you can still use openGym locally on this device.": 'Este navegador não suporta passkeys — ainda assim podes usar o openGym localmente neste dispositivo.',
|
||||
"This browser doesn't support passkeys, and this instance requires an account. Try a browser or device with passkey support.": 'Este navegador não suporta passkeys e este servidor exige uma conta. Experimenta um navegador ou dispositivo com suporte a passkeys.',
|
||||
'Continue without account': 'Continuar sem conta',
|
||||
'Passkeys use {0} — no passwords.': 'As passkeys usam {0} — sem palavras-passe.',
|
||||
'Each profile keeps its own plan, workouts & body weight.': 'Cada perfil guarda o seu plano, treinos e peso corporal.',
|
||||
@@ -360,6 +363,15 @@ export default {
|
||||
'Admin dashboard': 'Painel de administração',
|
||||
// --- muscle map ---
|
||||
'Muscle balance': 'Equilíbrio muscular',
|
||||
'Fatigue': 'Fadiga',
|
||||
'Ready': 'Pronto',
|
||||
'Recovering': 'Em recuperação',
|
||||
'Fatigued': 'Fatigado',
|
||||
'Fatigue shows how recently each muscle was trained. High means rest.': 'A fadiga mostra há quanto tempo cada músculo foi treinado. Um nível elevado significa que é preciso descansar.',
|
||||
'Strength shows retained muscle strength. Train again to reset it.': 'A força mostra quanta força muscular se mantém. Treina novamente para repor o valor.',
|
||||
'full': 'completo',
|
||||
'floor': 'mínimo',
|
||||
'Weeks since training: {0}': 'Treino: há {0} sem.',
|
||||
'by sets worked': 'por séries trabalhadas',
|
||||
'Week': 'Semana',
|
||||
'not trained': 'sem treino',
|
||||
@@ -554,4 +566,8 @@ export default {
|
||||
'{0} sets of {1} — time to add weight or move to a harder variation.': '{0} séries de {1} — hora de acrescentar peso ou passar a uma variação mais difícil.',
|
||||
'{0} per side': '{0} por lado',
|
||||
'You still log the total: {0} is {1} per side.': 'Continuas a registar o total: {0} são {1} por lado.',
|
||||
'{0} sets · {1} work': '{0} séries · {1} trabalho',
|
||||
'Make superset with previous': 'Fazer superset com o anterior',
|
||||
'Make superset with next': 'Fazer superset com o próximo',
|
||||
'Unpair': 'Desfazer'
|
||||
}
|
||||
@@ -154,13 +154,15 @@ export default {
|
||||
'Last time you hit all reps — try {0}': 'В прошлый раз все повторения сделаны — попробуй {0}',
|
||||
'Weights bumped to {0}': 'Веса подняты до {0}',
|
||||
'Remove set': 'Убрать подход',
|
||||
'Warm-up': 'Разминка',
|
||||
'Add warm-up set': 'Добавить разминочный подход',
|
||||
'Add set': 'Добавить подход',
|
||||
'Cardio logged': 'Кардио записано',
|
||||
'Discard workout?': 'Отменить тренировку?',
|
||||
'The sets you logged in this session will be lost.': 'Подходы, записанные в этой сессии, будут потеряны.',
|
||||
'Superset {0} / {1}': 'Суперсет {0} / {1}',
|
||||
'Exercise {0} / {1}': 'Упражнение {0} / {1}',
|
||||
'Superset · do these back-to-back, rest after both': 'Суперсет · выполняй подряд, отдых после обоих',
|
||||
'Superset · do these back-to-back, rest when done': 'Суперсет · выполняй подряд, отдых в конце',
|
||||
'Freestyle workout — add your first exercise.': 'Свободная тренировка — добавь первое упражнение.',
|
||||
'Finish workout early · {0} exercises': 'Завершить раньше · упражнений: {0}',
|
||||
'Rest over — next set!': 'Отдых окончен — следующий подход!',
|
||||
@@ -223,6 +225,7 @@ export default {
|
||||
'Sign in with passkey': 'Войти по ключу доступа',
|
||||
'Create new profile': 'Создать новый профиль',
|
||||
"This browser doesn't support passkeys — you can still use openGym locally on this device.": 'Этот браузер не поддерживает ключи доступа — но openGym можно использовать локально на этом устройстве.',
|
||||
"This browser doesn't support passkeys, and this instance requires an account. Try a browser or device with passkey support.": 'Этот браузер не поддерживает ключи доступа, а на этом сервере нужен аккаунт. Попробуйте браузер или устройство с поддержкой ключей доступа.',
|
||||
'Continue without account': 'Продолжить без аккаунта',
|
||||
'Passkeys use {0} — no passwords.': 'Ключи доступа используют {0} — без паролей.',
|
||||
'Each profile keeps its own plan, workouts & body weight.': 'У каждого профиля свой план, тренировки и вес тела.',
|
||||
@@ -360,6 +363,15 @@ export default {
|
||||
'Admin dashboard': 'Панель администратора',
|
||||
// --- muscle map ---
|
||||
'Muscle balance': 'Баланс мышц',
|
||||
'Fatigue': 'Усталость',
|
||||
'Ready': 'Готова',
|
||||
'Recovering': 'Восстанавливается',
|
||||
'Fatigued': 'Утомлена',
|
||||
'Fatigue shows how recently each muscle was trained. High means rest.': 'Усталость показывает, насколько недавно тренировалась каждая мышца. Высокий уровень означает, что пора отдохнуть.',
|
||||
'Strength shows retained muscle strength. Train again to reset it.': 'Сила показывает, сколько мышечной силы сохранилось. Повторная тренировка сбрасывает это значение.',
|
||||
'full': 'полная',
|
||||
'floor': 'минимум',
|
||||
'Weeks since training: {0}': 'Тренировка: {0} нед. назад',
|
||||
'by sets worked': 'по подходам',
|
||||
'Week': 'Неделя',
|
||||
'not trained': 'не тренировалась',
|
||||
@@ -554,4 +566,8 @@ export default {
|
||||
'{0} sets of {1} — time to add weight or move to a harder variation.': '{0} × {1} — пора добавить вес или перейти к более сложному варианту.',
|
||||
'{0} per side': '{0} на сторону',
|
||||
'You still log the total: {0} is {1} per side.': 'Ты по-прежнему записываешь общее число: {0} — это {1} на сторону.',
|
||||
'{0} sets · {1} work': '{0} подходов · {1} рабочих',
|
||||
'Make superset with previous': 'Суперсет с предыдущим',
|
||||
'Make superset with next': 'Суперсет со следующим',
|
||||
'Unpair': 'Разъединить'
|
||||
}
|
||||
@@ -154,13 +154,15 @@ export default {
|
||||
'Last time you hit all reps — try {0}': 'Geçen sefer tüm tekrarları yaptın — {0} dene',
|
||||
'Weights bumped to {0}': 'Ağırlıklar {0} değerine çıkarıldı',
|
||||
'Remove set': 'Set kaldır',
|
||||
'Warm-up': 'Isınma',
|
||||
'Add warm-up set': 'Isınma seti ekle',
|
||||
'Add set': 'Set ekle',
|
||||
'Cardio logged': 'Kardiyo kaydedildi',
|
||||
'Discard workout?': 'Antrenman iptal edilsin mi?',
|
||||
'The sets you logged in this session will be lost.': 'Bu oturumda kaydettiğin setler kaybolacak.',
|
||||
'Superset {0} / {1}': 'Süperset {0} / {1}',
|
||||
'Exercise {0} / {1}': 'Egzersiz {0} / {1}',
|
||||
'Superset · do these back-to-back, rest after both': 'Süperset · art arda yap, ikisinden sonra dinlen',
|
||||
'Superset · do these back-to-back, rest when done': 'Süperset · art arda yap, sonunda dinlen',
|
||||
'Freestyle workout — add your first exercise.': 'Serbest antrenman — ilk egzersizini ekle.',
|
||||
'Finish workout early · {0} exercises': 'Erken bitir · {0} egzersiz',
|
||||
'Rest over — next set!': 'Dinlenme bitti — sıradaki set!',
|
||||
@@ -223,6 +225,7 @@ export default {
|
||||
'Sign in with passkey': 'Geçiş anahtarıyla giriş yap',
|
||||
'Create new profile': 'Yeni profil oluştur',
|
||||
"This browser doesn't support passkeys — you can still use openGym locally on this device.": 'Bu tarayıcı geçiş anahtarlarını desteklemiyor — yine de openGym’i bu cihazda yerel olarak kullanabilirsin.',
|
||||
"This browser doesn't support passkeys, and this instance requires an account. Try a browser or device with passkey support.": 'Bu tarayıcı geçiş anahtarlarını desteklemiyor ve bu sunucu bir hesap gerektiriyor. Geçiş anahtarı destekleyen bir tarayıcı veya cihaz dene.',
|
||||
'Continue without account': 'Hesapsız devam et',
|
||||
'Passkeys use {0} — no passwords.': 'Geçiş anahtarları {0} kullanır — şifre yok.',
|
||||
'Each profile keeps its own plan, workouts & body weight.': 'Her profilin kendi planı, antrenmanları ve vücut ağırlığı vardır.',
|
||||
@@ -360,6 +363,15 @@ export default {
|
||||
'Admin dashboard': 'Yönetici paneli',
|
||||
// --- muscle map ---
|
||||
'Muscle balance': 'Kas dengesi',
|
||||
'Fatigue': 'Yorgunluk',
|
||||
'Ready': 'Hazır',
|
||||
'Recovering': 'Toparlanıyor',
|
||||
'Fatigued': 'Yorgun',
|
||||
'Fatigue shows how recently each muscle was trained. High means rest.': 'Yorgunluk, her kasın ne kadar süre önce çalıştırıldığını gösterir. Yüksek değer dinlenmek gerektiği anlamına gelir.',
|
||||
'Strength shows retained muscle strength. Train again to reset it.': 'Kuvvet, kas gücünün ne kadarının korunduğunu gösterir. Yeniden çalışarak değeri sıfırlayabilirsin.',
|
||||
'full': 'tam',
|
||||
'floor': 'minimum',
|
||||
'Weeks since training: {0}': 'Son antrenman: {0} hafta önce',
|
||||
'by sets worked': 'çalışılan sete göre',
|
||||
'Week': 'Hafta',
|
||||
'not trained': 'çalışılmadı',
|
||||
@@ -554,4 +566,8 @@ export default {
|
||||
'{0} sets of {1} — time to add weight or move to a harder variation.': '{1} tekrarlık {0} set — ağırlık ekleme ya da daha zor bir varyasyona geçme zamanı.',
|
||||
'{0} per side': 'Taraf başına {0}',
|
||||
'You still log the total: {0} is {1} per side.': 'Toplamı kaydetmeye devam ediyorsun: {0}, taraf başına {1} demek.',
|
||||
'{0} sets · {1} work': '{0} set · {1} çalışma',
|
||||
'Make superset with previous': 'Öncekiyle superset yap',
|
||||
'Make superset with next': 'Sonrakiyle superset yap',
|
||||
'Unpair': 'Ayır'
|
||||
}
|
||||
@@ -154,13 +154,15 @@ export default {
|
||||
'Last time you hit all reps — try {0}': '上次完成了所有次数——试试 {0}',
|
||||
'Weights bumped to {0}': '重量已提升到 {0}',
|
||||
'Remove set': '减一组',
|
||||
'Warm-up': '热身',
|
||||
'Add warm-up set': '添加热身组',
|
||||
'Add set': '加一组',
|
||||
'Cardio logged': '有氧已记录',
|
||||
'Discard workout?': '放弃训练?',
|
||||
'The sets you logged in this session will be lost.': '本次记录的组数将丢失。',
|
||||
'Superset {0} / {1}': '超级组 {0} / {1}',
|
||||
'Exercise {0} / {1}': '动作 {0} / {1}',
|
||||
'Superset · do these back-to-back, rest after both': '超级组 · 连续完成,两个都做完再休息',
|
||||
'Superset · do these back-to-back, rest when done': '超级组 · 连续完成,全部做完再休息',
|
||||
'Freestyle workout — add your first exercise.': '自由训练——添加你的第一个动作。',
|
||||
'Finish workout early · {0} exercises': '提前结束 · {0} 个动作',
|
||||
'Rest over — next set!': '休息结束——下一组!',
|
||||
@@ -223,6 +225,7 @@ export default {
|
||||
'Sign in with passkey': '用通行密钥登录',
|
||||
'Create new profile': '创建新档案',
|
||||
"This browser doesn't support passkeys — you can still use openGym locally on this device.": '此浏览器不支持通行密钥——你仍可在本设备上本地使用 openGym。',
|
||||
"This browser doesn't support passkeys, and this instance requires an account. Try a browser or device with passkey support.": '此浏览器不支持通行密钥,且此服务器需要账户。请换用支持通行密钥的浏览器或设备。',
|
||||
'Continue without account': '不用账号继续',
|
||||
'Passkeys use {0} — no passwords.': '通行密钥使用{0}——没有密码。',
|
||||
'Each profile keeps its own plan, workouts & body weight.': '每个档案有自己的计划、训练和体重。',
|
||||
@@ -360,6 +363,15 @@ export default {
|
||||
'Admin dashboard': '管理后台',
|
||||
// --- muscle map ---
|
||||
'Muscle balance': '肌肉平衡',
|
||||
'Fatigue': '疲劳',
|
||||
'Ready': '准备好',
|
||||
'Recovering': '恢复中',
|
||||
'Fatigued': '已疲劳',
|
||||
'Fatigue shows how recently each muscle was trained. High means rest.': '疲劳度显示每个肌群最近一次训练距今多久。数值越高,越需要休息。',
|
||||
'Strength shows retained muscle strength. Train again to reset it.': '力量显示肌肉力量保留了多少。再次训练即可重置。',
|
||||
'full': '完全',
|
||||
'floor': '下限',
|
||||
'Weeks since training: {0}': '上次训练:{0}周前',
|
||||
'by sets worked': '按训练组数',
|
||||
'Week': '本周',
|
||||
'not trained': '未训练',
|
||||
@@ -554,4 +566,8 @@ export default {
|
||||
'{0} sets of {1} — time to add weight or move to a harder variation.': '{0} 组 × {1} 次——该加重量或换更难的变式了。',
|
||||
'{0} per side': '每侧 {0} 次',
|
||||
'You still log the total: {0} is {1} per side.': '你记录的仍然是总数:{0} 表示每侧 {1} 次。',
|
||||
'{0} sets · {1} work': '{0} 组 · {1} 工作',
|
||||
'Make superset with previous': '与上一个组成超级组',
|
||||
'Make superset with next': '与下一个组成超级组',
|
||||
'Unpair': '取消组合'
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { useStore } from './store/useStore.js'
|
||||
import { useUI } from './store/useUI.js'
|
||||
import { EXDB, EXIDX, BODYPARTS, isCardio, isBodyweightEq, allExercises, equipmentOf } from './lib/exercises.js'
|
||||
import { EXDB, EXIDX, BODYPARTS, isCardio, isBodyweightEq, allExercises, equipmentOf, smOf } from './lib/exercises.js'
|
||||
import { fmtDate, fmtNum, fmtVol, fmtDur, durPart, todayISO, uid, exCount, DAYN, MONTHS_LONG, ACCENTS } from './lib/format.js'
|
||||
import { lastEntryFor, bestWeightFor, buildSets, effectiveRoutineId, workoutVolume, setsDone, setsDoneActive, lastBW, supersetUnits, unitOf, setLabel, defaultConfig, cleanupSg, modeOf, effortOf, isBw, isPerSide, sideReps } from './lib/history.js'
|
||||
import { lastEntryFor, bestWeightFor, buildSets, effectiveRoutineId, workoutVolume, setsDone, setsDoneActive, lastBW, supersetUnits, unitOf, setLabel, defaultConfig, cleanupSg, modeOf, effortOf, isBw, isPerSide, sideReps, workSetsDone } from './lib/history.js'
|
||||
import { beep, vibrate } from './lib/sound.js'
|
||||
import { t, instrFor, getLang, INSTR_LANGS } from './lib/i18n.js'
|
||||
import { nav } from './lib/nav.js'
|
||||
@@ -291,7 +291,7 @@ function ExerciseDetail({ ex, close }) {
|
||||
<span className="tag acc">{t(ex.bp)}</span>
|
||||
{ex.tg && <span className="tag"><Icon name="target" />{t(ex.tg)}</span>}
|
||||
<span className="tag"><Icon name="dumbbell" />{t(ex.eq)}</span>
|
||||
{(ex.sm || []).slice(0, 3).map((s, i) => <span key={i} className="tag">{t(s)}</span>)}
|
||||
{smOf(ex).slice(0, 3).map((s, i) => <span key={i} className="tag">{t(s)}</span>)}
|
||||
</div>
|
||||
{ex.desc && <div className="exnote">{ex.desc}</div>}
|
||||
{best > 0 && <div className="small row" style={{ marginBottom: 6, gap: 5 }}><Icon name="trophy" style={{ fontSize: 14, color: 'var(--yellow)' }} />{t('Best:')} <b className="accent">{fmtNum(best)} {st.unit}</b>{last ? ` · ${t('last')} ${fmtDate(last.d)}: ${last.sets.map(s => setLabel(ex.id, s, last.target)).join(', ')}` : ''}</div>}
|
||||
@@ -482,10 +482,10 @@ function ProgressionFields({ ex, mode, c, setC, routine, unit }) {
|
||||
</>
|
||||
}
|
||||
|
||||
function ExConfig({ ex, existing, onSave, onDelete, close, routine }) {
|
||||
function ExConfig({ ex, existing, onSave, onDelete, close, routine, initial }) {
|
||||
const st = useStore(s => s.S)
|
||||
const cardio = isCardio(ex.id)
|
||||
const [c, setC] = useState(existing || defaultConfig(ex.id))
|
||||
const [c, setC] = useState(existing || initial || defaultConfig(ex.id))
|
||||
// Cardio keeps its own duration+speed form; the reps/time choice (issue #16) is offered for
|
||||
// everything else, which is where the gap was — planks, hangs, wall sits, loaded carries.
|
||||
const mode = cardio ? 'cardio' : modeOf({ ...c, id: ex.id })
|
||||
@@ -596,7 +596,7 @@ function ExConfig({ ex, existing, onSave, onDelete, close, routine }) {
|
||||
{onDelete && <><div style={{ height: 8 }} /><Button variant="danger" onClick={() => { close(); onDelete() }}>{t('Remove from routine')}</Button></>}
|
||||
</>
|
||||
}
|
||||
export const exConfigSheet = (ex, existing, onSave, onDelete, routine) => ui().openSheet(close => <ExConfig ex={ex} existing={existing} onSave={onSave} onDelete={onDelete} routine={routine} close={close} />)
|
||||
export const exConfigSheet = (ex, existing, onSave, onDelete, routine, initial) => ui().openSheet(close => <ExConfig ex={ex} existing={existing} initial={initial} onSave={onSave} onDelete={onDelete} routine={routine} close={close} />)
|
||||
|
||||
/* ============================ glyph picker ============================ */
|
||||
// Grouped by what the glyph means for a training day, so picking one is a scan
|
||||
@@ -910,7 +910,7 @@ function FinishSummary({ w, prs, e1prs = [], close }) {
|
||||
<div className="tiles" style={{ textAlign: 'left' }}>
|
||||
<div className="tile"><div className="l">{t('Duration')}</div><div className="v" style={{ fontSize: '1.1rem' }}>{fmtDur(w.end - w.start)}</div></div>
|
||||
<div className="tile"><div className="l">{t('Volume')}</div><div className="v" style={{ fontSize: '1.1rem' }}>{fmtVol(w.vol, st.unit)}</div></div>
|
||||
<div className="tile"><div className="l">{t('Sets')}</div><div className="v" style={{ fontSize: '1.1rem' }}>{setsDone(w)}</div></div>
|
||||
<div className="tile"><div className="l">{t('Sets')}</div><div className="v" style={{ fontSize: '1.1rem' }}>{t('{0} sets · {1} work', setsDone(w), workSetsDone(w))}</div></div>
|
||||
<div className="tile"><div className="l">{t('PRs')}</div><div className="v" style={{ fontSize: 20 }}>{prs.length || '—'}</div></div>
|
||||
</div>
|
||||
{(prs.length > 0 || e1prs.length > 0) && <div style={{ textAlign: 'left', marginBottom: 12 }}>
|
||||
|
||||
@@ -3,6 +3,7 @@ import { api } from '../lib/api.js'
|
||||
import { localTZ } from '../lib/format.js'
|
||||
import { registerCustom } from '../lib/exercises.js'
|
||||
import { DEMO, DEMO_SEEDED } from '../lib/demo.js'
|
||||
import { guestAllowed } from '../lib/guest.js'
|
||||
import { MOBILE, nativeLoad, nativeSave, syncReminder } from '../lib/mobile.js'
|
||||
|
||||
const KEY = 'gym_state_v1'
|
||||
@@ -95,6 +96,16 @@ export const useStore = create((set, get) => {
|
||||
isGuest: () => localStorage.getItem('gym_guest') === '1',
|
||||
setGuest(v) { if (v) localStorage.setItem('gym_guest', '1'); else localStorage.removeItem('gym_guest'); set({}) },
|
||||
|
||||
// Public config from /api/config (invite_only, allow_guest). null until the first successful
|
||||
// fetch — the login screen and boot both read it, so it is fetched once and cached here
|
||||
// rather than by each screen that happens to need it.
|
||||
config: null,
|
||||
async loadConfig() {
|
||||
if (get().config) return get().config
|
||||
try { const c = await api('/api/config'); set({ config: c }); return c }
|
||||
catch { return null }
|
||||
},
|
||||
|
||||
setUser(u) {
|
||||
if (u) { localStorage.setItem('gym_user', JSON.stringify(u)); localStorage.removeItem('gym_guest') }
|
||||
else localStorage.removeItem('gym_user')
|
||||
@@ -172,6 +183,12 @@ export const useStore = create((set, get) => {
|
||||
set({ ready: true })
|
||||
return
|
||||
}
|
||||
// Guests never authenticate, so an instance that turned guest mode off has no request to
|
||||
// refuse — the only way the switch reaches someone already inside is here, on their next
|
||||
// boot. Ending the session needs a positive `allow_guest: false`; see lib/guest.js for why
|
||||
// an unreachable server must not be allowed to lock anyone out (#42).
|
||||
const cfg = await get().loadConfig()
|
||||
if (!guestAllowed(cfg)) get().setGuest(false)
|
||||
try {
|
||||
const me = await api('/api/me')
|
||||
get().setUser(me.user)
|
||||
|
||||
@@ -10,6 +10,42 @@ import { useStore } from './useStore.js'
|
||||
const pushRestTimer = sec => { if (useStore.getState().user) api('/api/push/rest-timer', { method: 'POST', body: JSON.stringify({ seconds: sec }) }).catch(() => {}) }
|
||||
const cancelPushRestTimer = () => { if (useStore.getState().user) api('/api/push/rest-timer/cancel', { method: 'POST', body: '{}' }).catch(() => {}) }
|
||||
|
||||
const notificationsSupported = () => typeof window !== 'undefined' && 'Notification' in window
|
||||
let requestRestNotificationPermissionP = null
|
||||
|
||||
const requestRestNotificationPermission = async () => {
|
||||
if (!notificationsSupported()) return false
|
||||
if (Notification.permission === 'granted') return true
|
||||
if (Notification.permission === 'denied') return false
|
||||
if (!requestRestNotificationPermissionP) {
|
||||
requestRestNotificationPermissionP = Notification.requestPermission()
|
||||
.then(perm => perm === 'granted')
|
||||
.catch(() => false)
|
||||
.finally(() => {
|
||||
requestRestNotificationPermissionP = null
|
||||
})
|
||||
}
|
||||
return requestRestNotificationPermissionP
|
||||
}
|
||||
|
||||
const maybeRestNotification = async () => {
|
||||
if (!notificationsSupported()) return
|
||||
if (!document.hidden && document.visibilityState !== 'hidden') return
|
||||
if (Notification.permission !== 'granted' && !(await requestRestNotificationPermission())) return
|
||||
try {
|
||||
// Android Chrome forbids the Notification constructor (Illegal constructor) - the
|
||||
// service-worker registration path is the one that actually pops there.
|
||||
const reg = await navigator.serviceWorker?.getRegistration?.()
|
||||
if (reg?.showNotification) {
|
||||
reg.showNotification(t('Rest over — next set!'), { body: t('Rest over — next set!') })
|
||||
return
|
||||
}
|
||||
new Notification(t('Rest over — next set!'), { body: t('Rest over — next set!') })
|
||||
} catch {
|
||||
// Intentionally ignore: notification APIs vary by browser and policy in edge cases.
|
||||
}
|
||||
}
|
||||
|
||||
let toastTm = null
|
||||
let timerInt = null
|
||||
let timerTick = null
|
||||
@@ -42,6 +78,7 @@ export const useUI = create((set, get) => ({
|
||||
get().stopRest()
|
||||
const endsAt = Date.now() + sec * 1000
|
||||
set({ timer: { left: sec, total: sec, endsAt } })
|
||||
requestRestNotificationPermission()
|
||||
pushRestTimer(sec)
|
||||
timerTick = () => {
|
||||
const tm = get().timer
|
||||
@@ -51,7 +88,7 @@ export const useUI = create((set, get) => ({
|
||||
const snd = useStore.getState().S.sound
|
||||
if (left <= 0) {
|
||||
beep(snd, 880, 0.15); beep(snd, 880, 0.15, 0.25); beep(snd, 1320, 0.4, 0.5)
|
||||
vibrate([200, 100, 200]); get().toast(t('Rest over — next set!')); get().stopRest(); return
|
||||
vibrate([200, 100, 200]); maybeRestNotification(); get().toast(t('Rest over — next set!')); get().stopRest(); return
|
||||
}
|
||||
if (left <= 3) beep(snd, 660, 0.1)
|
||||
set({ timer: { ...tm, left } })
|
||||
|
||||
@@ -1,21 +1,25 @@
|
||||
import { useStore } from '../store/useStore.js'
|
||||
import { useUI } from '../store/useUI.js'
|
||||
import { webauthnOK, passkeyLogin, passkeyRegister, api, BIO } from '../lib/api.js'
|
||||
import { webauthnOK, passkeyLogin, passkeyRegister, BIO } from '../lib/api.js'
|
||||
import { hasData } from '../store/useStore.js'
|
||||
import { t } from '../lib/i18n.js'
|
||||
import { DEMO, REPO } from '../lib/demo.js'
|
||||
import { guestAllowed } from '../lib/guest.js'
|
||||
import { useState, useRef, useEffect } from 'react'
|
||||
import Icon from '../components/Icon.jsx'
|
||||
import { Button } from '../components/ui.jsx'
|
||||
|
||||
function RegisterSheet({ close }) {
|
||||
const { setUser, pushState, pullState } = useStore()
|
||||
const { setUser, pushState, pullState, loadConfig } = useStore()
|
||||
const config = useStore(s => s.config)
|
||||
const [name, setName] = useState('')
|
||||
const [code, setCode] = useState('')
|
||||
const [inviteOnly, setInviteOnly] = useState(false)
|
||||
const inviteOnly = !!config?.invite_only
|
||||
const ref = useRef(null)
|
||||
useEffect(() => { setTimeout(() => ref.current?.focus(), 250) }, [])
|
||||
useEffect(() => { api('/api/config').then(c => setInviteOnly(!!c.invite_only)).catch(() => {}) }, [])
|
||||
// Boot already fetched this; retry here only if that attempt failed, so the invite field still
|
||||
// appears on an instance whose config arrived late rather than never.
|
||||
useEffect(() => { loadConfig() }, [loadConfig])
|
||||
const go = async () => {
|
||||
const n = name.trim()
|
||||
if (!n) { useUI.getState().toast(t('Enter a name')); return }
|
||||
@@ -44,6 +48,8 @@ function RegisterSheet({ close }) {
|
||||
|
||||
export default function Login() {
|
||||
const { setUser, pullState, setGuest } = useStore()
|
||||
const config = useStore(s => s.config)
|
||||
const canGuest = guestAllowed(config)
|
||||
const signIn = async () => {
|
||||
try { const u = await passkeyLogin(); setUser(u); await pullState(); useUI.getState().toast(t('Welcome back, {0}', u.name)) }
|
||||
catch (e) { if (e.name !== 'NotAllowedError' && e.name !== 'AbortError') useUI.getState().toast(e.message || t('Sign-in failed')) }
|
||||
@@ -77,9 +83,13 @@ export default function Login() {
|
||||
<Button variant="primary" icon="person" onClick={signIn}>{t('Sign in with passkey')}</Button>
|
||||
<div style={{ height: 10 }} />
|
||||
<Button icon="sparkles" onClick={() => useUI.getState().openSheet(close => <RegisterSheet close={close} />)}>{t('Create new profile')}</Button>
|
||||
<div style={{ height: 10 }} />
|
||||
</> : <div className="card small muted" style={{ textAlign: 'left' }}>{t("This browser doesn't support passkeys — you can still use openGym locally on this device.")}</div>}
|
||||
<Button variant="ghost" className="dim" onClick={() => setGuest(true)}>{t('Continue without account')}</Button>
|
||||
{canGuest && <div style={{ height: 10 }} />}
|
||||
</> : <div className="card small muted" style={{ textAlign: 'left' }}>{canGuest
|
||||
? t("This browser doesn't support passkeys — you can still use openGym locally on this device.")
|
||||
// Without passkeys and without the guest entrance there is no way in from this browser,
|
||||
// so say that plainly instead of offering a local profile that cannot be created.
|
||||
: t("This browser doesn't support passkeys, and this instance requires an account. Try a browser or device with passkey support.")}</div>}
|
||||
{canGuest && <Button variant="ghost" className="dim" onClick={() => setGuest(true)}>{t('Continue without account')}</Button>}
|
||||
<div className="dim small" style={{ marginTop: 26, lineHeight: 1.5 }}>{t('Passkeys use {0} — no passwords.', BIO)}<br />{t('Each profile keeps its own plan, workouts & body weight.')}</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
+156
-30
@@ -1,4 +1,4 @@
|
||||
import { useState } from 'react'
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useStore } from '../store/useStore.js'
|
||||
import { EXIDX } from '../lib/exercises.js'
|
||||
@@ -10,7 +10,9 @@ import LineChart from '../components/LineChart.jsx'
|
||||
import Heatmap from '../components/Heatmap.jsx'
|
||||
import Icon from '../components/Icon.jsx'
|
||||
import BodyMap, { BodyMapLegend } from '../components/BodyMap.jsx'
|
||||
import { loadOfWorkouts, rankOf, MUSCLE_NAME } from '../lib/muscles.js'
|
||||
import { loadOfWorkouts, rankOf, MUSCLE_NAME, musclesOf } from '../lib/muscles.js'
|
||||
import { fatigueOf, strengthOf, STRENGTH_FLOOR } from '../lib/recovery.js'
|
||||
import { fatigueStateOf } from '../lib/recovery-view.js'
|
||||
import { e1rmSeries, best1RM } from '../lib/onerm.js'
|
||||
import {
|
||||
hasEffort, displayScale, scaleName, toScale, avgRir, effortSummary, effortWeeks,
|
||||
@@ -20,11 +22,95 @@ import { Button, Segmented, SelectRow } from '../components/ui.jsx'
|
||||
|
||||
// Which muscles the training in a window actually hit — and, the point of the card,
|
||||
// which ones it keeps missing. Shading is relative within the window (lib/muscles.js).
|
||||
function latestMuscleTraining(workouts) {
|
||||
const latest = {}
|
||||
for (const workout of workouts || []) {
|
||||
const timestamp = Number(workout?.start || new Date(workout?.d).getTime())
|
||||
if (!Number.isFinite(timestamp)) continue
|
||||
for (const entry of workout.entries || []) {
|
||||
if (!(entry.sets || []).some(set => set?.done === true)) continue
|
||||
for (const slug of Object.keys(musclesOf(EXIDX[entry.id]))) {
|
||||
if (latest[slug] == null || timestamp > latest[slug]) latest[slug] = timestamp
|
||||
}
|
||||
}
|
||||
}
|
||||
return latest
|
||||
}
|
||||
|
||||
const FATIGUE_LEVELS = [
|
||||
{ at: 0, level: 0 },
|
||||
{ at: 0.15, level: 1 },
|
||||
{ at: 0.25, level: 2 },
|
||||
{ at: 0.4, level: 3 },
|
||||
{ at: 0.55, level: 4, exclusive: true },
|
||||
]
|
||||
|
||||
const STRENGTH_LEVELS = [
|
||||
{ at: STRENGTH_FLOOR, level: 0 },
|
||||
{ at: 0.625, level: 1 },
|
||||
{ at: 0.75, level: 2 },
|
||||
{ at: 0.875, level: 3 },
|
||||
{ at: 1, level: 4 },
|
||||
]
|
||||
|
||||
function useNow() {
|
||||
const [, setTick] = useState(0)
|
||||
useEffect(() => {
|
||||
const iv = setInterval(() => setTick(tick => tick + 1), 60000)
|
||||
return () => clearInterval(iv)
|
||||
}, [])
|
||||
return Date.now()
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the whole weeks since a completed muscle-training timestamp.
|
||||
*
|
||||
* @param {number} now Current render-time timestamp in milliseconds.
|
||||
* @param {number} lastTrained Timestamp of the latest completed training event.
|
||||
* @returns {number} Non-negative whole weeks, including zero for ages under seven days.
|
||||
*/
|
||||
export function weeksSinceTraining(now, lastTrained) {
|
||||
return Math.max(0, Math.floor((now - lastTrained) / 86400000 / 7))
|
||||
}
|
||||
|
||||
function FatigueLegend() {
|
||||
return <div className="hm-legend hm-fatigue" aria-label={t('Fatigue')}>
|
||||
<span>{t('Fatigued')}</span><div className="hm-c l4" />
|
||||
<span>{t('Recovering')}</span><div className="hm-c l2" />
|
||||
<span>{t('Ready')}</span><div className="hm-c l0" />
|
||||
</div>
|
||||
}
|
||||
|
||||
function StrengthLegend() {
|
||||
return <div className="hm-legend hm-strength" aria-label={t('Strength')}>
|
||||
<span>1 <span className="dim">{t('full')}</span></span><div className="hm-c l4" /><div className="hm-c l3" /><div className="hm-c l2" />
|
||||
<div className="hm-c l1" /><div className="hm-c l0" /><span>{fmtNum(STRENGTH_FLOOR)} <span className="dim">{t('floor')}</span></span>
|
||||
</div>
|
||||
}
|
||||
|
||||
function fatigueLabel(value) {
|
||||
const state = fatigueStateOf(value)
|
||||
return t(state === 'ready' ? 'Ready' : state === 'recovering' ? 'Recovering' : 'Fatigued')
|
||||
}
|
||||
|
||||
function MuscleBalance({ S }) {
|
||||
const [view, setView] = useState('balance')
|
||||
const [win, setWin] = useState(7)
|
||||
const [hard, setHard] = useState(false)
|
||||
const [sel, setSel] = useState(null)
|
||||
const now = Date.now()
|
||||
const now = useNow()
|
||||
const workouts = S.workouts
|
||||
const fatigue = useMemo(() => fatigueOf(workouts, now), [workouts, now])
|
||||
const strength = useMemo(() => strengthOf(workouts, now), [workouts, now])
|
||||
const lastTrained = useMemo(() => latestMuscleTraining(workouts), [workouts])
|
||||
const { worked: strengthOrder } = rankOf(strength)
|
||||
const detrained = strengthOrder.filter(slug => strength[slug] < 1)
|
||||
const strengthHint = slug => {
|
||||
if (lastTrained[slug] == null) return t('not trained')
|
||||
const weeks = weeksSinceTraining(now, lastTrained[slug])
|
||||
return t('Weeks since training: {0}', weeks)
|
||||
}
|
||||
const toggleSel = m => setSel(s => (s === m ? null : m))
|
||||
const inWin = S.workouts.filter(w =>
|
||||
win === 0 ? true
|
||||
: win === 7 ? weekKey(w.d) === weekKey(todayISO())
|
||||
@@ -36,41 +122,66 @@ function MuscleBalance({ S }) {
|
||||
const rated = inWin.some(w => w.entries.some(e => e.sets.some(s => s.done && isHardSet(s))))
|
||||
const on = hard && rated
|
||||
const load = loadOfWorkouts(inWin, on ? isHardSet : null)
|
||||
const volWin = S.workouts.filter(w => (w.start || new Date(w.d).getTime()) > now - 90 * 86400000)
|
||||
const vol90 = loadOfWorkouts(volWin, null)
|
||||
const { worked, missed } = rankOf(load)
|
||||
const top = worked.slice(0, 4)
|
||||
const max = worked.length ? load[worked[0]] : 0
|
||||
const sets = m => Math.round((load[m] || 0) * 10) / 10
|
||||
|
||||
return <div className="card">
|
||||
<div className="row between" style={{ marginBottom: 8 }}>
|
||||
<h2 style={{ margin: 0 }}>{t('Muscle balance')} <span className="dim" style={{ textTransform: 'none', letterSpacing: 0 }}>· {on ? t('by hard sets') : t('by sets worked')}</span></h2>
|
||||
{rated && <Button size="sm" icon="flame" style={on ? { color: 'var(--yellow)' } : undefined}
|
||||
onClick={() => { setHard(h => !h); setSel(null) }}>{on ? t('Hard') : t('All')}</Button>}
|
||||
</div>
|
||||
<Segmented className="seg-range" value={win} onChange={v => { setWin(v); setSel(null) }}
|
||||
options={[{ value: 7, label: t('Week') }, { value: 30, label: '30d' }, { value: 90, label: '90d' }, { value: 0, label: t('All') }]} />
|
||||
{inWin.length ? <>
|
||||
<BodyMap className="tappable" load={load} body={S.body} selected={sel}
|
||||
onMuscle={m => setSel(s => (s === m ? null : m))} />
|
||||
<BodyMapLegend />
|
||||
<Segmented className="seg-range" value={view} onChange={setView}
|
||||
options={[{ value: 'balance', label: t('Muscle balance') }, { value: 'fatigue', label: t('Fatigue') }, { value: 'strength', label: t('Strength') }]} />
|
||||
{view === 'balance' ? <>
|
||||
<div className="row between" style={{ marginBottom: 8 }}>
|
||||
<h2 style={{ margin: 0 }}>{t('Muscle balance')} <span className="dim" style={{ textTransform: 'none', letterSpacing: 0 }}>· {on ? t('by hard sets') : t('by sets worked')}</span></h2>
|
||||
{rated && <Button size="sm" icon="flame" style={on ? { color: 'var(--yellow)' } : undefined}
|
||||
onClick={() => { setHard(h => !h); setSel(null) }}>{on ? t('Hard') : t('All')}</Button>}
|
||||
</div>
|
||||
<Segmented className="seg-range" value={win} onChange={v => { setWin(v); setSel(null) }}
|
||||
options={[{ value: 7, label: t('Week') }, { value: 30, label: '30d' }, { value: 90, label: '90d' }, { value: 0, label: t('All') }]} />
|
||||
{inWin.length ? <>
|
||||
<BodyMap className="tappable" load={load} body={S.body} selected={sel}
|
||||
onMuscle={m => setSel(s => (s === m ? null : m))} />
|
||||
<BodyMapLegend />
|
||||
{sel && <div className="mrow" style={{ borderTop: 'var(--hair) solid var(--sep)', marginTop: 4, paddingTop: 10 }}>
|
||||
<span className="nm"><b>{t(MUSCLE_NAME[sel])}</b></span>
|
||||
<span className="v">{sets(sel) ? t('{0} sets', sets(sel)) : on ? t('no hard sets') : t('not trained')}</span>
|
||||
</div>}
|
||||
{!sel && top.map(m => <div key={m} className="mrow">
|
||||
<span className="nm">{t(MUSCLE_NAME[m])}</span>
|
||||
<span className="bar"><i style={{ width: Math.round(load[m] / max * 100) + '%', background: on ? 'var(--yellow)' : undefined }} /></span>
|
||||
<span className="v">{t('{0} sets', sets(m))}</span>
|
||||
</div>)}
|
||||
{missed.length > 0 && <>
|
||||
<h4 className="sec" style={{ marginTop: 12 }}>{on ? t('No hard sets in this period') : t('Not trained in this period')}</h4>
|
||||
<div className="mchips">{missed.map(m => <span key={m} className="mchip miss">{t(MUSCLE_NAME[m])}</span>)}</div>
|
||||
</>}
|
||||
{!missed.length && worked.length > 0 &&
|
||||
<div className="muted small" style={{ marginTop: 10 }}>{on
|
||||
? t('Every muscle group got at least one hard set in this period.')
|
||||
: t('Every muscle group got some work in this period.')}</div>}
|
||||
</> : <div className="muted small">{t('No workouts in this period yet.')}</div>}
|
||||
</> : view === 'fatigue' ? <>
|
||||
<h2>{t('Fatigue')}</h2>
|
||||
<BodyMap className="tappable hm-fatigue" load={fatigue} thresholds={FATIGUE_LEVELS} body={S.body} selected={sel} onMuscle={toggleSel} />
|
||||
<FatigueLegend />
|
||||
<div className="muted small" style={{ marginTop: 10 }}>{t('Fatigue shows how recently each muscle was trained. High means rest.')}</div>
|
||||
{sel && <div className="mrow" style={{ borderTop: 'var(--hair) solid var(--sep)', marginTop: 4, paddingTop: 10 }}>
|
||||
<span className="nm"><b>{t(MUSCLE_NAME[sel])}</b></span>
|
||||
<span className="v">{sets(sel) ? t('{0} sets', sets(sel)) : on ? t('no hard sets') : t('not trained')}</span>
|
||||
<span className="v">{fatigueLabel(fatigue[sel])}</span>
|
||||
</div>}
|
||||
{!sel && top.map(m => <div key={m} className="mrow">
|
||||
<span className="nm">{t(MUSCLE_NAME[m])}</span>
|
||||
<span className="bar"><i style={{ width: Math.round(load[m] / max * 100) + '%', background: on ? 'var(--yellow)' : undefined }} /></span>
|
||||
<span className="v">{t('{0} sets', sets(m))}</span>
|
||||
</> : <>
|
||||
<h2>{t('Strength')}</h2>
|
||||
<BodyMap className="tappable hm-strength" load={strength} thresholds={STRENGTH_LEVELS} body={S.body} selected={sel} onMuscle={toggleSel} />
|
||||
<StrengthLegend />
|
||||
<div className="muted small" style={{ marginTop: 10 }}>{t('Strength shows retained muscle strength. Train again to reset it.')}</div>
|
||||
{detrained.map(slug => <div key={slug} className="mrow">
|
||||
<span className="nm">{t(MUSCLE_NAME[slug])}</span>
|
||||
<span className="bar"><i style={{ width: Math.round(strength[slug] * 100) + '%' }} /></span>
|
||||
<span className="v">{t('{0} sets', vol90[slug] || 0)}</span>
|
||||
</div>)}
|
||||
{missed.length > 0 && <>
|
||||
<h4 className="sec" style={{ marginTop: 12 }}>{on ? t('No hard sets in this period') : t('Not trained in this period')}</h4>
|
||||
<div className="mchips">{missed.map(m => <span key={m} className="mchip miss">{t(MUSCLE_NAME[m])}</span>)}</div>
|
||||
</>}
|
||||
{!missed.length && worked.length > 0 &&
|
||||
<div className="muted small" style={{ marginTop: 10 }}>{on
|
||||
? t('Every muscle group got at least one hard set in this period.')
|
||||
: t('Every muscle group got some work in this period.')}</div>}
|
||||
</> : <div className="muted small">{t('No workouts in this period yet.')}</div>}
|
||||
</>}
|
||||
</div>
|
||||
}
|
||||
|
||||
@@ -147,7 +258,21 @@ export default function Stats() {
|
||||
const bwDelta30 = bw30.length > 1 ? bw30[bw30.length - 1].w - bw30[0].w : null
|
||||
const monthW = S.workouts.filter(w => w.d.slice(0, 7) === todayISO().slice(0, 7)).length
|
||||
|
||||
const exHist = [...new Set(S.workouts.flatMap(w => w.entries.map(e => e.id)))].filter(id => EXIDX[id]).sort((a, b) => EXIDX[a].n < EXIDX[b].n ? -1 : 1)
|
||||
const currentOf = id => {
|
||||
for (let i = S.workouts.length - 1; i >= 0; i--) {
|
||||
const en = S.workouts[i].entries.find(e => e.id === id)
|
||||
if (!en) continue
|
||||
const mode = modeOf({ ...(en.target || {}), id })
|
||||
const metric = s2 => mode === 'cardio' ? (s2.speed || 0) : mode === 'time' ? (s2.sec || 0) : (s2.w || 0)
|
||||
const mx = Math.max(0, ...en.sets.filter(s2 => s2.done).map(metric), mode === 'time' || mode === 'cardio' ? 0 : (en.topW || 0))
|
||||
if (mx > 0) return { mx, unit: mode === 'cardio' ? 'km/h' : mode === 'time' ? 's' : S.unit }
|
||||
}
|
||||
return { mx: 0, unit: S.unit }
|
||||
}
|
||||
const exHist = [...new Set(S.workouts.flatMap(w => w.entries.map(e => e.id)))].filter(id => EXIDX[id])
|
||||
const exCurrent = Object.fromEntries(exHist.map(id => [id, currentOf(id)]))
|
||||
exHist.sort((a, b) => exCurrent[b].mx - exCurrent[a].mx || (EXIDX[a].n < EXIDX[b].n ? -1 : 1))
|
||||
|
||||
const curEx = exId && exHist.includes(exId) ? exId : exHist[0] || null
|
||||
// How this exercise was logged most recently decides what the curve means: top weight,
|
||||
// longest hold or top speed. Sets logged in another mode lack the field and score 0, so a
|
||||
@@ -232,7 +357,8 @@ export default function Stats() {
|
||||
{exHist.length ? <>
|
||||
<div className="sect-b" style={{ marginBottom: 10 }}>
|
||||
<SelectRow title={t('Exercise')} sheetTitle={t('Exercise progress')} value={curEx} onChange={setExId}
|
||||
options={exHist.map(id => ({ value: id, label: EXIDX[id].n }))} />
|
||||
options={exHist.map(id => ({ value: id, label: EXIDX[id].n + (exCurrent[id].mx ? ' ' + '—' + ' ' + fmtNum(exCurrent[id].mx) + ' ' + exCurrent[id].unit : '') }))} />
|
||||
|
||||
</div>
|
||||
{exOpts.length > 1 && <Segmented className="seg-range" value={onEff ? 'effort' : onE1 ? 'e1rm' : 'top'} onChange={setExMetric} options={exOpts} />}
|
||||
<div className="chart">
|
||||
|
||||
@@ -0,0 +1,302 @@
|
||||
import React, { act } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import { parseHTML } from 'linkedom'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { MUSCLES, MUSCLE_NAME, levelsOf, rankOf } from '../lib/muscles.js'
|
||||
import { FATIGUE_STATES, STRENGTH_FLOOR } from '../lib/recovery.js'
|
||||
import { fatigueStateOf } from '../lib/recovery-view.js'
|
||||
import Stats, { weeksSinceTraining } from './Stats.jsx'
|
||||
|
||||
const DAY = 86400000
|
||||
const HOUR = 3600000
|
||||
const BASE_NOW = Date.UTC(2026, 0, 22, 12)
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
maps: [],
|
||||
mapMounts: 0,
|
||||
S: {
|
||||
unit: 'kg', body: 'male', effort: 'rir', targetW: null,
|
||||
bodyweight: [], routines: [], workouts: [],
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('../store/useStore.js', () => ({
|
||||
useStore: selector => selector({ S: mocks.S }),
|
||||
}))
|
||||
vi.mock('react-router-dom', () => ({ useNavigate: () => () => {} }))
|
||||
vi.mock('../sheets.jsx', () => ({
|
||||
bwSheet: () => {}, goalSheet: () => {}, calendarSheet: () => {}, workoutDetailSheet: () => {},
|
||||
WorkoutRow: () => React.createElement('div'), bwDeltaColor: () => 'inherit',
|
||||
}))
|
||||
vi.mock('../components/LineChart.jsx', () => ({ default: () => React.createElement('div') }))
|
||||
vi.mock('../components/Heatmap.jsx', () => ({ default: () => React.createElement('div') }))
|
||||
vi.mock('../components/Icon.jsx', () => ({ default: props => React.createElement('span', props) }))
|
||||
vi.mock('../components/BodyMap.jsx', () => ({
|
||||
default: props => {
|
||||
mocks.maps.push(props)
|
||||
React.useEffect(() => {
|
||||
mocks.mapMounts++
|
||||
return () => {}
|
||||
}, [])
|
||||
return React.createElement(
|
||||
'div',
|
||||
{ 'data-body-map': true, 'data-selected-muscle': props.selected || '' },
|
||||
React.createElement('button', {
|
||||
'data-muscle': 'chest',
|
||||
onClick: () => props.onMuscle?.('chest'),
|
||||
}, 'Chest'),
|
||||
)
|
||||
},
|
||||
BodyMapLegend: () => React.createElement('div', { 'data-balance-legend': true }),
|
||||
}))
|
||||
|
||||
let dom
|
||||
let root
|
||||
let container
|
||||
|
||||
function iso(timestamp) {
|
||||
return new Date(timestamp).toISOString().slice(0, 10)
|
||||
}
|
||||
|
||||
function set(done, extra = {}) {
|
||||
return { done, w: 10, r: 8, unit: 'kg', ...extra }
|
||||
}
|
||||
|
||||
function workout(id, start, entries) {
|
||||
return { id, d: iso(start), start, unit: 'kg', entries }
|
||||
}
|
||||
|
||||
function entry(id, sets) {
|
||||
return { id, sets }
|
||||
}
|
||||
|
||||
function lifecycleWorkouts(now = BASE_NOW) {
|
||||
// A 6-set chest day on the saturating curve crosses .5 at ~55.05 hours, so the edge
|
||||
// flips fatigued -> recovering after one 60-second interval tick.
|
||||
const fatigueEdge = now - (36 * Math.log2(6 / (3 * Math.LN2)) * HOUR - 30000)
|
||||
// This completed set is in the initial 30-day Balance window, then ages out after one tick.
|
||||
const balanceEdge = now - (30 * DAY - 30000)
|
||||
// The 14-day strength edge becomes sub-full after one tick.
|
||||
const strengthEdge = now - (14 * DAY - 30000)
|
||||
// This completed event must remain the latest training event for abs: the newer set is undone.
|
||||
const absCompleted = now - 20 * DAY
|
||||
const absUndone = now - DAY
|
||||
return [
|
||||
workout('fatigue-edge', fatigueEdge, [entry('1254', Array.from({ length: 6 }, () => set(true, { rir: 0 })))]),
|
||||
workout('balance-edge', balanceEdge, [entry('1254', [set(true, { rir: 2 })])]),
|
||||
workout('strength-edge', strengthEdge, [entry('1001', [set(true, { rir: 2 })])]),
|
||||
workout('abs-completed', absCompleted, [entry('1002', [set(true, { rir: 2 })])]),
|
||||
workout('abs-undone', absUndone, [entry('1002', [set(false, { rir: 0 })])]),
|
||||
]
|
||||
}
|
||||
|
||||
function allFatiguedWorkout(now = BASE_NOW) {
|
||||
// Eight completed sets per exercise: on the saturating curve every involved muscle gets
|
||||
// raw >= 3.2 (0.4 x 8), i.e. a fatigue value above the .55 top band regardless of the
|
||||
// catalogue's secondary-muscle metadata.
|
||||
const ids = [
|
||||
['1018', 1], // trapezius
|
||||
['1012', 1], // deltoids
|
||||
['1167', 1], // chest
|
||||
['1013', 1], // upper-back
|
||||
['3011', 1], // serratus
|
||||
['1413', 1], // biceps
|
||||
['1399', 1], // triceps
|
||||
['1016', 1], // forearm
|
||||
['1005', 2], // abs + obliques
|
||||
['1010', 1], // lower-back
|
||||
['1003', 1], // gluteal
|
||||
['1001', 1], // quadriceps
|
||||
['1511', 1], // hamstring
|
||||
['1494', 1], // adductors
|
||||
['1002', 2], // abs + hip-flexors
|
||||
['1000', 1], // calves
|
||||
['1396', 2], // calves + tibialis
|
||||
]
|
||||
return workout('all-fatigued', now, ids.map(([id]) => entry(id, Array.from({ length: 8 }, () => set(true)))))
|
||||
}
|
||||
|
||||
function allSubfullWorkout(now = BASE_NOW) {
|
||||
return workout('all-subfull', now - 15 * DAY, [entry('1254', [set(true)])])
|
||||
}
|
||||
|
||||
function resetFixture(workouts = lifecycleWorkouts()) {
|
||||
mocks.S.workouts = workouts
|
||||
mocks.maps.length = 0
|
||||
mocks.mapMounts = 0
|
||||
}
|
||||
|
||||
function installDom() {
|
||||
const parsed = parseHTML('<!doctype html><html><body><div id="root"></div></body></html>')
|
||||
dom = parsed.window
|
||||
globalThis.window = dom
|
||||
globalThis.document = dom.document
|
||||
Object.defineProperty(globalThis, 'navigator', { configurable: true, value: dom.navigator })
|
||||
for (const key of ['HTMLElement', 'Node', 'Element', 'Event']) globalThis[key] = dom[key]
|
||||
globalThis.IS_REACT_ACT_ENVIRONMENT = true
|
||||
container = document.getElementById('root')
|
||||
root = createRoot(container)
|
||||
}
|
||||
|
||||
async function mountStats() {
|
||||
installDom()
|
||||
await act(async () => { root.render(React.createElement(Stats)) })
|
||||
}
|
||||
|
||||
async function unmountStats() {
|
||||
if (!root) return
|
||||
await act(async () => { root.unmount() })
|
||||
root = null
|
||||
container = null
|
||||
dom = null
|
||||
}
|
||||
|
||||
function muscleCard() {
|
||||
return [...container.querySelectorAll('.card')].find(card =>
|
||||
[...card.querySelectorAll('.seg button')].some(button =>
|
||||
['Muscle balance', 'Fatigue', 'Strength'].includes(button.textContent.trim())))
|
||||
}
|
||||
|
||||
function buttonWithText(scope, text) {
|
||||
return [...scope.querySelectorAll('button')].find(button => button.textContent.trim() === text)
|
||||
}
|
||||
|
||||
function viewButton(text) {
|
||||
return buttonWithText(muscleCard(), text)
|
||||
}
|
||||
|
||||
function balanceRangeButton(text) {
|
||||
const segments = muscleCard().querySelectorAll('.seg')
|
||||
return buttonWithText(segments[1], text)
|
||||
}
|
||||
|
||||
async function click(button) {
|
||||
expect(button, `expected a button named ${button?.textContent || 'unknown'}`).toBeTruthy()
|
||||
await act(async () => { button.dispatchEvent(new dom.Event('click', { bubbles: true })) })
|
||||
}
|
||||
|
||||
async function tick(milliseconds) {
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(milliseconds) })
|
||||
}
|
||||
|
||||
function lastMap() {
|
||||
return mocks.maps.at(-1)
|
||||
}
|
||||
|
||||
function expectPressed(button) {
|
||||
expect(button?.getAttribute('aria-pressed')).toBe('true')
|
||||
}
|
||||
|
||||
function strengthRows() {
|
||||
return [...muscleCard().querySelectorAll('.mrow .nm')].map(node => node.textContent.trim())
|
||||
}
|
||||
|
||||
afterEach(async () => {
|
||||
await unmountStats()
|
||||
vi.useRealTimers()
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
vi.setSystemTime(BASE_NOW)
|
||||
resetFixture()
|
||||
})
|
||||
|
||||
describe('Stats muscle recovery view runtime', () => {
|
||||
it('starts in Balance and preserves range, hard filter, and selected muscle through every real view transition', async () => {
|
||||
await mountStats()
|
||||
const card = muscleCard()
|
||||
|
||||
expectPressed(buttonWithText(card, 'Muscle balance'))
|
||||
expectPressed(buttonWithText(card, 'Week'))
|
||||
|
||||
await click(balanceRangeButton('30d'))
|
||||
await click(buttonWithText(card, 'All'))
|
||||
await click(card.querySelector('[data-muscle="chest"]'))
|
||||
expectPressed(balanceRangeButton('30d'))
|
||||
expect(buttonWithText(muscleCard(), 'Hard')).toBeTruthy()
|
||||
expect(container.querySelector('[data-selected-muscle="chest"]')).toBeTruthy()
|
||||
|
||||
await click(viewButton('Fatigue'))
|
||||
expect(container.textContent).toContain('Fatigue shows how recently each muscle was trained. High means rest.')
|
||||
await click(viewButton('Strength'))
|
||||
expect(container.textContent).toContain('Strength shows retained muscle strength. Train again to reset it.')
|
||||
await click(viewButton('Muscle balance'))
|
||||
|
||||
expectPressed(balanceRangeButton('30d'))
|
||||
expect(buttonWithText(muscleCard(), 'Hard')).toBeTruthy()
|
||||
expect(container.querySelector('[data-selected-muscle="chest"]')).toBeTruthy()
|
||||
expect(lastMap().selected).toBe('chest')
|
||||
expect(lastMap().load.chest).toBe(7)
|
||||
})
|
||||
|
||||
it('refreshes fatigue presentation, Balance 30-day filtering, and the mounted tree on the 60-second tick', async () => {
|
||||
await mountStats()
|
||||
await click(balanceRangeButton('30d'))
|
||||
await click(viewButton('Fatigue'))
|
||||
await click(muscleCard().querySelector('[data-muscle="chest"]'))
|
||||
|
||||
const beforeTickMounts = mocks.mapMounts
|
||||
const beforeTick = lastMap().load.chest
|
||||
expect(fatigueStateOf(beforeTick)).toBe(FATIGUE_STATES.FATIGUED)
|
||||
expect(container.textContent).toContain('Fatigued')
|
||||
|
||||
await tick(60000)
|
||||
|
||||
const afterTick = lastMap().load.chest
|
||||
expect(mocks.mapMounts).toBe(beforeTickMounts)
|
||||
expect(afterTick).toBeLessThan(0.5)
|
||||
expect(fatigueStateOf(afterTick)).toBe(FATIGUE_STATES.RECOVERING)
|
||||
expect(container.textContent).toContain('Recovering')
|
||||
|
||||
await click(viewButton('Strength'))
|
||||
expect(lastMap().load.quadriceps).toBeLessThan(1)
|
||||
expect(strengthRows()).toContain('Quads')
|
||||
|
||||
await click(viewButton('Muscle balance'))
|
||||
expect(lastMap().load.chest).toBe(6)
|
||||
expectPressed(balanceRangeButton('30d'))
|
||||
})
|
||||
|
||||
it('ignores an undone latest set, floors rendered training age, and follows production rankOf ordering', async () => {
|
||||
await mountStats()
|
||||
await click(viewButton('Strength'))
|
||||
|
||||
const load = lastMap().load
|
||||
const expectedRows = rankOf(load).worked
|
||||
.filter(slug => load[slug] < 1)
|
||||
.map(slug => MUSCLE_NAME[slug])
|
||||
expect(strengthRows()).toEqual(expectedRows)
|
||||
|
||||
// The newer abs row is undone, so the rendered hint uses the completed event from 20 days ago.
|
||||
expect(container.textContent).toContain('1 sets')
|
||||
|
||||
// The production helper used by Stats' rendered strength hint floors six elapsed days to zero.
|
||||
expect(weeksSinceTraining(BASE_NOW, BASE_NOW - 6 * DAY)).toBe(0)
|
||||
})
|
||||
|
||||
it('uses production boundaries and fixed absolute bands for all-fatigued and all-subfull maps', async () => {
|
||||
expect(fatigueStateOf(0.2499)).toBe(FATIGUE_STATES.READY)
|
||||
expect(fatigueStateOf(0.25)).toBe(FATIGUE_STATES.RECOVERING)
|
||||
expect(fatigueStateOf(0.5)).toBe(FATIGUE_STATES.RECOVERING)
|
||||
expect(fatigueStateOf(0.5001)).toBe(FATIGUE_STATES.FATIGUED)
|
||||
|
||||
resetFixture([allFatiguedWorkout()])
|
||||
await mountStats()
|
||||
await click(viewButton('Fatigue'))
|
||||
const fatigueMap = lastMap()
|
||||
expect(Object.keys(fatigueMap.load)).toEqual(MUSCLES)
|
||||
expect(Object.values(fatigueMap.load).every(value => value > 0.5)).toBe(true)
|
||||
expect(Object.values(levelsOf(fatigueMap.load, fatigueMap.thresholds)).every(level => level === 4)).toBe(true)
|
||||
|
||||
await unmountStats()
|
||||
resetFixture([allSubfullWorkout()])
|
||||
await mountStats()
|
||||
await click(viewButton('Strength'))
|
||||
const strengthMap = lastMap()
|
||||
expect(Object.values(strengthMap.load).every(value => value < 1)).toBe(true)
|
||||
expect(Math.min(...Object.values(strengthMap.load))).toBe(STRENGTH_FLOOR)
|
||||
expect(strengthMap.thresholds.at(-1)).toEqual({ at: 1, level: 4 })
|
||||
})
|
||||
})
|
||||
@@ -3,7 +3,7 @@ import { useNavigate } from 'react-router-dom'
|
||||
import { useStore } from '../store/useStore.js'
|
||||
import { useUI } from '../store/useUI.js'
|
||||
import { exOr } from '../lib/exercises.js'
|
||||
import { effectiveRoutine, lastEntryFor, bestWeightFor, buildSets, setsDoneActive, supersetUnits, unitOf, setLabel, modeOf, isBw, isPerSide, sideReps, repStep, EFFORT, effortOf, stepEffort, capEffort } from '../lib/history.js'
|
||||
import { effectiveRoutine, lastEntryFor, bestWeightFor, buildSets, freestyleConfig, defaultConfig, setsDoneActive, supersetUnits, unitOf, setLabel, modeOf, isBw, isPerSide, sideReps, repStep, EFFORT, effortOf, stepEffort, capEffort, cascadeWeight, insertWarmupRow, removeRowAt, pairAdjacent, unpairSuperset } from '../lib/history.js'
|
||||
import { fmtNum, fmtDate, todayISO, exCount, DAYN } from '../lib/format.js'
|
||||
import { beep, vibrate } from '../lib/sound.js'
|
||||
import { t } from '../lib/i18n.js'
|
||||
@@ -54,7 +54,7 @@ function Elapsed({ start }) {
|
||||
}
|
||||
|
||||
/* ---------- one exercise block (reps: weight×reps · time: a held duration · cardio: duration+speed) ---------- */
|
||||
function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemoveSet, onStartTimed }) {
|
||||
function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemoveSet, onAddWarmup, onRemoveSetAt, onStartTimed, onPairPrev, onPairNext }) {
|
||||
const S = useStore(s => s.S)
|
||||
const working = useUI(s => s.work)
|
||||
const entry = S.active.entries[entryIdx]
|
||||
@@ -114,6 +114,10 @@ function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemov
|
||||
<div style={{ fontSize: compact ? 17 : 20, fontWeight: 600, letterSpacing: '-.02em', textTransform: 'capitalize', lineHeight: 1.2 }}>{ex.n}</div>
|
||||
<button className="iconbtn" aria-label={t('Details')} onClick={() => exerciseDetailSheet(ex)}><Icon name="info" /></button>
|
||||
</div>
|
||||
{!compact && (onPairPrev || onPairNext) && <div className="row" style={{ gap: 6, flexWrap: 'wrap', marginBottom: 8 }}>
|
||||
{onPairPrev && <Button size="xs" variant="tinted" icon="link" title={t('Make superset with previous')} onClick={onPairPrev}>{t('Make superset with previous')}</Button>}
|
||||
{onPairNext && <Button size="xs" variant="tinted" icon="link" title={t('Make superset with next')} onClick={onPairNext}>{t('Make superset with next')}</Button>}
|
||||
</div>}
|
||||
<div className="row" style={{ gap: 6, flexWrap: 'wrap', marginBottom: 8 }}>
|
||||
{cardio && <span className="tag acc"><Icon name="figureRun" />{t('Cardio')}</span>}
|
||||
{/* You log the total; this is the split, so the set in front of you is unambiguous
|
||||
@@ -131,19 +135,32 @@ function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemov
|
||||
<div className="card" style={{ marginTop: 10, marginBottom: 0 }}>
|
||||
{/* the header carries the same eff3 sizing as the rows, or the labels drift off their columns */}
|
||||
<div className={'sethead' + (col3 ? ' eff3' : '')}><span className="n-sp" /><span className="w-sp">{col1.hd}</span>{col2 && <span className="r-sp">{col2.hd}</span>}{col3 && <span className="eff-sp">{col3.hd}</span>}{timed && <span className="ck-sp" />}<span className="ck-sp" /></div>
|
||||
{entry.sets.map((s, i) => <div key={i} className={'setrow' + (s.done ? ' done' : '') + (col3 ? ' eff3' : '')}>
|
||||
<div className="n">{i + 1}</div>
|
||||
{cell(s, i, col1, 'w')}
|
||||
{col2 && cell(s, i, col2, 'r')}
|
||||
{col3 && cell(s, i, col3, 'eff')}
|
||||
{/* A timed set is started, not typed: the timer counts the hold down and checks the
|
||||
set off itself. The checkbox stays for anyone who timed it on their own watch. */}
|
||||
{timed && <button className="setgo" aria-label={t('Start set')} disabled={s.done || !!working}
|
||||
onClick={() => onStartTimed(i)}><Icon name="play" /></button>}
|
||||
<Check checked={s.done} onChange={() => onToggle(i)} />
|
||||
</div>)}
|
||||
{entry.sets.map((s, i) => {
|
||||
const warmBefore = i > 0 && !!entry.sets[i - 1].warmup
|
||||
const isFirstWarmup = !!s.warmup && !warmBefore
|
||||
// Numbering restarts per phase: with two warm-ups the first work set reads 1, not 3.
|
||||
const phaseNum = entry.sets.slice(0, i + 1).filter(x => (x.warmup === true) === (s.warmup === true)).length
|
||||
return <div key={i}>
|
||||
{isFirstWarmup && <div className="setph">{t('Warm-up')}</div>}
|
||||
{!s.warmup && warmBefore && <div className="setsep" />}
|
||||
<div className={'setrow' + (s.done ? ' done' : '') + (col3 ? ' eff3' : '')}>
|
||||
<div className="n">{phaseNum}</div>
|
||||
{cell(s, i, col1, 'w')}
|
||||
{col2 && cell(s, i, col2, 'r')}
|
||||
{col3 && cell(s, i, col3, 'eff')}
|
||||
{/* A timed set is started, not typed: the timer counts the hold down and checks the
|
||||
set off itself. The checkbox stays for anyone who timed it on their own watch. */}
|
||||
{timed && <button className="setgo" aria-label={t('Start set')} disabled={s.done || !!working}
|
||||
onClick={() => onStartTimed(i)}><Icon name="play" /></button>}
|
||||
{s.warmup && <button className="iconbtn" style={{ fontSize: 13 }} aria-label={t('Remove set')}
|
||||
disabled={entry.sets.length <= 1} onClick={() => onRemoveSetAt(i)}><Icon name="xmark" /></button>}
|
||||
<Check checked={s.done} onChange={() => onToggle(i)} />
|
||||
</div>
|
||||
</div>
|
||||
})}
|
||||
<div style={{ height: 8 }} />
|
||||
<div className="row">
|
||||
<div className="row" style={{ flexWrap: 'wrap' }}>
|
||||
<Button size="sm" icon="flame" onClick={onAddWarmup}>{t('Add warm-up set')}</Button>
|
||||
<Button size="sm" icon="minus" disabled={entry.sets.length <= 1} onClick={onRemoveSet}>{t('Remove set')}</Button>
|
||||
<Button size="sm" icon="plus" onClick={onAddSet}>{t('Add set')}</Button>
|
||||
</div>
|
||||
@@ -172,6 +189,11 @@ function ActiveWorkout() {
|
||||
// what was actually logged — in the session, in history and in a backup.
|
||||
const setField = (idx, i, field, v) => mutEntry(idx, e => {
|
||||
if (v == null) delete e.sets[i][field]; else e.sets[i][field] = v
|
||||
// Changing a weight cascades to the following sets of the same phase, so a
|
||||
// heavier bar carries through the set instead of retyping every row.
|
||||
if (field === 'w') {
|
||||
e.sets = cascadeWeight(e.sets, i, v)
|
||||
}
|
||||
})
|
||||
const modeAt = idx => modeOf({ ...(A.entries[idx].target || {}), id: A.entries[idx].id })
|
||||
const addSet = idx => mutEntry(idx, e => {
|
||||
@@ -182,6 +204,19 @@ function ActiveWorkout() {
|
||||
else e.sets.push({ w: l ? l.w : 0, r: l ? l.r : e.target.reps, done: false })
|
||||
})
|
||||
const removeSet = idx => mutEntry(idx, e => { if (e.sets.length > 1) e.sets.pop() })
|
||||
const addWarmup = idx => mutEntry(idx, e => {
|
||||
const m = modeOf({ ...(e.target || {}), id: e.id })
|
||||
e.sets = insertWarmupRow(e.sets, m, e.target || {})
|
||||
})
|
||||
const removeSetAt = (idx, i) => mutEntry(idx, e => { e.sets = removeRowAt(e.sets, i) })
|
||||
const pairAt = (first, second) => update(s => {
|
||||
s.active.entries = pairAdjacent(s.active.entries, first, second)
|
||||
})
|
||||
const unpairAt = idx => update(s => {
|
||||
s.active.entries = unpairSuperset(s.active.entries, idx)
|
||||
})
|
||||
const onPairPrev = !isSuperset && cur > 0 ? () => pairAt(cur - 1, cur) : null
|
||||
const onPairNext = !isSuperset && cur < A.entries.length - 1 ? () => pairAt(cur, cur + 1) : null
|
||||
|
||||
// A timed set is held, not typed. The work timer records what was actually held — an early
|
||||
// finish logs 0:38 of a 0:45 target rather than crediting the full prescription — and then
|
||||
@@ -263,15 +298,18 @@ function ActiveWorkout() {
|
||||
<div className="muted small" style={{ marginBottom: 6 }}>{isSuperset ? t('Superset {0} / {1}', unitIdx + 1, units.length) : t('Exercise {0} / {1}', unitIdx + 1, units.length)}</div>
|
||||
{isSuperset ? (
|
||||
<div className="ss-card">
|
||||
<div className="ss-hd"><Icon name="link" />{t('Superset · do these back-to-back, rest after both')}</div>
|
||||
<div className="ss-hd" style={{ justifyContent: 'space-between' }}>
|
||||
<span className="row" style={{ gap: 5 }}><Icon name="link" />{t('Superset · do these back-to-back, rest when done')}</span>
|
||||
<Button size="xs" variant="ghost" icon="link" title={t('Unpair')} onClick={() => unpairAt(cur)}>{t('Unpair')}</Button>
|
||||
</div>
|
||||
{unit.map((idx, k) => <div key={idx} className="ss-ex">
|
||||
{k > 0 && <div className="ss-amp">+</div>}
|
||||
<ExerciseBlock entryIdx={idx} compact
|
||||
onToggle={i => toggle(idx, i)} onField={(i, f, v) => setField(idx, i, f, v)} onAddSet={() => addSet(idx)} onRemoveSet={() => removeSet(idx)} onStartTimed={i => startTimed(idx, i)} />
|
||||
onToggle={i => toggle(idx, i)} onField={(i, f, v) => setField(idx, i, f, v)} onAddSet={() => addSet(idx)} onRemoveSet={() => removeSet(idx)} onAddWarmup={() => addWarmup(idx)} onRemoveSetAt={i => removeSetAt(idx, i)} onStartTimed={i => startTimed(idx, i)} />
|
||||
</div>)}
|
||||
</div>
|
||||
) : (
|
||||
<ExerciseBlock entryIdx={cur} onToggle={i => toggle(cur, i)} onField={(i, f, v) => setField(cur, i, f, v)} onAddSet={() => addSet(cur)} onRemoveSet={() => removeSet(cur)} onStartTimed={i => startTimed(cur, i)} />
|
||||
<ExerciseBlock entryIdx={cur} onToggle={i => toggle(cur, i)} onField={(i, f, v) => setField(cur, i, f, v)} onAddSet={() => addSet(cur)} onRemoveSet={() => removeSet(cur)} onAddWarmup={() => addWarmup(cur)} onRemoveSetAt={i => removeSetAt(cur, i)} onStartTimed={i => startTimed(cur, i)} onPairPrev={onPairPrev} onPairNext={onPairNext} />
|
||||
)}
|
||||
</> : <div className="empty"><div className="ico"><Icon name="shuffle" /></div>{t('Freestyle workout — add your first exercise.')}</div>}
|
||||
|
||||
@@ -281,12 +319,20 @@ function ActiveWorkout() {
|
||||
<Button trailingIcon="chevronRight" disabled={unitIdx < 0 || unitIdx >= units.length - 1} onClick={() => update(s => { s.active.cur = units[unitIdx + 1][0] })}>{t('Next')}</Button>
|
||||
</div>
|
||||
<div style={{ height: 10 }} />
|
||||
<Button onClick={() => exercisePicker(ex => exConfigSheet(ex, null, cfg => update(s => {
|
||||
const full = { ...cfg, id: ex.id }
|
||||
const plan = nextPrescription(s, full, s.routines.find(r => r.id === s.active.routineId))
|
||||
s.active.entries.push({ id: ex.id, target: { ...cfg }, plan, sets: applyPrescription(buildSets(s, full), plan) })
|
||||
s.active.cur = s.active.entries.length - 1
|
||||
}), null, S.routines.find(r => r.id === A.routineId)))} icon="plus">{t('Add exercise')}</Button>
|
||||
<Button onClick={() => exercisePicker(ex => {
|
||||
const routine = S.routines.find(r => r.id === A.routineId)
|
||||
const freestyle = !A.routineId
|
||||
// Freestyle has no routine prescription to apply: show the last target in the config
|
||||
// sheet and carry its completed rows forward. A planned session keeps its existing path.
|
||||
const seed = freestyle ? freestyleConfig(S, { id: ex.id, ...defaultConfig(ex.id) }) : null
|
||||
exConfigSheet(ex, null, cfg => update(s => {
|
||||
const full = { ...cfg, id: ex.id }
|
||||
const plan = freestyle ? null : nextPrescription(s, full, s.routines.find(r => r.id === s.active.routineId))
|
||||
const sets = buildSets(s, full, freestyle ? { preferLast: true } : undefined)
|
||||
s.active.entries.push({ id: ex.id, target: { ...cfg }, plan, sets: freestyle ? sets : applyPrescription(sets, plan) })
|
||||
s.active.cur = s.active.entries.length - 1
|
||||
}), null, routine, seed)
|
||||
})} icon="plus">{t('Add exercise')}</Button>
|
||||
<div style={{ height: 10 }} />
|
||||
{(() => {
|
||||
const exDone = A.entries.filter(e => e.sets.length && e.sets.every(s => s.done)).length
|
||||
|
||||
+136
@@ -0,0 +1,136 @@
|
||||
# openGym MCP server
|
||||
|
||||
A [Model Context Protocol](https://modelcontextprotocol.io) bridge that lets an external LLM
|
||||
application (Claude Desktop, Cursor, Cline, Continue, etc.) read your openGym profile —
|
||||
routines, workouts, body-weight log, estimated 1RMs, and muscle balance — directly from your
|
||||
self-hosted `./data` directory.
|
||||
|
||||
It is read-only, runs locally as a stdio process spawned by the LLM client, adds no new
|
||||
container, and requires no extra authentication. The LLM never sees passkeys, VAPID keys, or
|
||||
session secrets — it can only read the same `state-<uid>.json` files the openGym api already
|
||||
writes.
|
||||
|
||||
The numbers it answers with are computed by the **same pure functions the React UI uses**
|
||||
(`frontend/src/lib/*.js`) — `estimate1RM`, `loadOfWorkouts`, `effectiveRoutine`, etc. — so a
|
||||
"what's my bench 1RM?" answer matches the Stats screen exactly.
|
||||
|
||||
> Phase 1 of a multi-phase plan. Read-only today; long-lived token auth + write tools are
|
||||
> planned but not shipped yet. See **Roadmap** below.
|
||||
|
||||
## Quick start
|
||||
|
||||
### 1. Install
|
||||
|
||||
```bash
|
||||
cd mcp
|
||||
npm install
|
||||
```
|
||||
|
||||
### 2. Point it at your data
|
||||
|
||||
The MCP server reads the same `./data` directory `docker compose up` creates. Pick the profile
|
||||
to answer for — its user id is in `./data/db.json` under `users[].id`:
|
||||
|
||||
```bash
|
||||
# single-user instance (the common self-hosted case) — auto-detected:
|
||||
node src/index.js
|
||||
|
||||
# multi-user instance, or just to be explicit:
|
||||
OPENGYM_UID=<your-uid> OPENGYM_DATA=/path/to/openGym/data node src/index.js
|
||||
```
|
||||
|
||||
### 3. Register with your LLM client
|
||||
|
||||
Add the server to your LLM client's MCP config. For Claude Desktop, edit
|
||||
`claude_desktop_config.json` (macOS: `~/Library/Application Support/Claude/claude_desktop_config.json`):
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"mcpServers": {
|
||||
"opengym": {
|
||||
"command": "node",
|
||||
"args": ["/absolute/path/to/openGym/mcp/src/index.js"],
|
||||
"env": {
|
||||
"OPENGYM_DATA": "/absolute/path/to/openGym/data",
|
||||
"OPENGYM_UID": "<your-uid>" // optional — auto-detected if you have one profile
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
For Cursor and other MCP-compatible clients, see the client's MCP docs — the same `command` +
|
||||
`args` + `env` shape is what every stdio MCP server expects.
|
||||
|
||||
Restart the client; you should see the openGym tools appear with "serving profile \<name\>" on
|
||||
the server's stderr.
|
||||
|
||||
## Tools
|
||||
|
||||
Eight read-only tools in v1:
|
||||
|
||||
| Tool | What it answers |
|
||||
|---|---|
|
||||
| `list_routines` | What routines are saved in my profile? (names + exercise counts) |
|
||||
| `get_routine` | What does the Push Day routine prescribe? (sets/reps/weight per exercise) |
|
||||
| `get_week_plan` | What's on my plan this week, including today with any date-specific override? |
|
||||
| `list_workouts` | Recent sessions — newest first, with dates, sets done/planned, volume, duration, PRs. |
|
||||
| `get_workout` | Full set-by-set breakdown of one session, by `workout_id` or by date. On a day with two sessions the date alone returns both ids to pick from rather than guessing at one. |
|
||||
| `get_bodyweight` | Weigh-ins with the latest weight, the goal line, and deltas vs goal. |
|
||||
| `estimate_1rm` | All-time best 1RM for an exercise + the trend, or a PR table across all exercises. |
|
||||
| `muscle_balance` | Which muscles I've trained this week/month/all-time, ranked + which I've neglected. |
|
||||
|
||||
Each tool returns JSON the LLM can format as it likes; structured fields (sets, dates, levels)
|
||||
are pre-formatted into human-readable labels in `src/labels.js` so the LLM doesn't need to
|
||||
re-interpret them.
|
||||
|
||||
## How it reuses the training logic
|
||||
|
||||
The MCP server imports the training helpers under `frontend/src/lib/` directly as Node ESM
|
||||
and calls the same functions the React UI does (`history.js`, `onerm.js`, `muscles.js`,
|
||||
`exercises.js`). The numbers it returns match what the Stats screen shows, because they are
|
||||
the same code.
|
||||
|
||||
The one lib file that wasn't Node-safe was `i18n.js` (Vite's `import.meta.glob` at module
|
||||
top level) — split into `i18n-core.js` (pure, Node-safe) + `i18n.js` (Vite/React bits,
|
||||
re-exports from core). `exercises.js` got a one-line `import.meta.env || {}` guard. No new
|
||||
dependencies landed in `frontend/`, no public exports changed.
|
||||
|
||||
## Design constraints honoured
|
||||
|
||||
- **One runtime dependency beyond the MCP SDK:** none. No database driver, no HTTP framework.
|
||||
- **No new container.** stdio transport is spawned by the LLM client; nothing to add to
|
||||
`docker-compose.yml`.
|
||||
- **No new auth.** The filesystem is the boundary — same as `docker compose` running on the
|
||||
user's box. No passkey material, VAPID keys, or session secrets ever cross it.
|
||||
- **No telemetry, no network.** Reads `./data/*.json` and exits when the LLM client
|
||||
disconnects.
|
||||
|
||||
## Tests
|
||||
|
||||
```bash
|
||||
cd mcp && npm test
|
||||
```
|
||||
|
||||
32 cases seeding state from `frontend/src/lib/demoSeed.js` (the same deterministic fixture
|
||||
the public demo runs on). Pins JSON shape and the user-facing edge cases: rest-day override,
|
||||
missing routine, zero-workout history, no synced state, superset links, three 1RM formulas.
|
||||
"Today" is pinned via `vi.useFakeTimers({ now: ..., toFake: ['Date'] })` so date-dependent
|
||||
tools see consistent values regardless of when the suite runs. The pure lib functions have
|
||||
their own 92 tests in `frontend/src/lib/*.test.js`.
|
||||
|
||||
## Roadmap
|
||||
|
||||
- **Done (Phase 1):** read-only stdio, 8 tools, direct `./data` access.
|
||||
- **Phase 1.5:** a `progression_next` tool (what does the policy prescribe next?). No new
|
||||
deps; small surface area.
|
||||
- **Phase 2:** read+write over stdio. Requires a long-lived token auth path minted from the
|
||||
admin dashboard (new `./data/tokens.json`) and a write-lock against the web UI's read-modify-
|
||||
write of `state-<uid>.json`. Tools: `log_workout`, `add_bodyweight`, `edit_routine`,
|
||||
`assign_weekday`, `override_day`.
|
||||
- **Phase 3:** Streamable HTTP transport, opt-in 4th container in `docker-compose.yml`. Same
|
||||
tool implementations, second transport — the MCP SDK supports both behind one tool registration.
|
||||
|
||||
## License
|
||||
|
||||
AGPL-3.0-or-later, same as openGym.
|
||||
Generated
+2465
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"name": "opengym-mcp",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "MCP (Model Context Protocol) bridge for openGym \u2014 lets an external LLM read your routines, workouts, body-weight log, estimated 1RMs and muscle balance from your self-hosted data. Read-only, stdio transport; no extra container.",
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"main": "src/index.js",
|
||||
"bin": {
|
||||
"opengym-mcp": "src/index.js"
|
||||
},
|
||||
"scripts": {
|
||||
"start": "node src/index.js",
|
||||
"test": "vitest run",
|
||||
"check:node-loadable": "node scripts/check-node-loadable.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"@modelcontextprotocol/sdk": "^1.0.4",
|
||||
"zod": "^3.23.8"
|
||||
},
|
||||
"devDependencies": {
|
||||
"vitest": "^4.1.10"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
#!/usr/bin/env node
|
||||
/* Does the server's import graph still load under plain node?
|
||||
*
|
||||
* This exists because the test suite cannot answer that question. `npm test` runs vitest, and
|
||||
* vitest resolves modules through Vite — `import.meta.glob`, `?raw`, a stray `.jsx` import all
|
||||
* work there. The server does not run under Vite. So a Vite-only import can land in a shared
|
||||
* lib module, leave all 33 tests green, and still kill the server at startup. That is exactly
|
||||
* what happened once: `history.js` began importing `t` from `i18n.js` (import.meta.glob over
|
||||
* the locale packs, plus React), and the server died on `import` with the suite none the wiser.
|
||||
*
|
||||
* Run by bare `node` on purpose — being outside vitest IS the check. Do not port this to a
|
||||
* vitest test file; that would make it pass unconditionally.
|
||||
*
|
||||
* Importing the two entry modules is enough on its own: everything the server touches hangs off
|
||||
* them, so a lib module that grows a browser-only dependency next year fails here without this
|
||||
* list being updated. The named list below only exists to point at the culprit instead of at a
|
||||
* stack trace ten frames deep.
|
||||
*/
|
||||
const LIB = new URL('../../frontend/src/lib/', import.meta.url)
|
||||
|
||||
// Every frontend/src/lib module the server reaches today. Named individually so a failure says
|
||||
// which one, rather than which import chain.
|
||||
const MODULES = [
|
||||
'i18n-core.js', 'format.js', 'exercises.js', 'exercises-data.js',
|
||||
'history.js', 'muscles.js', 'onerm.js', 'progression.js'
|
||||
]
|
||||
|
||||
let failed = 0
|
||||
for (const m of MODULES) {
|
||||
try {
|
||||
await import(new URL(m, LIB))
|
||||
console.log(` ok ${m}`)
|
||||
} catch (e) {
|
||||
failed++
|
||||
console.error(` FAIL ${m} — ${e.message}`)
|
||||
}
|
||||
}
|
||||
|
||||
// The real assertion: the server's own entry points, which pull the whole graph transitively.
|
||||
// A module added to the graph later is covered by this even if the list above never learns it.
|
||||
for (const entry of ['../src/state.js', '../src/tools.js']) {
|
||||
try {
|
||||
await import(new URL(entry, import.meta.url))
|
||||
console.log(` ok mcp/${entry.replace('../', '')}`)
|
||||
} catch (e) {
|
||||
failed++
|
||||
console.error(` FAIL mcp/${entry.replace('../', '')} — ${e.message}`)
|
||||
}
|
||||
}
|
||||
|
||||
if (failed) {
|
||||
console.error(`\n${failed} module(s) do not load under plain node — the MCP server would not start.`)
|
||||
process.exit(1)
|
||||
}
|
||||
console.log('\nthe whole MCP import graph loads under plain node.')
|
||||
@@ -0,0 +1,50 @@
|
||||
#!/usr/bin/env node
|
||||
/* openGym MCP server — stdio transport. The LLM client (Claude Desktop, Cursor, …) spawns
|
||||
this process locally, talks JSON-RPC over stdin/stdout, tears it down when the session ends.
|
||||
No extra container, no new outbound network — your data stays in a folder you control. */
|
||||
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
|
||||
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'
|
||||
import { TOOLS } from './tools.js'
|
||||
import { init, getUser } from './state.js'
|
||||
|
||||
const server = new McpServer({
|
||||
name: 'opengym',
|
||||
version: '0.1.0'
|
||||
})
|
||||
|
||||
// Fail fast on bad config so a misnamed OPENGYM_DATA doesn't silently answer every call with
|
||||
// the no-state sentinel. Always register every tool so the LLM sees the full list at
|
||||
// handshake, even when state didn't resolve.
|
||||
try {
|
||||
init()
|
||||
const u = getUser()
|
||||
console.error(`[opengym-mcp] serving profile ${u.name} (${u.id})`)
|
||||
} catch (e) {
|
||||
console.error(`[opengym-mcp] ${e.message}`)
|
||||
// Don't exit — keep the tool listings up so the user sees a useful error after fixing their
|
||||
// env and restarting.
|
||||
}
|
||||
|
||||
for (const t of TOOLS) {
|
||||
server.tool(
|
||||
t.name,
|
||||
t.description,
|
||||
t.schema,
|
||||
async (params) => {
|
||||
try {
|
||||
const result = t.handler(params || {})
|
||||
return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] }
|
||||
} catch (err) {
|
||||
const code = err.code || 'ERROR'
|
||||
return {
|
||||
isError: true,
|
||||
content: [{ type: 'text', text: `${code}: ${err.message}` }]
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
const transport = new StdioServerTransport()
|
||||
await server.connect(transport)
|
||||
// Process stays alive serving JSON-RPC over stdio until the LLM client disconnects.
|
||||
@@ -0,0 +1,47 @@
|
||||
// Formatting glue between lib helpers (which speak {0}/{1} templates) and the JSON returned
|
||||
// to the LLM.
|
||||
import { MUSCLE_NAME, MUSCLES } from '../../frontend/src/lib/muscles.js'
|
||||
import { modeOf, fmtSec, setLabel } from '../../frontend/src/lib/history.js'
|
||||
import { POLICY_NAME } from '../../frontend/src/lib/progression.js'
|
||||
import { fmtDate, fmtNum, fmtDur } from '../../frontend/src/lib/format.js'
|
||||
|
||||
// Apply {0},{1},… substitutions to the template strings the lib returns.
|
||||
export function fmt(template, args) {
|
||||
let v = template
|
||||
for (let i = 0; i < (args || []).length; i++) v = v.replaceAll('{' + i + '}', String(args[i]))
|
||||
return v
|
||||
}
|
||||
|
||||
export { setLabel }
|
||||
|
||||
export function exLine(cfg, unit) {
|
||||
const mode = modeOf(cfg)
|
||||
const n = cfg.sets || 1
|
||||
const load = cfg.weight ? ' · ' + fmtNum(cfg.weight) + ' ' + unit : ''
|
||||
if (mode === 'cardio') return `${n} × ${cfg.min || 20} min @ ${fmtNum(cfg.speed || 8)} km/h`
|
||||
if (mode === 'time') return `${n} × ${fmtSec(cfg.sec || 45)}${load}`
|
||||
return `${n} × ${cfg.reps}${load}`
|
||||
}
|
||||
|
||||
export function muscleName(slug) {
|
||||
return MUSCLE_NAME[slug] || slug
|
||||
}
|
||||
|
||||
export function policyName(policy) {
|
||||
return POLICY_NAME[policy] || policy
|
||||
}
|
||||
|
||||
export function friendlyDate(iso) {
|
||||
if (!iso) return null
|
||||
return fmtDate(iso)
|
||||
}
|
||||
|
||||
export function friendlyDuration(ms) {
|
||||
return ms ? fmtDur(ms) : null
|
||||
}
|
||||
|
||||
export function ratio(done, total) {
|
||||
return `${done}/${total}`
|
||||
}
|
||||
|
||||
export function muscleOrder() { return MUSCLES.slice() }
|
||||
@@ -0,0 +1,137 @@
|
||||
/* opengym-mcp state — reads ./data/state-<uid>.json + db.json (read-only). Cached with an
|
||||
fs.watch + mtime fallback so a session the api server just wrote is visible on the next
|
||||
tool call without a restart. */
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
|
||||
const DATA_DIR = process.env.OPENGYM_DATA || path.join(process.cwd(), 'data')
|
||||
|
||||
// null = no state file (brand-new account); undefined = not yet loaded.
|
||||
let _state = undefined
|
||||
let _db = undefined
|
||||
let _uid = null
|
||||
let _watcher = null
|
||||
let _loadedMtime = 0 // mtimeMs we last read at — used to catch watcher omissions
|
||||
|
||||
function readJsonOrNull(file) {
|
||||
try { return JSON.parse(fs.readFileSync(file, 'utf8')) } catch { return null }
|
||||
}
|
||||
|
||||
function reloadDb() { _db = readJsonOrNull(path.join(DATA_DIR, 'db.json')) || { users: [], creds: [], subs: [], invites: [] } }
|
||||
|
||||
function stateFile(uid) {
|
||||
return path.join(DATA_DIR, 'state-' + uid.replace(/[^a-zA-Z0-9_-]/g, '') + '.json')
|
||||
}
|
||||
|
||||
// Pick the uid: OPENGYM_UID env, else the only state-* file, else the only user in db.json.
|
||||
// Throws listing the options if ambiguous. The sanitiser on stateFile() keeps a sneaky
|
||||
// '..' in OPENGYM_UID harmless.
|
||||
function resolveUid() {
|
||||
const envUid = (process.env.OPENGYM_UID || '').trim()
|
||||
if (envUid) {
|
||||
if (!/^[a-zA-Z0-9_-]+$/.test(envUid)) throw new Error(`OPENGYM_UID contains characters that aren't safe in a filename: ${JSON.stringify(envUid)}`)
|
||||
return envUid
|
||||
}
|
||||
const files = fs.readdirSync(DATA_DIR)
|
||||
.filter(f => /^state-[a-zA-Z0-9_-]+\.json$/.test(f))
|
||||
.map(f => f.replace(/^state-/, '').replace(/\.json$/, ''))
|
||||
if (files.length === 1) return files[0]
|
||||
if (files.length === 0) {
|
||||
reloadDb()
|
||||
if (_db.users.length === 1) return _db.users[0].id
|
||||
if (_db.users.length === 0) throw new Error(`no openGym users found in ${path.join(DATA_DIR, 'db.json')} — sign in at least once on a device`)
|
||||
// Multiple users in db.json but no state files yet — list their ids, not the (empty)
|
||||
// files list. Hit when accounts exist but none has signed in on a device.
|
||||
throw new Error(
|
||||
`multiple openGym users found — set OPENGYM_UID to one of: ${_db.users.map(u => u.id).join(', ')}\n` +
|
||||
` (look them up in ${path.join(DATA_DIR, 'db.json')} under "users"[].id)`
|
||||
)
|
||||
}
|
||||
throw new Error(
|
||||
`multiple openGym users found — set OPENGYM_UID to one of: ${files.join(', ')}\n` +
|
||||
` (look them up in ${path.join(DATA_DIR, 'db.json')} under "users"[].id)`
|
||||
)
|
||||
}
|
||||
|
||||
// Idempotent. Picks the uid, loads db.json, attaches the watcher, primes state.
|
||||
export function init() {
|
||||
if (_uid !== null) return
|
||||
if (!fs.existsSync(DATA_DIR)) throw new Error(`OPENGYM_DATA dir does not exist: ${DATA_DIR}`)
|
||||
_uid = resolveUid()
|
||||
reloadDb()
|
||||
const file = stateFile(_uid)
|
||||
if (fs.existsSync(file)) {
|
||||
_state = readJsonOrNull(file)
|
||||
if (_state) _state = Object.assign({}, defaultsShape(), _state)
|
||||
try { _loadedMtime = fs.statSync(file).mtimeMs } catch {}
|
||||
}
|
||||
if (_watcher) _watcher.close()
|
||||
// fs.watch is best-effort: the api server's atomic write at PUT /api/data is the source of
|
||||
// truth, and a stale read just gets corrected on the next change or the next tool call.
|
||||
try {
|
||||
_watcher = fs.watch(file, () => {
|
||||
// On change, simply clear the cache — the next getState() will re-read. Avoids reading
|
||||
// twice if the watcher fires multiple events for one atomic-write (rename + create).
|
||||
_state = undefined
|
||||
_loadedMtime = 0
|
||||
})
|
||||
// Unref'd, or the watcher alone holds the event loop open and the process outlives the
|
||||
// client that spawned it — "exits when the LLM client disconnects" stops being true the
|
||||
// moment there is a state file to watch. Most clients kill the child anyway, but one that
|
||||
// merely closes the pipe would leak a process per session. Watching is unaffected: the
|
||||
// stdio transport is what keeps the loop alive while a client is actually attached.
|
||||
_watcher.unref()
|
||||
} catch { /* fs.watch unsupported on this platform; tools will re-read on mtime change */ }
|
||||
}
|
||||
|
||||
// Returns the state object, or null for a fresh account that never signed in on a device.
|
||||
export function getState() {
|
||||
init()
|
||||
const file = stateFile(_uid)
|
||||
// Re-read if the file's mtime changed since our last load — covers watcher omissions and
|
||||
// platforms with no fs.watch.
|
||||
let mtime
|
||||
try { mtime = fs.statSync(file).mtimeMs } catch {
|
||||
return _state === undefined ? null : _state
|
||||
}
|
||||
if (_state === undefined || mtime !== _loadedMtime) {
|
||||
const fresh = readJsonOrNull(file)
|
||||
if (fresh) {
|
||||
// Same shape the frontend builds on pullState — defaults merged with stored state so any
|
||||
// field the app added since the snapshot was last saved shows up undefined-safe.
|
||||
_state = Object.assign({}, defaultsShape(), fresh)
|
||||
_loadedMtime = mtime
|
||||
} else if (_state === undefined) {
|
||||
_state = null // no state file at all — never signed in on a device
|
||||
}
|
||||
}
|
||||
return _state
|
||||
}
|
||||
|
||||
// Returns the user record (id + name). No passkey material, no VAPID keys, no push subs.
|
||||
export function getUser() {
|
||||
init()
|
||||
const u = _db.users.find(x => x.id === _uid) || { id: _uid, name: 'Profile', created: null }
|
||||
return { id: u.id, name: u.name, created: u.created || null }
|
||||
}
|
||||
|
||||
export const dataDir = () => DATA_DIR
|
||||
|
||||
// Test-only: work against a passed-in state, not the disk.
|
||||
export function _seedStateForTests(state) {
|
||||
_uid = 'test-uid'
|
||||
_db = { users: [{ id: _uid, name: 'Test', created: '2026-07-26T00:00:00.000Z' }], creds: [], subs: [], invites: [] }
|
||||
_state = state
|
||||
_loadedMtime = Number.MAX_SAFE_INTEGER // never re-read from disk in a test
|
||||
if (_watcher) { _watcher.close(); _watcher = null }
|
||||
}
|
||||
|
||||
function defaultsShape() {
|
||||
return {
|
||||
unit: 'kg', restSec: 90, sound: true, lang: 'en',
|
||||
theme: 'dark', accent: 'lime', body: 'male', targetW: null,
|
||||
bodyweight: [], routines: [], week: {}, dayPlan: {},
|
||||
exWeights: {}, workouts: [], customEx: [], gifSize: 'full',
|
||||
reminder: { on: false, time: '08:00', tz: null }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,389 @@
|
||||
/* The eight read-only tools. Each handler returns JSON; labels.js pre-substitutes any
|
||||
{0}/{1} template the lib returns so the LLM gets final text, not template strings.
|
||||
ISO dates are validated on the way in; the handlers never see 'yesterday'. */
|
||||
import { z } from 'zod'
|
||||
import { getState, getUser } from './state.js'
|
||||
import {
|
||||
setLabel, exLine, muscleName, policyName, friendlyDuration, ratio, muscleOrder
|
||||
} from './labels.js'
|
||||
import {
|
||||
modeOf, workoutVolume, setsDone, effectiveRoutine, effectiveRoutineId
|
||||
} from '../../frontend/src/lib/history.js'
|
||||
import { EXIDX, exOr } from '../../frontend/src/lib/exercises.js'
|
||||
import {
|
||||
estimate1RM, best1RM, e1rmSeries, DEFAULT_FORMULA, REP_CAP
|
||||
} from '../../frontend/src/lib/onerm.js'
|
||||
import { loadOfWorkouts, rankOf, levelsOf } from '../../frontend/src/lib/muscles.js'
|
||||
|
||||
/* ---------- helpers ---------- */
|
||||
|
||||
function entryView(e, S) {
|
||||
const ex = exOr(e.id)
|
||||
// Spread id into the cfg the way every call site in the app does (Workout.jsx, Stats.jsx,
|
||||
// progression.js) — the sheet saves a cardio target as {sets, min, speed} with no id and no
|
||||
// mode, so modeOf needs the id to fall through to isCardio(id).
|
||||
const cfg = { ...(e.target || {}), id: e.id }
|
||||
const mode = modeOf(cfg)
|
||||
return {
|
||||
id: e.id,
|
||||
name: ex.n,
|
||||
body_part: ex.bp || null,
|
||||
mode,
|
||||
target: e.target || null,
|
||||
sets: (e.sets || []).map(s => ({
|
||||
done: !!s.done,
|
||||
label: setLabel(e.id, { ...s, done: undefined }, cfg),
|
||||
w: Number(s.w) || 0,
|
||||
r: Number(s.r) || 0,
|
||||
sec: Number(s.sec) || 0,
|
||||
min: Number(s.min) || 0,
|
||||
speed: Number(s.speed) || 0
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
// Best estimate per exercise, mirroring the UI's PR table: every eligible set across history, biggest wins.
|
||||
function prTable(S, formula) {
|
||||
const byId = new Map()
|
||||
for (const w of (S.workouts || [])) {
|
||||
for (const e of (w.entries || [])) {
|
||||
for (const s of (e.sets || [])) {
|
||||
if (!s.done) continue
|
||||
const est = estimate1RM(s.w, s.r, formula)
|
||||
if (est == null) continue
|
||||
const ex = exOr(e.id)
|
||||
const prev = byId.get(e.id)
|
||||
if (!prev || est > prev.est) {
|
||||
// exId as well as exName: the consumer needs an id, not a name — exOr() treats any
|
||||
// string as both, so passing exName where exId belongs would silently "work" wrong.
|
||||
byId.set(e.id, { exId: e.id, exName: ex.n, bp: ex.bp || null, est, w: Number(s.w), r: Math.round(Number(s.r)), date: w.d })
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return [...byId.values()].sort((a, b) => b.est - a.est)
|
||||
}
|
||||
|
||||
/* ---------- the 8 tools ---------- */
|
||||
|
||||
/** list_routines — names + counts of each routine in the user's plan. */
|
||||
export const listRoutines = {
|
||||
name: 'list_routines',
|
||||
description: 'List the workout routines saved in the user\'s openGym profile (the same list the Plan screen shows). Each routine is a named set of exercises with set/rep targets. Use this to discover the plan structure before diving into a specific routine or today\'s workout.',
|
||||
schema: {},
|
||||
handler: () => {
|
||||
const S = getState()
|
||||
if (!S) return noState()
|
||||
return {
|
||||
unit: S.unit || 'kg',
|
||||
routines: (S.routines || []).map(r => ({
|
||||
id: r.id,
|
||||
name: r.name,
|
||||
emoji: r.emoji || null,
|
||||
exercise_count: (r.ex || []).length,
|
||||
superset_groups: [...new Set((r.ex || []).map(e => e.sg).filter(Boolean))].length || 0,
|
||||
policy: r.policy || 'off'
|
||||
}))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** get_routine — the full exercise list for one routine, including set/rep targets. */
|
||||
export const getRoutine = {
|
||||
name: 'get_routine',
|
||||
description: 'Get the full exercise list for a single routine (the same view the routine editor shows). Returns mode (reps/time/cardio), set/rep/weight targets, superset links, and any per-exercise custom increment you can override. Use routine_id from list_routines.',
|
||||
schema: { routine_id: z.string().min(1) },
|
||||
handler: ({ routine_id }) => {
|
||||
const S = getState()
|
||||
if (!S) return noState()
|
||||
const r = (S.routines || []).find(x => x.id === routine_id)
|
||||
if (!r) { const e = new Error(`no routine with id ${JSON.stringify(routine_id)}`); e.code = 'ENOENT'; throw e }
|
||||
return {
|
||||
id: r.id,
|
||||
name: r.name,
|
||||
emoji: r.emoji || null,
|
||||
policy: r.policy || 'off',
|
||||
policy_name: policyName(r.policy || 'off'),
|
||||
unit: S.unit || 'kg',
|
||||
exercises: (r.ex || []).map((cfg, i) => {
|
||||
const ex = exOr(cfg.id)
|
||||
const mode = modeOf(cfg)
|
||||
return {
|
||||
position: i + 1,
|
||||
id: cfg.id,
|
||||
name: ex.n,
|
||||
body_part: ex.bp || null,
|
||||
mode,
|
||||
sets: cfg.sets || 1,
|
||||
reps: mode === 'reps' ? (cfg.reps || 0) : undefined,
|
||||
reps_min: mode === 'reps' && cfg.repsMin != null ? cfg.repsMin : undefined,
|
||||
sec: mode === 'time' ? (cfg.sec || 0) : undefined,
|
||||
min: mode === 'cardio' ? (cfg.min || 0) : undefined,
|
||||
speed: mode === 'cardio' ? (cfg.speed || 0) : undefined,
|
||||
weight: cfg.weight != null ? cfg.weight : undefined,
|
||||
increment: cfg.inc != null ? cfg.inc : undefined,
|
||||
policy_override: cfg.policy || null,
|
||||
superset_group: cfg.sg || null,
|
||||
summary: exLine(cfg, S.unit || 'kg')
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** get_week_plan — what's scheduled each weekday + today. */
|
||||
export const getWeekPlan = {
|
||||
name: 'get_week_plan',
|
||||
description: 'Show the user\'s weekly plan: which routine (if any) is assigned to each weekday, keyed by JS getDay() (Sunday=0, Monday=1, … Saturday=6 — the same convention the openGym state file uses). Also reports today\'s date and what routine applies today, accounting for one-off overrides the user may have set for a specific date (a "rest" override cancels the day).',
|
||||
schema: {},
|
||||
handler: () => {
|
||||
const S = getState()
|
||||
if (!S) return noState()
|
||||
const today = new Date()
|
||||
const isoToday = today.getFullYear() + '-' + String(today.getMonth() + 1).padStart(2, '0') + '-' + String(today.getDate()).padStart(2, '0')
|
||||
const todayWd = today.getDay()
|
||||
return {
|
||||
today: isoToday,
|
||||
weekdays: [0, 1, 2, 3, 4, 5, 6].map(d => {
|
||||
const rid = S.week?.[d] || null
|
||||
const r = rid ? (S.routines || []).find(x => x.id === rid) : null
|
||||
// Surface today's override only (not the whole dayPlan dict — usually empty, but might
|
||||
// have grown from repeated "move this day" actions).
|
||||
const overrideForToday = d === todayWd ? (S.dayPlan?.[isoToday] ?? null) : null
|
||||
return {
|
||||
weekday: d,
|
||||
weekday_name: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][d],
|
||||
routine_id: rid,
|
||||
routine_name: r?.name || null,
|
||||
routine_emoji: r?.emoji || null,
|
||||
override_for_today_or_null: overrideForToday
|
||||
}
|
||||
}),
|
||||
today_routine_id: effectiveRoutineId(S, isoToday),
|
||||
today_routine_name: effectiveRoutine(S, isoToday)?.name || null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** list_workouts — newest-first summary of recent sessions. */
|
||||
export const listWorkouts = {
|
||||
name: 'list_workouts',
|
||||
description: 'List recent finished workouts, newest first. Each item summarises the date, exercise count, sets done / planned, total volume (in the user\'s unit), duration and whether PRs were set. Use this before drilling into a specific date with get_workout.',
|
||||
schema: {
|
||||
from: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional().describe('Inclusive start date YYYY-MM-DD. Defaults to no lower bound (list most recent).'),
|
||||
to: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional().describe('Inclusive end date YYYY-MM-DD. Defaults to today.'),
|
||||
limit: z.number().int().min(1).max(200).optional().describe('Max items to return. Defaults to 25.')
|
||||
},
|
||||
handler: ({ from, to, limit }) => {
|
||||
const S = getState()
|
||||
if (!S) return noState()
|
||||
const lim = Math.min(Math.max(limit || 25, 1), 200)
|
||||
const all = (S.workouts || []).slice().sort((a, b) => (b.d || '').localeCompare(a.d || ''))
|
||||
const filtered = all.filter(w => {
|
||||
if (from && w.d < from) return false
|
||||
if (to && w.d > to) return false
|
||||
return true
|
||||
}).slice(0, lim)
|
||||
return {
|
||||
unit: S.unit || 'kg',
|
||||
total_count: all.length,
|
||||
returned_count: filtered.length,
|
||||
workouts: filtered.map(w => ({
|
||||
// The only thing that identifies a session uniquely. Two workouts on one day is
|
||||
// ordinary — a lifting session and an evening run — and without an id here the second
|
||||
// one cannot be asked about at all.
|
||||
id: w.id || null,
|
||||
date: w.d,
|
||||
routine_id: w.routineId || null,
|
||||
routine_name: w.name || null,
|
||||
exercise_count: (w.entries || []).length,
|
||||
sets_done: setsDone(w),
|
||||
sets_planned: plannedSets(w),
|
||||
sets_ratio: ratio(setsDone(w), plannedSets(w)),
|
||||
volume: workoutVolume(w),
|
||||
duration_ms: w.end && w.start ? (w.end - w.start) : null,
|
||||
duration: w.end && w.start ? friendlyDuration(w.end - w.start) : null,
|
||||
prs: (w.prs || []).length,
|
||||
bodyweight_at_workout: w.bw || null
|
||||
}))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function plannedSets(w) {
|
||||
let n = 0
|
||||
;(w.entries || []).forEach(e => { n += (e.sets || []).length })
|
||||
return n
|
||||
}
|
||||
|
||||
/** get_workout — full entry/set breakdown for one date. */
|
||||
export const getWorkout = {
|
||||
name: 'get_workout',
|
||||
description: 'Get the full breakdown of one workout: every exercise, its mode (reps/time/cardio), the target, and per-set labels (e.g. "5 @ 60 kg", "1:30 · 20 kg"). Identify it by workout_id (from list_workouts) or by date. Use list_workouts first if you don\'t know either.',
|
||||
schema: {
|
||||
date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional().describe('The workout date as YYYY-MM-DD. If two sessions share that date, the answer lists them instead and asks for a workout_id.'),
|
||||
workout_id: z.string().min(1).optional().describe('The id from list_workouts. Preferred: it names one session even on a day with two.')
|
||||
},
|
||||
handler: ({ date, workout_id }) => {
|
||||
const S = getState()
|
||||
if (!S) return noState()
|
||||
const workouts = S.workouts || []
|
||||
let w
|
||||
if (workout_id) {
|
||||
w = workouts.find(x => x.id === workout_id)
|
||||
if (!w) { const e = new Error(`no workout with id ${workout_id}`); e.code = 'ENOENT'; throw e }
|
||||
} else if (date) {
|
||||
const sameDay = workouts.filter(x => x.d === date)
|
||||
if (!sameDay.length) { const e = new Error(`no workout on ${date}`); e.code = 'ENOENT'; throw e }
|
||||
// Answering with the first of two is how a question about the evening run gets the
|
||||
// morning's lifting numbers, stated with total confidence. Say there are two instead.
|
||||
if (sameDay.length > 1) {
|
||||
return {
|
||||
ambiguous: true,
|
||||
date,
|
||||
message: `${sameDay.length} workouts were logged on ${date} — call get_workout again with one of these workout_id values.`,
|
||||
workouts: sameDay.map(x => ({
|
||||
id: x.id || null,
|
||||
routine_name: x.name || null,
|
||||
sets_done: setsDone(x),
|
||||
volume: workoutVolume(x),
|
||||
duration: x.end && x.start ? friendlyDuration(x.end - x.start) : null
|
||||
}))
|
||||
}
|
||||
}
|
||||
w = sameDay[0]
|
||||
} else {
|
||||
const e = new Error('get_workout needs either workout_id or date'); e.code = 'EINVAL'; throw e
|
||||
}
|
||||
return {
|
||||
id: w.id || null,
|
||||
date: w.d,
|
||||
routine_id: w.routineId || null,
|
||||
routine_name: w.name || null,
|
||||
unit: S.unit || 'kg',
|
||||
bodyweight_at_workout: w.bw || null,
|
||||
volume: workoutVolume(w),
|
||||
sets_done: setsDone(w),
|
||||
sets_planned: plannedSets(w),
|
||||
duration: w.end && w.start ? friendlyDuration(w.end - w.start) : null,
|
||||
prs: (w.prs || []).map(id => EXIDX[id]?.n || id),
|
||||
entries: (w.entries || []).map(e => entryView(e, S))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** get_bodyweight — recent weigh-ins with the goal line. */
|
||||
export const getBodyweight = {
|
||||
name: 'get_bodyweight',
|
||||
description: 'Get the body-weight log: chronological weigh-ins with weights, current goal, deltas vs goal (signed positive = above goal), and a latest summary. Useful for "am I trending toward my weight goal?" questions.',
|
||||
schema: {
|
||||
from: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional().describe('Inclusive start date YYYY-MM-DD.'),
|
||||
to: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional().describe('Inclusive end date YYYY-MM-DD. Defaults to today.')
|
||||
},
|
||||
handler: ({ from, to }) => {
|
||||
const S = getState()
|
||||
if (!S) return noState()
|
||||
const goal = S.targetW || null
|
||||
const bw = (S.bodyweight || []).filter(b => {
|
||||
if (from && b.d < from) return false
|
||||
if (to && b.d > to) return false
|
||||
return true
|
||||
}).sort((a, b) => (a.d || '').localeCompare(b.d || ''))
|
||||
const latest = bw.length ? bw[bw.length - 1] : null
|
||||
return {
|
||||
unit: S.unit || 'kg',
|
||||
goal,
|
||||
count: bw.length,
|
||||
latest: latest ? { date: latest.d, weight: latest.w, delta_vs_goal: goal != null ? Math.round((latest.w - goal) * 10) / 10 : null } : null,
|
||||
entries: bw.map(b => ({
|
||||
date: b.d,
|
||||
weight: b.w,
|
||||
delta_vs_goal: goal != null ? Math.round((b.w - goal) * 10) / 10 : null
|
||||
}))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** estimate_1rm — best-ever 1RM for one exercise or a PR table across all reps-mode exercises. */
|
||||
export const estimate1rm = {
|
||||
name: 'estimate_1rm',
|
||||
description: `Estimate one-rep max using Epley, Brzycki or Lombardi formulas. If an exercise_id is given, returns the all-time best estimate for that exercise with the source set (weight × reps + date) and the trend across history. If no exercise_id is given, returns a PR table across all reps-mode exercises (sorted highest first). Refuses to guess above ${REP_CAP} reps — above that, formulas diverge past 10% and "work capacity" is read instead of "maximal strength".`,
|
||||
schema: {
|
||||
exercise_id: z.string().optional().describe('An exercise id from list_routines or get_workout entries. If omitted, returns a full PR table.'),
|
||||
formula: z.enum(['epley', 'brzycki', 'lombardi']).optional().describe(`Formula to use. Defaults to ${DEFAULT_FORMULA}.`)
|
||||
},
|
||||
handler: ({ exercise_id, formula }) => {
|
||||
const S = getState()
|
||||
if (!S) return noState()
|
||||
const f = formula || DEFAULT_FORMULA
|
||||
if (exercise_id) {
|
||||
const ex = exOr(exercise_id)
|
||||
const best = best1RM(S, exercise_id, f)
|
||||
const series = e1rmSeries(S, exercise_id, f)
|
||||
// A null best has two very different causes: never trained, or trained only above the
|
||||
// rep cap. Without saying which, an exercise logged for years at 15 reps reads as "no
|
||||
// records for calf raise" — a confident statement about the opposite of the truth.
|
||||
const trainedAtAll = (S.workouts || []).some(w =>
|
||||
(w.entries || []).some(e => e.id === exercise_id && (e.sets || []).some(s => s.done)))
|
||||
// w/r (not weight/reps) matches pr_table and entry-view — every set in the API surface uses the same couple.
|
||||
return {
|
||||
exercise: { id: exercise_id, name: ex.n, body_part: ex.bp || null },
|
||||
formula: f,
|
||||
formula_note: `Estimates use the ${f} formula. Cap at ${REP_CAP} reps applies; r=1 is treated as the measurement, not an estimate.`,
|
||||
best: best ? { est: best.est, w: best.w, r: best.r, date: best.d } : null,
|
||||
no_estimate_reason: best ? null
|
||||
: trainedAtAll
|
||||
? `This exercise has logged sets, but none of them qualify: every set was above the ${REP_CAP}-rep cap, or carried no weight. That is not the same as never having trained it.`
|
||||
: 'No completed sets logged for this exercise.',
|
||||
trend: series.map(p => ({ date: p.d, est: p.y, w: p.w, r: p.r }))
|
||||
}
|
||||
}
|
||||
return {
|
||||
formula: f,
|
||||
formula_note: `Estimates use the ${f} formula. Cap at ${REP_CAP} reps applies; r=1 is treated as the measurement, not an estimate.`,
|
||||
pr_table: prTable(S, f)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** muscle_balance — training distribution per muscle over a period (week/month/all). */
|
||||
export const muscleBalance = {
|
||||
name: 'muscle_balance',
|
||||
description: 'Show which muscles the user has trained in a period, ranked by "effective sets" (volume in kg is intentionally not used — 100 kg leg press vs 12 kg lateral raise say nothing about which muscle worked harder). Reports worked muscles with a 0-4 relative level (1 = some work, 4 = most worked) and the muscles trained zero times in that period — useful for "what am I neglecting?" questions.',
|
||||
schema: {
|
||||
period: z.enum(['week', 'month', 'all']).describe('window: last 7 days, last 30 days, or all-time')
|
||||
},
|
||||
handler: ({ period }) => {
|
||||
const S = getState()
|
||||
if (!S) return noState()
|
||||
const now = Date.now()
|
||||
const cutoff = period === 'week' ? now - 7 * 86400000
|
||||
: period === 'month' ? now - 30 * 86400000
|
||||
: Number.NEGATIVE_INFINITY
|
||||
const workouts = (S.workouts || []).filter(w => (w.start || new Date(w.d + 'T12:00:00').getTime()) >= cutoff)
|
||||
const load = loadOfWorkouts(workouts)
|
||||
const { worked, missed } = rankOf(load)
|
||||
const levels = levelsOf(load)
|
||||
return {
|
||||
period,
|
||||
cutoff_iso: period === 'all' ? null : new Date(cutoff).toISOString().slice(0, 10),
|
||||
workouts_in_period: workouts.length,
|
||||
worked: worked.map(slug => ({ slug, name: muscleName(slug), level: levels[slug], effective_sets: Math.round((load[slug] || 0) * 10) / 10 })),
|
||||
neglected: missed.map(slug => ({ slug, name: muscleName(slug) })),
|
||||
muscle_order_head_to_toe: muscleOrder()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------- registration list ---------- */
|
||||
|
||||
export const TOOLS = [
|
||||
listRoutines, getRoutine, getWeekPlan, listWorkouts, getWorkout, getBodyweight, estimate1rm, muscleBalance
|
||||
]
|
||||
|
||||
function noState() {
|
||||
return {
|
||||
error: 'no synced state yet — sign in at least once from a device so the openGym api can save a state file for this profile',
|
||||
unit: 'kg'
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,535 @@
|
||||
// Tool-layer tests for mcp/src/tools.js, seeded from frontend/src/lib/demoSeed.js — the same
|
||||
// deterministic fixture the public demo runs on. The pure lib functions have their own 92
|
||||
// tests in frontend/src/lib/*.test.js; here we pin JSON shape + the user-facing edge cases
|
||||
// (rest-day override, missing routine, zero-workout history, no synced state, superset links).
|
||||
import { describe, beforeAll, afterAll, beforeEach, test, expect, vi } from 'vitest'
|
||||
import { buildDemoState } from '../../frontend/src/lib/demoSeed.js'
|
||||
import { EXDB } from '../../frontend/src/lib/exercises.js'
|
||||
import { _seedStateForTests } from '../src/state.js'
|
||||
import { TOOLS } from '../src/tools.js'
|
||||
|
||||
// Re-stated here so the assertions stand alone without reaching into lib internals to learn
|
||||
// the demo state's exact values.
|
||||
const FAKE_TODAY_ISO = '2026-07-27' // Monday — Push Day is scheduled
|
||||
const GOAL_WEIGHT = 77
|
||||
// Re-pinned against the v1.2.4 seed, which moved when the demo learned about bodyweight work
|
||||
// and effort. Hand-checked rather than copied off a failing run: 18412.5 is the sum of w×r
|
||||
// over the twenty completed sets, and 1.3 is 78.3 − 77.
|
||||
const NEWEST_WORKOUT = { date: '2026-07-24', name: 'Leg Day', volume: 18412.5, bw: 78.4, sets_done: 20, sets_total: 20, duration: '1h 11m' }
|
||||
const LATEST_BW = { date: '2026-07-27', weight: 78.3, delta: 1.3 }
|
||||
const LEG_PRESS_ID = '0739' // sled 45° leg press in the demo data
|
||||
const LEG_PRESS_BEST = { w: 152.5, r: 12, epley: 213.5, brzycki: 219.6 }
|
||||
|
||||
const byName = Object.fromEntries(TOOLS.map(t => [t.name, t.handler]))
|
||||
|
||||
let S = null
|
||||
|
||||
function call(name, params = {}) {
|
||||
const h = byName[name]
|
||||
if (!h) throw new Error(`unknown tool ${name}`)
|
||||
return h(params)
|
||||
}
|
||||
|
||||
function freshState() {
|
||||
const s = buildDemoState()
|
||||
s.unit = 'kg'
|
||||
return s
|
||||
}
|
||||
|
||||
// Pin "today" before building state so dayPlan/week alignment matches the assertions below.
|
||||
// `toFake: ['Date']` only — keeps fs.watch and the rest of the event loop real.
|
||||
beforeAll(() => {
|
||||
vi.useFakeTimers({ now: new Date(FAKE_TODAY_ISO + 'T12:00:00Z'), toFake: ['Date'] })
|
||||
S = freshState()
|
||||
_seedStateForTests(S)
|
||||
})
|
||||
|
||||
afterAll(() => {
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
// Fresh state per test — tests that mutate dayPlan can't leak into siblings.
|
||||
beforeEach(() => {
|
||||
S = freshState()
|
||||
_seedStateForTests(S)
|
||||
})
|
||||
|
||||
/* ---------- list_routines ---------- */
|
||||
|
||||
describe('list_routines', () => {
|
||||
test('returns the three starter routines with names + counts', () => {
|
||||
const r = call('list_routines')
|
||||
expect(r.unit).toBe('kg')
|
||||
expect(r.routines.length).toBe(3)
|
||||
expect(r.routines.map(x => x.name).sort()).toEqual(['Leg Day', 'Pull Day', 'Push Day'])
|
||||
r.routines.forEach(rn => {
|
||||
expect(typeof rn.id).toBe('string')
|
||||
expect(rn.exercise_count).toBeGreaterThan(0)
|
||||
expect(typeof rn.superset_groups).toBe('number')
|
||||
expect(['off', 'linear', 'greyskull', 'double', 'time']).toContain(rn.policy)
|
||||
})
|
||||
})
|
||||
|
||||
test('list_routines entries line up with get_routine (no id drift)', () => {
|
||||
const list = call('list_routines').routines
|
||||
list.forEach(summary => {
|
||||
const detail = call('get_routine', { routine_id: summary.id })
|
||||
expect(detail.id).toBe(summary.id)
|
||||
expect(detail.name).toBe(summary.name)
|
||||
expect(detail.exercises.length).toBe(summary.exercise_count)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
/* ---------- get_routine ---------- */
|
||||
|
||||
describe('get_routine', () => {
|
||||
test('returns the full exercise list for Push Day with per-exercise summaries', () => {
|
||||
const push = call('list_routines').routines.find(x => x.name === 'Push Day')
|
||||
const r = call('get_routine', { routine_id: push.id })
|
||||
expect(r.name).toBe('Push Day')
|
||||
expect(r.exercises.length).toBe(push.exercise_count)
|
||||
expect(r.policy_name).toBeTruthy()
|
||||
r.exercises.forEach(e => {
|
||||
expect(['reps', 'time', 'cardio']).toContain(e.mode)
|
||||
// Every summary has "N × M" with a non-ASCII × (the lib uses U+00D7, not ASCII 'x')
|
||||
expect(e.summary).toMatch(/\d+\s*×\s*\d+/)
|
||||
expect(e.superset_group === null || typeof e.superset_group === 'string').toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
test('throws ENOENT on a bogus routine id', () => {
|
||||
expect(() => call('get_routine', { routine_id: 'bogus' })).toThrow()
|
||||
})
|
||||
|
||||
test('reports superset links when an adjacent pair shares an sg id', () => {
|
||||
// Inject a superset pair into a clone, since the starter plan has none.
|
||||
S.routines[0].ex[0].sg = 'A'
|
||||
S.routines[0].ex[1].sg = 'A'
|
||||
const r = call('get_routine', { routine_id: S.routines[0].id })
|
||||
expect(r.exercises[0].superset_group).toBe('A')
|
||||
expect(r.exercises[1].superset_group).toBe('A')
|
||||
expect(r.exercises[2].superset_group).toBeNull()
|
||||
})
|
||||
|
||||
test('preserves mode + per-mode fields for a timed entry and a cardio entry', () => {
|
||||
// Append synthetic entries the starter plan doesn't ship: a timed plank (sec, no w) and a
|
||||
// cardio treadmill block (min + speed). These exercise ids don't exist in EXDB, so exOr
|
||||
// returns a placeholder named "Unknown exercise" — that's fine, we test the cfg fields.
|
||||
const push = S.routines.find(r => r.name === 'Push Day')
|
||||
push.ex.push({ id: 'synth-plank', sets: 3, sec: 60, weight: 0, mode: 'time' })
|
||||
push.ex.push({ id: 'synth-treadmill', sets: 1, min: 20, speed: 8, mode: 'cardio' })
|
||||
const r = call('get_routine', { routine_id: push.id })
|
||||
const t = r.exercises[r.exercises.length - 2]
|
||||
const c = r.exercises[r.exercises.length - 1]
|
||||
expect(t.mode).toBe('time')
|
||||
expect(t.sec).toBe(60)
|
||||
expect(t.reps).toBeUndefined()
|
||||
expect(c.mode).toBe('cardio')
|
||||
expect(c.min).toBe(20)
|
||||
expect(c.speed).toBe(8)
|
||||
})
|
||||
})
|
||||
|
||||
/* ---------- get_week_plan ---------- */
|
||||
|
||||
describe('get_week_plan', () => {
|
||||
test('reports each weekday in getDay() order (Sunday=0 … Saturday=6) with names', () => {
|
||||
const r = call('get_week_plan')
|
||||
expect(r.weekdays.length).toBe(7)
|
||||
expect(r.weekdays.map(d => d.weekday)).toEqual([0, 1, 2, 3, 4, 5, 6])
|
||||
expect(r.weekdays.map(d => d.weekday_name))
|
||||
.toEqual(['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'])
|
||||
})
|
||||
|
||||
test('today is the pinned Monday, and Push Day is scheduled', () => {
|
||||
const r = call('get_week_plan')
|
||||
expect(r.today).toBe(FAKE_TODAY_ISO)
|
||||
const push = S.routines.find(x => x.name === 'Push Day')
|
||||
expect(r.today_routine_id).toBe(push.id)
|
||||
expect(r.today_routine_name).toBe('Push Day')
|
||||
})
|
||||
|
||||
test('week[1]/[3]/[5] map to Push/Pull/Leg, other weekdays are rest', () => {
|
||||
const r = call('get_week_plan')
|
||||
const byWd = Object.fromEntries(r.weekdays.map(d => [d.weekday, d]))
|
||||
expect(byWd[1].routine_name).toBe('Push Day')
|
||||
expect(byWd[3].routine_name).toBe('Pull Day')
|
||||
expect(byWd[5].routine_name).toBe('Leg Day')
|
||||
;[0, 2, 4, 6].forEach(wd => {
|
||||
expect(byWd[wd].routine_id).toBeNull()
|
||||
expect(byWd[wd].routine_name).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
test('a "rest" override on today cancels the scheduled routine', () => {
|
||||
// Sanity check first — without the override, today has a routine.
|
||||
const before = call('get_week_plan')
|
||||
expect(before.today_routine_id).not.toBeNull()
|
||||
S.dayPlan[FAKE_TODAY_ISO] = 'rest'
|
||||
const after = call('get_week_plan')
|
||||
expect(after.today_routine_id).toBeNull()
|
||||
expect(after.today_routine_name).toBeNull()
|
||||
// The override is surfaced on the matching weekday entry.
|
||||
const todayWd = new Date(FAKE_TODAY_ISO + 'T12:00:00Z').getDay()
|
||||
expect(after.weekdays.find(d => d.weekday === todayWd).override_for_today_or_null).toBe('rest')
|
||||
})
|
||||
|
||||
test('a routine-id override on today replaces the weekday default', () => {
|
||||
const legs = S.routines.find(r => r.name === 'Leg Day')
|
||||
S.dayPlan[FAKE_TODAY_ISO] = legs.id
|
||||
const r = call('get_week_plan')
|
||||
expect(r.today_routine_id).toBe(legs.id)
|
||||
expect(r.today_routine_name).toBe('Leg Day')
|
||||
})
|
||||
|
||||
test('empty week + no override → today has no routine (a quiet Sunday)', () => {
|
||||
S.week = {}
|
||||
S.dayPlan = {}
|
||||
const r = call('get_week_plan')
|
||||
expect(r.today_routine_id).toBeNull()
|
||||
expect(r.today_routine_name).toBeNull()
|
||||
r.weekdays.forEach(d => expect(d.routine_id).toBeNull())
|
||||
})
|
||||
})
|
||||
|
||||
/* ---------- list_workouts ---------- */
|
||||
|
||||
describe('list_workouts', () => {
|
||||
test('newest first, with computed volume/duration matching hand-calculated values', () => {
|
||||
const r = call('list_workouts', {})
|
||||
expect(r.returned_count).toBeGreaterThan(0)
|
||||
expect(r.total_count).toBeGreaterThanOrEqual(r.returned_count)
|
||||
// newest-first check
|
||||
const dates = r.workouts.map(w => w.date)
|
||||
expect([...dates].sort().reverse()).toEqual(dates)
|
||||
// The newest workout is the Friday before the pinned Monday today.
|
||||
expect(r.workouts[0].date).toBe(NEWEST_WORKOUT.date)
|
||||
expect(r.workouts[0].routine_name).toBe(NEWEST_WORKOUT.name)
|
||||
expect(r.workouts[0].volume).toBe(NEWEST_WORKOUT.volume)
|
||||
expect(r.workouts[0].sets_done).toBe(NEWEST_WORKOUT.sets_done)
|
||||
expect(r.workouts[0].sets_planned).toBe(NEWEST_WORKOUT.sets_total)
|
||||
expect(r.workouts[0].sets_ratio).toBe(`${NEWEST_WORKOUT.sets_done}/${NEWEST_WORKOUT.sets_total}`)
|
||||
// Past the hour the lib switches format, so the expectation carries the rendered string
|
||||
// rather than assuming a "N min" shape that only held while the session was shorter.
|
||||
expect(r.workouts[0].duration).toBe(NEWEST_WORKOUT.duration)
|
||||
expect(r.workouts[0].bodyweight_at_workout).toBe(NEWEST_WORKOUT.bw)
|
||||
r.workouts.forEach(w => {
|
||||
expect(w.sets_done).toBeLessThanOrEqual(w.sets_planned)
|
||||
expect(typeof w.volume).toBe('number')
|
||||
expect(w.sets_ratio).toMatch(/^\d+\/\d+$/)
|
||||
})
|
||||
})
|
||||
|
||||
test('date range filter narrows results (closed interval, both endpoints inclusive)', () => {
|
||||
const all = call('list_workouts')
|
||||
expect(all.workouts.length).toBeGreaterThan(2)
|
||||
const earliest = all.workouts[all.workouts.length - 1].date
|
||||
// closed on both ends — earliest's own date should still appear
|
||||
const restricted = call('list_workouts', { from: earliest, to: earliest })
|
||||
expect(restricted.returned_count).toBe(1)
|
||||
expect(restricted.workouts[0].date).toBe(earliest)
|
||||
})
|
||||
|
||||
test('a from > to range yields zero workouts (not an error, not silently everything)', () => {
|
||||
const r = call('list_workouts', { from: '2026-07-27', to: '2026-01-01' })
|
||||
expect(r.returned_count).toBe(0)
|
||||
expect(r.workouts).toEqual([])
|
||||
expect(r.total_count).toBeGreaterThan(0) // total still reflects the real history
|
||||
})
|
||||
|
||||
test('respects limit (caps returned_count, never total_count)', () => {
|
||||
const r = call('list_workouts', { limit: 3 })
|
||||
expect(r.returned_count).toBeLessThanOrEqual(3)
|
||||
expect(r.total_count).toBeGreaterThanOrEqual(r.returned_count)
|
||||
})
|
||||
})
|
||||
|
||||
/* ---------- get_workout ---------- */
|
||||
|
||||
describe('get_workout', () => {
|
||||
test('matches the newest workout from list_workouts, every set has a readable label', () => {
|
||||
const list = call('list_workouts', {}).workouts
|
||||
const w = call('get_workout', { date: list[0].date })
|
||||
expect(w.date).toBe(list[0].date)
|
||||
expect(w.entries.length).toBe(list[0].exercise_count)
|
||||
expect(w.volume).toBe(list[0].volume)
|
||||
w.entries.forEach(e => {
|
||||
expect(['reps', 'time', 'cardio']).toContain(e.mode)
|
||||
e.sets.forEach(s => {
|
||||
expect(typeof s.label).toBe('string')
|
||||
expect(s.label.length).toBeGreaterThan(0)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
test('throws ENOENT on a date with no workout', () => {
|
||||
expect(() => call('get_workout', { date: '1900-01-01' })).toThrow()
|
||||
})
|
||||
|
||||
test('two sessions on one day are both reachable, and the date alone never picks one silently', () => {
|
||||
// Lifting in the morning, a run in the evening: ordinary, and it used to make the second
|
||||
// session unreachable while questions about it were answered with the first one's numbers.
|
||||
const day = '2026-07-26'
|
||||
S.workouts.push(
|
||||
{ id: 'w-morning', d: day, name: 'Pull', start: 1000, end: 1000 + 40 * 60000, vol: 0, prs: [], entries: [] },
|
||||
{ id: 'w-evening', d: day, name: 'Cardio', start: 2000, end: 2000 + 55 * 60000, vol: 0, prs: [], entries: [] }
|
||||
)
|
||||
_seedStateForTests(S)
|
||||
|
||||
const amb = call('get_workout', { date: day })
|
||||
expect(amb.ambiguous).toBe(true)
|
||||
expect(amb.workouts.map(w => w.id).sort()).toEqual(['w-evening', 'w-morning'])
|
||||
|
||||
// Each is retrievable by the id the ambiguous answer handed back.
|
||||
expect(call('get_workout', { workout_id: 'w-evening' }).routine_name).toBe('Cardio')
|
||||
expect(call('get_workout', { workout_id: 'w-morning' }).routine_name).toBe('Pull')
|
||||
// And list_workouts carries the id, or nothing above could ask for one.
|
||||
expect(call('list_workouts', {}).workouts.every(w => 'id' in w)).toBe(true)
|
||||
})
|
||||
|
||||
test('an unknown workout_id is an error, not the wrong workout', () => {
|
||||
expect(() => call('get_workout', { workout_id: 'nope' })).toThrow()
|
||||
expect(() => call('get_workout', {})).toThrow()
|
||||
})
|
||||
|
||||
test('renders reps/time/cardio set labels in the lib format on a synthetic workout', () => {
|
||||
// The starter routine has only reps-mode exercises — synthesise a workout that includes a
|
||||
// timed plank and a cardio row so the label rendering is actually exercised.
|
||||
S.workouts = [{
|
||||
id: 'synth-1', d: '2026-07-25', start: 0, end: 1800000, routineId: 'x', name: 'Synth',
|
||||
bw: 78, vol: 0, prs: [],
|
||||
entries: [
|
||||
{ id: 'squat', target: { mode: 'reps' }, sets: [{ w: 60, r: 5, done: true }] },
|
||||
{ id: 'plank', target: { mode: 'time' }, sets: [{ sec: 90, w: 0, done: true }] },
|
||||
{ id: 'plank-w', target: { mode: 'time' }, sets: [{ sec: 90, w: 20, done: true }] },
|
||||
{ id: 'row', target: { mode: 'cardio' }, sets: [{ min: 20, speed: 8, done: true }] }
|
||||
]
|
||||
}]
|
||||
const w = call('get_workout', { date: '2026-07-25' })
|
||||
expect(w.entries[0].sets[0].label).toBe('60×5') // reps
|
||||
// 90 sec → 1 min 30 sec → mm:ss label is "1:30" (fmtSec in history.js)
|
||||
expect(w.entries[1].sets[0].label).toBe('1:30') // 90 s in mm:ss, no weight
|
||||
expect(w.entries[2].sets[0].label).toBe('1:30 · 20') // weighted plank
|
||||
expect(w.entries[3].sets[0].label).toBe('20 min @ 8 km/h') // cardio
|
||||
})
|
||||
|
||||
test('infers cardio mode from the exercise id when the target has no mode key', () => {
|
||||
// Reproduces the review bug: the sheet saves a cardio target as {sets, min, speed} with
|
||||
// no mode and no id. modeOf must fall through to isCardio(id), which needs the id on the
|
||||
// cfg — entryView has to spread id into the cfg the way every app call site does.
|
||||
const CARDIO_ID = EXDB.find(e => e.bp === 'cardio').id
|
||||
S.workouts = [{
|
||||
id: 'synth-cardio', d: '2026-07-25', start: 0, end: 1800000, routineId: 'x', name: 'Synth',
|
||||
bw: 78, vol: 0, prs: [],
|
||||
entries: [
|
||||
{ id: CARDIO_ID, target: { sets: 1, min: 20, speed: 8 }, sets: [{ min: 20, speed: 8, done: true }] }
|
||||
]
|
||||
}]
|
||||
const w = call('get_workout', { date: '2026-07-25' })
|
||||
expect(w.entries[0].mode).toBe('cardio')
|
||||
expect(w.entries[0].sets[0].label).toBe('20 min @ 8 km/h')
|
||||
})
|
||||
})
|
||||
|
||||
/* ---------- get_bodyweight ---------- */
|
||||
|
||||
describe('get_bodyweight', () => {
|
||||
test('returns weigh-ins with the goal, the latest entry, and exact delta vs goal', () => {
|
||||
const r = call('get_bodyweight')
|
||||
expect(r.goal).toBe(GOAL_WEIGHT)
|
||||
expect(r.entries.length).toBeGreaterThan(0)
|
||||
// Newest is the LATEST_BW entry (deterministic from the demo seed at the pinned time).
|
||||
expect(r.latest).toBeTruthy()
|
||||
expect(r.latest.date).toBe(LATEST_BW.date)
|
||||
expect(r.latest.weight).toBe(LATEST_BW.weight)
|
||||
expect(r.latest.delta_vs_goal).toBe(LATEST_BW.delta)
|
||||
// entries are chronological
|
||||
const dates = r.entries.map(e => e.date)
|
||||
expect([...dates].sort()).toEqual(dates)
|
||||
})
|
||||
|
||||
test('closed date range returns a single matching entry on the boundary', () => {
|
||||
const all = call('get_bodyweight')
|
||||
expect(all.entries.length).toBeGreaterThan(1)
|
||||
const earliest = all.entries[0].date
|
||||
const restricted = call('get_bodyweight', { from: earliest, to: earliest })
|
||||
expect(restricted.entries.length).toBe(1)
|
||||
expect(restricted.entries[0].date).toBe(earliest)
|
||||
})
|
||||
|
||||
test('no goal set → delta_vs_goal is null, not NaN, not zero', () => {
|
||||
S.targetW = null
|
||||
const r = call('get_bodyweight')
|
||||
expect(r.goal).toBeNull()
|
||||
r.entries.forEach(e => expect(e.delta_vs_goal).toBeNull())
|
||||
expect(r.latest.delta_vs_goal).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
/* ---------- estimate_1rm ---------- */
|
||||
|
||||
describe('estimate_1rm', () => {
|
||||
test('PR table across all reps-mode exercises; epley formula is the default', () => {
|
||||
const r = call('estimate_1rm', {})
|
||||
expect(r.formula).toBe('epley')
|
||||
expect(Array.isArray(r.pr_table)).toBe(true)
|
||||
expect(r.pr_table.length).toBeGreaterThan(0)
|
||||
r.pr_table.forEach(p => {
|
||||
expect(typeof p.est).toBe('number')
|
||||
expect(p.est).toBeGreaterThan(0)
|
||||
expect(typeof p.exName).toBe('string')
|
||||
expect(typeof p.exId).toBe('string') // exId surfaced (regression test for the bug where callers passed exName as id)
|
||||
})
|
||||
// sort order: descending by est
|
||||
for (let i = 1; i < r.pr_table.length; i++) {
|
||||
expect(r.pr_table[i].est).toBeLessThanOrEqual(r.pr_table[i - 1].est)
|
||||
}
|
||||
})
|
||||
|
||||
test('top-of-table values exactly match the hand-computed Epley for the demo seed', () => {
|
||||
const r = call('estimate_1rm', {})
|
||||
const top = r.pr_table[0]
|
||||
// Demo seed's hardest set: sled 45° leg press at 152.5×12 (r=12 hits estimate1RM's REP_CAP).
|
||||
expect(top.exId).toBe(LEG_PRESS_ID)
|
||||
expect(top.w).toBe(LEG_PRESS_BEST.w)
|
||||
expect(top.r).toBe(LEG_PRESS_BEST.r)
|
||||
expect(top.est).toBeCloseTo(LEG_PRESS_BEST.epley, 1)
|
||||
})
|
||||
|
||||
test('per-exercise trend + best, with formula honours (Epley vs Brzycki numbers diverge)', () => {
|
||||
const epley = call('estimate_1rm', { exercise_id: LEG_PRESS_ID, formula: 'epley' })
|
||||
expect(epley.exercise.id).toBe(LEG_PRESS_ID)
|
||||
expect(epley.formula).toBe('epley')
|
||||
expect(Array.isArray(epley.trend)).toBe(true)
|
||||
expect(epley.best).toBeTruthy()
|
||||
expect(epley.best.w).toBe(LEG_PRESS_BEST.w)
|
||||
expect(epley.best.r).toBe(LEG_PRESS_BEST.r)
|
||||
expect(epley.best.est).toBeCloseTo(LEG_PRESS_BEST.epley, 1)
|
||||
const brz = call('estimate_1rm', { exercise_id: LEG_PRESS_ID, formula: 'brzycki' })
|
||||
expect(brz.formula).toBe('brzycki')
|
||||
expect(brz.best.est).toBeCloseTo(LEG_PRESS_BEST.brzycki, 1)
|
||||
// Distinct formulas must produce distinct estimates for this set.
|
||||
expect(epley.best.est).not.toBeCloseTo(brz.best.est, 1)
|
||||
})
|
||||
|
||||
test('exercises with no reps-mode history get null best + empty trend (not a 0 estimate)', () => {
|
||||
S.workouts = []
|
||||
_seedStateForTests(S)
|
||||
const r = call('estimate_1rm', { exercise_id: LEG_PRESS_ID })
|
||||
expect(r.best).toBeNull()
|
||||
expect(r.trend).toEqual([])
|
||||
const table = call('estimate_1rm', {}).pr_table
|
||||
expect(table).toEqual([])
|
||||
})
|
||||
|
||||
test('a null estimate says which kind of null it is', () => {
|
||||
// "Never trained" and "trained, but always above the rep cap" are opposite facts that both
|
||||
// arrive as best: null. Undistinguished, the second one reads as the first and an assistant
|
||||
// reports "no records" for an exercise in the log every week.
|
||||
S.workouts = [{
|
||||
id: 'w-highrep', d: '2026-07-26', name: 'Accessories', start: 1000, end: 1000 + 20 * 60000,
|
||||
vol: 0, prs: [],
|
||||
entries: [{
|
||||
id: LEG_PRESS_ID, target: { sets: 2, reps: 20, mode: 'reps' },
|
||||
sets: [{ w: 40, r: 20, done: true }, { w: 40, r: 18, done: true }]
|
||||
}]
|
||||
}]
|
||||
_seedStateForTests(S)
|
||||
|
||||
const capped = call('estimate_1rm', { exercise_id: LEG_PRESS_ID })
|
||||
expect(capped.best).toBeNull()
|
||||
expect(capped.no_estimate_reason).toMatch(/above the \d+-rep cap/)
|
||||
|
||||
// An exercise that genuinely has no sets must not borrow that explanation.
|
||||
const never = call('estimate_1rm', { exercise_id: '0684' })
|
||||
expect(never.best).toBeNull()
|
||||
expect(never.no_estimate_reason).toMatch(/No completed sets/)
|
||||
|
||||
// And the cap is stated on this branch at all, which it never used to be.
|
||||
expect(capped.formula_note).toMatch(/Cap at/)
|
||||
})
|
||||
|
||||
test('all three formulas are accepted', () => {
|
||||
['epley', 'brzycki', 'lombardi'].forEach(f => {
|
||||
const r = call('estimate_1rm', { exercise_id: LEG_PRESS_ID, formula: f })
|
||||
expect(r.formula).toBe(f)
|
||||
expect(r.best).not.toBeNull()
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
/* ---------- muscle_balance ---------- */
|
||||
|
||||
describe('muscle_balance', () => {
|
||||
test('reports worked + neglected muscles in head-to-toe order over all time', () => {
|
||||
const r = call('muscle_balance', { period: 'all' })
|
||||
expect(r.period).toBe('all')
|
||||
expect(r.workouts_in_period).toBeGreaterThan(0)
|
||||
expect(Array.isArray(r.worked)).toBe(true)
|
||||
expect(Array.isArray(r.neglected)).toBe(true)
|
||||
expect(r.muscle_order_head_to_toe[0]).toBe('trapezius')
|
||||
expect(r.muscle_order_head_to_toe.at(-1)).toBe('tibialis')
|
||||
r.worked.forEach(w => {
|
||||
expect(w.level).toBeGreaterThanOrEqual(1)
|
||||
expect(w.level).toBeLessThanOrEqual(4)
|
||||
expect(typeof w.name).toBe('string')
|
||||
expect(typeof w.effective_sets).toBe('number')
|
||||
})
|
||||
})
|
||||
|
||||
test('worked + neglected partition every muscle exactly once', () => {
|
||||
const r = call('muscle_balance', { period: 'all' })
|
||||
const all = new Set(r.muscle_order_head_to_toe)
|
||||
const worked = new Set(r.worked.map(w => w.slug))
|
||||
const neg = new Set(r.neglected.map(n => n.slug))
|
||||
expect(worked.size + neg.size).toBe(all.size)
|
||||
expect([...worked].every(s => all.has(s))).toBe(true)
|
||||
expect([...neg].every(s => all.has(s))).toBe(true)
|
||||
})
|
||||
|
||||
test('period windows are inclusive: week ≤ month ≤ all', () => {
|
||||
const all = call('muscle_balance', { period: 'all' }).workouts_in_period
|
||||
const month = call('muscle_balance', { period: 'month' }).workouts_in_period
|
||||
const week = call('muscle_balance', { period: 'week' }).workouts_in_period
|
||||
expect(week).toBeLessThanOrEqual(month)
|
||||
expect(month).toBeLessThanOrEqual(all)
|
||||
})
|
||||
|
||||
test('zero-workout state still returns all 18 muscles as neglected (not empty)', () => {
|
||||
S.workouts = []
|
||||
const r = call('muscle_balance', { period: 'all' })
|
||||
expect(r.workouts_in_period).toBe(0)
|
||||
expect(r.worked).toEqual([])
|
||||
expect(r.neglected.length).toBe(r.muscle_order_head_to_toe.length)
|
||||
expect(r.neglected.length).toBe(18)
|
||||
})
|
||||
})
|
||||
|
||||
/* ---------- shared: no-state fallback ---------- */
|
||||
|
||||
describe('shared: no-state fallback', () => {
|
||||
test('every tool answers gracefully when state is null (fresh account, never signed in)', () => {
|
||||
_seedStateForTests(null)
|
||||
// Each tool gets the minimum args its zod schema mandates; under real LLM-client use the
|
||||
// SDK rejects missing ones before the handler runs, so we only test the post-validation path.
|
||||
const calls = {
|
||||
list_routines: {},
|
||||
get_routine: { routine_id: '0031' },
|
||||
get_week_plan: {},
|
||||
list_workouts: {},
|
||||
get_workout: { date: '2026-07-26' },
|
||||
get_bodyweight: {},
|
||||
estimate_1rm: {},
|
||||
muscle_balance: { period: 'all' }
|
||||
}
|
||||
for (const t of TOOLS) {
|
||||
const r = t.handler(calls[t.name] || {})
|
||||
expect(r).toHaveProperty('error')
|
||||
}
|
||||
})
|
||||
|
||||
// Restore state after the no-state detour so a future test that forgets to seed sees the
|
||||
// failure rather than inherits null silently.
|
||||
afterAll(() => { _seedStateForTests(S = freshState()) })
|
||||
})
|
||||
@@ -0,0 +1,12 @@
|
||||
import { defineConfig } from 'vitest/config'
|
||||
|
||||
export default defineConfig({
|
||||
test: {
|
||||
include: ['test/**/*.test.js'],
|
||||
globals: false,
|
||||
environment: 'node',
|
||||
pool: 'forks',
|
||||
isolate: true,
|
||||
reporters: ['default']
|
||||
}
|
||||
})
|
||||
+1
-1
@@ -126,7 +126,7 @@
|
||||
<li class="no">No cross-device sync</li>
|
||||
</ul>
|
||||
<a class="btn" href="openGym.apk" download>Download for Android</a>
|
||||
<p class="meta">v1.2.3 · 4.3 MB · Android 6.0+ · signed APK, sideload (your browser will ask — that's normal outside the Play Store)</p>
|
||||
<p class="meta">v1.2.4 · 4.3 MB · Android 6.0+ · signed APK, sideload (your browser will ask — that's normal outside the Play Store)</p>
|
||||
<p class="meta"><b>iPhone?</b> Apple doesn't allow installs outside the App Store — use the
|
||||
self-hosted version as a home-screen app instead, or see <a href="docs.html#iphone">the docs</a>.</p>
|
||||
</div>
|
||||
|
||||
Reference in new issue
Block a user