Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9007aeefb6 | ||
|
|
71b22b3216 | ||
|
|
5bf149e60b | ||
|
|
c17632ea3d | ||
|
|
aac6b185ec | ||
|
|
3b720b0332 | ||
|
|
8fe980343d | ||
|
|
8323e06819 | ||
|
|
55b9dcb864 | ||
|
|
76a2d3b7a5 | ||
|
|
09baee49a7 | ||
|
|
374f6bdadc | ||
|
|
32c9a2380d | ||
|
|
9976b7a278 | ||
|
|
d4169690a6 | ||
|
|
55de70ad23 | ||
|
|
f860edd24a | ||
|
|
329eed4ce0 | ||
|
|
5d7e13361c | ||
|
|
1ba378b632 | ||
|
|
0e00e1029c | ||
|
|
011a3f7790 | ||
|
|
4e842b00e1 | ||
|
|
f3ba7de479 | ||
|
|
57f04febbe | ||
|
|
23a5b6c228 | ||
|
|
ed666df237 | ||
|
|
a95104b675 | ||
|
|
edde72f9cb | ||
|
|
237d1c5cf2 | ||
|
|
b42d2baa6e | ||
|
|
f32c4d0b73 |
No files matched your search
@@ -52,8 +52,27 @@ RP_NAME=openGym
|
||||
#
|
||||
# SESSION_DAYS=90
|
||||
|
||||
# ── Fitting into an existing stack (optional) ──────────────────────────────
|
||||
# The defaults assume openGym is on its own: an API service called `api` on
|
||||
# port 3000, and nginx listening on 80 inside the web container. If you are
|
||||
# merging this into a compose file that already has an `api`, or you front the
|
||||
# web container with your own reverse proxy, move them here. The web image
|
||||
# renders its nginx config at start-up, so these apply to a prebuilt image and
|
||||
# need no rebuild. BACKEND and PORT together are what /api is proxied to, so
|
||||
# they must name a service the web container can reach on your network:
|
||||
#
|
||||
# NGINX_PORT=80
|
||||
# BACKEND=api
|
||||
# PORT=3000
|
||||
|
||||
# ── Notifications (optional) ───────────────────────────────────────────────
|
||||
# Push works out of the box — nothing to set. VAPID keys are generated on first
|
||||
# run and saved to ./data/vapid.json. Each user's browser reports its own
|
||||
# timezone automatically, so the workout-day reminder fires at their local
|
||||
# time regardless of where the server runs or where they're travelling.
|
||||
#
|
||||
# Push services want a contact address for whoever operates the server, in case
|
||||
# they need to get in touch about your pushes. Defaults to your ORIGIN, which is
|
||||
# fine; set a mailto: if you would rather they mailed you:
|
||||
#
|
||||
# VAPID_SUBJECT=mailto:you@example.com
|
||||
@@ -1,9 +1,14 @@
|
||||
name: Publish Docker images
|
||||
|
||||
# Images are published from a *published release*, never from a bare tag push.
|
||||
# A tag that is later deleted (the versioning rule consolidates unreleased tags)
|
||||
# would otherwise leave its image tags behind in GHCR forever, and dependency
|
||||
# bots read those as a newer version. See issue #87.
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
tags: ['v*']
|
||||
release:
|
||||
types: [published]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
@@ -29,6 +34,19 @@ jobs:
|
||||
id: repo
|
||||
run: echo "owner=$(echo '${{ github.repository_owner }}' | tr '[:upper:]' '[:lower:]')" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Set version metadata
|
||||
id: version_meta
|
||||
run: |
|
||||
# On a release the ref is refs/tags/vX.Y.Z; on a main push it is a branch ref,
|
||||
# which would otherwise label the image "refs/heads/main".
|
||||
case "$GITHUB_REF" in
|
||||
refs/tags/*) VERSION="${GITHUB_REF#refs/tags/}" ;;
|
||||
*) VERSION="main-${GITHUB_SHA::7}" ;;
|
||||
esac
|
||||
echo "VERSION=$VERSION" >> $GITHUB_OUTPUT
|
||||
echo "VCS_REF=${GITHUB_SHA}" >> $GITHUB_OUTPUT
|
||||
echo "BUILD_DATE=$(date -u +'%Y-%m-%dT%H:%M:%SZ')" >> $GITHUB_OUTPUT
|
||||
|
||||
- uses: docker/setup-qemu-action@v4
|
||||
- uses: docker/setup-buildx-action@v4
|
||||
|
||||
@@ -52,6 +70,10 @@ jobs:
|
||||
context: ${{ matrix.context }}
|
||||
file: ${{ matrix.file }}
|
||||
platforms: linux/amd64,linux/arm64
|
||||
build-args: |
|
||||
VERSION=${{ steps.version_meta.outputs.VERSION }}
|
||||
VCS_REF=${{ steps.version_meta.outputs.VCS_REF }}
|
||||
BUILD_DATE=${{ steps.version_meta.outputs.BUILD_DATE }}
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
|
||||
@@ -43,6 +43,15 @@ jobs:
|
||||
working-directory: frontend
|
||||
- run: node scripts/check-locales.mjs
|
||||
working-directory: frontend
|
||||
# check-locales compares the packs to each other, so a key missing from ALL of them is
|
||||
# invisible to it. This walks src/ instead. Report-only for now: there is a known
|
||||
# backlog of untranslated demo-view strings to clear before it can fail the build.
|
||||
- run: node scripts/check-source-strings.mjs
|
||||
working-directory: frontend
|
||||
# The fatigue model must never read higher after a rest day than before it.
|
||||
# Property probe over ~108k comparisons; too slow for the unit suite, cheap here.
|
||||
- run: npm run test:fatigue-probe
|
||||
working-directory: frontend
|
||||
|
||||
mcp:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
@@ -1,5 +1,71 @@
|
||||
# Changelog
|
||||
|
||||
## v1.2.7 — 2026-08-18
|
||||
|
||||
The muscle map answers a third question. Balance showed where the volume went and Fatigue what was
|
||||
still recovering; Strength now names the exercises behind a muscle and what each one is worth in
|
||||
estimated 1RM. Fatigue itself got harder to fool — a set counts for more the closer it is to your
|
||||
maximum, and it can no longer creep upward across a rest week. In a session, supersets finally
|
||||
behave: pair them as you go, rest once per round, and drop an exercise you have decided against.
|
||||
|
||||
### The muscle map, read as strength
|
||||
|
||||
- **A per-muscle exercise breakdown** behind the muscle card — estimated 1RM per exercise, decay
|
||||
bars, and primary/secondary tags, with a best-weight fallback for holds and carries that have no
|
||||
reps to work from. Contributed by [@Space-Hermes](https://github.com/Space-Hermes) in
|
||||
[#92](https://github.com/DuarteSantos8/openGym/pull/92),
|
||||
[#93](https://github.com/DuarteSantos8/openGym/pull/93) and
|
||||
[#94](https://github.com/DuarteSantos8/openGym/pull/94).
|
||||
- **Fatigue is now intensity-weighted**, not volume alone: a set counts for more the closer it is
|
||||
to your estimated maximum. It also reads against a stable historical reference, so fatigue can no
|
||||
longer *rise* across a rest week, and bodyweight movements no longer register as zero load. A
|
||||
property probe over 108,000 comparisons runs in CI to keep it that way. Contributed by
|
||||
[@Space-Hermes](https://github.com/Space-Hermes) in
|
||||
[#55](https://github.com/DuarteSantos8/openGym/pull/55).
|
||||
|
||||
### In a session
|
||||
|
||||
- 🔗 **Supersets advance properly.** Completing a set moves to the next member of the group, the
|
||||
active exercise scrolls into view, and rest starts once the whole round is done rather than after
|
||||
each set. Contributed by [@Space-Hermes](https://github.com/Space-Hermes) in
|
||||
[#80](https://github.com/DuarteSantos8/openGym/pull/80).
|
||||
- ➖ **Remove an exercise from a running session**, with a superset-aware picker and a confirmation.
|
||||
Contributed by [@Space-Hermes](https://github.com/Space-Hermes) in
|
||||
[#83](https://github.com/DuarteSantos8/openGym/pull/83).
|
||||
- ⬅️ **The Android back button closes the open sheet** instead of leaving the screen or the app
|
||||
([#63]). Each open sheet gets its own history entry, so stacked sheets unwind one at a time.
|
||||
Contributed by [@Space-Hermes](https://github.com/Space-Hermes) in
|
||||
[#85](https://github.com/DuarteSantos8/openGym/pull/85).
|
||||
|
||||
### Self-hosting
|
||||
|
||||
- 🐳 **The API service no longer has to be called `api`** ([#99]). The web image builds its nginx
|
||||
config at startup from `BACKEND`, `PORT` and `NGINX_PORT`, all defaulted to today's values, so
|
||||
existing compose files are unaffected. Reported and fixed by
|
||||
[@GAS85](https://github.com/GAS85) in [#100](https://github.com/DuarteSantos8/openGym/pull/100).
|
||||
- **…and the shipped `docker-compose.yml` now actually passes those through.** The `web` service
|
||||
had no environment of its own and published a hardcoded `:80`, so setting `BACKEND` or
|
||||
`NGINX_PORT` in `.env` did nothing at all on the stock stack — the setting existed, the wiring
|
||||
did not. Both services now read `PORT` from the same place, so nginx cannot end up proxying to a
|
||||
port the API is not listening on. Defaults are unchanged, so an existing `.env` behaves exactly
|
||||
as before.
|
||||
- 🏷️ **Health checks and OCI image labels** on both images — source, licence, version, revision and
|
||||
build date, so image tooling can tell what it is holding. Contributed by
|
||||
[@GAS85](https://github.com/GAS85) in [#98](https://github.com/DuarteSantos8/openGym/pull/98).
|
||||
- **Images are published from a release, not from any tag** ([#87]). A tag that gets consolidated
|
||||
away before it becomes a release used to leave its image tags behind in the registry, where
|
||||
dependency bots read them as newer versions.
|
||||
|
||||
### Fixes
|
||||
|
||||
- **Imported warm-up sets were counted as work.** The importer marks them with `phase`, but several
|
||||
places still read the older boolean, so warm-ups from FitNotes/Strong/Hevy history inflated set
|
||||
counts, progression and the fatigue map.
|
||||
|
||||
[#63]: https://github.com/DuarteSantos8/openGym/issues/63
|
||||
[#87]: https://github.com/DuarteSantos8/openGym/issues/87
|
||||
[#99]: https://github.com/DuarteSantos8/openGym/issues/99
|
||||
|
||||
## v1.2.6 — 2026-08-11
|
||||
|
||||
The muscle map learned to answer a second question — not just where the volume went, but what is
|
||||
|
||||
@@ -61,21 +61,24 @@ as a home-screen app, passkey sign-in, offline support, sync across your phone a
|
||||
- 🗓️ **Reschedule any day** — sick, missed a session, or fewer gym days this week? Move a workout to another day without touching your weekly plan
|
||||
- ▶️ **Guided workouts** — it knows what day it is and starts today's session; asks your body weight first, pre-fills your weights from last time, rest timer, PR detection, per-exercise weight tracking
|
||||
- ☀️ **The screen stays awake while you train** — no unlocking the phone and finding your place again between every set. On for as long as a workout is running, released the moment you finish it, and switchable off in Settings
|
||||
- 🔗 **Supersets** — build them, and log them back-to-back with a rest only after the pair
|
||||
- 🔗 **Supersets** — plan them into a routine or pair two exercises *mid-session* with “make superset with previous/next”, then work through the group back-to-back with a single rest at the end of each round. Unpair at any time; a group of one dissolves itself
|
||||
- 🔥 **Warm-up sets** — mark the ramp-up rows as warm-ups and they stay out of the numbers that should not see them: no effect on your estimated 1RM, your progression, or the fatigue map, while still being there in the session where you need them. A weight change cascades down the rows that share their phase, not across the divide
|
||||
- ➖ **Change your mind mid-session** — add an exercise you decided to do, or remove one you didn't, without ending the workout. Removing a member of a superset asks which one
|
||||
- ⏱️ **Timed exercises** — planks, hangs, wall sits and loaded carries are logged by time, not reps, with a work timer that counts the set itself (separate from the rest timer) and logs the time you actually held. They can carry weight too
|
||||
- 📈 **Progression that follows a rule** — pick one per routine, override it per exercise: linear, **Greyskull LP** (AMRAP top set, double jumps, 10 % resets), double progression through a rep range, or adding time. Your weights are already right when the session opens, and every target says *why* it's that number. Missed reps never advance the load, stalls trigger a deload, and bodyweight exercises progress in reps instead
|
||||
- 💪 **Estimated 1RM** — per exercise, from your best eligible set (it names which one), with its own progress curve and a calculator for sets you haven't done. Won't guess above 12 reps
|
||||
- 🎯 **Effort per set, in your scale** — an optional third column rating how hard a set was, as **RIR** (reps left in the tank) or **RPE** (the same judgement on a 10-point scale). Off by default; each set keeps the scale it was logged with, and nothing else reads the value — your progression and 1RM are unaffected
|
||||
- 💪 **Bodyweight exercises, logged as bodyweight** — push-ups, pull-ups, dips and 300-odd others arrive knowing they carry no load, so there's no weight column and no working-weight prompt: one stepper, log the reps. Add a dip belt and it reads as an addition, and progression goes back to following the weight. Without one, reps climb — and past a ceiling you set, a set is added instead of a rep, up to the point where the honest advice is load or a harder variation
|
||||
- ↔️ **Reps per side** — for lunges, single-arm rows and the rest. You log the total, the app shows the split ("8 per side"), and the target steps in twos so it never lands on a number one side can't have
|
||||
- 🎲 **Freestyle sessions** — train without a plan and pick exercises as you go. Each one arrives prefilled from the last time you did it — same sets, same reps and weight by position — so an unplanned session doesn't start by asking you to retype last week
|
||||
- 🏃 **Cardio** — log time + speed, not just weight × reps
|
||||
- 📤 **Share a plan** — send someone your routines and week schedule as a small file (no workouts, no weigh-ins), or print it as a clean PDF. Importing merges, so their plan is never overwritten
|
||||
- 🔧 **Filter by equipment** — narrow the library to what you actually own; the options adapt to what you've picked, so every combination on screen has results behind it
|
||||
- ✨ **Your own exercises** — a name and a body part is enough; they behave like built-in ones everywhere, with an optional description instead of an animation
|
||||
- 🟩 **Activity heatmap** — a GitHub-style year view, shaded by time spent training
|
||||
- 💪 **Muscle map** — a front-and-back body diagram shaded by how much work each muscle got, over a week, a month or all time. It names the muscles you *haven't* trained in that period, previews what a routine hits while you build it, and shows what you just trained when you finish. Male or female figure, your pick
|
||||
- 💪 **Muscle map, three ways** — a front-and-back body diagram you can read as **Balance** (where the volume went, over a week, a month or all time — naming the muscles you *haven't* trained), **Fatigue** (what is still recovering, weighted by how close each set was to your maximum, decaying smoothly rather than expiring at a window edge) or **Strength** (how long since you trained each muscle, and behind every one the exercises that built it with their estimated 1RM). It previews what a routine hits while you build it, and shows what you just trained when you finish. Male or female figure, your pick
|
||||
- 🔔 **Push notifications** — rest-timer alerts even with the app closed, plus an optional reminder on days you have a workout planned but haven't logged one. Opt in per profile; keys are generated on first run, nothing to configure
|
||||
- 🔑 **Passkeys, not passwords** — Face ID / Touch ID / fingerprint login; each profile keeps its own data, synced across devices
|
||||
- 🔑 **Passkeys, not passwords** — Face ID / Touch ID / fingerprint login; each profile keeps its own data, synced across devices. Sign-ins last 90 days by default (configurable), and “sign out everywhere” in Settings ends every session on every device at once
|
||||
- 🛠️ **Admin dashboard** (optional) — for whoever runs the instance: who's training right now, per-user history, disable accounts, and invite-only signup. Off by default, so a fresh instance stays open with no admin
|
||||
- 🎨 **Designed, not assembled** — light/dark themes and 8 accent colors saved to your profile, over a hand-drawn icon set instead of emoji, so it looks the same on every phone
|
||||
- 🌍 **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
|
||||
@@ -133,7 +136,7 @@ mobile app is the install-and-done flavor.
|
||||
```
|
||||
|
||||
- **frontend/** — React + Vite (React Router + Zustand), built to static files **inside Docker**
|
||||
- **api/** — Node with no framework, one dependency (`@simplewebauthn/server`), storing everything as plain JSON files under `./data`
|
||||
- **api/** — Node with no framework, two dependencies (`@simplewebauthn/server` for passkeys, `web-push` for notifications), storing everything as plain JSON files under `./data`
|
||||
- **web/** — a multi-stage image that builds the frontend and serves it with nginx, proxying `/api` to the backend so it's all on **one origin** (passkeys require this)
|
||||
|
||||
## Your data
|
||||
@@ -152,12 +155,19 @@ All via `.env` (see `.env.example`):
|
||||
| `RP_ID` | Hostname passkeys are bound to | `localhost` |
|
||||
| `ORIGIN` | Full URL the app is served from | `http://localhost:8080` |
|
||||
| `WEB_PORT` | Host port for the web UI | `8080` |
|
||||
| `NGINX_PORT` | Port the web container listens on, inside the container | `80` |
|
||||
| `BACKEND` | Name of the API service that `/api` is proxied to — change it if yours isn't called `api` | `api` |
|
||||
| `PORT` | Port the API listens on; the web container proxies to the same value | `3000` |
|
||||
| `RP_NAME` | Name shown in the passkey prompt | `openGym` |
|
||||
| `SESSION_DAYS`| How long a sign-in lasts, in days | `90` |
|
||||
| `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)* |
|
||||
| `VAPID_SUBJECT` | Contact URL sent with push notifications | your `ORIGIN` |
|
||||
|
||||
Push notification keys are generated on first run and saved to `./data/vapid.json` — nothing to set.
|
||||
`DATA_DIR` is pinned to `/data` by `docker-compose.yml` and mapped to `./data` on the host; change the
|
||||
host side of that volume, not the variable.
|
||||
|
||||
## Roadmap
|
||||
|
||||
|
||||
@@ -1,8 +1,32 @@
|
||||
FROM node:22-alpine
|
||||
|
||||
ARG VERSION=dev
|
||||
ARG VCS_REF=dev
|
||||
ARG BUILD_DATE=unknown
|
||||
|
||||
LABEL maintainer="Duarte Santos https://github.com/DuarteSantos8" \
|
||||
org.opencontainers.image.title="opengym-api" \
|
||||
org.opencontainers.image.description="Backend for Self-hosted gym & body-weight tracker — plan routines, log workouts (supersets & cardio too), track your weight and progress, passkey login. Your data, your server." \
|
||||
org.opencontainers.image.source="https://github.com/DuarteSantos8/openGym" \
|
||||
org.opencontainers.image.url="https://ghcr.io/duartesantos8/opengym-api" \
|
||||
org.opencontainers.image.documentation="https://github.com/DuarteSantos8/openGym#readme" \
|
||||
org.opencontainers.image.licenses="AGPL-3.0-or-later" \
|
||||
org.opencontainers.image.version=$VERSION \
|
||||
org.opencontainers.image.revision=$VCS_REF \
|
||||
org.opencontainers.image.created=$BUILD_DATE
|
||||
|
||||
WORKDIR /app
|
||||
COPY package.json package-lock.json* ./
|
||||
RUN npm install --omit=dev && npm cache clean --force
|
||||
COPY server.js ./
|
||||
|
||||
ENV NODE_ENV=production
|
||||
ENV PORT=3000
|
||||
|
||||
EXPOSE 3000
|
||||
CMD ["node", "server.js"]
|
||||
|
||||
HEALTHCHECK --interval=5m \
|
||||
--timeout=5s \
|
||||
--retries=3 \
|
||||
CMD wget --spider -q "http://127.0.0.1:${PORT}/api/health" || exit 1
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "gym-api",
|
||||
"version": "1.2.6",
|
||||
"version": "1.2.7",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "server.js",
|
||||
|
||||
|
Before Width: | Height: | Size: 175 KiB After Width: | Height: | Size: 187 KiB |
|
Before Width: | Height: | Size: 320 KiB After Width: | Height: | Size: 320 KiB |
|
Before Width: | Height: | Size: 162 KiB After Width: | Height: | Size: 166 KiB |
|
Before Width: | Height: | Size: 182 KiB After Width: | Height: | Size: 296 KiB |
|
Before Width: | Height: | Size: 381 KiB After Width: | Height: | Size: 246 KiB |
@@ -29,7 +29,9 @@ services:
|
||||
restart: unless-stopped
|
||||
env_file: .env
|
||||
environment:
|
||||
- PORT=3000 # internal port (nginx proxies here) — do not change
|
||||
# The port the API listens on. web proxies to this same value, so the two
|
||||
# cannot drift — change it in .env and both follow.
|
||||
- PORT=${PORT:-3000}
|
||||
- DATA_DIR=/data
|
||||
volumes:
|
||||
- ./data:/data # users, passkeys, per-user state, session secret — BACK THIS UP
|
||||
@@ -48,7 +50,14 @@ services:
|
||||
api:
|
||||
condition: service_started
|
||||
ports:
|
||||
- "${WEB_PORT:-8080}:80"
|
||||
- "${WEB_PORT:-8080}:${NGINX_PORT:-80}"
|
||||
# nginx renders its config at start-up from these (web/nginx.conf.template),
|
||||
# so the API service does not have to be called `api`. Defaults are the old
|
||||
# hardcoded values, so an existing .env and an existing stack are unaffected.
|
||||
environment:
|
||||
- NGINX_PORT=${NGINX_PORT:-80}
|
||||
- BACKEND=${BACKEND:-api}
|
||||
- PORT=${PORT:-3000}
|
||||
volumes:
|
||||
- ./media/img:/usr/share/nginx/html/img:ro
|
||||
- ./media/gif:/usr/share/nginx/html/gif:ro
|
||||
@@ -8,14 +8,14 @@ This guide takes you from "just cloned it" to "using it from my phone over the i
|
||||
Requirements: [Docker](https://docs.docker.com/get-docker/) with the Compose plugin.
|
||||
|
||||
```bash
|
||||
git clone https://github.com/DuarteSantos8/gym-app opengym
|
||||
cd opengym
|
||||
git clone https://github.com/DuarteSantos8/openGym
|
||||
cd openGym
|
||||
cp .env.example .env
|
||||
docker compose pull # prebuilt images from ghcr.io (amd64 + arm64) — or skip and build from source
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
- First start downloads the exercise images/GIFs (~140 MB) once into `app/img` and `app/gif`.
|
||||
- First start downloads the exercise images/GIFs (~140 MB) once into `media/img` and `media/gif`.
|
||||
- Open **http://localhost:8080** and create a profile with a passkey.
|
||||
- Rather build from source than pull prebuilt images? Skip `docker compose pull` and run
|
||||
`docker compose up -d --build` instead — no Node needed locally either way.
|
||||
@@ -118,7 +118,30 @@ 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.
|
||||
|
||||
## 5. Backups
|
||||
## 5. Fitting it into an existing stack
|
||||
|
||||
The defaults assume openGym is the only thing here: a service called `api` on port 3000, and nginx
|
||||
on port 80 inside its container. If you are merging this into a compose file that already has an
|
||||
`api`, or you put the web container behind your own reverse proxy on a different port, four
|
||||
settings in `.env` move those without editing any config file:
|
||||
|
||||
```bash
|
||||
WEB_PORT=8080 # host port — what you browse to
|
||||
NGINX_PORT=80 # port the web container listens on, inside the container
|
||||
BACKEND=api # name of the API service that /api is proxied to
|
||||
PORT=3000 # port the API listens on; web proxies to the same value
|
||||
SESSION_DAYS=90 # how long a sign-in lasts
|
||||
```
|
||||
|
||||
The web image renders its nginx config from these when the container starts, so they take effect
|
||||
on a **prebuilt image** — no rebuild. `BACKEND` and `PORT` together are what `/api` is proxied to,
|
||||
so they have to name a service the web container can actually reach on your compose network.
|
||||
|
||||
Note the difference from `VITE_IMG_BASE` / `VITE_GIF_BASE` (see Troubleshooting): those are
|
||||
build-time values baked into the frontend bundle, and setting them next to `docker compose` does
|
||||
nothing to an image you pulled.
|
||||
|
||||
## 6. Backups
|
||||
|
||||
Everything is in `./data`:
|
||||
|
||||
@@ -129,7 +152,7 @@ tar czf opengym-backup-$(date +%F).tar.gz data/
|
||||
That archive contains all profiles, passkeys and workout history. Restore by unpacking it back
|
||||
into the project folder. (Individual users can also export their own data as JSON from Settings.)
|
||||
|
||||
## 6. Notifications
|
||||
## 7. Notifications
|
||||
|
||||
openGym can push two kinds of alert to your phone/desktop, even when the app isn't open:
|
||||
rest-timer-over, and a reminder on days you have a workout planned but haven't logged one yet.
|
||||
@@ -146,7 +169,11 @@ Wake Lock API is only available over HTTPS or on `http://localhost`, so on a pla
|
||||
instance the switch shows as unsupported. Nothing to configure server-side either way, and iOS
|
||||
refuses the lock while the phone is in Low Power Mode.
|
||||
|
||||
## 7. Updating
|
||||
Push services like a contact address for whoever runs the server, in case they ever need to reach
|
||||
you about your pushes. openGym sends your `ORIGIN` by default; set `VAPID_SUBJECT=mailto:you@example.com`
|
||||
in `.env` if you would rather they had an inbox.
|
||||
|
||||
## 8. Updating
|
||||
|
||||
Running prebuilt images:
|
||||
|
||||
@@ -175,7 +202,7 @@ downloaded media are untouched.
|
||||
| Media didn't download | `docker compose logs media`. Re-run `docker compose up -d`, or run `./scripts/fetch-media.sh`. |
|
||||
| Port 8080 already used | Set `WEB_PORT=9090` in `.env` (and update `ORIGIN` for local testing). |
|
||||
| No "Notifications" option in Settings | Requires a signed-in profile and HTTPS (or `localhost`) — guest mode and plain HTTP over LAN can't subscribe. |
|
||||
| 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). |
|
||||
| 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 7). |
|
||||
| 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. |
|
||||
|
||||
@@ -7,8 +7,8 @@ android {
|
||||
applicationId "ch.duartesantos.opengym"
|
||||
minSdkVersion rootProject.ext.minSdkVersion
|
||||
targetSdkVersion rootProject.ext.targetSdkVersion
|
||||
versionCode 7
|
||||
versionName "1.2.6"
|
||||
versionCode 8
|
||||
versionName "1.2.7"
|
||||
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
||||
aaptOptions {
|
||||
// Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps.
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "opengym-frontend",
|
||||
"version": "1.2.5",
|
||||
"version": "1.2.6",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "opengym-frontend",
|
||||
"version": "1.2.5",
|
||||
"version": "1.2.6",
|
||||
"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",
|
||||
"happy-dom": "^20.11.2",
|
||||
"linkedom": "^0.18.13",
|
||||
"vite": "^8.1.5",
|
||||
"vitest": "^4.1.10"
|
||||
@@ -1265,6 +1266,23 @@
|
||||
"integrity": "sha512-+OpjSaq85gvlZAYINyzKpLeiFkSC4EsC6IIiT6v6TLSU5k5U83fHGj9Lel8oKEXM0HqgrMVCjXPDPVICtxF7EQ==",
|
||||
"dev": true
|
||||
},
|
||||
"node_modules/@types/whatwg-mimetype": {
|
||||
"version": "3.0.2",
|
||||
"resolved": "https://registry.npmjs.org/@types/whatwg-mimetype/-/whatwg-mimetype-3.0.2.tgz",
|
||||
"integrity": "sha512-c2AKvDT8ToxLIOUlN51gTiHXflsfIFisS4pO7pDPoKouJCESkhZnEy623gwP9laCy5lnLDAw1vAzu2vM2YLOrA==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/ws": {
|
||||
"version": "8.18.1",
|
||||
"resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz",
|
||||
"integrity": "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/node": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@typescript/typescript-aix-ppc64": {
|
||||
"version": "7.0.2",
|
||||
"resolved": "https://registry.npmjs.org/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz",
|
||||
@@ -2071,6 +2089,19 @@
|
||||
"node": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/buffer-image-size": {
|
||||
"version": "0.6.4",
|
||||
"resolved": "https://registry.npmjs.org/buffer-image-size/-/buffer-image-size-0.6.4.tgz",
|
||||
"integrity": "sha512-nEh+kZOPY1w+gcCMobZ6ETUp9WfibndnosbpwB1iJk/8Gt5ZF2bhS6+B6bPYz424KtwsR6Rflc3tCz1/ghX2dQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/node": "*"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=4.0"
|
||||
}
|
||||
},
|
||||
"node_modules/camelcase": {
|
||||
"version": "5.3.1",
|
||||
"resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz",
|
||||
@@ -2599,8 +2630,7 @@
|
||||
"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"
|
||||
"dev": true
|
||||
},
|
||||
"node_modules/dargs": {
|
||||
"version": "7.0.0",
|
||||
@@ -3276,6 +3306,38 @@
|
||||
"uglify-js": "^3.1.4"
|
||||
}
|
||||
},
|
||||
"node_modules/happy-dom": {
|
||||
"version": "20.11.2",
|
||||
"resolved": "https://registry.npmjs.org/happy-dom/-/happy-dom-20.11.2.tgz",
|
||||
"integrity": "sha512-7MB+bJLkxu3SowAfBJbjW+c55kNz5tkR45gu2qzrxznezhLeN5YIlJbwUgSzlGc+qWoZ8Ykg71H5ezz69xixrw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/node": ">=20.0.0",
|
||||
"@types/whatwg-mimetype": "^3.0.2",
|
||||
"@types/ws": "^8.18.1",
|
||||
"buffer-image-size": "^0.6.4",
|
||||
"entities": "^7.0.1",
|
||||
"whatwg-mimetype": "^3.0.0",
|
||||
"ws": "^8.21.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/happy-dom/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/hard-rejection": {
|
||||
"version": "2.1.0",
|
||||
"resolved": "https://registry.npmjs.org/hard-rejection/-/hard-rejection-2.1.0.tgz",
|
||||
@@ -3349,8 +3411,7 @@
|
||||
"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"
|
||||
"dev": true
|
||||
},
|
||||
"node_modules/htmlparser2": {
|
||||
"version": "10.1.0",
|
||||
@@ -3364,7 +3425,6 @@
|
||||
"url": "https://github.com/sponsors/fb55"
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"domelementtype": "^2.3.0",
|
||||
"domhandler": "^5.0.3",
|
||||
@@ -3377,7 +3437,6 @@
|
||||
"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",
|
||||
@@ -3392,7 +3451,6 @@
|
||||
"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"
|
||||
},
|
||||
@@ -3405,7 +3463,6 @@
|
||||
"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"
|
||||
},
|
||||
@@ -3421,7 +3478,6 @@
|
||||
"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",
|
||||
@@ -3436,7 +3492,6 @@
|
||||
"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"
|
||||
},
|
||||
@@ -3938,7 +3993,6 @@
|
||||
"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",
|
||||
@@ -3963,7 +4017,6 @@
|
||||
"resolved": "https://registry.npmjs.org/boolbase/-/boolbase-2.0.0.tgz",
|
||||
"integrity": "sha512-DkVaaQHymRhpYEYo9x1oo7Q7B0Y6KJUsjm3c9eTyFDby4MHLBTwZ6ZDWBel5zrYxj1WsZgC5oLpiz+93MluXeA==",
|
||||
"dev": true,
|
||||
"license": "ISC",
|
||||
"engines": {
|
||||
"node": ">=20.19.0"
|
||||
},
|
||||
@@ -3977,7 +4030,6 @@
|
||||
"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",
|
||||
@@ -3998,7 +4050,6 @@
|
||||
"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"
|
||||
},
|
||||
@@ -4012,7 +4063,6 @@
|
||||
"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",
|
||||
@@ -4037,7 +4087,6 @@
|
||||
"url": "https://github.com/sponsors/fb55"
|
||||
}
|
||||
],
|
||||
"license": "BSD-2-Clause",
|
||||
"engines": {
|
||||
"node": ">=20.19.0"
|
||||
}
|
||||
@@ -4047,7 +4096,6 @@
|
||||
"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"
|
||||
},
|
||||
@@ -4064,7 +4112,6 @@
|
||||
"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",
|
||||
@@ -4083,7 +4130,6 @@
|
||||
"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"
|
||||
},
|
||||
@@ -4096,7 +4142,6 @@
|
||||
"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"
|
||||
},
|
||||
@@ -6172,8 +6217,7 @@
|
||||
"version": "0.2.0",
|
||||
"resolved": "https://registry.npmjs.org/uhyphen/-/uhyphen-0.2.0.tgz",
|
||||
"integrity": "sha512-qz3o9CHXmJJPGBdqzab7qAYuW8kQGKNEuoHFYrBwV6hWIMcpAmxDLXojcHfFr9US1Pe6zUswEIJIbLI610fuqA==",
|
||||
"dev": true,
|
||||
"license": "ISC"
|
||||
"dev": true
|
||||
},
|
||||
"node_modules/undici-types": {
|
||||
"version": "8.3.0",
|
||||
@@ -6418,6 +6462,16 @@
|
||||
"integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==",
|
||||
"dev": true
|
||||
},
|
||||
"node_modules/whatwg-mimetype": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-3.0.0.tgz",
|
||||
"integrity": "sha512-nt+N2dzIutVRxARx1nghPKGv1xHikU7HKdfafKkLNLindmPU/ch3U31NOCGGA/dmPcmb1VlofO0vnKAcsm0o/Q==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/whatwg-url": {
|
||||
"version": "5.0.0",
|
||||
"resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz",
|
||||
@@ -6494,6 +6548,28 @@
|
||||
"integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",
|
||||
"dev": true
|
||||
},
|
||||
"node_modules/ws": {
|
||||
"version": "8.21.3",
|
||||
"resolved": "https://registry.npmjs.org/ws/-/ws-8.21.3.tgz",
|
||||
"integrity": "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=10.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"bufferutil": "^4.0.1",
|
||||
"utf-8-validate": ">=5.0.2"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"bufferutil": {
|
||||
"optional": true
|
||||
},
|
||||
"utf-8-validate": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/xcode": {
|
||||
"version": "3.0.1",
|
||||
"resolved": "https://registry.npmjs.org/xcode/-/xcode-3.0.1.tgz",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "opengym-frontend",
|
||||
"private": true,
|
||||
"version": "1.2.6",
|
||||
"version": "1.2.7",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
@@ -9,7 +9,8 @@
|
||||
"build:mobile": "VITE_MOBILE=1 VITE_IMG_BASE=https://cdn.jsdelivr.net/gh/hasaneyldrm/exercises-dataset@7455efae41b330c265e7cd4b78dfa848e7ce5ebd/images/ VITE_GIF_BASE=https://cdn.jsdelivr.net/gh/hasaneyldrm/exercises-dataset@7455efae41b330c265e7cd4b78dfa848e7ce5ebd/videos/ vite build && cap sync",
|
||||
"preview": "vite preview",
|
||||
"test": "vitest run",
|
||||
"test:watch": "vitest"
|
||||
"test:watch": "vitest",
|
||||
"test:fatigue-probe": "node scripts/fatigue-monotonic-probe.mjs"
|
||||
},
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"dependencies": {
|
||||
@@ -28,6 +29,7 @@
|
||||
"@capacitor/cli": "^7.6.8",
|
||||
"@capacitor/ios": "^7.6.8",
|
||||
"@vitejs/plugin-react": "^6.0.3",
|
||||
"happy-dom": "^20.11.2",
|
||||
"linkedom": "^0.18.13",
|
||||
"vite": "^8.1.5",
|
||||
"vitest": "^4.1.10"
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
#!/usr/bin/env node
|
||||
// The companion to check-locales.mjs, which compares the locale packs to each other and so
|
||||
// cannot see a key that is missing from all of them: that renders English in every language
|
||||
// while every check stays green. This walks src/ instead, collects the literals actually
|
||||
// passed to t(), and reports the ones no pack defines.
|
||||
//
|
||||
// node scripts/check-source-strings.mjs # report only, exit 0
|
||||
// node scripts/check-source-strings.mjs --strict # exit 1 if anything is missing
|
||||
//
|
||||
// English is the source language and has no pack, so the key IS the English string.
|
||||
// Only literal single-argument calls are collected — t(variable) and template literals are
|
||||
// resolved at runtime and are deliberately out of scope.
|
||||
|
||||
import { readdirSync, readFileSync, statSync } from 'node:fs'
|
||||
import { dirname, join, relative } from 'node:path'
|
||||
import { fileURLToPath, pathToFileURL } from 'node:url'
|
||||
|
||||
const root = join(dirname(fileURLToPath(import.meta.url)), '..')
|
||||
const srcDir = join(root, 'src')
|
||||
const localesDir = join(srcDir, 'locales')
|
||||
const strict = process.argv.includes('--strict')
|
||||
|
||||
function walk(dir, out = []) {
|
||||
for (const name of readdirSync(dir)) {
|
||||
const p = join(dir, name)
|
||||
if (statSync(p).isDirectory()) {
|
||||
if (p === localesDir || name === 'instr' || name === 'node_modules') continue
|
||||
walk(p, out)
|
||||
} else if (/\.(js|jsx)$/.test(name) && !/\.test\.(js|jsx)$/.test(name)) {
|
||||
out.push(p)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// t('literal') / t("literal") — preceded by a non-identifier char so DateTimeFormat( misses.
|
||||
const CALL = /(^|[^A-Za-z0-9_$.])t\(\s*(['"])((?:\\.|(?!\2)[^\\])*)\2/g
|
||||
|
||||
const used = new Map()
|
||||
for (const file of walk(srcDir)) {
|
||||
const text = readFileSync(file, 'utf8')
|
||||
for (const m of text.matchAll(CALL)) {
|
||||
const key = m[3].replace(/\\(['"\\])/g, '$1')
|
||||
if (!key) continue
|
||||
if (!used.has(key)) used.set(key, new Set())
|
||||
used.get(key).add(relative(root, file))
|
||||
}
|
||||
}
|
||||
|
||||
const defined = new Set()
|
||||
for (const file of readdirSync(localesDir).filter(f => f.endsWith('.js'))) {
|
||||
const pack = (await import(pathToFileURL(join(localesDir, file)).href)).default
|
||||
for (const key of Object.keys(pack)) defined.add(key)
|
||||
}
|
||||
|
||||
const missing = [...used.keys()].filter(k => !defined.has(k)).sort()
|
||||
|
||||
if (!missing.length) {
|
||||
console.log(`${used.size} translated strings in src/, all present in the locale packs.`)
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
console.log(`${used.size} translated strings in src/, ${missing.length} defined in no locale pack:\n`)
|
||||
for (const key of missing) {
|
||||
console.log(` ${JSON.stringify(key)}`)
|
||||
for (const f of [...used.get(key)].sort()) console.log(` ${f}`)
|
||||
}
|
||||
console.log(`\nThese render English in all ${readdirSync(localesDir).filter(f => f.endsWith('.js')).length} translated languages.`)
|
||||
process.exit(strict ? 1 : 0)
|
||||
@@ -0,0 +1,100 @@
|
||||
import { FATIGUE_SCAN_MS, fatigueOf } from '../src/lib/recovery.js'
|
||||
|
||||
const HOUR = 60 * 60 * 1000
|
||||
const DAY = 24 * HOUR
|
||||
const BASE = Date.UTC(2026, 0, 31, 12)
|
||||
const ID = '1254'
|
||||
|
||||
const workout = (start, weight, count = 8) => ({
|
||||
d: new Date(start).toISOString(),
|
||||
start,
|
||||
entries: [{
|
||||
id: ID,
|
||||
sets: Array.from({ length: count }, () => ({ done: true, w: weight, r: 8 })),
|
||||
}],
|
||||
})
|
||||
|
||||
// Deterministic LCG: failures reproduce exactly without an external property-testing dependency.
|
||||
let seed = 0x5eed1234
|
||||
const random = () => {
|
||||
seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0
|
||||
return seed / 0x100000000
|
||||
}
|
||||
|
||||
let comparisons = 0
|
||||
let deletionComparisons = 0
|
||||
let largestIncrease = -Infinity
|
||||
for (let historyIndex = 0; historyIndex < 100; historyIndex += 1) {
|
||||
const sessionCount = 3 + Math.floor(random() * 10)
|
||||
const history = Array.from({ length: sessionCount }, () => {
|
||||
const ageHours = Math.floor(random() * 120 * 24)
|
||||
const weight = 40 + Math.floor(random() * 141)
|
||||
const count = 1 + Math.floor(random() * 12)
|
||||
return workout(BASE - ageHours * HOUR, weight, count)
|
||||
})
|
||||
|
||||
let previous = fatigueOf(history, BASE).chest
|
||||
for (let hour = 1; hour <= 1080; hour += 1) {
|
||||
const current = fatigueOf(history, BASE + hour * HOUR).chest
|
||||
const increase = current - previous
|
||||
largestIncrease = Math.max(largestIncrease, increase)
|
||||
if (increase > 1e-12) {
|
||||
throw new Error(
|
||||
`fatigue increased in history ${historyIndex} at hour ${hour}: ${previous} -> ${current}`,
|
||||
)
|
||||
}
|
||||
previous = current
|
||||
comparisons += 1
|
||||
}
|
||||
|
||||
const beforeDeletion = fatigueOf(history, BASE)
|
||||
for (let deleted = 0; deleted < history.length; deleted += 1) {
|
||||
const afterDeletion = fatigueOf(history.filter((_, index) => index !== deleted), BASE)
|
||||
for (const [slug, before] of Object.entries(beforeDeletion)) {
|
||||
if (afterDeletion[slug] > before + Number.EPSILON) {
|
||||
throw new Error(
|
||||
`deleting workout ${deleted} in history ${historyIndex} increased ${slug}: `
|
||||
+ `${before} -> ${afterDeletion[slug]}`,
|
||||
)
|
||||
}
|
||||
deletionComparisons += 1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (comparisons !== 108000) throw new Error(`expected 108000 comparisons, got ${comparisons}`)
|
||||
|
||||
// Pin the two history-edit invariants alongside the randomized property probes.
|
||||
const today = workout(BASE, 100, 5)
|
||||
const baseline = fatigueOf([today], BASE).chest
|
||||
for (const oldImport of [workout(BASE - 90 * DAY, 140, 10), workout(BASE - 90 * DAY, 100, 20)]) {
|
||||
if (fatigueOf([oldImport, today], BASE).chest !== baseline) {
|
||||
throw new Error('an import older than the scan changed current fatigue')
|
||||
}
|
||||
}
|
||||
|
||||
const deletionHistory = [
|
||||
workout(BASE - FATIGUE_SCAN_MS - DAY, 100, 15),
|
||||
workout(BASE - 3 * DAY, 100, 8),
|
||||
workout(BASE - 2 * DAY, 100, 8),
|
||||
workout(BASE - DAY, 60, 4),
|
||||
workout(BASE, 120, 10),
|
||||
]
|
||||
const beforePinnedDeletion = fatigueOf(deletionHistory, BASE)
|
||||
for (let deleted = 0; deleted < deletionHistory.length; deleted += 1) {
|
||||
const afterDeletion = fatigueOf(
|
||||
deletionHistory.filter((_, index) => index !== deleted),
|
||||
BASE,
|
||||
)
|
||||
for (const [slug, before] of Object.entries(beforePinnedDeletion)) {
|
||||
if (afterDeletion[slug] > before + Number.EPSILON) {
|
||||
throw new Error(`deleting workout ${deleted} increased ${slug}: ${before} -> ${afterDeletion[slug]}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`monotonic probe: ${comparisons} comparisons, largest increase ${largestIncrease}, PASS`)
|
||||
console.log(
|
||||
`history-edit probe: out-of-scan imports stable; ${deletionComparisons} randomized `
|
||||
+ 'single-workout deletion comparisons non-increasing, PASS',
|
||||
)
|
||||
@@ -35,13 +35,38 @@ function Sheet({ sheet }) {
|
||||
else el.style.transform = ''
|
||||
d.startY = null
|
||||
}
|
||||
// Mouse drag (desktop testing / trackpads): same swipe-to-dismiss behaviour.
|
||||
const onMouseDown = e => {
|
||||
if (e.button !== 0) return
|
||||
if (e.target.closest && e.target.closest('input[type=range], [data-nodrag]')) {
|
||||
drag.current = { startY: null, delta: 0 }
|
||||
return
|
||||
}
|
||||
const el = ref.current
|
||||
drag.current = { startY: el.scrollTop <= 0 ? e.clientY : null, delta: 0 }
|
||||
}
|
||||
const onMouseMove = e => {
|
||||
const el = ref.current, d = drag.current
|
||||
if (d.startY === null) return
|
||||
d.delta = e.clientY - d.startY
|
||||
if (d.delta > 0 && el.scrollTop <= 0) {
|
||||
e.preventDefault()
|
||||
el.style.transition = 'none'
|
||||
el.style.transform = `translateY(${d.delta}px)`
|
||||
} else d.delta = 0
|
||||
}
|
||||
const onMouseUp = () => onTouchEnd()
|
||||
|
||||
// non-passive touchmove so preventDefault works (bottom sheets only; centered dialogs have no ref)
|
||||
useEffect(() => {
|
||||
const el = ref.current
|
||||
if (!el) return
|
||||
el.addEventListener('touchmove', onTouchMove, { passive: false })
|
||||
return () => el.removeEventListener('touchmove', onTouchMove)
|
||||
window.addEventListener('mouseup', onMouseUp)
|
||||
return () => {
|
||||
el.removeEventListener('touchmove', onTouchMove)
|
||||
window.removeEventListener('mouseup', onMouseUp)
|
||||
}
|
||||
}, [])
|
||||
|
||||
const close = () => closeSheet(sheet.id)
|
||||
@@ -56,7 +81,8 @@ function Sheet({ sheet }) {
|
||||
return (
|
||||
<div>
|
||||
<div className="mback" onClick={() => { if (!sheet.locked) close() }} />
|
||||
<div className="sheet" ref={ref} onTouchStart={onTouchStart} onTouchEnd={onTouchEnd}>
|
||||
<div className="sheet" ref={ref} onTouchStart={onTouchStart} onTouchEnd={onTouchEnd}
|
||||
onMouseDown={onMouseDown} onMouseMove={onMouseMove} onMouseUp={onMouseUp} onMouseLeave={onMouseUp}>
|
||||
<div className="grab" />
|
||||
{sheet.render(close)}
|
||||
</div>
|
||||
@@ -66,8 +92,67 @@ function Sheet({ sheet }) {
|
||||
|
||||
export default function Modals() {
|
||||
const sheets = useUI(s => s.sheets)
|
||||
const closeSheet = useUI(s => s.closeSheet)
|
||||
const prevLen = useRef(0)
|
||||
const suppressPop = useRef(false)
|
||||
const pushedEntries = useRef(0)
|
||||
const sheetEntries = useRef([])
|
||||
|
||||
// Every opened sheet gets a history entry so Android back dismisses it instead of
|
||||
// leaving the page (issue #63). Keep the pushed-entry count and each active sheet's
|
||||
// live-entry status explicit: sheet count cannot tell whether popstate already spent
|
||||
// an entry (especially for a locked sheet) or whether several sheets opened at once.
|
||||
useEffect(() => {
|
||||
const prev = prevLen.current
|
||||
prevLen.current = sheets.length
|
||||
if (sheets.length > prev) {
|
||||
for (let i = prev; i < sheets.length; i++) {
|
||||
sheetEntries.current.push({ openedAt: location.href, live: true })
|
||||
history.pushState({ openGymSheet: true }, '')
|
||||
pushedEntries.current++
|
||||
}
|
||||
} else if (sheets.length < prev) {
|
||||
const closedEntries = sheetEntries.current.splice(sheets.length, prev - sheets.length)
|
||||
const rewind = closedEntries.filter(entry =>
|
||||
entry.live && !(typeof entry.openedAt === 'string' && location.href !== entry.openedAt)).length
|
||||
if (rewind > 0) {
|
||||
pushedEntries.current = Math.max(0, pushedEntries.current - rewind)
|
||||
suppressPop.current = true
|
||||
history.go(-rewind)
|
||||
}
|
||||
// Entries skipped because the app moved on remain in pushedEntries as deliberate
|
||||
// leaks until a later popstate consumes them with no corresponding active sheet.
|
||||
}
|
||||
}, [sheets.length])
|
||||
|
||||
useEffect(() => {
|
||||
const onPop = () => {
|
||||
if (suppressPop.current) { suppressPop.current = false; return }
|
||||
if (pushedEntries.current <= 0) return
|
||||
pushedEntries.current--
|
||||
// The browser has already spent one pushed entry. Mark the latest live active
|
||||
// sheet entry spent even when the sheet is locked; with no active entry this is a
|
||||
// moved-on leak, which is still accounted for by the counter decrement above.
|
||||
for (let i = sheetEntries.current.length - 1; i >= 0; i--) {
|
||||
if (sheetEntries.current[i].live) {
|
||||
sheetEntries.current[i].live = false
|
||||
break
|
||||
}
|
||||
}
|
||||
const top = sheets[sheets.length - 1]
|
||||
if (top && !top.locked) closeSheet(top.id)
|
||||
}
|
||||
window.addEventListener('popstate', onPop)
|
||||
return () => window.removeEventListener('popstate', onPop)
|
||||
}, [sheets, closeSheet])
|
||||
|
||||
// lock the page behind any open sheet (iOS-safe)
|
||||
useEffect(() => {
|
||||
if (!sheets.length) return
|
||||
const onKey = e => { if (e.key === 'Escape') { const top = useUI.getState().sheets[useUI.getState().sheets.length - 1]; if (top && !top.locked) useUI.getState().closeSheet(top.id) } }
|
||||
window.addEventListener('keydown', onKey)
|
||||
return () => window.removeEventListener('keydown', onKey)
|
||||
}, [sheets.length])
|
||||
useEffect(() => {
|
||||
if (!sheets.length) return
|
||||
const y = window.scrollY || 0
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
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 Modals from './Modals.jsx'
|
||||
|
||||
const mocks = vi.hoisted(() => {
|
||||
const listeners = new Set()
|
||||
const state = {
|
||||
sheets: [],
|
||||
closeSheet(id) {
|
||||
state.sheets = state.sheets.filter(sheet => sheet.id !== id)
|
||||
listeners.forEach(listener => listener())
|
||||
},
|
||||
}
|
||||
return {
|
||||
state,
|
||||
subscribe(listener) {
|
||||
listeners.add(listener)
|
||||
return () => listeners.delete(listener)
|
||||
},
|
||||
setSheets(sheets) {
|
||||
state.sheets = sheets
|
||||
listeners.forEach(listener => listener())
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('../store/useUI.js', async () => {
|
||||
const React = await import('react')
|
||||
const useUI = (selector = state => state) => React.useSyncExternalStore(
|
||||
mocks.subscribe,
|
||||
() => selector(mocks.state),
|
||||
() => selector(mocks.state),
|
||||
)
|
||||
useUI.getState = () => mocks.state
|
||||
return { useUI }
|
||||
})
|
||||
|
||||
let dom
|
||||
let root
|
||||
let container
|
||||
let historyMock
|
||||
let locationMock
|
||||
|
||||
function sheet(id, { locked = false, render = () => React.createElement('div') } = {}) {
|
||||
return { id, locked, kind: 'sheet', render }
|
||||
}
|
||||
|
||||
function installDom() {
|
||||
const parsed = parseHTML('<!doctype html><html><body><div id="root"></div></body></html>')
|
||||
dom = parsed.window
|
||||
dom.scrollTo = vi.fn()
|
||||
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
|
||||
|
||||
locationMock = { href: 'https://opengym.test/#/workout' }
|
||||
historyMock = { pushState: vi.fn(), go: vi.fn() }
|
||||
Object.defineProperty(globalThis, 'location', { configurable: true, value: locationMock })
|
||||
Object.defineProperty(globalThis, 'history', { configurable: true, value: historyMock })
|
||||
|
||||
container = document.getElementById('root')
|
||||
root = createRoot(container)
|
||||
}
|
||||
|
||||
async function setSheets(sheets) {
|
||||
await act(async () => { mocks.setSheets(sheets) })
|
||||
}
|
||||
|
||||
async function popstate() {
|
||||
await act(async () => { window.dispatchEvent(new dom.Event('popstate')) })
|
||||
}
|
||||
|
||||
function mouse(target, type, clientY) {
|
||||
const event = new dom.Event(type, { bubbles: true })
|
||||
Object.defineProperties(event, {
|
||||
button: { value: 0 },
|
||||
clientY: { value: clientY },
|
||||
})
|
||||
target.dispatchEvent(event)
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
mocks.state.sheets = []
|
||||
installDom()
|
||||
await act(async () => { root.render(React.createElement(Modals)) })
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
if (root) await act(async () => { root.unmount() })
|
||||
root = null
|
||||
container = null
|
||||
dom = null
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
describe('Modals sheet history accounting', () => {
|
||||
it('does not rewind a real page after back spends a locked FinishSummary entry', async () => {
|
||||
const confirm = sheet('confirm')
|
||||
const summary = sheet('summary', { locked: true })
|
||||
|
||||
await setSheets([confirm])
|
||||
expect(historyMock.pushState).toHaveBeenCalledTimes(1)
|
||||
|
||||
// ConfirmDialog closes and FinishSummary opens in the same batch: length remains one,
|
||||
// so the existing pushed entry now belongs to the locked summary.
|
||||
await setSheets([summary])
|
||||
await popstate()
|
||||
expect(mocks.state.sheets).toEqual([summary])
|
||||
|
||||
await act(async () => { mocks.state.closeSheet('summary') })
|
||||
expect(historyMock.go).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('pushes and rewinds the exact number of entries for batched sheets', async () => {
|
||||
await setSheets([sheet('one'), sheet('two')])
|
||||
expect(historyMock.pushState).toHaveBeenCalledTimes(2)
|
||||
|
||||
await setSheets([])
|
||||
expect(historyMock.go).toHaveBeenCalledTimes(1)
|
||||
expect(historyMock.go).toHaveBeenCalledWith(-2)
|
||||
})
|
||||
|
||||
it('closes stacked sheets one entry at a time on back', async () => {
|
||||
await setSheets([sheet('one'), sheet('two')])
|
||||
await popstate()
|
||||
|
||||
expect(mocks.state.sheets.map(item => item.id)).toEqual(['one'])
|
||||
expect(historyMock.pushState).toHaveBeenCalledTimes(2)
|
||||
|
||||
await popstate()
|
||||
expect(mocks.state.sheets).toEqual([])
|
||||
expect(historyMock.go).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('closes an unlocked sheet on back without rewinding its already-spent entry', async () => {
|
||||
await setSheets([sheet('open')])
|
||||
await popstate()
|
||||
|
||||
expect(mocks.state.sheets).toEqual([])
|
||||
expect(historyMock.go).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('accounts for a moved-on entry even when popstate has no current sheet', async () => {
|
||||
await setSheets([sheet('navigating')])
|
||||
locationMock.href = 'https://opengym.test/#/home'
|
||||
await setSheets([])
|
||||
expect(historyMock.go).not.toHaveBeenCalled()
|
||||
|
||||
// This spends the deliberately leaked entry with top === undefined.
|
||||
await popstate()
|
||||
|
||||
const locked = sheet('locked', { locked: true })
|
||||
await setSheets([locked])
|
||||
await popstate()
|
||||
await setSheets([])
|
||||
expect(historyMock.go).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('Modals mouse dragging', () => {
|
||||
it('leaves range sliders opted out of sheet dragging', async () => {
|
||||
await setSheets([sheet('slider', {
|
||||
render: () => React.createElement('input', { type: 'range' }),
|
||||
})])
|
||||
const sheetEl = container.querySelector('.sheet')
|
||||
const slider = container.querySelector('input[type="range"]')
|
||||
sheetEl.scrollTop = 0
|
||||
|
||||
await act(async () => {
|
||||
mouse(slider, 'mousedown', 10)
|
||||
mouse(sheetEl, 'mousemove', 150)
|
||||
window.dispatchEvent(new dom.Event('mouseup'))
|
||||
})
|
||||
|
||||
expect(sheetEl.style.transform).toBe('')
|
||||
expect(mocks.state.sheets).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('releases a drag when mouseup occurs outside the sheet', async () => {
|
||||
await setSheets([sheet('drag')])
|
||||
const sheetEl = container.querySelector('.sheet')
|
||||
sheetEl.scrollTop = 0
|
||||
|
||||
await act(async () => {
|
||||
mouse(sheetEl, 'mousedown', 10)
|
||||
mouse(sheetEl, 'mousemove', 60)
|
||||
})
|
||||
expect(sheetEl.style.transform).toBe('translateY(50px)')
|
||||
|
||||
await act(async () => { window.dispatchEvent(new dom.Event('mouseup')) })
|
||||
expect(sheetEl.style.transform).toBe('')
|
||||
|
||||
await act(async () => { mouse(sheetEl, 'mousemove', 120) })
|
||||
expect(sheetEl.style.transform).toBe('')
|
||||
expect(mocks.state.sheets).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
@@ -8,6 +8,7 @@
|
||||
// floor of 6 is only a convention about which sets are worth rating. RPE 8 == RIR 2.
|
||||
import { EFFORT, effortOf } from './history.js'
|
||||
import { weekKey } from './format.js'
|
||||
import { isWarmupRow } from './workout-model.js'
|
||||
|
||||
// At or below this a set is close enough to failure to be the kind that drives adaptation.
|
||||
// 3 rather than 2: the line is a convention, and drawn one rep too generously it still
|
||||
@@ -44,7 +45,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 && !s.warmup) fn(s, w, e) })))
|
||||
(e.sets || []).forEach(s => { if (s.done && !isWarmupRow(s)) fn(s, w, e) })))
|
||||
}
|
||||
|
||||
// A window in days, counted back from now. 0 = everything, which is also what an empty
|
||||
|
||||
@@ -116,6 +116,17 @@ describe('effortSummary', () => {
|
||||
it('survives a profile with no training at all', () => {
|
||||
expect(effortSummary({ workouts: [] }, 30)).toEqual({ done: 0, rated: 0, hard: 0, avg: null, hardPct: null })
|
||||
})
|
||||
|
||||
it('uses phase as authoritative while retaining legacy boolean warm-up fallback', () => {
|
||||
const summary = effortSummary(S(W(1, [
|
||||
{ rir: 0, phase: 'warmup' },
|
||||
{ rir: 1, phase: 'work', warmup: true },
|
||||
{ rir: 2 }, { rir: 2 }, { rir: 2 }, { rir: 2 },
|
||||
])), 0)
|
||||
expect(summary.done).toBe(5)
|
||||
expect(summary.rated).toBe(5)
|
||||
expect(summary.hard).toBe(5)
|
||||
})
|
||||
})
|
||||
|
||||
describe('hasEffort', () => {
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
// The persisted boundary for a finished session. Keep this pure so compatibility tests can
|
||||
// exercise the exact shape the UI writes without mounting React or mutating store state.
|
||||
export function buildCompletedWorkout(active, { end = Date.now(), prs = [], snapshotFor } = {}) {
|
||||
const entries = (active?.entries || []).map(entry => {
|
||||
const completed = {
|
||||
id: entry.id,
|
||||
sets: entry.sets,
|
||||
topW: entry.topW || null,
|
||||
target: entry.target || null,
|
||||
}
|
||||
const snapshot = typeof snapshotFor === 'function' ? snapshotFor(entry) : null
|
||||
if (snapshot && typeof snapshot === 'object' && !Array.isArray(snapshot) && Object.keys(snapshot).length) {
|
||||
completed.muscleSnapshot = { ...snapshot }
|
||||
}
|
||||
return completed
|
||||
}).filter(entry => entry.sets.some(set => set.done))
|
||||
|
||||
return {
|
||||
id: active.id,
|
||||
d: active.d,
|
||||
start: active.start,
|
||||
end,
|
||||
routineId: active.routineId,
|
||||
name: active.name,
|
||||
bw: active.bw,
|
||||
entries,
|
||||
prs,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { buildCompletedWorkout } from './finish-workout.js'
|
||||
|
||||
describe('completed workout boundary', () => {
|
||||
it('builds the same legacy-shaped record doFinishWorkout stores and keeps it visible', () => {
|
||||
const active = {
|
||||
id: 'active-1', d: '2026-08-08', start: 1000, routineId: 'routine-1', name: 'Push', bw: 80,
|
||||
entries: [{ id: '0025', sets: [{ done: true, w: 60, r: 8 }], topW: 60, target: { sets: 1, reps: 8 } }],
|
||||
}
|
||||
const completed = buildCompletedWorkout(active, { end: 2000, prs: [] })
|
||||
expect(completed).toEqual({
|
||||
id: 'active-1', d: '2026-08-08', start: 1000, end: 2000, routineId: 'routine-1', name: 'Push', bw: 80,
|
||||
entries: [{ id: '0025', sets: [{ done: true, w: 60, r: 8 }], topW: 60, target: { sets: 1, reps: 8 } }],
|
||||
prs: []
|
||||
})
|
||||
})
|
||||
|
||||
it('persists a muscle snapshot only when the caller supplies one', () => {
|
||||
const active = {
|
||||
id: 'active-1', d: '2026-08-08', start: 1000,
|
||||
entries: [
|
||||
{ id: 'catalogue', sets: [{ done: true }] },
|
||||
{ id: 'custom', sets: [{ done: true }] },
|
||||
],
|
||||
}
|
||||
const completed = buildCompletedWorkout(active, {
|
||||
end: 2000,
|
||||
snapshotFor: entry => entry.id === 'custom'
|
||||
? { n: 'Custom lift', muscleWeights: { chest: 1 } }
|
||||
: null,
|
||||
})
|
||||
|
||||
expect(completed.entries[0]).not.toHaveProperty('muscleSnapshot')
|
||||
expect(completed.entries[1].muscleSnapshot).toEqual({
|
||||
n: 'Custom lift', muscleWeights: { chest: 1 },
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,6 +1,16 @@
|
||||
// Pure helpers over the state object S (ported 1:1 from the vanilla app).
|
||||
import { todayISO, isoOf, weekKey, fmtNum } from './format.js'
|
||||
import { isCardio, isBodyweightEq } from './exercises.js'
|
||||
import { phaseForSet, modeForSet, modeForEntry, isWarmupRow, normalizeMode } from './workout-model.js'
|
||||
const objectOf = value => value && typeof value === 'object' && !Array.isArray(value) ? value : {}
|
||||
// Completed-state-independent work rows whose authoritative mode matches the requested mode.
|
||||
const workRowsForMode = (entry = {}, mode = 'reps') => {
|
||||
const source = objectOf(entry)
|
||||
const target = objectOf(source.target || source)
|
||||
const expectedMode = normalizeMode(mode, 'reps')
|
||||
return (Array.isArray(source.sets) ? source.sets : [])
|
||||
.filter(set => phaseForSet(set) === 'work' && modeForSet(set, target) === expectedMode)
|
||||
}
|
||||
// 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
|
||||
@@ -224,10 +234,7 @@ export function freestyleConfig(S, cfg) {
|
||||
export function bestWeightFor(S, exId) {
|
||||
let best = 0
|
||||
S.workouts.forEach(w => w.entries.forEach(e => {
|
||||
if (e.id === exId) {
|
||||
e.sets.forEach(s => { if (s.done && s.w > best) best = s.w })
|
||||
if (e.topW && e.topW > best) best = e.topW
|
||||
}
|
||||
if (e.id === exId) best = Math.max(best, bestWeightForEntry(e))
|
||||
}))
|
||||
return best
|
||||
}
|
||||
@@ -330,10 +337,10 @@ export function streakWeeks(S) {
|
||||
* 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 warm = isWarmupRow(rows[from])
|
||||
const next = rows.slice()
|
||||
for (let j = from + 1; j < next.length; j++) {
|
||||
if (!!next[j].warmup === warm && !next[j].done) {
|
||||
if (isWarmupRow(next[j]) === warm && !next[j].done) {
|
||||
if (value == null) delete next[j].w
|
||||
else next[j].w = value
|
||||
}
|
||||
@@ -343,14 +350,14 @@ export function cascadeWeight(rows, from, value) {
|
||||
|
||||
/** 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 firstWork = rows.findIndex(x => !isWarmupRow(x))
|
||||
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 }
|
||||
? { min: l ? l.min : (target.min || 20), speed: l ? l.speed : (target.speed || 8), done: false, phase: 'warmup', warmup: true }
|
||||
: mode === 'time'
|
||||
? { sec: l ? l.sec : (target.sec || 45), w: l ? (l.w || 0) : (target.weight || 0), done: false, warmup: true }
|
||||
: { w: l ? l.w : 0, r: l ? l.r : target.reps, done: false, warmup: true }
|
||||
? { sec: l ? l.sec : (target.sec || 45), w: l ? (l.w || 0) : (target.weight || 0), done: false, phase: 'warmup', warmup: true }
|
||||
: { w: l ? l.w : 0, r: l ? l.r : target.reps, done: false, phase: 'warmup', warmup: true }
|
||||
const next = rows.slice()
|
||||
next.splice(at, 0, warm)
|
||||
return next
|
||||
@@ -367,6 +374,57 @@ export function removeRowAt(rows, i) {
|
||||
/** 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,
|
||||
(n, e) => n + (e.sets || []).filter(s => s.done && !isWarmupRow(s)).length, 0,
|
||||
)
|
||||
}
|
||||
|
||||
const METRIC_MODES = ['reps', 'time', 'cardio']
|
||||
const completedRowsForMode = (entry, mode) => workRowsForMode(entry, mode).filter(s => s.done === true && !isWarmupRow(s))
|
||||
|
||||
export function metricRowsForEntry(entry, mode) {
|
||||
const requested = typeof mode === 'string' ? mode.trim().toLowerCase() : ''
|
||||
const resolved = METRIC_MODES.includes(requested) ? requested : metricModeForEntry(entry)
|
||||
return resolved ? completedRowsForMode(entry, resolved) : []
|
||||
}
|
||||
|
||||
/** The authoritative metric for an entry; reps rows take precedence over timed/cardio rows. */
|
||||
|
||||
export function metricModeForEntry(entry, fallback = null) {
|
||||
for (const mode of METRIC_MODES) {
|
||||
if (completedRowsForMode(entry, mode).length) return mode
|
||||
}
|
||||
return modeForEntry(entry, fallback)
|
||||
}
|
||||
|
||||
/** Best load from completed work rows, with a guarded reps-only legacy topW fallback. */
|
||||
|
||||
export function bestWeightForEntry(entry = {}) {
|
||||
const target = entry.target || entry
|
||||
const workRows = Array.isArray(entry.sets)
|
||||
? entry.sets.filter(s => phaseForSet(s) === 'work')
|
||||
: []
|
||||
const repsRows = metricRowsForEntry(entry, 'reps')
|
||||
if (!repsRows.length) {
|
||||
return workRows.reduce((best, set) => {
|
||||
if (set?.done !== true || isWarmupRow(set)) return best
|
||||
const weight = Number(set.w)
|
||||
return Number.isFinite(weight) && weight > best ? weight : best
|
||||
}, 0)
|
||||
}
|
||||
|
||||
let best = 0
|
||||
repsRows.forEach(set => {
|
||||
const weight = Number(set?.w)
|
||||
if (Number.isFinite(weight) && weight > best) best = weight
|
||||
})
|
||||
|
||||
const parentMode = modeForSet({}, target)
|
||||
const hasNonRepsWorkRow = workRows.some(set => modeForSet(set, target) !== 'reps')
|
||||
const hasWarmupRow = Array.isArray(entry.sets) && entry.sets.some(isWarmupRow)
|
||||
const topWeight = Number(entry.topW)
|
||||
// topW predates phase-tagged warm-ups. It remains a fallback for legacy all-work records,
|
||||
// but cannot override resolved work rows once any warm-up marker exists.
|
||||
if (parentMode === 'reps' && !hasNonRepsWorkRow && !hasWarmupRow
|
||||
&& Number.isFinite(topWeight) && topWeight > best) best = topWeight
|
||||
return best
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
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 { modeOf, isTimed, fmtSec, setLabel, defaultConfig, buildSets, freestyleConfig, exLine, workoutVolume, bestWeightFor, bestWeightForEntry, effortOf, stepEffort, capEffort, isBw, isPerSide, sideReps, repStep, cascadeWeight, insertWarmupRow, removeRowAt, workSetsDone, pairAdjacent, unpairSuperset, supersetUnits } from './history.js'
|
||||
import { EXDB } from './exercises.js'
|
||||
|
||||
// Real ids out of the shipped catalogue, so the body-part fallback is exercised for real.
|
||||
@@ -9,49 +9,6 @@ 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')
|
||||
@@ -520,6 +477,139 @@ describe('workoutVolume', () => {
|
||||
const w = { entries: [{ id: BW, target: { bodyweight: true }, sets: [{ w: 0, r: 20, done: true }] }] }
|
||||
expect(workoutVolume(w)).toBe(0)
|
||||
})
|
||||
|
||||
it('recognizes both warm-up schemas in work-set counts', () => {
|
||||
const w = {
|
||||
unit: 'kg',
|
||||
entries: [{
|
||||
id: LIFT,
|
||||
unit: 'kg',
|
||||
sets: [
|
||||
{ warmup: true, unit: 'kg', w: 20, r: 5, done: true },
|
||||
{ phase: 'warmup', unit: 'kg', w: 30, r: 5, done: true },
|
||||
{ phase: 'work', unit: 'kg', w: 60, r: 5, done: true },
|
||||
],
|
||||
}],
|
||||
}
|
||||
expect(workSetsDone(w)).toBe(1)
|
||||
})
|
||||
|
||||
it('does not use a warm-up as the previous best working weight', () => {
|
||||
expect(bestWeightFor({ workouts: [{ entries: [{ id: LIFT, topW: 120, sets: [
|
||||
{ phase: 'warmup', done: true, w: 120 },
|
||||
{ phase: 'work', done: true, w: 80 },
|
||||
] }] }] }, LIFT)).toBe(80)
|
||||
expect(bestWeightFor({ workouts: [{ entries: [{ id: LIFT, topW: 120, sets: [
|
||||
{ phase: 'warmup', done: true, w: 120 },
|
||||
] }] }] }, LIFT)).toBe(0)
|
||||
})
|
||||
|
||||
it('uses completed non-warm-up load for timed entries', () => {
|
||||
expect(bestWeightForEntry({ target: { mode: 'time' }, topW: 200, sets: [
|
||||
{ phase: 'warmup', sec: 30, w: 30, done: true },
|
||||
{ phase: 'work', sec: 60, w: 20, done: true },
|
||||
{ phase: 'work', sec: 75, w: 25, done: true },
|
||||
{ phase: 'work', sec: 90, w: 40, done: false },
|
||||
] })).toBe(25)
|
||||
})
|
||||
|
||||
it('does not report a repeated weighted timed hold as a new load PR (blocker 3)', () => {
|
||||
const prior = {
|
||||
id: LIFT,
|
||||
target: { mode: 'time' },
|
||||
sets: [{ phase: 'work', sec: 60, w: 20, done: true }],
|
||||
}
|
||||
const repeated = {
|
||||
id: LIFT,
|
||||
target: { mode: 'time' },
|
||||
sets: [{ phase: 'work', sec: 60, w: 20, done: true }],
|
||||
}
|
||||
const state = { workouts: [{ entries: [prior] }] }
|
||||
const repeatedWeight = Math.max(0, ...repeated.sets.filter(set => set.done).map(set => set.w || 0))
|
||||
|
||||
expect(bestWeightForEntry(prior)).toBe(20)
|
||||
expect(repeatedWeight > bestWeightFor(state, LIFT)).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
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('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' }])
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@@ -572,3 +662,25 @@ describe('session row helpers', () => {
|
||||
expect(next[0].w).toBe(70)
|
||||
})
|
||||
})
|
||||
|
||||
// The importer writes `phase: 'warmup'` and no `warmup` boolean (import-csv.js), so anything
|
||||
// reading the raw flag counts an imported warm-up as work. Read through the model instead.
|
||||
describe('warm-up rows identified by phase alone', () => {
|
||||
const imported = { w: 40, r: 10, done: true, phase: 'warmup' }
|
||||
const work = { w: 100, r: 5, done: true }
|
||||
|
||||
it('workSetsDone does not count a phase-only warm-up', () => {
|
||||
expect(workSetsDone({ entries: [{ sets: [imported, work] }] })).toBe(1)
|
||||
})
|
||||
|
||||
it('cascadeWeight keeps phase-only warm-ups in their own lane', () => {
|
||||
const rows = [
|
||||
{ w: 40, r: 10, phase: 'warmup' },
|
||||
{ w: 45, r: 10, phase: 'warmup' },
|
||||
{ w: 100, r: 5 },
|
||||
]
|
||||
const next = cascadeWeight(rows, 0, 50)
|
||||
expect(next[1].w).toBe(50)
|
||||
expect(next[2].w).toBe(100)
|
||||
})
|
||||
})
|
||||
@@ -20,6 +20,7 @@
|
||||
|
||||
import { EXDB, EXIDX } from './exercises.js'
|
||||
import { uid } from './format.js'
|
||||
import { isWarmupRow } from './workout-model.js'
|
||||
|
||||
/* ----------------------------------------------------------------- CSV ---- */
|
||||
|
||||
@@ -345,7 +346,8 @@ export function parseWorkoutCSV(text, { unit = 'kg' } = {}) {
|
||||
? num(cell(r, 'distanceKm'))
|
||||
: toKm(cell(r, 'distance'), cell(r, 'distanceUnit'))
|
||||
if (!w && !reps && !mins && !km) { skipped++; continue }
|
||||
if (/warm/i.test(cell(r, 'setType'))) warmups++
|
||||
const warmup = /warm/i.test(cell(r, 'setType'))
|
||||
if (warmup) warmups++
|
||||
|
||||
const key = keyOf(name)
|
||||
let id = resolved.get(key)
|
||||
@@ -368,8 +370,8 @@ export function parseWorkoutCSV(text, { unit = 'kg' } = {}) {
|
||||
// `u` carries the row's own unit into the conversion pass below and is dropped there —
|
||||
// it never reaches the stored set.
|
||||
const set = isCardio
|
||||
? { min: mins || 0, speed: mins > 0 ? Math.round(km / (mins / 60) * 10) / 10 : 0, done: true }
|
||||
: { w, r: reps || 0, done: true, u: rowUnit }
|
||||
? { min: mins || 0, speed: mins > 0 ? Math.round(km / (mins / 60) * 10) / 10 : 0, done: true, ...(warmup ? { phase: 'warmup' } : {}) }
|
||||
: { w, r: reps || 0, done: true, u: rowUnit, ...(warmup ? { phase: 'warmup' } : {}) }
|
||||
// Effort rides along only where the app can show it again: a weighted rep set. A treadmill
|
||||
// row with an RPE would have nowhere to put it. A set is kept on one scale, so a file
|
||||
// carrying both columns is read as RIR — the same precedence setLabel reads them back with.
|
||||
@@ -416,7 +418,7 @@ export function parseWorkoutCSV(text, { unit = 'kg' } = {}) {
|
||||
const day = byDate.get(d)
|
||||
const entries = [...day.ex.entries()].map(([id, ss]) => {
|
||||
const conv2 = ss.map(({ u, ...s }) => (s.w !== undefined ? { ...s, w: convRow({ ...s, u }) } : s))
|
||||
const mx = Math.max(0, ...conv2.map(s => s.w || 0))
|
||||
const mx = Math.max(0, ...conv2.filter(s => !isWarmupRow(s)).map(s => s.w || 0))
|
||||
return { id, sets: conv2, topW: mx || null }
|
||||
})
|
||||
const base = new Date(d + 'T00:00:00').getTime()
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { parseWorkoutCSV } from './import-csv.js'
|
||||
|
||||
const CSV = [
|
||||
'Date,Exercise,Weight,Reps,Set Type',
|
||||
'2026-08-08,Bench Press,100,5,Warm-up',
|
||||
'2026-08-08,Bench Press,80,5,Working',
|
||||
].join('\n')
|
||||
|
||||
describe('CSV warm-up provenance', () => {
|
||||
it('retains the imported warm-up phase and excludes it from topW', () => {
|
||||
const parsed = parseWorkoutCSV(CSV, { unit: 'kg' })
|
||||
const entry = parsed.workouts[0].entries[0]
|
||||
|
||||
expect(parsed.warmups).toBe(1)
|
||||
expect(entry.sets).toEqual([
|
||||
{ w: 100, r: 5, done: true, phase: 'warmup' },
|
||||
{ w: 80, r: 5, done: true },
|
||||
])
|
||||
expect(entry.topW).toBe(80)
|
||||
})
|
||||
})
|
||||
@@ -7,7 +7,8 @@
|
||||
// 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 , smOf } from './exercises.js'
|
||||
import { isWarmupRow } from './workout-model.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.
|
||||
@@ -69,21 +70,118 @@ const BY_BODYPART = {
|
||||
|
||||
const SECONDARY = 0.4 // a supporting muscle counts this much against a primary
|
||||
|
||||
/** Muscles one exercise trains: { slug: 0…1 }. */
|
||||
const arrayOf = value => Array.isArray(value) ? value : value == null || value === '' ? [] : [value]
|
||||
|
||||
// Completed history entries may retain a nested snapshot after their custom exercise is
|
||||
// deleted from the profile catalogue. Prefer that snapshot when the outer entry has no muscle
|
||||
// metadata of its own, while keeping direct/legacy entry fields authoritative when present.
|
||||
function metadataOf(ex) {
|
||||
if (!ex || typeof ex !== 'object') return ex
|
||||
const hasDirect = ['muscleGroups', 'muscles', 'targetMuscles'].some(key => Object.prototype.hasOwnProperty.call(ex, key))
|
||||
|| [ex.tg, ex.mg, ...arrayOf(ex.sm)].some(value => value != null && value !== '')
|
||||
return !hasDirect && ex.muscleSnapshot && typeof ex.muscleSnapshot === 'object' && !Array.isArray(ex.muscleSnapshot)
|
||||
? ex.muscleSnapshot
|
||||
: ex
|
||||
}
|
||||
|
||||
function explicitGroupsOf(ex) {
|
||||
if (!ex || typeof ex !== 'object') return null
|
||||
if (Object.prototype.hasOwnProperty.call(ex, 'muscleGroups')) {
|
||||
const groups = arrayOf(ex.muscleGroups)
|
||||
return groups.length ? groups : null
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(ex, 'muscles')) {
|
||||
const groups = arrayOf(ex.muscles)
|
||||
return groups.length ? groups : null
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(ex, 'targetMuscles')) {
|
||||
const groups = arrayOf(ex.targetMuscles)
|
||||
return groups.length ? groups : null
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** True only when the catalogue explicitly supplied muscle groups, not a body-part fallback. */
|
||||
export function hasExplicitMuscleMetadata(ex) {
|
||||
const source = metadataOf(ex)
|
||||
if (!source || typeof source !== 'object') return false
|
||||
const groups = explicitGroupsOf(source)
|
||||
if (groups && groups.some(value => canonicalMuscle(value))) return true
|
||||
return [source.tg, source.mg, ...arrayOf(source.sm)].some(value => canonicalMuscle(value))
|
||||
}
|
||||
|
||||
function canonicalMuscle(value) {
|
||||
const name = String(value || '').toLowerCase().trim()
|
||||
if (MUSCLES.includes(name)) return name
|
||||
return ALIAS[name] || null
|
||||
}
|
||||
|
||||
/** Canonical unique muscle groups, accepting both new arrays and legacy single fields. */
|
||||
export function muscleGroupsOf(ex) {
|
||||
const sourceEx = metadataOf(ex)
|
||||
const explicit = explicitGroupsOf(sourceEx)
|
||||
const source = explicit || [sourceEx?.tg, sourceEx?.mg, ...arrayOf(smOf(sourceEx))]
|
||||
const out = []
|
||||
source.forEach(value => {
|
||||
const slug = canonicalMuscle(value)
|
||||
if (slug && !out.includes(slug)) out.push(slug)
|
||||
})
|
||||
if (!out.length && explicit == null) Object.keys(BY_BODYPART[sourceEx?.bp] || {}).forEach(slug => { if (!out.includes(slug)) out.push(slug) })
|
||||
return out
|
||||
}
|
||||
|
||||
export const normalizeMuscleGroups = muscleGroupsOf
|
||||
|
||||
/** True when any requested group matches; an empty request is an intentionally unfiltered query. */
|
||||
export function matchesMuscleGroups(ex, requested) {
|
||||
const wanted = arrayOf(requested).map(canonicalMuscle).filter(Boolean)
|
||||
if (!wanted.length) return true
|
||||
const groups = new Set(muscleGroupsOf(ex))
|
||||
return wanted.some(group => groups.has(group))
|
||||
}
|
||||
|
||||
/** Muscles one exercise trains: { slug: 0…1 }. Duplicate metadata never adds load twice. */
|
||||
export function musclesOf(ex) {
|
||||
if (!ex) return {}
|
||||
const sourceEx = metadataOf(ex)
|
||||
if (sourceEx !== ex) return musclesOf(sourceEx)
|
||||
if (ex.muscleWeights && typeof ex.muscleWeights === 'object' && !Array.isArray(ex.muscleWeights)) {
|
||||
const snapshot = {}
|
||||
MUSCLES.forEach(slug => {
|
||||
const weight = Number(ex.muscleWeights[slug])
|
||||
if (Number.isFinite(weight) && weight > 0) snapshot[slug] = weight
|
||||
})
|
||||
if (Object.keys(snapshot).length) return snapshot
|
||||
}
|
||||
const out = {}
|
||||
const add = (name, w) => {
|
||||
const slug = ALIAS[String(name || '').toLowerCase().trim()]
|
||||
const slug = canonicalMuscle(name)
|
||||
if (slug) out[slug] = Math.max(out[slug] || 0, w)
|
||||
}
|
||||
add(ex.tg, 1)
|
||||
;smOf(ex).forEach(m => add(m, SECONDARY))
|
||||
const explicit = explicitGroupsOf(ex)
|
||||
if (explicit) explicit.forEach(m => add(m, 1))
|
||||
else {
|
||||
add(ex.tg, 1)
|
||||
add(ex.mg, SECONDARY)
|
||||
arrayOf(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
|
||||
}
|
||||
|
||||
/** Snapshot display and weighted muscle metadata into a completed history entry. */
|
||||
export function exerciseMuscleSnapshot(ex) {
|
||||
if (!ex || typeof ex !== 'object') return {}
|
||||
const out = {}
|
||||
if (ex.n != null) out.n = ex.n
|
||||
if (ex.bp != null) out.bp = ex.bp
|
||||
const weights = musclesOf(ex)
|
||||
if (Object.keys(weights).length) out.muscleWeights = { ...weights }
|
||||
if (hasExplicitMuscleMetadata(ex)) out.muscleGroups = [...muscleGroupsOf(ex)]
|
||||
return out
|
||||
}
|
||||
|
||||
/**
|
||||
* Training load per muscle, in "effective sets".
|
||||
* `items` is [{ id, sets }] — sets being a count, so a 4×8 bench press weighs four
|
||||
@@ -92,9 +190,12 @@ export function musclesOf(ex) {
|
||||
*/
|
||||
export function loadOf(items) {
|
||||
const load = {}
|
||||
items.forEach(({ id, sets }) => {
|
||||
items.forEach(item => {
|
||||
const { id, sets } = item || {}
|
||||
if (!sets) return
|
||||
const m = musclesOf(EXIDX[id])
|
||||
const historical = item.ex || item.exercise
|
||||
const source = historical?.muscleWeights ? historical : (EXIDX[id] || historical || item)
|
||||
const m = musclesOf(source)
|
||||
for (const slug in m) load[slug] = (load[slug] || 0) + m[slug] * sets
|
||||
})
|
||||
return load
|
||||
@@ -108,15 +209,15 @@ 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 && !s.warmup && (!pick || pick(s))).length }))))
|
||||
(w.entries || []).map(e => ({ id: e.id, ex: e.exercise || e, sets: (e.sets || []).filter(s => s.done && !isWarmupRow(s) && (!pick || pick(s))).length }))))
|
||||
|
||||
/** Load a routine *would* produce, from its planned set counts. */
|
||||
export const loadOfRoutine = routine =>
|
||||
loadOf((routine?.ex || []).map(c => ({ id: c.id, sets: c.sets || 1 })))
|
||||
loadOf((routine?.ex || []).map(c => ({ id: c.id, ex: c, sets: c.sets || 1 })))
|
||||
|
||||
/** 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 && !s.warmup).length })))
|
||||
loadOf((active?.entries || []).map(e => ({ id: e.id, ex: e.exercise || e, sets: (e.sets || []).filter(s => s.done && !isWarmupRow(s)).length })))
|
||||
|
||||
/**
|
||||
* Shade buckets 0–4 per muscle.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { EXIDX, EXDB, smOf } from './exercises.js'
|
||||
import { musclesOf } from './muscles.js'
|
||||
import { loadOfWorkouts, 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.
|
||||
@@ -42,3 +42,21 @@ describe('catalogue secondary additions', () => {
|
||||
expect(musclesOf(raw)).toHaveProperty('deltoids')
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
describe('map load with warm-up phases', () => {
|
||||
it('excludes warm-up sets from the by-sets-worked map', () => {
|
||||
const w = {
|
||||
id: 'w1', d: '2026-08-01', start: Date.UTC(2026, 7, 1, 10), unit: 'kg',
|
||||
entries: [{
|
||||
id: '0025',
|
||||
sets: [
|
||||
{ done: true, phase: 'warmup', w: 20, r: 8 },
|
||||
{ done: true, phase: 'work', w: 60, r: 8 },
|
||||
],
|
||||
}],
|
||||
}
|
||||
const load = loadOfWorkouts([w], null)
|
||||
expect(load.chest).toBe(1)
|
||||
})
|
||||
})
|
||||
@@ -1,3 +1,4 @@
|
||||
import { isWarmupRow } from './workout-model.js'
|
||||
// Estimated one-rep max (issue #18).
|
||||
//
|
||||
// Deliberately knows nothing about the exercise database: an estimate needs a weight AND a
|
||||
@@ -44,7 +45,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 || s.warmup) return
|
||||
if (!s.done || isWarmupRow(s)) 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)) }
|
||||
})
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
|
||||
import { modeOf, repStep } from './history.js'
|
||||
import { EXIDX } from './exercises.js'
|
||||
import { isWarmupRow } from './workout-model.js'
|
||||
|
||||
export const POLICIES = ['off', 'linear', 'greyskull', 'double', 'time']
|
||||
|
||||
@@ -103,7 +104,7 @@ export function readSession(entry, fallback) {
|
||||
const mode = modeOf({ ...target, id: entry && entry.id })
|
||||
// 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 sets = ((entry && entry.sets) || []).filter(s => !isWarmupRow(s))
|
||||
const planned = target.sets || sets.length
|
||||
const enough = sets.length >= planned
|
||||
|
||||
@@ -134,7 +135,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 && !s.warmup)) out.push({ d: w.d, ...readSession(entry, fallback) })
|
||||
if (entry && entry.sets.some(s => s.done && !isWarmupRow(s))) out.push({ d: w.d, ...readSession(entry, fallback) })
|
||||
})
|
||||
return out
|
||||
}
|
||||
@@ -255,7 +256,7 @@ export function applyPrescription(sets, p) {
|
||||
// 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
|
||||
if (s.done || isWarmupRow(s)) return s
|
||||
const o = { ...s }
|
||||
if (p.weight != null) o.w = p.weight
|
||||
if (p.reps != null) o.r = p.reps
|
||||
@@ -265,13 +266,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.
|
||||
const workRows = out.filter(s => !s.warmup)
|
||||
const workRows = out.filter(s => !isWarmupRow(s))
|
||||
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 })
|
||||
while (out.filter(s => !isWarmupRow(s)).length < p.sets) out.push({ ...seed, done: false })
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -476,6 +476,17 @@ describe('warm-up rows in session reads (round 3)', () => {
|
||||
expect(s.held).toEqual([45, 30])
|
||||
expect(s.ok).toBe(false) // the 30s work row is the miss, not the warm-up
|
||||
})
|
||||
|
||||
it('uses phase as authoritative and falls back to the legacy warm-up flag', () => {
|
||||
const s = readSession({ id: LIFT, target: { sets: 1, reps: 5 }, sets: [
|
||||
{ phase: 'warmup', w: 120, r: 20, done: true },
|
||||
{ phase: 'work', warmup: true, w: 60, r: 5, done: true },
|
||||
] })
|
||||
expect(s.count).toBe(1)
|
||||
expect(s.weight).toBe(60)
|
||||
expect(s.low).toBe(5)
|
||||
expect(s.ok).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('applyPrescription never touches warm-up rows (round 3)', () => {
|
||||
|
||||
@@ -1,14 +1,21 @@
|
||||
import { EXIDX } from './exercises.js'
|
||||
import { MUSCLES, musclesOf } from './muscles.js'
|
||||
import { isWarmupRow } from './workout-model.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
|
||||
export const FATIGUE_REF_VOLUME = 2000 // default reference: kg of intensity-weighted volume per session
|
||||
export const FATIGUE_MIN_SESSIONS = 3 // smoothing horizon for the causal per-muscle reference
|
||||
// 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
|
||||
export const BODYWEIGHT_REF_LOAD = 75 // kg assumed for bodyweight exercises when no load is logged
|
||||
export const CARDIO_TONNAGE_PER_MIN = 50 // duration proxy for cardio/timed work
|
||||
|
||||
// Preserve the shipped set-count signal when a completed custom/imported exercise has no load.
|
||||
// Two such sets therefore retain the old 1 - exp(-2 / 3) starting-fatigue reading.
|
||||
const ZERO_LOAD_SET_STIMULUS = FATIGUE_REF_VOLUME / 3
|
||||
|
||||
/** Exponential half-life for fatigue stimulus. */
|
||||
export const FATIGUE_HALF_LIFE_MS = 129600000
|
||||
@@ -54,31 +61,184 @@ function emptyMuscleMap(value) {
|
||||
return Object.fromEntries(MUSCLES.map(slug => [slug, value]))
|
||||
}
|
||||
|
||||
function clamp(value, min, max) {
|
||||
return Math.min(max, Math.max(min, value))
|
||||
// Epley one-rep-max estimate, matching onerm.js (REP_CAP included so high-rep sets do not
|
||||
// inflate the estimate). Used only to express a set's intensity relative to the lifter's own
|
||||
// capacity - the same formula the app already shows for estimated 1RM.
|
||||
const REP_CAP = 12
|
||||
const epley1RM = (load, reps) => load * (1 + Math.min(reps || 1, REP_CAP) / 30)
|
||||
|
||||
export const LB_TO_KG = 0.45359237
|
||||
|
||||
function numeric(value) {
|
||||
if (value === null || value === undefined || value === '' || typeof value === 'boolean') return null
|
||||
const n = Number(value)
|
||||
return Number.isFinite(n) ? n : null
|
||||
}
|
||||
|
||||
// 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 })
|
||||
}
|
||||
}
|
||||
function isPounds(unit) {
|
||||
return /^(?:lb|lbs|pound|pounds)$/i.test(String(unit ?? '').trim())
|
||||
}
|
||||
|
||||
function unitOf(...records) {
|
||||
for (const record of records) {
|
||||
if (!record || typeof record !== 'object') continue
|
||||
for (const key of ['unit', 'u', 'weightUnit', 'weight_unit', 'loadUnit']) {
|
||||
if (record[key] !== undefined && record[key] !== null && String(record[key]).trim() !== '') return record[key]
|
||||
}
|
||||
}
|
||||
return 'kg'
|
||||
}
|
||||
|
||||
function kgOf(value, unit) {
|
||||
const n = numeric(value)
|
||||
if (n === null) return 0
|
||||
return Math.max(0, n) * (isPounds(unit) ? LB_TO_KG : 1)
|
||||
}
|
||||
|
||||
// A bodyweight value stamped on a workout is the best historical value. When old records do not
|
||||
// carry one, use the current profile's canonical bodyweight supplied by Stats, then the stable
|
||||
// fallback used by the original fatigue model. `bodyweightKg` is already canonical; `bodyweight`
|
||||
// is accepted for callers that provide a display-unit value explicitly.
|
||||
function bodyweightKgFor(workout, opts = {}, stampedLoadUnit) {
|
||||
const stamped = numeric(workout?.bw) ?? numeric(workout?.bodyweight)
|
||||
if (stamped !== null) {
|
||||
return kgOf(stamped, unitOf(
|
||||
{ unit: workout?.bwUnit },
|
||||
{ unit: workout?.bodyweightUnit },
|
||||
workout,
|
||||
stampedLoadUnit && { unit: stampedLoadUnit },
|
||||
opts,
|
||||
))
|
||||
}
|
||||
const canonical = numeric(opts.bodyweightKg)
|
||||
if (canonical !== null) return Math.max(0, canonical)
|
||||
const display = numeric(opts.bodyweight)
|
||||
if (display !== null) return kgOf(display, opts.bodyweightUnit || opts.unit || opts.profileUnit)
|
||||
return BODYWEIGHT_REF_LOAD
|
||||
}
|
||||
|
||||
function bodyweightTarget(entry) {
|
||||
const target = entry?.target
|
||||
if (target && Object.prototype.hasOwnProperty.call(target, 'bodyweight')) return !!target.bodyweight
|
||||
if (entry && Object.prototype.hasOwnProperty.call(entry, 'bodyweight')) return !!entry.bodyweight
|
||||
return null
|
||||
}
|
||||
|
||||
function hasUnitStamp(...records) {
|
||||
return records.some(record => record && typeof record === 'object'
|
||||
&& ['unit', 'u', 'weightUnit', 'weight_unit', 'loadUnit'].some(key => Object.prototype.hasOwnProperty.call(record, key)
|
||||
&& record[key] !== undefined && record[key] !== null && String(record[key]).trim() !== ''))
|
||||
}
|
||||
|
||||
function bodyweightConfigured(ex, entry, set, workout, opts = {}) {
|
||||
const configured = bodyweightTarget(entry)
|
||||
if (configured !== null) return configured
|
||||
// Before target.bodyweight was persisted, a positive `w` on a catalogue bodyweight exercise
|
||||
// already meant an explicitly entered load. Keep those rows compatible when no body-mass
|
||||
// context is available; a stamped workout or a profile bodyweight makes the intended total-load
|
||||
// semantics unambiguous even for old entries.
|
||||
const added = kgOf(set?.w, unitOf(set, entry?.target, entry, workout, opts))
|
||||
const hasBodyweightContext = numeric(workout?.bw) !== null
|
||||
|| numeric(workout?.bodyweight) !== null
|
||||
|| numeric(opts.bodyweightKg) !== null
|
||||
|| numeric(opts.bodyweight) !== null
|
||||
|| hasUnitStamp(set, entry?.target, entry, workout)
|
||||
return ex?.eq === 'body weight' && (added === 0 || hasBodyweightContext)
|
||||
}
|
||||
|
||||
function loadKgFor(ex, entry, set, workout, opts = {}) {
|
||||
const setUnit = unitOf(set, entry?.target, entry, workout, opts)
|
||||
const addedKg = kgOf(set?.w, setUnit)
|
||||
const loadUnit = hasUnitStamp(set, entry?.target, entry) ? setUnit : undefined
|
||||
return bodyweightConfigured(ex, entry, set, workout, opts)
|
||||
? bodyweightKgFor(workout, opts, loadUnit) + addedKg
|
||||
: addedKg
|
||||
}
|
||||
|
||||
// Best Epley estimate inside one session. Keeping intensity context on the session makes a
|
||||
// scored stimulus independent of later imports/deletes; unlike an all-history maximum, a
|
||||
// 90-day-old CSV row cannot retroactively reweight today's sets.
|
||||
function session1RMs(workout, opts = {}) {
|
||||
const best = new Map()
|
||||
for (const entry of workout?.entries || []) {
|
||||
const ex = EXIDX[entry.id]
|
||||
for (const set of entry.sets || []) {
|
||||
const load = loadKgFor(ex, entry, set, workout, opts)
|
||||
if (set?.done !== true || !(load > 0) || !(set.r > 0)) continue
|
||||
const est = epley1RM(load, set.r)
|
||||
if (!best.has(entry.id) || est > best.get(entry.id)) best.set(entry.id, est)
|
||||
}
|
||||
}
|
||||
return best
|
||||
}
|
||||
|
||||
// Intensity-weighted tonnage for one completed set: load x reps x (load / exercise 1RM)^1.5.
|
||||
// The exponent saturates the "hard set" effect - a set at 90% of your 1RM counts ~0.81 of its
|
||||
// raw tonnage, one at 50% only ~0.35. Cardio, timed holds, and sets whose exercise has no
|
||||
// 1RM history stay unweighted (duration proxies, or intensity 1 for the first sessions).
|
||||
function setTonnage(ex, entry, set, workout, oneRm, opts = {}) {
|
||||
if (ex?.bp === 'cardio') {
|
||||
return Math.max(set?.min || 0, (set?.sec || 0) / 60) * CARDIO_TONNAGE_PER_MIN
|
||||
}
|
||||
if (set?.sec != null && set?.r == null) {
|
||||
return (set.sec / 60) * CARDIO_TONNAGE_PER_MIN
|
||||
}
|
||||
const reps = set?.r || 1
|
||||
const load = loadKgFor(ex, entry, set, workout, opts)
|
||||
const raw = load * reps
|
||||
// A bodyweight target is already an external-load-normalised total (body mass + any added
|
||||
// load). It has no meaningful barbell-style 1RM intensity ratio in the legacy data model, so
|
||||
// retain the monotonic total-load stimulus instead of letting a newly created low 1RM shrink
|
||||
// a weighted bodyweight set below the unloaded version.
|
||||
if (bodyweightConfigured(ex, entry, set, workout, opts)) return raw
|
||||
if (!(oneRm > 0) || !(load > 0)) return raw
|
||||
return raw * Math.min(1, load / oneRm) ** 1.5
|
||||
}
|
||||
|
||||
// One session's per-muscle stimulus, calculated only from that session. A completed zero-load
|
||||
// set gets the set-equivalent fallback instead of disappearing from fatigue.
|
||||
function sessionTonnages(workout, opts = {}) {
|
||||
const sums = emptyMuscleMap(0)
|
||||
const oneRms = session1RMs(workout, opts)
|
||||
for (const entry of workout?.entries || []) {
|
||||
const weights = musclesOf(EXIDX[entry.id])
|
||||
for (const set of entry.sets || []) {
|
||||
if (set?.done !== true) continue
|
||||
const measured = setTonnage(EXIDX[entry.id], entry, set, workout, oneRms.get(entry.id), opts)
|
||||
const tonnage = Number.isFinite(measured) && measured > 0 ? measured : ZERO_LOAD_SET_STIMULUS
|
||||
for (const [slug, weight] of Object.entries(weights)) {
|
||||
if (Object.prototype.hasOwnProperty.call(MUSCLES_BY_SLUG, slug)) sums[slug] += tonnage * weight
|
||||
}
|
||||
}
|
||||
}
|
||||
return stimuli
|
||||
return sums
|
||||
}
|
||||
|
||||
// Build normalised stimuli in workout order. The reference seen by a session is strictly the
|
||||
// reference left by earlier in-window sessions; the session cannot dilute its own score. The
|
||||
// downward-only EWMA is deliberate: removing any earlier workout can only raise a later
|
||||
// denominator (and removes its own positive stimulus), so deletion can never increase fatigue.
|
||||
// Rebuilding from the bounded scan also makes imports older than the scan exactly irrelevant.
|
||||
function fatigueStimuli(workouts, current, opts = {}) {
|
||||
const cutoff = current - FATIGUE_SCAN_MS
|
||||
const ordered = (workouts || [])
|
||||
.map((workout, index) => ({ workout, index, timestamp: workoutTimestamp(workout) }))
|
||||
.filter(item => Number.isFinite(item.timestamp) && item.timestamp > cutoff)
|
||||
.sort((a, b) => a.timestamp - b.timestamp || a.index - b.index)
|
||||
const references = emptyMuscleMap(FATIGUE_REF_VOLUME)
|
||||
const byMuscle = Object.fromEntries(MUSCLES.map(slug => [slug, []]))
|
||||
|
||||
for (const { workout, timestamp } of ordered) {
|
||||
const sums = sessionTonnages(workout, opts)
|
||||
for (const slug of MUSCLES) {
|
||||
const stimulus = sums[slug]
|
||||
if (!(stimulus > 0)) continue
|
||||
byMuscle[slug].push({ slug, timestamp, stimulus: stimulus / references[slug] })
|
||||
const ewma = references[slug] + (stimulus - references[slug]) / FATIGUE_MIN_SESSIONS
|
||||
references[slug] = Math.min(references[slug], ewma)
|
||||
}
|
||||
}
|
||||
return byMuscle
|
||||
}
|
||||
|
||||
const MUSCLES_BY_SLUG = Object.fromEntries(MUSCLES.map(slug => [slug, true]))
|
||||
@@ -94,10 +254,10 @@ function fatigueValue(events, now) {
|
||||
value += event.stimulus
|
||||
lastTimestamp = event.timestamp
|
||||
}
|
||||
value *= halfLifeDecay(now - lastTimestamp, FATIGUE_HALF_LIFE_MS)
|
||||
value *= halfLifeDecay(Math.max(0, 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)
|
||||
return 1 - Math.exp(-value)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -106,22 +266,22 @@ function fatigueValue(events, now) {
|
||||
* 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).
|
||||
* decayed to `now`, and normalised with the saturation curve 1 - exp(-v). Each session is scored
|
||||
* against a causal, downward-only EWMA left by strictly earlier in-window sessions. Session-local
|
||||
* intensity estimates and the causal reference make out-of-window imports irrelevant, while
|
||||
* deleting a workout can only remove stimulus and/or raise later references.
|
||||
* 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.
|
||||
* @param {{unit?: string}} options Reserved profile-level options; unit is supplied at the UI boundary.
|
||||
* @returns {Record<string, number>} Fatigue values keyed by every drawable muscle slug.
|
||||
*/
|
||||
export function fatigueOf(workouts, now) {
|
||||
export function fatigueOf(workouts, now, opts = {}) {
|
||||
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
|
||||
const byMuscle = fatigueStimuli(workouts, current, opts)
|
||||
for (const slug of MUSCLES) result[slug] = fatigueValue(byMuscle[slug], current)
|
||||
return result
|
||||
}
|
||||
@@ -138,12 +298,20 @@ export function fatigueOf(workouts, now) {
|
||||
* @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) {
|
||||
export function strengthOf(workouts, now, opts = {}) {
|
||||
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
|
||||
for (const workout of workouts || []) {
|
||||
const timestamp = workoutTimestamp(workout)
|
||||
if (!Number.isFinite(timestamp)) continue
|
||||
for (const entry of workout.entries || []) {
|
||||
if (!(entry.sets || []).some(set => set?.done === true && !isWarmupRow(set))) continue
|
||||
for (const slug of Object.keys(musclesOf(EXIDX[entry.id]))) {
|
||||
if (Object.prototype.hasOwnProperty.call(MUSCLES_BY_SLUG, slug) && timestamp > latest[slug]) {
|
||||
latest[slug] = timestamp
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const result = emptyMuscleMap(STRENGTH_FLOOR)
|
||||
@@ -174,8 +342,8 @@ export function strengthOf(workouts, now) {
|
||||
* @example
|
||||
* const avoid = fatiguedMuscles(workouts, now)
|
||||
*/
|
||||
export function fatiguedMuscles(workouts, now) {
|
||||
return Object.entries(fatigueOf(workouts, now))
|
||||
export function fatiguedMuscles(workouts, now, opts = {}) {
|
||||
return Object.entries(fatigueOf(workouts, now, opts))
|
||||
.filter(([, value]) => value > 0.5)
|
||||
.map(([slug]) => slug)
|
||||
}
|
||||
@@ -190,8 +358,8 @@ export function fatiguedMuscles(workouts, now) {
|
||||
* @example
|
||||
* const targets = detrainedMuscles(workouts, now)
|
||||
*/
|
||||
export function detrainedMuscles(workouts, now) {
|
||||
return Object.entries(strengthOf(workouts, now))
|
||||
export function detrainedMuscles(workouts, now, opts = {}) {
|
||||
return Object.entries(strengthOf(workouts, now, opts))
|
||||
.filter(([, value]) => value < 1)
|
||||
.map(([slug]) => slug)
|
||||
}
|
||||
@@ -1,9 +1,12 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
FATIGUE_HALF_LIFE_MS,
|
||||
FATIGUE_MIN_SESSIONS,
|
||||
FATIGUE_REF_VOLUME,
|
||||
FATIGUE_SCAN_MS,
|
||||
FATIGUE_STATES,
|
||||
BODYWEIGHT_REF_LOAD,
|
||||
CARDIO_TONNAGE_PER_MIN,
|
||||
STRENGTH_FLOOR,
|
||||
STRENGTH_FULL_MS,
|
||||
STRENGTH_HALF_LIFE_MS,
|
||||
@@ -13,7 +16,7 @@ import {
|
||||
halfLifeDecay,
|
||||
strengthOf,
|
||||
} from './recovery.js'
|
||||
import { EXDB } from './exercises.js'
|
||||
import { EXDB, registerCustom } from './exercises.js'
|
||||
import { MUSCLES, musclesOf } from './muscles.js'
|
||||
import { fatigueStateOf } from './recovery-view.js'
|
||||
|
||||
@@ -44,19 +47,37 @@ const workoutAt = (id, start, sets = [{ done: true }]) => ({
|
||||
start,
|
||||
entries: [{ id, sets: sets.map(set => ({ ...set })) }],
|
||||
})
|
||||
const V = 640 * (30 / 38) ** 1.5 // intensity-weighted tonnage of one 80x8 fixture set (its own Epley estimate implies intensity 30/38)
|
||||
|
||||
const doneWorkoutAt = (id, start, count = 1) =>
|
||||
workoutAt(id, start, Array.from({ length: count }, () => ({ done: true })))
|
||||
workoutAt(id, start, Array.from({ length: count }, () => ({ done: true, w: 80, r: 8 })))
|
||||
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))
|
||||
const referenceAfter = (reference, stimulus) => Math.min(
|
||||
reference,
|
||||
reference + (stimulus - reference) / FATIGUE_MIN_SESSIONS,
|
||||
)
|
||||
|
||||
const expectedFatigue = sessions => {
|
||||
let reference = FATIGUE_REF_VOLUME
|
||||
let normalised = 0
|
||||
for (const { stimulus, age = 0 } of sessions) {
|
||||
normalised += stimulus / reference * halfLifeDecay(age, FATIGUE_HALF_LIFE_MS)
|
||||
reference = referenceAfter(reference, stimulus)
|
||||
}
|
||||
return 1 - Math.exp(-normalised)
|
||||
}
|
||||
|
||||
describe('recovery constants', () => {
|
||||
it('exports the pinned windows, half-lives, floor, and state labels', () => {
|
||||
expect(FATIGUE_REF_VOLUME).toBe(3)
|
||||
expect(FATIGUE_REF_VOLUME).toBe(2000)
|
||||
expect(FATIGUE_SCAN_MS).toBe(30 * DAY)
|
||||
expect(FATIGUE_HALF_LIFE_MS).toBe(36 * HOUR)
|
||||
expect(BODYWEIGHT_REF_LOAD).toBe(75)
|
||||
expect(CARDIO_TONNAGE_PER_MIN).toBe(50)
|
||||
expect(STRENGTH_FULL_MS).toBe(14 * DAY)
|
||||
expect(STRENGTH_HALF_LIFE_MS).toBe(28 * DAY)
|
||||
expect(STRENGTH_FLOOR).toBe(0.5)
|
||||
@@ -88,24 +109,36 @@ describe('fatigueOf and strengthOf', () => {
|
||||
|
||||
for (const slug of MUSCLES) {
|
||||
const weight = WEIGHTED_WEIGHTS[slug] || 0
|
||||
expect(fatigue[slug]).toBeCloseTo(1 - Math.exp(-weight / FATIGUE_REF_VOLUME), 10)
|
||||
expect(fatigue[slug]).toBeCloseTo(1 - Math.exp(-V * weight / FATIGUE_REF_VOLUME), 10)
|
||||
expect(strength[slug]).toBe(weight ? 1 : STRENGTH_FLOOR)
|
||||
}
|
||||
// one set never crosses the fatigued threshold on the saturating curve
|
||||
// one set (80 x 8) never crosses the fatigued threshold on the saturating curve
|
||||
expect(fatiguedMuscles(workouts, NOW)).toEqual([])
|
||||
|
||||
// pure volume: one high-rep set at medium weight registers real tonnage (weighted by
|
||||
// its intensity - its own Epley estimate with the 12-rep cap is 50 x 40/30 = 70 kg)
|
||||
const highRep = [doneWorkoutAt(SINGLE.id, NOW, 1)]
|
||||
highRep[0].entries[0].sets[0].w = 50
|
||||
highRep[0].entries[0].sets[0].r = 50
|
||||
const weighted = 2500 * (50 / (50 * (1 + 12 / 30))) ** 1.5
|
||||
expect(fatigueOf(highRep, NOW)[SINGLE_SLUG]).toBeCloseTo(
|
||||
1 - Math.exp(-weighted / FATIGUE_REF_VOLUME),
|
||||
10,
|
||||
)
|
||||
expect(fatigueOf(highRep, NOW)[SINGLE_SLUG]).toBeGreaterThan(0.5)
|
||||
})
|
||||
|
||||
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(1)).toBeCloseTo(1 - Math.exp(-V / FATIGUE_REF_VOLUME), 10)
|
||||
expect(at0(5)).toBeCloseTo(1 - Math.exp(-5 * V / FATIGUE_REF_VOLUME), 10)
|
||||
expect(at0(12)).toBeCloseTo(1 - Math.exp(-12 * V / 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).toBeCloseTo(1 - Math.exp(-6 * V / 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]
|
||||
@@ -118,13 +151,22 @@ describe('fatigueOf and strengthOf', () => {
|
||||
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)
|
||||
expect(fatigue[slug]).toBeCloseTo(
|
||||
1 - Math.exp(-V * 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)
|
||||
expect(fatigue[WEIGHTED_PRIMARY_SLUG]).toBeCloseTo(
|
||||
1 - Math.exp(-V * 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)
|
||||
expect(fatigue[WEIGHTED_PRIMARY_SLUG]).toBeCloseTo(
|
||||
1 - Math.exp(-V * (0.5 ** 0.5) / FATIGUE_REF_VOLUME),
|
||||
10,
|
||||
)
|
||||
}
|
||||
}
|
||||
})
|
||||
@@ -153,9 +195,9 @@ describe('fatigue state boundaries', () => {
|
||||
|
||||
it('classifies exactly .25 as recovering and .2499 as ready', () => {
|
||||
const weight = WEIGHTED_WEIGHTS[SECONDARY_SLUG]
|
||||
const sets = 3
|
||||
const sets = 4
|
||||
const valueAt = target => {
|
||||
const age = FATIGUE_HALF_LIFE_MS * Math.log2(sets * weight / rawAt(target))
|
||||
const age = FATIGUE_HALF_LIFE_MS * Math.log2(sets * V * weight / rawAt(target))
|
||||
const value = fatigueOf([doneWorkoutAt(WEIGHTED.id, NOW - age, sets)], NOW)[SECONDARY_SLUG]
|
||||
expect(value).toBeCloseTo(target, 10)
|
||||
return stableFloat(value)
|
||||
@@ -166,10 +208,18 @@ describe('fatigue state boundaries', () => {
|
||||
})
|
||||
|
||||
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 sets = 4
|
||||
const atHalf = [doneWorkoutAt(
|
||||
SINGLE.id,
|
||||
NOW - FATIGUE_HALF_LIFE_MS * Math.log2(sets * V / rawAt(0.4999)),
|
||||
sets,
|
||||
)]
|
||||
const aboveHalf = [
|
||||
doneWorkoutAt(SINGLE.id, NOW - FATIGUE_HALF_LIFE_MS * Math.log2(sets / rawAt(0.5001)), sets),
|
||||
doneWorkoutAt(
|
||||
SINGLE.id,
|
||||
NOW - FATIGUE_HALF_LIFE_MS * Math.log2(sets * V / rawAt(0.5001)),
|
||||
sets,
|
||||
),
|
||||
]
|
||||
const half = fatigueOf(atHalf, NOW)[SINGLE_SLUG]
|
||||
const above = fatigueOf(aboveHalf, NOW)[SINGLE_SLUG]
|
||||
@@ -183,6 +233,92 @@ describe('fatigue state boundaries', () => {
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
describe('causal fatigue reference', () => {
|
||||
const loadedWorkout = (start, weight, count = 8) => workoutAt(
|
||||
'1254',
|
||||
start,
|
||||
Array.from({ length: count }, () => ({ done: true, w: weight, r: 8 })),
|
||||
)
|
||||
|
||||
it('scores each session against only the reference left by strictly earlier sessions', () => {
|
||||
const old = doneWorkoutAt(SINGLE.id, NOW - DAY)
|
||||
const today = doneWorkoutAt(SINGLE.id, NOW)
|
||||
const earlierReference = referenceAfter(FATIGUE_REF_VOLUME, V)
|
||||
const expected = 1 - Math.exp(-(
|
||||
V / FATIGUE_REF_VOLUME * halfLifeDecay(DAY, FATIGUE_HALF_LIFE_MS)
|
||||
+ V / earlierReference
|
||||
))
|
||||
|
||||
expect(fatigueOf([old, today], NOW)[SINGLE_SLUG]).toBeCloseTo(expected, 10)
|
||||
expect(fatigueOf([today], NOW)[SINGLE_SLUG]).toBeCloseTo(
|
||||
1 - Math.exp(-V / FATIGUE_REF_VOLUME),
|
||||
10,
|
||||
)
|
||||
})
|
||||
|
||||
it('keeps the 8x100x8 ten-day reproduction non-increasing as sessions leave the scan', () => {
|
||||
const base = Date.UTC(2026, 0, 31, 12)
|
||||
const workouts = [-20, -10, 0].map(days => loadedWorkout(base + days * DAY, 100))
|
||||
const observed = Array.from(
|
||||
{ length: 31 * 24 + 1 },
|
||||
(_, hour) => fatigueOf(workouts, base + hour * HOUR).chest,
|
||||
)
|
||||
|
||||
expect(observed[0]).toBeGreaterThan(0.5)
|
||||
expect(observed.at(-1)).toBe(0)
|
||||
for (let index = 1; index < observed.length; index += 1) {
|
||||
expect(observed[index]).toBeLessThanOrEqual(observed[index - 1] + Number.EPSILON)
|
||||
}
|
||||
})
|
||||
|
||||
it('ignores imports older than the scan, including their heavier 1RM data', () => {
|
||||
const today = loadedWorkout(NOW, 100, 5)
|
||||
const baseline = fatigueOf([today], NOW).chest
|
||||
const heavyImport = loadedWorkout(NOW - 90 * DAY, 140, 10)
|
||||
const highVolumeImport = loadedWorkout(NOW - 90 * DAY, 100, 20)
|
||||
|
||||
expect(fatigueOf([heavyImport, today], NOW).chest).toBe(baseline)
|
||||
expect(fatigueOf([highVolumeImport, today], NOW).chest).toBe(baseline)
|
||||
})
|
||||
|
||||
it('never increases fatigue when any one workout is deleted', () => {
|
||||
const workouts = [
|
||||
loadedWorkout(NOW - 40 * DAY, 100, 15),
|
||||
loadedWorkout(NOW - 3 * DAY, 100, 8),
|
||||
loadedWorkout(NOW - 2 * DAY, 100, 8),
|
||||
loadedWorkout(NOW - DAY, 60, 4),
|
||||
loadedWorkout(NOW, 120, 10),
|
||||
]
|
||||
const before = fatigueOf(workouts, NOW)
|
||||
|
||||
workouts.forEach((_, deletedIndex) => {
|
||||
const after = fatigueOf(workouts.filter((__, index) => index !== deletedIndex), NOW)
|
||||
for (const slug of MUSCLES) expect(after[slug]).toBeLessThanOrEqual(before[slug] + Number.EPSILON)
|
||||
})
|
||||
})
|
||||
|
||||
it('rates a lighter current week below repeating the established load', () => {
|
||||
const prior = [-21, -14, -7].map(days => loadedWorkout(NOW + days * DAY, 100))
|
||||
const lighter = fatigueOf([...prior, loadedWorkout(NOW, 50)], NOW).chest
|
||||
const repeated = fatigueOf([...prior, loadedWorkout(NOW, 100)], NOW).chest
|
||||
|
||||
expect(lighter).toBeLessThan(repeated)
|
||||
})
|
||||
|
||||
it('uses the last registered bodyweight for bodyweight exercises', () => {
|
||||
const bwEx = EXDB.find(ex => ex.eq === 'body weight' && ex.bp !== 'cardio')
|
||||
if (!bwEx) throw new Error('test requires a bodyweight exercise fixture')
|
||||
const slug = Object.keys(musclesOf(bwEx))[0]
|
||||
const workout = { d: new Date(NOW).toISOString(), start: NOW, entries: [{ id: bwEx.id, sets: [{ done: true, r: 10 }] }] }
|
||||
const at80 = fatigueOf([workout], NOW, { bodyweightKg: 80 })[slug]
|
||||
const at90 = fatigueOf([workout], NOW, { bodyweightKg: 90 })[slug]
|
||||
expect(at80).toBeCloseTo(1 - Math.exp(-800 / FATIGUE_REF_VOLUME), 10)
|
||||
expect(at90).toBeCloseTo(1 - Math.exp(-900 / FATIGUE_REF_VOLUME), 10)
|
||||
expect(at90).toBeGreaterThan(at80)
|
||||
})
|
||||
})
|
||||
|
||||
describe('strengthOf', () => {
|
||||
const strengthAt = age => strengthOf([doneWorkoutAt(SINGLE.id, NOW - age)], NOW)[SINGLE_SLUG]
|
||||
|
||||
@@ -210,10 +346,15 @@ describe('accumulation and purity', () => {
|
||||
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),
|
||||
(sum, age) => sum + V * 0.5 ** (age / FATIGUE_HALF_LIFE_MS),
|
||||
0,
|
||||
)
|
||||
const expected = 1 - Math.exp(-raw / FATIGUE_REF_VOLUME)
|
||||
const firstAge = ages[0]
|
||||
const secondAge = ages[1]
|
||||
const expected = expectedFatigue([
|
||||
{ stimulus: V, age: firstAge },
|
||||
{ stimulus: V, age: secondAge },
|
||||
])
|
||||
|
||||
expect(raw).toBeLessThan(FATIGUE_REF_VOLUME)
|
||||
expect(fatigueOf(workouts, NOW)[SINGLE_SLUG]).toBeCloseTo(expected, 10)
|
||||
@@ -222,7 +363,10 @@ describe('accumulation and purity', () => {
|
||||
|
||||
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]).toBeCloseTo(
|
||||
1 - Math.exp(-2 * V / FATIGUE_REF_VOLUME),
|
||||
10,
|
||||
)
|
||||
expect(fatigueOf(saturated, NOW)[SINGLE_SLUG]).toBeLessThan(1)
|
||||
|
||||
const workouts = [
|
||||
@@ -240,3 +384,122 @@ describe('accumulation and purity', () => {
|
||||
expect(workouts).toEqual(before)
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
describe('warm-up flag in strength and fatigue', () => {
|
||||
it('a warm-up set does not reset strength but still adds fatigue volume', () => {
|
||||
const now = Date.UTC(2026, 7, 1, 12)
|
||||
const oldWork = { id: 'w1', d: '2026-07-10', start: now - 20 * 86400000, unit: 'kg',
|
||||
entries: [{ id: '1254', sets: [{ done: true, w: 80, r: 8 }] }] }
|
||||
const warm = { id: 'w2', d: '2026-08-01', start: now - 3600000, unit: 'kg',
|
||||
entries: [{ id: '1254', sets: [{ done: true, warmup: true, w: 20, r: 8 }] }] }
|
||||
const workouts = [oldWork, warm]
|
||||
const strength = strengthOf(workouts, now)
|
||||
// the strength edge is 20 days old: the fresh warm-up must NOT be the latest training event
|
||||
expect(strength.chest).toBeLessThan(1)
|
||||
// but the warm-up still contributes to the fatigue stimulus (real mechanical work)
|
||||
const fatigue = fatigueOf(workouts, now)
|
||||
expect(fatigue.chest).toBeGreaterThan(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('canonical loads and configured bodyweight', () => {
|
||||
const loaded = EXDB.find(ex => {
|
||||
const weights = musclesOf(ex)
|
||||
return ex.bp !== 'cardio' && ex.eq !== 'body weight'
|
||||
&& Object.keys(weights).length === 1 && Object.values(weights)[0] === 1
|
||||
})
|
||||
const bodyweight = EXDB.find(ex => ex.bp !== 'cardio' && ex.eq === 'body weight')
|
||||
if (!loaded || !bodyweight) throw new Error('recovery tests require loaded and bodyweight fixtures')
|
||||
const loadedSlug = Object.keys(musclesOf(loaded))[0]
|
||||
const bodyweightSlug = Object.keys(musclesOf(bodyweight))[0]
|
||||
const stampedWorkout = ({ id, start, unit, weight, target, bw }) => ({
|
||||
d: new Date(start).toISOString(), start, unit, bw,
|
||||
entries: [{ id, target, sets: [{ done: true, w: weight, r: 8 }] }],
|
||||
})
|
||||
|
||||
it('gives kg and physically equivalent stamped-pound histories the same fatigue', () => {
|
||||
const kg = stampedWorkout({ id: loaded.id, start: NOW, unit: 'kg', weight: 80 })
|
||||
const lb = stampedWorkout({ id: loaded.id, start: NOW, unit: 'lb', weight: 176.3696 })
|
||||
|
||||
expect(fatigueOf([lb], NOW, { unit: 'kg' })[loadedSlug])
|
||||
.toBeCloseTo(fatigueOf([kg], NOW, { unit: 'kg' })[loadedSlug], 6)
|
||||
})
|
||||
|
||||
it('normalizes mixed stamped units before computing the causal reference volume', () => {
|
||||
const starts = [NOW - 3 * DAY, NOW - 2 * DAY, NOW - DAY, NOW]
|
||||
const kg = starts.map(start => stampedWorkout({ id: loaded.id, start, unit: 'kg', weight: 80 }))
|
||||
const mixed = starts.map((start, i) => stampedWorkout({
|
||||
id: loaded.id, start, unit: i % 2 ? 'lb' : 'kg', weight: i % 2 ? 176.3696 : 80,
|
||||
}))
|
||||
|
||||
expect(fatigueOf(mixed, NOW, { unit: 'kg' })[loadedSlug])
|
||||
.toBeCloseTo(fatigueOf(kg, NOW, { unit: 'kg' })[loadedSlug], 6)
|
||||
})
|
||||
|
||||
it('treats an unstamped legacy history as being in the profile unit', () => {
|
||||
const kg = stampedWorkout({ id: loaded.id, start: NOW, unit: 'kg', weight: 80 })
|
||||
const legacyLb = { ...kg, unit: undefined, entries: [{ ...kg.entries[0], sets: [{ done: true, w: 176.3696, r: 8 }] }] }
|
||||
|
||||
expect(fatigueOf([legacyLb], NOW, { unit: 'lb' })[loadedSlug])
|
||||
.toBeCloseTo(fatigueOf([kg], NOW, { unit: 'kg' })[loadedSlug], 6)
|
||||
})
|
||||
|
||||
it('uses configured bodyweight for a non-catalogue bodyweight target', () => {
|
||||
const workout = stampedWorkout({
|
||||
id: loaded.id, start: NOW, unit: 'kg', weight: 0,
|
||||
target: { bodyweight: true }, bw: 80,
|
||||
})
|
||||
|
||||
expect(fatigueOf([workout], NOW, { unit: 'kg' })[loadedSlug]).toBeGreaterThan(0)
|
||||
expect(strengthOf([workout], NOW, { unit: 'kg' })[loadedSlug]).toBe(1)
|
||||
})
|
||||
|
||||
it('adds external load to bodyweight instead of replacing the body mass', () => {
|
||||
const unloaded = stampedWorkout({ id: bodyweight.id, start: NOW, unit: 'kg', weight: 0, bw: 80 })
|
||||
const loadedSet = { done: true, w: 10, r: 8 }
|
||||
const added = { ...unloaded, entries: [{ ...unloaded.entries[0], sets: [loadedSet] }] }
|
||||
|
||||
expect(fatigueOf([added], NOW, { unit: 'kg' })[bodyweightSlug])
|
||||
.toBeGreaterThan(fatigueOf([unloaded], NOW, { unit: 'kg' })[bodyweightSlug])
|
||||
})
|
||||
|
||||
it('lets explicitly configured custom bodyweight work reset strength', () => {
|
||||
const id = 'recovery-custom-bodyweight'
|
||||
registerCustom([{ id, n: 'Custom bodyweight', bp: 'chest', tg: 'chest', eq: 'custom', sm: [] }])
|
||||
try {
|
||||
const workout = stampedWorkout({ id, start: NOW, unit: 'kg', weight: 0, bw: 80, target: { bodyweight: true } })
|
||||
expect(fatigueOf([workout], NOW, { unit: 'kg' }).chest).toBeGreaterThan(0)
|
||||
expect(strengthOf([workout], NOW, { unit: 'kg' }).chest).toBe(1)
|
||||
} finally {
|
||||
registerCustom([])
|
||||
}
|
||||
})
|
||||
|
||||
it('treats a future-dated workout as its own timestamp, never amplified', () => {
|
||||
// A CSV import with a bad timezone can date a workout 10 days in the future. The final
|
||||
// decay clamps the age to zero instead of exponentiating, so the session counts exactly
|
||||
// like the same workout dated now - no 2^(10d/36h) ~ 102x amplification.
|
||||
const future = doneWorkoutAt(SINGLE.id, NOW + 10 * DAY, 5)
|
||||
const now = doneWorkoutAt(SINGLE.id, NOW, 5)
|
||||
const futureValue = fatigueOf([future], NOW)[SINGLE_SLUG]
|
||||
const nowValue = fatigueOf([now], NOW)[SINGLE_SLUG]
|
||||
expect(futureValue).toBeCloseTo(nowValue, 10)
|
||||
expect(futureValue).toBeLessThan(1)
|
||||
})
|
||||
|
||||
it('counts a default custom zero-load ring push-up for fatigue and load-blind strength', () => {
|
||||
const id = 'recovery-ring-push-up'
|
||||
registerCustom([{ id, n: 'Ring push-up', bp: 'chest', tg: 'chest', eq: 'custom', sm: [] }])
|
||||
try {
|
||||
const workout = workoutAt(id, NOW, [
|
||||
{ done: true, w: 0, r: 20 },
|
||||
{ done: true, w: 0, r: 20 },
|
||||
])
|
||||
expect(fatigueOf([workout], NOW).chest).toBeCloseTo(1 - Math.exp(-2 / 3), 10)
|
||||
expect(strengthOf([workout], NOW).chest).toBe(1)
|
||||
} finally {
|
||||
registerCustom([])
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,143 @@
|
||||
// Per-exercise rows for the Strength view: best estimated 1RM from the user's own logged
|
||||
// sets, the exercise's OWN retained-strength decay (same 14-day plateau / 28-day half-life
|
||||
// / 0.5 floor model as the muscle map, applied to the exercise's last done work set), and
|
||||
// the expected CURRENT 1RM (= estimate x decay). The body map keeps the per-muscle model;
|
||||
// the exercise list deliberately reads per-exercise, so an old exercise shows its own
|
||||
// decline even when its muscle is kept fresh by other work. Muscle mapping is
|
||||
// catalogue-first (EXIDX), exactly like the fatigue/strength maps, falling back to the
|
||||
// logged snapshot (muscleWeights) for exercises no longer in the catalogue.
|
||||
import { best1RM } from './onerm.js'
|
||||
import { STRENGTH_FULL_MS, STRENGTH_HALF_LIFE_MS, STRENGTH_FLOOR, halfLifeDecay } from './recovery.js'
|
||||
import { musclesOf } from './muscles.js'
|
||||
import { EXIDX } from './exercises.js'
|
||||
import { isWarmupRow } from './workout-model.js'
|
||||
|
||||
const round1 = value => Math.round(value * 10) / 10
|
||||
|
||||
// Same retained-strength curve the muscle map uses, applied to one exercise's age.
|
||||
function strengthFromAge(ageMs) {
|
||||
if (!Number.isFinite(ageMs) || ageMs < 0) return STRENGTH_FLOOR
|
||||
if (ageMs <= STRENGTH_FULL_MS) return 1
|
||||
return Math.max(STRENGTH_FLOOR, halfLifeDecay(ageMs - STRENGTH_FULL_MS, STRENGTH_HALF_LIFE_MS))
|
||||
}
|
||||
|
||||
// Timestamp of the exercise's latest completed WORK set (warm-ups excluded - they are prep,
|
||||
// not stimulus, and the strength model is built on effective work).
|
||||
function lastWorkSetAt(S, id) {
|
||||
let latest = -Infinity
|
||||
for (const workout of S?.workouts || []) {
|
||||
const ts = workout.start || new Date(workout.d).getTime()
|
||||
if (!Number.isFinite(ts) || ts <= latest) continue
|
||||
const entry = (workout.entries || []).find(e => e.id === id)
|
||||
if (!entry) continue
|
||||
if ((entry.sets || []).some(s => s.done === true && !isWarmupRow(s))) latest = ts
|
||||
}
|
||||
return Number.isFinite(latest) ? latest : null
|
||||
}
|
||||
|
||||
function snapshotWeights(entry) {
|
||||
const catalogue = entry && typeof entry === 'object' ? EXIDX[entry.id] : null
|
||||
if (catalogue) {
|
||||
const weights = musclesOf(catalogue)
|
||||
if (Object.keys(weights).length) return weights
|
||||
}
|
||||
const direct = entry && typeof entry === 'object'
|
||||
? (entry.muscleWeights || entry.muscleSnapshot?.muscleWeights)
|
||||
: null
|
||||
if (direct && typeof direct === 'object' && !Array.isArray(direct) && Object.keys(direct).length) {
|
||||
return direct
|
||||
}
|
||||
return musclesOf(entry)
|
||||
}
|
||||
|
||||
// Highest-weight muscle of an exercise - used for the primary/secondary badge and the
|
||||
// per-muscle link, not for the decay (the exercise's own decay is what the row shows).
|
||||
export function primaryMuscleOf(entry) {
|
||||
const weights = snapshotWeights(entry)
|
||||
let best = null
|
||||
for (const [slug, weight] of Object.entries(weights)) {
|
||||
if (!best || weight > best.weight) best = { slug, weight }
|
||||
}
|
||||
return best
|
||||
}
|
||||
|
||||
function exerciseName(entry) {
|
||||
// Imported history often has no name snapshot (entries are { id, sets, topW }) - the
|
||||
// catalogue (or the registered custom) is the canonical name source.
|
||||
const ex = entry && typeof entry === 'object' ? EXIDX[entry.id] : null
|
||||
if (ex?.n) return ex.n
|
||||
if (entry?.muscleSnapshot?.n) return entry.muscleSnapshot.n
|
||||
return entry && typeof entry === 'object' && entry.n ? entry.n : null
|
||||
}
|
||||
|
||||
function firstEntryWithId(S, id) {
|
||||
for (const workout of S?.workouts || []) {
|
||||
const entry = (workout.entries || []).find(e => e.id === id)
|
||||
if (entry) return entry
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* Strength rows for every exercise with an estimate: best estimated 1RM (work sets only,
|
||||
* warm-ups excluded), the estimate's date, the exercise's primary muscle, the exercise's
|
||||
* OWN decay (from its last done work set), and the expected current 1RM (estimate x decay).
|
||||
* Sorted by expected current 1RM, strongest first. Exercises without a usable estimate are
|
||||
* omitted - a made-up number is worse than no number.
|
||||
*/
|
||||
export function strengthExerciseRows(S, now) {
|
||||
const workouts = S?.workouts || []
|
||||
const ids = [...new Set(workouts.flatMap(w => (w.entries || []).map(e => e.id)))]
|
||||
const rows = []
|
||||
for (const id of ids) {
|
||||
const best = best1RM(S, id)
|
||||
if (!best) continue
|
||||
const entry = firstEntryWithId(S, id)
|
||||
const lastAt = lastWorkSetAt(S, id)
|
||||
const decay = lastAt == null ? STRENGTH_FLOOR : strengthFromAge(Number(now) - lastAt)
|
||||
rows.push({
|
||||
id,
|
||||
name: exerciseName(entry) || id,
|
||||
est: best.est,
|
||||
estDate: best.d,
|
||||
primary: primaryMuscleOf(entry) ? primaryMuscleOf(entry).slug : null,
|
||||
decay,
|
||||
current: round1(best.est * decay),
|
||||
})
|
||||
}
|
||||
return rows.sort((a, b) => b.current - a.current || String(a.name).localeCompare(String(b.name)))
|
||||
}
|
||||
|
||||
/**
|
||||
* Strength rows for the exercises whose logged snapshot includes `slug` (primary 1 /
|
||||
* secondary 0.4 badge), each with the exercise's OWN decay and expected current 1RM - the
|
||||
* tapped muscle filters the list, the row still speaks for the exercise.
|
||||
*/
|
||||
export function strengthExerciseRowsForMuscle(S, now, slug) {
|
||||
const workouts = S?.workouts || []
|
||||
const seen = new Map()
|
||||
for (const workout of workouts) {
|
||||
for (const entry of workout.entries || []) {
|
||||
if (seen.has(entry.id)) continue
|
||||
const weights = snapshotWeights(entry)
|
||||
const weight = weights[slug]
|
||||
if (!weight) continue
|
||||
const best = best1RM(S, entry.id)
|
||||
if (!best) continue
|
||||
const lastAt = lastWorkSetAt(S, entry.id)
|
||||
const decay = lastAt == null ? STRENGTH_FLOOR : strengthFromAge(Number(now) - lastAt)
|
||||
const primary = primaryMuscleOf(entry)
|
||||
seen.set(entry.id, {
|
||||
id: entry.id,
|
||||
name: exerciseName(entry) || entry.id,
|
||||
weight,
|
||||
primary: primary ? primary.slug : null,
|
||||
est: best.est,
|
||||
estDate: best.d,
|
||||
decay,
|
||||
current: round1(best.est * decay),
|
||||
})
|
||||
}
|
||||
}
|
||||
return [...seen.values()].sort((a, b) => b.current - a.current || String(a.name).localeCompare(String(b.name)))
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
|
||||
import { strengthExerciseRows, strengthExerciseRowsForMuscle, primaryMuscleOf } from './strength-exercises.js'
|
||||
import { registerCustom } from './exercises.js'
|
||||
|
||||
const DAY = 86400000
|
||||
const NOW = Date.UTC(2026, 7, 8, 12) // 2026-08-08 12:00 UTC
|
||||
|
||||
const CUSTOMS = [
|
||||
{ id: 'bench', n: 'Bench Press', tg: 'chest', mg: 'triceps', sm: ['deltoids'] },
|
||||
{ id: 'squat', n: 'Squat', tg: 'quadriceps', mg: 'glutes' },
|
||||
{ id: 'fly', n: 'Cable Crossovers', tg: 'deltoids', mg: 'chest' },
|
||||
{ id: 'pushdown', n: 'Triceps Pushdown', tg: 'triceps' },
|
||||
{ id: 'undone', n: 'Undone Lift', tg: 'upper-back' },
|
||||
{ id: 'stretch', n: 'Chest Stretch', tg: 'chest' },
|
||||
]
|
||||
|
||||
beforeEach(() => registerCustom(CUSTOMS))
|
||||
afterEach(() => registerCustom([]))
|
||||
|
||||
function workout(dayAgo, entries) {
|
||||
const d = new Date(NOW - dayAgo * DAY)
|
||||
const iso = d.toISOString().slice(0, 10)
|
||||
return { id: 'x' + iso, d: iso, start: NOW - dayAgo * DAY, unit: 'kg', entries }
|
||||
}
|
||||
|
||||
const bench = { id: 'bench', n: 'Bench Press', muscleWeights: { chest: 1, triceps: 0.4, deltoids: 0.4 }, sets: [
|
||||
{ phase: 'warmup', w: 40, r: 8, done: true, unit: 'kg' },
|
||||
{ phase: 'work', w: 80, r: 8, done: true, unit: 'kg' },
|
||||
{ phase: 'work', w: 85, r: 6, done: true, unit: 'kg' },
|
||||
] }
|
||||
// est 85x6 -> 102.0 ; 80x8 -> 101.3 ; warmup 40x8 -> 50.7 (must never win)
|
||||
|
||||
const squat = { id: 'squat', n: 'Squat', muscleWeights: { quadriceps: 1, glutes: 0.4 }, sets: [
|
||||
{ phase: 'work', w: 100, r: 5, done: true, unit: 'kg' },
|
||||
] }
|
||||
// est 100x5 -> 116.7 ; trained 30 days ago -> quadriceps decayed (30d - 14d = 16d / 28d half-life)
|
||||
|
||||
const fly = { id: 'fly', n: 'Cable Crossovers', muscleWeights: { chest: 0.4, deltoids: 1 }, sets: [
|
||||
{ phase: 'work', w: 20, r: 12, done: true, unit: 'kg' },
|
||||
] }
|
||||
// est 20x12 -> 28 ; chest is SECONDARY here
|
||||
|
||||
const pushdown = { id: 'pushdown', n: 'Triceps Pushdown', muscleWeights: { triceps: 1 }, sets: [
|
||||
{ phase: 'work', w: 30, r: 10, done: true, unit: 'kg' },
|
||||
] }
|
||||
// est 30x10 -> 40
|
||||
|
||||
const undone = { id: 'undone', n: 'Undone Lift', muscleWeights: { 'upper-back': 1 }, sets: [
|
||||
{ phase: 'work', w: 200, r: 5, done: false, unit: 'kg' },
|
||||
] }
|
||||
|
||||
const noLoad = { id: 'stretch', n: 'Chest Stretch', muscleWeights: { chest: 0.4 }, sets: [
|
||||
{ phase: 'work', w: 0, r: 10, done: true },
|
||||
] }
|
||||
|
||||
const unitState = (workouts) => ({ unit: 'kg', workouts })
|
||||
|
||||
describe('strengthExerciseRows', () => {
|
||||
it('lists every exercise with an estimate, warm-ups excluded, sorted by expected current 1RM', () => {
|
||||
const S = unitState([
|
||||
workout(3, [bench]),
|
||||
workout(30, [squat]),
|
||||
workout(3, [fly, pushdown]),
|
||||
workout(2, [undone, noLoad]),
|
||||
])
|
||||
const rows = strengthExerciseRows(S, NOW)
|
||||
// undone (no completed set) and stretch (no load) have no estimate -> omitted
|
||||
expect(rows.map(r => r.id).sort()).toEqual(['bench', 'fly', 'pushdown', 'squat'])
|
||||
// strongest expected current first: bench 102 > squat ~78.5 > pushdown 40 > fly 28
|
||||
expect(rows[0].id).toBe('bench')
|
||||
expect(rows.at(-1).id).toBe('fly')
|
||||
})
|
||||
|
||||
it('keeps warm-up sets out of the estimate and reports the date of the best work set', () => {
|
||||
const S = unitState([workout(3, [bench])])
|
||||
const rows = strengthExerciseRows(S, NOW)
|
||||
expect(rows).toHaveLength(1)
|
||||
expect(rows[0].est).toBe(102) // 85x6, not 80x8, not the 40x8 warm-up
|
||||
expect(rows[0].estDate).toBe('2026-08-05')
|
||||
expect(rows[0].primary).toBe('chest')
|
||||
})
|
||||
|
||||
it('resolves real exercise names from the catalogue even when entries lack a name snapshot', () => {
|
||||
// Imported history entries are { id, sets, topW } - no `n` snapshot. The catalogue
|
||||
// (or the registered custom) must supply the display name, not the raw id.
|
||||
const nameless = { id: 'bench', sets: bench.sets } // no n, no muscleWeights
|
||||
const S = unitState([workout(3, [nameless])])
|
||||
const rows = strengthExerciseRows(S, NOW)
|
||||
expect(rows).toHaveLength(1)
|
||||
expect(rows[0].name).toBe('Bench Press')
|
||||
expect(rows[0].id).toBe('bench')
|
||||
const muscleRows = strengthExerciseRowsForMuscle(S, NOW, 'chest')
|
||||
expect(muscleRows[0].name).toBe('Bench Press')
|
||||
})
|
||||
|
||||
it('uses nested exercise snapshots for a deleted custom exercise', () => {
|
||||
const deleted = {
|
||||
id: 'deleted-custom',
|
||||
muscleSnapshot: { n: 'Deleted custom', muscleWeights: { chest: 1 } },
|
||||
sets: [{ phase: 'work', warmup: true, w: 80, r: 8, done: true, unit: 'kg' }],
|
||||
}
|
||||
const S = unitState([workout(3, [deleted])])
|
||||
const rows = strengthExerciseRows(S, NOW)
|
||||
expect(rows).toHaveLength(1)
|
||||
expect(rows[0]).toMatchObject({ id: 'deleted-custom', name: 'Deleted custom', primary: 'chest', est: 101.3 })
|
||||
expect(strengthExerciseRowsForMuscle(S, NOW, 'chest')[0].name).toBe('Deleted custom')
|
||||
})
|
||||
|
||||
it('applies the exercise own decay to the expected current 1RM', () => {
|
||||
const S = unitState([workout(3, [bench]), workout(30, [squat])])
|
||||
const rows = strengthExerciseRows(S, NOW)
|
||||
const benchRow = rows.find(r => r.id === 'bench')
|
||||
const squatRow = rows.find(r => r.id === 'squat')
|
||||
// bench last done 3 days ago -> still inside the 14-day full-retention plateau
|
||||
expect(benchRow.decay).toBe(1)
|
||||
expect(benchRow.current).toBe(102)
|
||||
// squat last done 30 days ago -> 16 days past the plateau at a 28-day half-life
|
||||
const squatDecay = 0.5 ** (16 / 28)
|
||||
expect(squatRow.decay).toBeCloseTo(squatDecay, 4)
|
||||
expect(squatRow.current).toBeCloseTo(Math.round(116.7 * squatDecay * 10) / 10, 2)
|
||||
})
|
||||
|
||||
it('keeps the exercise own decay even when its muscle is kept fresh by other work', () => {
|
||||
// bench last done 30 days ago, but chest is fresh (fly trained 3 days ago): the row
|
||||
// speaks for the exercise, so bench still shows its own decline.
|
||||
const S = unitState([workout(30, [bench]), workout(3, [fly])])
|
||||
const rows = strengthExerciseRows(S, NOW)
|
||||
const benchRow = rows.find(r => r.id === 'bench')
|
||||
const benchDecay = 0.5 ** (16 / 28)
|
||||
expect(benchRow.decay).toBeCloseTo(benchDecay, 4)
|
||||
expect(benchRow.current).toBeCloseTo(Math.round(102 * benchDecay * 10) / 10, 2)
|
||||
})
|
||||
})
|
||||
|
||||
describe('strengthExerciseRowsForMuscle', () => {
|
||||
it('lists primary and secondary exercises for the tapped muscle, with that muscle decay', () => {
|
||||
const S = unitState([workout(3, [bench, fly, pushdown])])
|
||||
const rows = strengthExerciseRowsForMuscle(S, NOW, 'chest')
|
||||
expect(rows.map(r => r.id).sort()).toEqual(['bench', 'fly'])
|
||||
const benchRow = rows.find(r => r.id === 'bench')
|
||||
const flyRow = rows.find(r => r.id === 'fly')
|
||||
expect(benchRow.weight).toBe(1)
|
||||
expect(benchRow.primary).toBe('chest')
|
||||
expect(flyRow.weight).toBe(0.4)
|
||||
expect(flyRow.primary).toBe('deltoids')
|
||||
expect(flyRow.decay).toBe(1) // chest is at full retention
|
||||
expect(flyRow.current).toBe(28)
|
||||
})
|
||||
|
||||
it('the tapped muscle filters the list; the row decay stays the exercise own', () => {
|
||||
const S = unitState([workout(3, [bench]), workout(30, [fly])])
|
||||
const rows = strengthExerciseRowsForMuscle(S, NOW, 'triceps')
|
||||
const benchRow = rows.find(r => r.id === 'bench')
|
||||
// bench trains triceps secondarily (0.4), so it appears under the tapped triceps -
|
||||
// but the decay is bench's own (3 days ago -> full), not triceps' stale muscle value.
|
||||
expect(benchRow.weight).toBe(0.4)
|
||||
expect(benchRow.primary).toBe('chest')
|
||||
expect(benchRow.decay).toBe(1)
|
||||
expect(benchRow.current).toBe(102)
|
||||
})
|
||||
|
||||
it('returns nothing for a muscle nothing trains', () => {
|
||||
const S = unitState([workout(3, [bench])])
|
||||
expect(strengthExerciseRowsForMuscle(S, NOW, 'biceps')).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('primaryMuscleOf', () => {
|
||||
it('prefers the catalogue, then the logged snapshot, and handles missing metadata', () => {
|
||||
expect(primaryMuscleOf({ id: 'bench', muscleWeights: {} }).slug).toBe('chest') // catalogue wins
|
||||
expect(primaryMuscleOf({ muscleWeights: { chest: 1, triceps: 0.4 } }).slug).toBe('chest') // snapshot fallback
|
||||
expect(primaryMuscleOf({ tg: 'back', mg: 'biceps' }).slug).toBe('upper-back') // canonicalised
|
||||
expect(primaryMuscleOf({})).toBeNull()
|
||||
expect(primaryMuscleOf(null)).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,28 @@
|
||||
// Pure decisions for the active-workout superset flow. Keeping these independent of React and
|
||||
// the stores makes the uneven-round and re-check rules explicit and directly testable.
|
||||
const hasWork = (entries, idx) => !!entries[idx]?.sets?.some(set => !set.done)
|
||||
|
||||
// A completion is new progress only when it takes this exercise beyond the largest number of
|
||||
// simultaneously completed sets seen in this mounted session. Uncheck/re-check therefore does
|
||||
// not repeat navigation or rest side effects, while completing an added set still can.
|
||||
export function setProgressHighWater(entry, previous = 0) {
|
||||
const done = entry?.sets?.reduce((count, set) => count + (set.done ? 1 : 0), 0) || 0
|
||||
return { isNew: done > previous, highWater: Math.max(previous, done) }
|
||||
}
|
||||
|
||||
// Decide where a newly completed superset set goes next. Spent members are skipped, including
|
||||
// across the wrap. A round ends when no later member in display order has work left; this makes
|
||||
// the last *active* member the boundary rather than blindly using the group's last array index.
|
||||
export function supersetFlowStep(entries, unit, fromIdx) {
|
||||
if (!Array.isArray(entries) || !Array.isArray(unit) || unit.length <= 1) return null
|
||||
const pos = unit.indexOf(fromIdx)
|
||||
if (pos < 0) return null
|
||||
|
||||
const unitDone = !unit.some(idx => hasWork(entries, idx))
|
||||
if (unitDone) return { unitDone: true, roundDone: false, nextIdx: null }
|
||||
|
||||
const wrapped = [...unit.slice(pos + 1), ...unit.slice(0, pos + 1)]
|
||||
const nextIdx = wrapped.find(idx => hasWork(entries, idx)) ?? null
|
||||
const roundDone = !unit.slice(pos + 1).some(idx => hasWork(entries, idx))
|
||||
return { unitDone: false, roundDone, nextIdx }
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { setProgressHighWater, supersetFlowStep } from './supersetFlow.js'
|
||||
|
||||
const entry = done => ({ sets: done.map(value => ({ done: value })) })
|
||||
|
||||
describe('supersetFlowStep', () => {
|
||||
it('does not create navigation or rest flow for a normal singleton exercise', () => {
|
||||
const entries = [entry([true]), entry([false])]
|
||||
expect(supersetFlowStep(entries, [0], 0)).toBeNull()
|
||||
})
|
||||
|
||||
it('does not count an uncheck/re-check of previously completed work as new progress', () => {
|
||||
const finished = entry([true, true, true])
|
||||
expect(setProgressHighWater(finished, 3)).toEqual({ isNew: false, highWater: 3 })
|
||||
expect(setProgressHighWater(finished, 2)).toEqual({ isNew: true, highWater: 3 })
|
||||
})
|
||||
|
||||
it('skips a spent short member and uses the last member with work as the round boundary', () => {
|
||||
// A has just completed set two of three; B's only set was completed last round.
|
||||
const entries = [entry([true, true, false]), entry([true])]
|
||||
expect(supersetFlowStep(entries, [0, 1], 0)).toEqual({
|
||||
unitDone: false,
|
||||
roundDone: true,
|
||||
nextIdx: 0
|
||||
})
|
||||
})
|
||||
|
||||
it('wraps to the next member with work at a normal round boundary', () => {
|
||||
const entries = [entry([true, false, false]), entry([true])]
|
||||
expect(supersetFlowStep(entries, [0, 1], 1)).toEqual({
|
||||
unitDone: false,
|
||||
roundDone: true,
|
||||
nextIdx: 0
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,74 @@
|
||||
// Focused workout semantics shared by session, history, and strength views.
|
||||
// Legacy records have no explicit phase or mode, so the defaults preserve main's work/reps shape.
|
||||
|
||||
const MODES = ['reps', 'time', 'cardio']
|
||||
const objectOf = value => value && typeof value === 'object' && !Array.isArray(value) ? value : {}
|
||||
|
||||
function normalizedPhase(value, fallback = 'work') {
|
||||
const token = typeof value === 'string' ? value.trim().toLowerCase() : ''
|
||||
if (token === 'warmup' || token === 'warm-up' || token === 'warm_up') return 'warmup'
|
||||
if (token === 'work') return 'work'
|
||||
return fallback === 'warmup' ? 'warmup' : 'work'
|
||||
}
|
||||
|
||||
/** Resolve a row's phase. An explicit phase wins over the legacy warmup boolean. */
|
||||
export function phaseForSet(set, fallback = 'work') {
|
||||
const source = objectOf(set)
|
||||
if (source.phase != null && source.phase !== '') return normalizedPhase(source.phase, fallback)
|
||||
return source.warmup === true ? 'warmup' : normalizedPhase(undefined, fallback)
|
||||
}
|
||||
|
||||
export function isWarmupRow(set) {
|
||||
return phaseForSet(set) === 'warmup'
|
||||
}
|
||||
|
||||
export function normalizeMode(value, fallback = 'reps') {
|
||||
const token = typeof value === 'string' ? value.trim().toLowerCase() : ''
|
||||
if (MODES.includes(token)) return token
|
||||
return MODES.includes(fallback) ? fallback : 'reps'
|
||||
}
|
||||
|
||||
function modeFromUnit(value) {
|
||||
const token = typeof value === 'string' ? value.trim().toLowerCase() : ''
|
||||
if (['rep', 'reps', 'repetition', 'repetitions'].includes(token)) return 'reps'
|
||||
if (['sec', 'secs', 'second', 'seconds'].includes(token)) return 'time'
|
||||
if (['min', 'mins', 'minute', 'minutes'].includes(token)) return 'cardio'
|
||||
return null
|
||||
}
|
||||
|
||||
function explicitMode(source) {
|
||||
const value = objectOf(source).mode
|
||||
const token = typeof value === 'string' ? value.trim().toLowerCase() : ''
|
||||
return MODES.includes(token) ? token : modeFromUnit(objectOf(source).unit)
|
||||
}
|
||||
|
||||
function inferredMode(source) {
|
||||
const value = objectOf(source)
|
||||
const explicit = explicitMode(value)
|
||||
if (explicit) return explicit
|
||||
if (String(value.mode || '').trim().toLowerCase() === 'amrap') return 'reps'
|
||||
if (value.min != null || value.speed != null) return 'cardio'
|
||||
if (value.sec != null || value.seconds != null || value.durationSec != null) return 'time'
|
||||
if (value.r != null || value.reps != null || value.actualReps != null) return 'reps'
|
||||
return null
|
||||
}
|
||||
|
||||
/** Resolve one row's mode: explicit row, parent target, then legacy result fields. */
|
||||
export function modeForSet(set, target = {}) {
|
||||
return explicitMode(set) || inferredMode(target) || inferredMode(set) || 'reps'
|
||||
}
|
||||
|
||||
/** Resolve a single mode for an entry; mixed work-row modes intentionally return null. */
|
||||
export function modeForEntry(entry, fallback = null) {
|
||||
const source = objectOf(entry)
|
||||
const target = objectOf(source.target || source)
|
||||
const sets = Array.isArray(source.sets) ? source.sets : []
|
||||
const work = sets.filter(set => !isWarmupRow(set))
|
||||
const observed = work.length ? work : sets
|
||||
const modes = [...new Set(observed.map(set => modeForSet(set, target)))]
|
||||
if (modes.length > 1) return null
|
||||
if (modes.length === 1) return modes[0]
|
||||
const targetMode = inferredMode(target)
|
||||
if (targetMode) return targetMode
|
||||
return fallback == null ? modeForSet(source, target) : normalizeMode(fallback)
|
||||
}
|
||||
@@ -94,6 +94,11 @@ export default {
|
||||
'Weight ({0})': 'Gewicht ({0})',
|
||||
'Add to routine': 'Zur Routine hinzufügen',
|
||||
'Remove exercise': 'Übung entfernen',
|
||||
'Remove {0}?': '{0} entfernen?',
|
||||
'The sets you logged for this exercise in this session will be lost.': 'Die in dieser Einheit für diese Übung protokollierten Sätze gehen verloren.',
|
||||
'This removes the exercise from your current session.': 'Dadurch wird die Übung aus deiner aktuellen Einheit entfernt.',
|
||||
'Remove': 'Entfernen',
|
||||
'Which exercise in this superset do you want to remove?': 'Welche Übung in diesem Supersatz möchtest du entfernen?',
|
||||
'Pick an icon': 'Symbol auswählen',
|
||||
// --- day planning / calendar ---
|
||||
'Back to weekly plan': 'Zurück zum Wochenplan',
|
||||
@@ -586,5 +591,9 @@ export default {
|
||||
'{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',
|
||||
'primary': 'primär',
|
||||
'secondary': 'sekundär',
|
||||
'No exercises with an estimated 1RM yet.': 'Noch keine Übungen mit geschätztem 1RM.',
|
||||
'Tap a muscle to see its exercises.': 'Tippe auf einen Muskel, um seine Übungen zu sehen.',
|
||||
'Unpair': 'Trennen'
|
||||
}
|
||||
@@ -90,6 +90,11 @@ export default {
|
||||
'Weight ({0})': 'Peso ({0})',
|
||||
'Add to routine': 'Añadir a la rutina',
|
||||
'Remove exercise': 'Quitar ejercicio',
|
||||
'Remove {0}?': '¿Quitar {0}?',
|
||||
'The sets you logged for this exercise in this session will be lost.': 'Se perderán las series que registraste para este ejercicio en esta sesión.',
|
||||
'This removes the exercise from your current session.': 'Esto quita el ejercicio de tu sesión actual.',
|
||||
'Remove': 'Quitar',
|
||||
'Which exercise in this superset do you want to remove?': '¿Qué ejercicio de esta superserie quieres quitar?',
|
||||
'Pick an icon': 'Elige un icono',
|
||||
'Back to weekly plan': 'Volver al plan semanal',
|
||||
'{0} set to rest': '{0} marcado como descanso',
|
||||
@@ -569,5 +574,9 @@ export default {
|
||||
'{0} sets · {1} work': '{0} series · {1} trabajo',
|
||||
'Make superset with previous': 'Hacer superserie con anterior',
|
||||
'Make superset with next': 'Hacer superserie con siguiente',
|
||||
'primary': 'principal',
|
||||
'secondary': 'secundario',
|
||||
'No exercises with an estimated 1RM yet.': 'Aún no hay ejercicios con 1RM estimado.',
|
||||
'Tap a muscle to see its exercises.': 'Toca un músculo para ver sus ejercicios.',
|
||||
'Unpair': 'Desvincular'
|
||||
}
|
||||
@@ -90,6 +90,11 @@ export default {
|
||||
'Weight ({0})': 'Poids ({0})',
|
||||
'Add to routine': 'Ajouter à la routine',
|
||||
'Remove exercise': "Retirer l'exercice",
|
||||
'Remove {0}?': 'Retirer {0} ?',
|
||||
'The sets you logged for this exercise in this session will be lost.': 'Les séries enregistrées pour cet exercice pendant cette séance seront perdues.',
|
||||
'This removes the exercise from your current session.': 'Cela retire l’exercice de ta séance actuelle.',
|
||||
'Remove': 'Retirer',
|
||||
'Which exercise in this superset do you want to remove?': 'Quel exercice de ce superset veux-tu retirer ?',
|
||||
'Pick an icon': 'Choisis une icône',
|
||||
'Back to weekly plan': 'Retour au plan hebdo',
|
||||
'{0} set to rest': '{0} passé en repos',
|
||||
@@ -569,5 +574,9 @@ export default {
|
||||
'{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',
|
||||
'primary': 'principal',
|
||||
'secondary': 'secondaire',
|
||||
"No exercises with an estimated 1RM yet.": "Aucun exercice avec un 1RM estimé pour l'instant.",
|
||||
'Tap a muscle to see its exercises.': 'Touchez un muscle pour voir ses exercices.',
|
||||
'Unpair': 'Dissocier'
|
||||
}
|
||||
@@ -90,6 +90,11 @@ export default {
|
||||
'Weight ({0})': 'वज़न ({0})',
|
||||
'Add to routine': 'रूटीन में जोड़ें',
|
||||
'Remove exercise': 'व्यायाम हटाएँ',
|
||||
'Remove {0}?': '{0} हटाएँ?',
|
||||
'The sets you logged for this exercise in this session will be lost.': 'इस सत्र में इस व्यायाम के लिए लॉग किए गए सेट मिट जाएँगे।',
|
||||
'This removes the exercise from your current session.': 'यह व्यायाम आपके मौजूदा सत्र से हट जाएगा।',
|
||||
'Remove': 'हटाएँ',
|
||||
'Which exercise in this superset do you want to remove?': 'इस सुपरसेट से कौन-सा व्यायाम हटाना है?',
|
||||
'Pick an icon': 'आइकन चुनें',
|
||||
'Back to weekly plan': 'साप्ताहिक योजना पर वापस',
|
||||
'{0} set to rest': '{0} आराम के लिए सेट',
|
||||
@@ -569,5 +574,9 @@ export default {
|
||||
'{0} sets · {1} work': '{0} सेट · {1} काम',
|
||||
'Make superset with previous': 'पिछले के साथ सुपरसेट',
|
||||
'Make superset with next': 'अगले के साथ सुपरसेट',
|
||||
'primary': 'प्राथमिक',
|
||||
'secondary': 'द्वितीयक',
|
||||
'No exercises with an estimated 1RM yet.': 'अभी तक अनुमानित 1RM वाला कोई व्यायाम नहीं।',
|
||||
'Tap a muscle to see its exercises.': 'व्यायाम देखने के लिए किसी मांसपेशी पर टैप करें।',
|
||||
'Unpair': 'अलग करें'
|
||||
}
|
||||
@@ -90,6 +90,11 @@ export default {
|
||||
'Weight ({0})': 'Peso ({0})',
|
||||
'Add to routine': 'Aggiungi alla routine',
|
||||
'Remove exercise': 'Rimuovi esercizio',
|
||||
'Remove {0}?': 'Rimuovere {0}?',
|
||||
'The sets you logged for this exercise in this session will be lost.': 'Le serie registrate per questo esercizio in questa sessione andranno perse.',
|
||||
'This removes the exercise from your current session.': 'Questo rimuove l’esercizio dalla sessione corrente.',
|
||||
'Remove': 'Rimuovi',
|
||||
'Which exercise in this superset do you want to remove?': 'Quale esercizio di questa superserie vuoi rimuovere?',
|
||||
'Pick an icon': 'Scegli un’icona',
|
||||
'Back to weekly plan': 'Torna al piano settimanale',
|
||||
'{0} set to rest': '{0} impostato a riposo',
|
||||
@@ -569,5 +574,9 @@ export default {
|
||||
'{0} sets · {1} work': '{0} serie · {1} lavoro',
|
||||
'Make superset with previous': 'Superset con il precedente',
|
||||
'Make superset with next': 'Superset con il successivo',
|
||||
'primary': 'primario',
|
||||
'secondary': 'secondario',
|
||||
'No exercises with an estimated 1RM yet.': 'Nessun esercizio con 1RM stimato finora.',
|
||||
'Tap a muscle to see its exercises.': 'Tocca un muscolo per vedere i suoi esercizi.',
|
||||
'Unpair': 'Separa'
|
||||
}
|
||||
@@ -90,6 +90,11 @@ export default {
|
||||
'Weight ({0})': '무게 ({0})',
|
||||
'Add to routine': '루틴에 추가',
|
||||
'Remove exercise': '운동 제거',
|
||||
'Remove {0}?': '{0}을(를) 제거할까요?',
|
||||
'The sets you logged for this exercise in this session will be lost.': '이 세션에서 이 운동에 기록한 세트가 사라집니다.',
|
||||
'This removes the exercise from your current session.': '현재 세션에서 이 운동을 제거합니다.',
|
||||
'Remove': '제거',
|
||||
'Which exercise in this superset do you want to remove?': '이 슈퍼세트에서 어떤 운동을 제거할까요?',
|
||||
'Pick an icon': '아이콘 선택',
|
||||
'Back to weekly plan': '주간 계획으로 복귀',
|
||||
'{0} set to rest': '{0}을(를) 휴식일로 설정',
|
||||
@@ -569,5 +574,9 @@ export default {
|
||||
'{0} sets · {1} work': '{0} 세트 · {1} 작업',
|
||||
'Make superset with previous': '이전 운동과 슈퍼셋',
|
||||
'Make superset with next': '다음 운동과 슈퍼셋',
|
||||
'primary': '주동',
|
||||
'secondary': '보조',
|
||||
'No exercises with an estimated 1RM yet.': '추정 1RM이 있는 운동이 아직 없습니다.',
|
||||
'Tap a muscle to see its exercises.': '근육을 눌러 해당 운동을 확인하세요.',
|
||||
'Unpair': '분리'
|
||||
}
|
||||
@@ -90,6 +90,11 @@ export default {
|
||||
'Weight ({0})': 'Ciężar ({0})',
|
||||
'Add to routine': 'Dodaj do planu',
|
||||
'Remove exercise': 'Usuń ćwiczenie',
|
||||
'Remove {0}?': 'Usunąć {0}?',
|
||||
'The sets you logged for this exercise in this session will be lost.': 'Serie zapisane dla tego ćwiczenia w tej sesji zostaną utracone.',
|
||||
'This removes the exercise from your current session.': 'Spowoduje to usunięcie ćwiczenia z bieżącej sesji.',
|
||||
'Remove': 'Usuń',
|
||||
'Which exercise in this superset do you want to remove?': 'Które ćwiczenie z tej superserii chcesz usunąć?',
|
||||
'Pick an icon': 'Wybierz ikonę',
|
||||
'Back to weekly plan': 'Wróć do planu tygodnia',
|
||||
'{0} set to rest': '{0} ustawiono jako odpoczynek',
|
||||
@@ -569,5 +574,9 @@ export default {
|
||||
'{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',
|
||||
'primary': 'główny',
|
||||
'secondary': 'drugorzędny',
|
||||
'No exercises with an estimated 1RM yet.': 'Brak ćwiczeń z oszacowanym 1RM.',
|
||||
'Tap a muscle to see its exercises.': 'Dotknij mięśnia, aby zobaczyć jego ćwiczenia.',
|
||||
'Unpair': 'Rozłącz'
|
||||
}
|
||||
@@ -90,6 +90,11 @@ export default {
|
||||
'Weight ({0})': 'Peso ({0})',
|
||||
'Add to routine': 'Adicionar à rotina',
|
||||
'Remove exercise': 'Remover exercício',
|
||||
'Remove {0}?': 'Remover {0}?',
|
||||
'The sets you logged for this exercise in this session will be lost.': 'As séries registadas para este exercício nesta sessão serão perdidas.',
|
||||
'This removes the exercise from your current session.': 'Isto remove o exercício da tua sessão atual.',
|
||||
'Remove': 'Remover',
|
||||
'Which exercise in this superset do you want to remove?': 'Que exercício desta supersérie queres remover?',
|
||||
'Pick an icon': 'Escolhe um ícone',
|
||||
'Back to weekly plan': 'Voltar ao plano semanal',
|
||||
'{0} set to rest': '{0} marcado como descanso',
|
||||
@@ -569,5 +574,9 @@ export default {
|
||||
'{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',
|
||||
'primary': 'primário',
|
||||
'secondary': 'secundário',
|
||||
'No exercises with an estimated 1RM yet.': 'Ainda não há exercícios com 1RM estimado.',
|
||||
'Tap a muscle to see its exercises.': 'Toque num músculo para ver os seus exercícios.',
|
||||
'Unpair': 'Desfazer'
|
||||
}
|
||||
@@ -90,6 +90,11 @@ export default {
|
||||
'Weight ({0})': 'Вес ({0})',
|
||||
'Add to routine': 'Добавить в программу',
|
||||
'Remove exercise': 'Убрать упражнение',
|
||||
'Remove {0}?': 'Удалить {0}?',
|
||||
'The sets you logged for this exercise in this session will be lost.': 'Подходы, записанные для этого упражнения в этой сессии, будут потеряны.',
|
||||
'This removes the exercise from your current session.': 'Упражнение будет удалено из текущей сессии.',
|
||||
'Remove': 'Удалить',
|
||||
'Which exercise in this superset do you want to remove?': 'Какое упражнение из этого суперсета удалить?',
|
||||
'Pick an icon': 'Выбери иконку',
|
||||
'Back to weekly plan': 'Вернуться к недельному плану',
|
||||
'{0} set to rest': '{0} — теперь день отдыха',
|
||||
@@ -569,5 +574,9 @@ export default {
|
||||
'{0} sets · {1} work': '{0} подходов · {1} рабочих',
|
||||
'Make superset with previous': 'Суперсет с предыдущим',
|
||||
'Make superset with next': 'Суперсет со следующим',
|
||||
'primary': 'основная',
|
||||
'secondary': 'вспомогательная',
|
||||
'No exercises with an estimated 1RM yet.': 'Пока нет упражнений с расчётным 1ПМ.',
|
||||
'Tap a muscle to see its exercises.': 'Нажмите на мышцу, чтобы увидеть её упражнения.',
|
||||
'Unpair': 'Разъединить'
|
||||
}
|
||||
@@ -90,6 +90,11 @@ export default {
|
||||
'Weight ({0})': 'Ağırlık ({0})',
|
||||
'Add to routine': 'Rutine ekle',
|
||||
'Remove exercise': 'Egzersizi kaldır',
|
||||
'Remove {0}?': '{0} kaldırılsın mı?',
|
||||
'The sets you logged for this exercise in this session will be lost.': 'Bu seansta bu egzersiz için kaydettiğin setler kaybolacak.',
|
||||
'This removes the exercise from your current session.': 'Bu işlem egzersizi mevcut seansından kaldırır.',
|
||||
'Remove': 'Kaldır',
|
||||
'Which exercise in this superset do you want to remove?': 'Bu süper sette hangi egzersizi kaldırmak istiyorsun?',
|
||||
'Pick an icon': 'Bir simge seç',
|
||||
'Back to weekly plan': 'Haftalık plana dön',
|
||||
'{0} set to rest': '{0} dinlenme olarak ayarlandı',
|
||||
@@ -569,5 +574,9 @@ export default {
|
||||
'{0} sets · {1} work': '{0} set · {1} çalışma',
|
||||
'Make superset with previous': 'Öncekiyle superset yap',
|
||||
'Make superset with next': 'Sonrakiyle superset yap',
|
||||
'primary': 'birincil',
|
||||
'secondary': 'ikincil',
|
||||
'No exercises with an estimated 1RM yet.': 'Henüz tahmini 1RM olan egzersiz yok.',
|
||||
'Tap a muscle to see its exercises.': 'Egzersizlerini görmek için bir kas seçin.',
|
||||
'Unpair': 'Ayır'
|
||||
}
|
||||
@@ -90,6 +90,11 @@ export default {
|
||||
'Weight ({0})': '重量({0})',
|
||||
'Add to routine': '加入训练日',
|
||||
'Remove exercise': '移除动作',
|
||||
'Remove {0}?': '移除 {0}?',
|
||||
'The sets you logged for this exercise in this session will be lost.': '本次训练中为该动作记录的组数将丢失。',
|
||||
'This removes the exercise from your current session.': '这会从当前训练中移除该动作。',
|
||||
'Remove': '移除',
|
||||
'Which exercise in this superset do you want to remove?': '你想移除这个超级组中的哪个动作?',
|
||||
'Pick an icon': '选择图标',
|
||||
'Back to weekly plan': '恢复每周计划',
|
||||
'{0} set to rest': '{0} 已设为休息',
|
||||
@@ -569,5 +574,9 @@ export default {
|
||||
'{0} sets · {1} work': '{0} 组 · {1} 工作',
|
||||
'Make superset with previous': '与上一个组成超级组',
|
||||
'Make superset with next': '与下一个组成超级组',
|
||||
'primary': '主要',
|
||||
'secondary': '次要',
|
||||
'No exercises with an estimated 1RM yet.': '暂无估算1RM的动作。',
|
||||
'Tap a muscle to see its exercises.': '点击肌肉查看其动作。',
|
||||
'Unpair': '取消组合'
|
||||
}
|
||||
@@ -14,12 +14,14 @@ import Icon from './components/Icon.jsx'
|
||||
import { Button, Slider, Switch, Segmented, SelectRow, Row } from './components/ui.jsx'
|
||||
import { glyphOf, GLYPH_GROUPS, DEFAULT_GLYPH } from './lib/glyphs.js'
|
||||
import BodyMap from './components/BodyMap.jsx'
|
||||
import { loadOfWorkouts } from './lib/muscles.js'
|
||||
import { exerciseMuscleSnapshot, loadOfWorkouts } from './lib/muscles.js'
|
||||
import { parseImport, mergeImport } from './lib/import-csv.js'
|
||||
import { buildPlanBundle, parsePlan, mergePlan, printPlan } from './lib/plan-share.js'
|
||||
import { estimate1RM, best1RM, is1RMRecord, REP_CAP } from './lib/onerm.js'
|
||||
import { nextPrescription, applyPrescription, policyFor, defaultIncrement, POLICIES_FOR, POLICY_NAME, POLICY_DESC, MAX_BW_SETS } from './lib/progression.js'
|
||||
import { MOBILE, shareExport } from './lib/mobile.js'
|
||||
import { buildCompletedWorkout } from './lib/finish-workout.js'
|
||||
import { isWarmupRow } from './lib/workout-model.js'
|
||||
|
||||
const S = () => useStore.getState().S
|
||||
const update = (...a) => useStore.getState().update(...a)
|
||||
@@ -388,10 +390,15 @@ export function deleteCustomEx(ex, afterDelete) {
|
||||
confirmText: t('Delete'), danger: true,
|
||||
onConfirm: () => {
|
||||
update(s => {
|
||||
// Keep display and muscle metadata in history before the custom catalogue row disappears.
|
||||
const snapshot = exerciseMuscleSnapshot(ex)
|
||||
s.workouts.forEach(w => w.entries.forEach(e => {
|
||||
if (e.id !== ex.id) return
|
||||
e.n = ex.n
|
||||
if (!e.muscleSnapshot || !Object.keys(e.muscleSnapshot).length) e.muscleSnapshot = snapshot
|
||||
}))
|
||||
s.customEx = (s.customEx || []).filter(x => x.id !== ex.id)
|
||||
s.routines.forEach(r => { r.ex = r.ex.filter(e => e.id !== ex.id); cleanupSg(r.ex) })
|
||||
// stamp the name into history entries so past workouts stay readable
|
||||
s.workouts.forEach(w => w.entries.forEach(e => { if (e.id === ex.id) e.n = ex.n }))
|
||||
delete s.exWeights[ex.id]
|
||||
})
|
||||
toast(t('Exercise deleted'))
|
||||
@@ -849,7 +856,7 @@ function TopWeight({ entryIdx, close }) {
|
||||
// to sit after every one of them.
|
||||
const entry = A ? A.entries[entryIdx] : null
|
||||
const ex = entry && EXIDX[entry.id]
|
||||
const maxSet = entry ? Math.max(0, ...entry.sets.filter(s => s.done).map(s => s.w || 0)) : 0
|
||||
const maxSet = entry ? Math.max(0, ...entry.sets.filter(s => s.done && !isWarmupRow(s)).map(s => s.w || 0)) : 0
|
||||
const prevBest = entry ? Math.max((st.exWeights[entry.id] || {}).w || 0, bestWeightFor(st, entry.id)) : 0
|
||||
const [v, setV] = useState(entry ? (Math.max(maxSet, prevBest) || entry.target.weight || 0) : 0)
|
||||
useEffect(() => { if (!entry) close() }, [!entry])
|
||||
@@ -939,25 +946,22 @@ function doFinishWorkout() {
|
||||
const prs = []
|
||||
const e1prs = []
|
||||
A.entries.forEach(e => {
|
||||
const mx = Math.max(0, ...e.sets.filter(s => s.done).map(s => s.w))
|
||||
const mx = Math.max(0, ...e.sets.filter(s => s.done && !isWarmupRow(s)).map(s => s.w))
|
||||
if (mx > 0 && mx > bestWeightFor(st, e.id)) prs.push(e.id)
|
||||
// A heavier estimate without a heavier top set is its own kind of progress —
|
||||
// same weight for more reps. Reported separately so it can't be read as a load PR.
|
||||
const rec = is1RMRecord(st, e.id, e)
|
||||
if (rec && !prs.includes(e.id)) e1prs.push({ id: e.id, ...rec })
|
||||
})
|
||||
const w = {
|
||||
id: A.id, d: A.d, start: A.start, end: Date.now(), routineId: A.routineId, name: A.name, bw: A.bw,
|
||||
// `target` (what the session prescribed) is kept alongside the sets: without it a
|
||||
// finished workout cannot say whether it hit its reps, and a timed session reads back
|
||||
// as "0 reps". It is what the progression engine works from.
|
||||
entries: A.entries.map(e => ({ id: e.id, sets: e.sets, topW: e.topW || null, target: e.target || null })).filter(e => e.sets.some(s => s.done)),
|
||||
prs
|
||||
}
|
||||
const w = buildCompletedWorkout(A, {
|
||||
end: Date.now(),
|
||||
prs,
|
||||
snapshotFor: e => EXIDX[e.id]?.custom ? exerciseMuscleSnapshot(EXIDX[e.id]) : null,
|
||||
})
|
||||
w.vol = workoutVolume(w)
|
||||
update(s => {
|
||||
w.entries.forEach(e => {
|
||||
const mx = Math.max(0, ...e.sets.filter(x => x.done).map(x => x.w || 0), e.topW || 0)
|
||||
const mx = Math.max(0, ...e.sets.filter(x => x.done && !isWarmupRow(x)).map(x => x.w || 0), e.topW || 0)
|
||||
if (mx > 0) { const cur = s.exWeights[e.id]; if (!cur || mx > cur.w) s.exWeights[e.id] = { w: mx, d: w.d } }
|
||||
})
|
||||
s.workouts.push(w)
|
||||
|
||||
@@ -2,7 +2,7 @@ import { useEffect, useMemo, useState } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useStore } from '../store/useStore.js'
|
||||
import { EXIDX } from '../lib/exercises.js'
|
||||
import { lastBW, streakWeeks, setLabel, modeOf, effortOf } from '../lib/history.js'
|
||||
import { lastBW, streakWeeks, setLabel, modeOf, effortOf, metricModeForEntry, metricRowsForEntry, bestWeightForEntry } from '../lib/history.js'
|
||||
import { fmtNum, fmtDate, fmtVol, todayISO, weekKey } from '../lib/format.js'
|
||||
import { t } from '../lib/i18n.js'
|
||||
import { bwSheet, goalSheet, calendarSheet, workoutDetailSheet, WorkoutRow, bwDeltaColor } from '../sheets.jsx'
|
||||
@@ -11,7 +11,8 @@ import Heatmap from '../components/Heatmap.jsx'
|
||||
import Icon from '../components/Icon.jsx'
|
||||
import BodyMap, { BodyMapLegend } from '../components/BodyMap.jsx'
|
||||
import { loadOfWorkouts, rankOf, MUSCLE_NAME, musclesOf } from '../lib/muscles.js'
|
||||
import { fatigueOf, strengthOf, STRENGTH_FLOOR } from '../lib/recovery.js'
|
||||
import { fatigueOf, strengthOf, STRENGTH_FLOOR, LB_TO_KG } from '../lib/recovery.js'
|
||||
import { strengthExerciseRowsForMuscle } from '../lib/strength-exercises.js'
|
||||
import { fatigueStateOf } from '../lib/recovery-view.js'
|
||||
import { e1rmSeries, best1RM } from '../lib/onerm.js'
|
||||
import {
|
||||
@@ -19,6 +20,7 @@ import {
|
||||
effortHistogram, isHardSet, HARD_RIR
|
||||
} from '../lib/effort.js'
|
||||
import { Button, Segmented, SelectRow } from '../components/ui.jsx'
|
||||
import { isWarmupRow } from '../lib/workout-model.js'
|
||||
|
||||
// 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).
|
||||
@@ -28,8 +30,9 @@ function latestMuscleTraining(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 (!(entry.sets || []).some(set => set?.done === true && !isWarmupRow(set))) continue
|
||||
const exercise = EXIDX[entry.id] || entry.exercise || entry
|
||||
for (const slug of Object.keys(musclesOf(exercise))) {
|
||||
if (latest[slug] == null || timestamp > latest[slug]) latest[slug] = timestamp
|
||||
}
|
||||
}
|
||||
@@ -37,7 +40,7 @@ function latestMuscleTraining(workouts) {
|
||||
return latest
|
||||
}
|
||||
|
||||
const FATIGUE_LEVELS = [
|
||||
export const FATIGUE_LEVELS = [
|
||||
{ at: 0, level: 0 },
|
||||
{ at: 0.15, level: 1 },
|
||||
{ at: 0.25, level: 2 },
|
||||
@@ -45,7 +48,7 @@ const FATIGUE_LEVELS = [
|
||||
{ at: 0.55, level: 4, exclusive: true },
|
||||
]
|
||||
|
||||
const STRENGTH_LEVELS = [
|
||||
export const STRENGTH_LEVELS = [
|
||||
{ at: STRENGTH_FLOOR, level: 0 },
|
||||
{ at: 0.625, level: 1 },
|
||||
{ at: 0.75, level: 2 },
|
||||
@@ -100,11 +103,18 @@ function MuscleBalance({ S }) {
|
||||
const [sel, setSel] = useState(null)
|
||||
const now = useNow()
|
||||
const workouts = S.workouts
|
||||
const fatigue = useMemo(() => fatigueOf(workouts, now), [workouts, now])
|
||||
const strength = useMemo(() => strengthOf(workouts, now), [workouts, now])
|
||||
// The user's own last registered bodyweight drives bodyweight-exercise tonnage.
|
||||
const bodyweightKg = useMemo(() => {
|
||||
const entries = S.bodyweight || []
|
||||
if (!entries.length) return null
|
||||
const last = entries.slice().sort((a, b) => String(a.d).localeCompare(String(b.d))).at(-1)
|
||||
if (!last || !(last.w > 0)) return null
|
||||
return S.unit === 'lb' ? last.w * LB_TO_KG : last.w
|
||||
}, [S.bodyweight, S.unit])
|
||||
const fatigue = useMemo(() => fatigueOf(workouts, now, { bodyweightKg, unit: S.unit }), [workouts, now, bodyweightKg, S.unit])
|
||||
const strength = useMemo(() => strengthOf(workouts, now, { bodyweightKg, unit: S.unit }), [workouts, now, bodyweightKg, S.unit])
|
||||
const muscleExercises = useMemo(() => (sel ? strengthExerciseRowsForMuscle(S, now, sel) : []), [S, now, sel])
|
||||
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])
|
||||
@@ -125,6 +135,8 @@ function MuscleBalance({ S }) {
|
||||
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 { worked: strengthOrder } = rankOf(strength)
|
||||
const detrained = strengthOrder.filter(slug => strength[slug] < 1)
|
||||
const top = worked.slice(0, 4)
|
||||
const max = worked.length ? load[worked[0]] : 0
|
||||
const sets = m => Math.round((load[m] || 0) * 10) / 10
|
||||
@@ -176,6 +188,25 @@ function MuscleBalance({ S }) {
|
||||
<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>
|
||||
{sel && <>
|
||||
<h4 className="sec" style={{ marginTop: 14 }}>{t('Exercises')} · {t(MUSCLE_NAME[sel])}</h4>
|
||||
{muscleExercises.length ? muscleExercises.map(row => (
|
||||
<div key={row.id} className="mrow" style={{ minHeight: 48, alignItems: 'stretch' }}>
|
||||
<span className="nm" style={{ whiteSpace: 'normal', lineHeight: 1.35, display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
|
||||
<span style={{ display: 'block', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
|
||||
{row.name}
|
||||
{row.primary === sel
|
||||
? <span className="dim" style={{ fontSize: 11, marginLeft: 6 }}>{t('primary')}</span>
|
||||
: <span className="dim" style={{ fontSize: 11, marginLeft: 6 }}>{t('secondary')}</span>}
|
||||
</span>
|
||||
<span className="small dim" style={{ display: 'block', fontWeight: 400 }}>{t('Est. 1RM')}: {fmtNum(row.est)} {S.unit} · {fmtDate(row.estDate, true)}</span>
|
||||
</span>
|
||||
<span className="bar" style={{ alignSelf: 'center' }}><i style={{ width: '100%', background: 'linear-gradient(to right, var(--acc) ' + Math.round(row.decay * 100) + '%, var(--surface-2) ' + Math.round(row.decay * 100) + '%)' }} /></span>
|
||||
<span className="v" style={{ alignSelf: 'center' }}>{fmtNum(row.current)} {S.unit}<span className="dim"> · {Math.round(row.decay * 100)}%</span></span>
|
||||
</div>
|
||||
)) : <div className="muted small">{t('No exercises with an estimated 1RM yet.')}</div>}
|
||||
</>}
|
||||
{!sel && <div className="muted small" style={{ marginTop: 10 }}>{t('Tap a muscle to see its exercises.')}</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>
|
||||
@@ -185,6 +216,7 @@ function MuscleBalance({ S }) {
|
||||
</div>
|
||||
}
|
||||
|
||||
|
||||
// How hard the training was — the half of the picture a volume chart cannot show. Everything
|
||||
// is computed in RIR (lib/effort.js) and converted to whichever scale this profile reads.
|
||||
// Every number carries how much of the training it speaks for: rating is optional and off by
|
||||
@@ -248,7 +280,6 @@ export default function Stats() {
|
||||
const [exId, setExId] = useState(null)
|
||||
const [exMetric, setExMetric] = useState('top')
|
||||
const now = Date.now()
|
||||
const anyEffort = hasEffort(S)
|
||||
const kind = displayScale(S)
|
||||
const hd = scaleName(kind)
|
||||
|
||||
@@ -256,31 +287,34 @@ export default function Stats() {
|
||||
.map(b => ({ t: b.t || new Date(b.d).getTime(), y: b.w, d: b.d }))
|
||||
const bw30 = S.bodyweight.filter(b => (b.t || new Date(b.d).getTime()) > now - 30 * 86400000)
|
||||
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 workouts = S.workouts
|
||||
const monthW = workouts.filter(w => String(w.d || '').slice(0, 7) === todayISO().slice(0, 7)).length
|
||||
|
||||
const nameOf = id => EXIDX[id]?.n || workouts.flatMap(w => w.entries).find(e => e.id === id)?.n || id
|
||||
const currentOf = id => {
|
||||
for (let i = S.workouts.length - 1; i >= 0; i--) {
|
||||
const en = S.workouts[i].entries.find(e => e.id === id)
|
||||
for (let i = workouts.length - 1; i >= 0; i--) {
|
||||
const en = 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))
|
||||
const mode = metricModeForEntry(en) || modeOf({ id })
|
||||
const rows = metricRowsForEntry(en, mode)
|
||||
const mx = mode === 'reps' ? bestWeightForEntry(en) : Math.max(0, ...rows.map(s => mode === 'cardio' ? (s.speed || 0) : mode === 'time' ? (s.sec || 0) : (s.w || 0)))
|
||||
if (mx > 0) return { mx, unit: mode === 'cardio' ? 'km/h' : mode === 'time' ? 's' : S.unit }
|
||||
}
|
||||
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 exHist = [...new Set(workouts.flatMap(w => w.entries.map(e => e.id)))].filter(id => EXIDX[id] || nameOf(id) !== 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))
|
||||
|
||||
exHist.sort((a, b) => exCurrent[b].mx - exCurrent[a].mx || nameOf(a).localeCompare(nameOf(b)))
|
||||
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
|
||||
// switched exercise drops its old points instead of mixing seconds into a weight chart.
|
||||
// A completed reps work row is authoritative for strength metrics, even when the parent
|
||||
// target also contains timed/cardio work. Entries without reps rows use their selected mode.
|
||||
const curMode = curEx ? (() => {
|
||||
for (let i = S.workouts.length - 1; i >= 0; i--) {
|
||||
const en = S.workouts[i].entries.find(e => e.id === curEx)
|
||||
if (en) return modeOf({ ...(en.target || {}), id: curEx })
|
||||
for (let i = workouts.length - 1; i >= 0; i--) {
|
||||
const en = workouts[i].entries.find(e => e.id === curEx)
|
||||
if (en) {
|
||||
const mode = metricModeForEntry(en)
|
||||
if (mode) return mode
|
||||
}
|
||||
}
|
||||
return modeOf({ id: curEx })
|
||||
})() : 'reps'
|
||||
@@ -290,16 +324,25 @@ export default function Stats() {
|
||||
const exUnit = curCardio ? 'km/h' : curTimed ? 's' : S.unit
|
||||
let exPts = [], exList = [], exBest = 0
|
||||
if (curEx) {
|
||||
S.workouts.forEach(w => {
|
||||
workouts.forEach(w => {
|
||||
const en = w.entries.find(e => e.id === curEx)
|
||||
if (en) { const mx = Math.max(0, ...en.sets.filter(s => s.done).map(metric), curCardio || curTimed ? 0 : (en.topW || 0)); if (mx > 0) { exPts.push({ t: w.start, y: mx, d: w.d, sets: en.sets.filter(s => s.done), target: en.target }); if (mx > exBest) exBest = mx } }
|
||||
if (en) {
|
||||
const loggedMode = metricModeForEntry(en)
|
||||
if (loggedMode !== curMode) return
|
||||
const doneSets = metricRowsForEntry(en, curMode)
|
||||
const mx = curMode === 'reps' ? bestWeightForEntry(en) : Math.max(0, ...doneSets.map(metric))
|
||||
if (mx > 0) {
|
||||
exPts.push({ t: w.start, y: mx, d: w.d, sets: doneSets, target: en.target })
|
||||
if (mx > exBest) exBest = mx
|
||||
}
|
||||
}
|
||||
})
|
||||
exList = exPts.slice(-5).reverse()
|
||||
}
|
||||
// Estimated 1RM (issue #18) — only reps-mode training produces one, so cardio and timed
|
||||
// work simply have no points and the toggle stays hidden.
|
||||
const e1Pts = curEx ? e1rmSeries(S, curEx) : []
|
||||
const e1Best = curEx ? best1RM(S, curEx) : null
|
||||
const e1Pts = curEx && curMode === 'reps' ? e1rmSeries(S, curEx) : []
|
||||
const e1Best = curEx && curMode === 'reps' ? best1RM(S, curEx) : null
|
||||
const showE1 = e1Pts.length > 0
|
||||
// Effort on this exercise, per session. It rides on the top-set curve as well as having a
|
||||
// curve of its own, because the two only mean something together: the same weight moved
|
||||
@@ -324,19 +367,20 @@ export default function Stats() {
|
||||
<button className="iconbtn" onClick={() => nav('/history')} aria-label={t('History')}><Icon name="history" /></button></div>
|
||||
|
||||
<div className="tiles">
|
||||
<div className="tile"><div className="l"><Icon name="dumbbell" />{t('Workouts')}</div><div className="v">{S.workouts.length}</div></div>
|
||||
<div className="tile"><div className="l"><Icon name="dumbbell" />{t('Workouts')}</div><div className="v">{workouts.length}</div></div>
|
||||
<div className="tile"><div className="l"><Icon name="calendar" />{t('This month')}</div><div className="v">{monthW}</div></div>
|
||||
<div className="tile"><div className="l"><Icon name="flame" />{t('Week streak')}</div><div className="v">{streakWeeks(S)}</div></div>
|
||||
<div className="tile"><div className="l"><Icon name="scale" />{t('Weight 30d')}</div><div className="v" style={{ fontSize: 22, color: bwDelta30 === null ? 'inherit' : bwDeltaColor(bwDelta30, (lastBW(S) || {}).w || 0) }}>{bwDelta30 === null ? '—' : (bwDelta30 > 0 ? '+' : '') + fmtNum(bwDelta30) + ' ' + S.unit}</div></div>
|
||||
|
||||
</div>
|
||||
|
||||
<div className="card">
|
||||
<h2>{t('Activity — last 12 months')} <span className="dim" style={{ textTransform: 'none', letterSpacing: 0 }}>· {t('by time trained')}</span></h2>
|
||||
<Heatmap S={S} onDay={iso => { const ws = S.workouts.filter(w => w.d === iso); if (ws.length === 1) workoutDetailSheet(ws[0]); else if (ws.length) calendarSheet(iso) }} />
|
||||
<Heatmap S={S} onDay={iso => { const ws = workouts.filter(w => w.d === iso); if (ws.length === 1) workoutDetailSheet(ws[0]); else if (ws.length) calendarSheet(iso) }} />
|
||||
</div>
|
||||
|
||||
{S.workouts.length > 0 && <MuscleBalance S={S} />}
|
||||
{anyEffort && <EffortCard S={S} />}
|
||||
{workouts.length > 0 && <MuscleBalance S={S} />}
|
||||
{hasEffort(S) && <EffortCard S={S} />}
|
||||
|
||||
<div className="cols">
|
||||
<div className="card">
|
||||
@@ -357,8 +401,7 @@ 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 + (exCurrent[id].mx ? ' ' + '—' + ' ' + fmtNum(exCurrent[id].mx) + ' ' + exCurrent[id].unit : '') }))} />
|
||||
|
||||
options={exHist.map(id => ({ value: id, label: nameOf(id) + (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">
|
||||
@@ -382,12 +425,12 @@ export default function Stats() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{S.workouts.length > 0 && <>
|
||||
{workouts.length > 0 && <>
|
||||
<div className="row between" style={{ marginBottom: 10 }}>
|
||||
<h4 className="sec" style={{ margin: 0 }}>{t('Recent workouts')}</h4>
|
||||
<Button size="sm" variant="ghost" trailingIcon="chevronRight" onClick={() => nav('/history')}>{t('All')} {S.workouts.length}</Button>
|
||||
<Button size="sm" variant="ghost" trailingIcon="chevronRight" onClick={() => nav('/history')}>{t('All')} {workouts.length}</Button>
|
||||
</div>
|
||||
<div className="list">{[...S.workouts].reverse().slice(0, 6).map(w => <WorkoutRow key={w.id} w={w} onClick={() => workoutDetailSheet(w)} />)}</div>
|
||||
<div className="list">{[...workouts].reverse().slice(0, 6).map(w => <WorkoutRow key={w.id} w={w} onClick={() => workoutDetailSheet(w)} />)}</div>
|
||||
</>}
|
||||
</>
|
||||
}
|
||||
@@ -1,11 +1,11 @@
|
||||
import React, { act } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import { parseHTML } from 'linkedom'
|
||||
import { Window } from 'happy-dom'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { MUSCLES, MUSCLE_NAME, levelsOf, rankOf } from '../lib/muscles.js'
|
||||
import { MUSCLES, levelsOf } 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'
|
||||
import Stats from './Stats.jsx'
|
||||
|
||||
const DAY = 86400000
|
||||
const HOUR = 3600000
|
||||
@@ -35,7 +35,7 @@ vi.mock('../components/BodyMap.jsx', () => ({
|
||||
default: props => {
|
||||
mocks.maps.push(props)
|
||||
React.useEffect(() => {
|
||||
mocks.mapMounts++
|
||||
mocks.mapMounts += 1
|
||||
return () => {}
|
||||
}, [])
|
||||
return React.createElement(
|
||||
@@ -59,7 +59,7 @@ function iso(timestamp) {
|
||||
}
|
||||
|
||||
function set(done, extra = {}) {
|
||||
return { done, w: 10, r: 8, unit: 'kg', ...extra }
|
||||
return { done, w: 80, r: 8, unit: 'kg', ...extra }
|
||||
}
|
||||
|
||||
function workout(id, start, entries) {
|
||||
@@ -71,49 +71,34 @@ function entry(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.
|
||||
// The old one-set session lowers the causal reference seen by the six-set session. Position
|
||||
// that newer stimulus 30 seconds before its .5 crossing so the real interval update flips it.
|
||||
const weightedSet = 640 * (30 / 38) ** 1.5
|
||||
const referenceAfterOldSession = 2000 + (weightedSet - 2000) / 3
|
||||
const fatigueEdge = now - (
|
||||
36 * Math.log2((6 * weightedSet / referenceAfterOldSession) / Math.LN2) * HOUR - 30000
|
||||
)
|
||||
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 })])]),
|
||||
workout('abs-completed', now - 20 * DAY, [entry('1002', [set(true, { rir: 2 })])]),
|
||||
workout('abs-undone', now - DAY, [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
|
||||
'1018', '1012', '1167', '1013', '3011', '1413', '1399', '1016', '1005',
|
||||
'1010', '1003', '1001', '1511', '1494', '1002', '1000', '1396',
|
||||
]
|
||||
return workout('all-fatigued', now, ids.map(([id]) => entry(id, Array.from({ length: 8 }, () => set(true)))))
|
||||
return workout(
|
||||
'all-fatigued',
|
||||
now,
|
||||
ids.map(id => entry(id, Array.from({ length: 12 }, () => set(true)))),
|
||||
)
|
||||
}
|
||||
|
||||
function allSubfullWorkout(now = BASE_NOW) {
|
||||
@@ -121,20 +106,24 @@ function allSubfullWorkout(now = BASE_NOW) {
|
||||
}
|
||||
|
||||
function resetFixture(workouts = lifecycleWorkouts()) {
|
||||
mocks.S.unit = 'kg'
|
||||
mocks.S.bodyweight = []
|
||||
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
|
||||
dom = new Window({ url: 'http://localhost/' })
|
||||
globalThis.window = dom
|
||||
globalThis.document = dom.document
|
||||
Object.defineProperty(globalThis, 'navigator', { configurable: true, value: dom.navigator })
|
||||
for (const key of ['HTMLElement', 'Node', 'Element', 'Event']) globalThis[key] = dom[key]
|
||||
for (const key of ['HTMLElement', 'HTMLIFrameElement', 'Node', 'Element', 'Event', 'MouseEvent']) {
|
||||
globalThis[key] = dom[key]
|
||||
}
|
||||
globalThis.IS_REACT_ACT_ENVIRONMENT = true
|
||||
container = document.getElementById('root')
|
||||
container = document.createElement('div')
|
||||
document.body.append(container)
|
||||
root = createRoot(container)
|
||||
}
|
||||
|
||||
@@ -148,6 +137,7 @@ async function unmountStats() {
|
||||
await act(async () => { root.unmount() })
|
||||
root = null
|
||||
container = null
|
||||
dom.close()
|
||||
dom = null
|
||||
}
|
||||
|
||||
@@ -166,36 +156,20 @@ function viewButton(text) {
|
||||
}
|
||||
|
||||
function balanceRangeButton(text) {
|
||||
const segments = muscleCard().querySelectorAll('.seg')
|
||||
return buttonWithText(segments[1], text)
|
||||
return buttonWithText(muscleCard().querySelectorAll('.seg')[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 })) })
|
||||
await act(async () => { button.dispatchEvent(new dom.MouseEvent('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()
|
||||
})
|
||||
const lastMap = () => mocks.maps.at(-1)
|
||||
const expectPressed = button => expect(button?.getAttribute('aria-pressed')).toBe('true')
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
@@ -203,41 +177,48 @@ beforeEach(() => {
|
||||
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()
|
||||
afterEach(async () => {
|
||||
await unmountStats()
|
||||
vi.useRealTimers()
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
expectPressed(buttonWithText(card, 'Muscle balance'))
|
||||
expectPressed(buttonWithText(card, 'Week'))
|
||||
describe('Stats muscle recovery view runtime', () => {
|
||||
it('dispatches real clicks through Balance, Fatigue, and Strength and preserves selection', async () => {
|
||||
await mountStats()
|
||||
expectPressed(viewButton('Muscle balance'))
|
||||
expectPressed(balanceRangeButton('Week'))
|
||||
|
||||
await click(balanceRangeButton('30d'))
|
||||
await click(buttonWithText(card, 'All'))
|
||||
await click(card.querySelector('[data-muscle="chest"]'))
|
||||
expectPressed(balanceRangeButton('30d'))
|
||||
await click(buttonWithText(muscleCard(), 'All'))
|
||||
await click(muscleCard().querySelector('[data-muscle="chest"]'))
|
||||
expect(buttonWithText(muscleCard(), 'Hard')).toBeTruthy()
|
||||
expect(container.querySelector('[data-selected-muscle="chest"]')).toBeTruthy()
|
||||
|
||||
await click(viewButton('Fatigue'))
|
||||
expectPressed(viewButton('Fatigue'))
|
||||
expect(lastMap().thresholds).toBeTruthy()
|
||||
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'))
|
||||
expect(container.querySelector('[data-selected-muscle="chest"]')).toBeTruthy()
|
||||
|
||||
await click(viewButton('Strength'))
|
||||
expectPressed(viewButton('Strength'))
|
||||
expect(lastMap().thresholds.at(-1)).toEqual({ at: 1, level: 4 })
|
||||
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 () => {
|
||||
it('updates the rendered Fatigue map and Balance window on the real 60-second interval', async () => {
|
||||
await mountStats()
|
||||
await click(balanceRangeButton('30d'))
|
||||
await click(viewButton('Fatigue'))
|
||||
await click(muscleCard().querySelector('[data-muscle="chest"]'))
|
||||
|
||||
const beforeTickMounts = mocks.mapMounts
|
||||
const mountsBeforeTick = mocks.mapMounts
|
||||
const beforeTick = lastMap().load.chest
|
||||
expect(fatigueStateOf(beforeTick)).toBe(FATIGUE_STATES.FATIGUED)
|
||||
expect(container.textContent).toContain('Fatigued')
|
||||
@@ -245,43 +226,34 @@ describe('Stats muscle recovery view runtime', () => {
|
||||
await tick(60000)
|
||||
|
||||
const afterTick = lastMap().load.chest
|
||||
expect(mocks.mapMounts).toBe(beforeTickMounts)
|
||||
expect(afterTick).toBeLessThan(0.5)
|
||||
expect(mocks.mapMounts).toBe(mountsBeforeTick)
|
||||
expect(afterTick).toBeLessThan(beforeTick)
|
||||
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 () => {
|
||||
it('derives a pound-profile bodyweight in kg and passes it into the rendered Fatigue map', async () => {
|
||||
const bodyweightWorkout = workout('bodyweight', BASE_NOW, [
|
||||
entry('0001', [{ done: true, w: 0, r: 10 }]),
|
||||
])
|
||||
resetFixture([bodyweightWorkout])
|
||||
mocks.S.unit = 'lb'
|
||||
mocks.S.bodyweight = [{ d: '2026-01-20', w: 180 }, { d: '2026-01-22', w: 220.462262 }]
|
||||
|
||||
await mountStats()
|
||||
await click(viewButton('Strength'))
|
||||
await click(viewButton('Fatigue'))
|
||||
|
||||
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)
|
||||
// 220.462262 lb ~= 100 kg; ten reps score 1000 kg against the initial 2000 kg reference.
|
||||
expect(lastMap().load.abs).toBeCloseTo(1 - Math.exp(-0.5), 6)
|
||||
expect(lastMap().thresholds).toBeTruthy()
|
||||
})
|
||||
|
||||
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)
|
||||
|
||||
it('renders fixed absolute bands through the actual Fatigue and Strength views', async () => {
|
||||
resetFixture([allFatiguedWorkout()])
|
||||
await mountStats()
|
||||
await click(viewButton('Fatigue'))
|
||||
|
||||
@@ -1,19 +1,21 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useStore } from '../store/useStore.js'
|
||||
import { useUI } from '../store/useUI.js'
|
||||
import { exOr } from '../lib/exercises.js'
|
||||
import { effectiveRoutine, lastEntryFor, bestWeightFor, buildSets, freestyleConfig, defaultConfig, setsDoneActive, supersetUnits, unitOf, setLabel, modeOf, isBw, isPerSide, sideReps, repStep, EFFORT, effortOf, stepEffort, capEffort, cascadeWeight, insertWarmupRow, removeRowAt, pairAdjacent, unpairSuperset } from '../lib/history.js'
|
||||
import { effectiveRoutine, lastEntryFor, bestWeightFor, buildSets, freestyleConfig, defaultConfig, setsDoneActive, supersetUnits, unitOf, setLabel, modeOf, isBw, isPerSide, sideReps, repStep, EFFORT, effortOf, stepEffort, capEffort, cascadeWeight, insertWarmupRow, removeRowAt, pairAdjacent, unpairSuperset, cleanupSg } 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'
|
||||
import { api } from '../lib/api.js'
|
||||
import { setProgressHighWater, supersetFlowStep } from '../lib/supersetFlow.js'
|
||||
import Media from '../components/Media.jsx'
|
||||
import { startFlow, exercisePicker, exConfigSheet, exerciseDetailSheet, topWeightSheet, finishWorkout, workoutCompleteSheet, confirmSheet } from '../sheets.jsx'
|
||||
import Icon from '../components/Icon.jsx'
|
||||
import { Button, Check, NumberField } from '../components/ui.jsx'
|
||||
import { nextPrescription, applyPrescription } from '../lib/progression.js'
|
||||
import { glyphOf } from '../lib/glyphs.js'
|
||||
import { isWarmupRow } from '../lib/workout-model.js'
|
||||
|
||||
/* ---------- start chooser (no active workout) ---------- */
|
||||
function StartChooser() {
|
||||
@@ -136,13 +138,14 @@ function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemov
|
||||
{/* 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) => {
|
||||
const warmBefore = i > 0 && !!entry.sets[i - 1].warmup
|
||||
const isFirstWarmup = !!s.warmup && !warmBefore
|
||||
const warm = isWarmupRow(s)
|
||||
const warmBefore = i > 0 && isWarmupRow(entry.sets[i - 1])
|
||||
const isFirstWarmup = warm && !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
|
||||
const phaseNum = entry.sets.slice(0, i + 1).filter(x => isWarmupRow(x) === warm).length
|
||||
return <div key={i}>
|
||||
{isFirstWarmup && <div className="setph">{t('Warm-up')}</div>}
|
||||
{!s.warmup && warmBefore && <div className="setsep" />}
|
||||
{!warm && warmBefore && <div className="setsep" />}
|
||||
<div className={'setrow' + (s.done ? ' done' : '') + (col3 ? ' eff3' : '')}>
|
||||
<div className="n">{phaseNum}</div>
|
||||
{cell(s, i, col1, 'w')}
|
||||
@@ -152,7 +155,7 @@ function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemov
|
||||
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')}
|
||||
{warm && <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>
|
||||
@@ -169,17 +172,46 @@ function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemov
|
||||
}
|
||||
|
||||
/* ---------- active workout ---------- */
|
||||
export function removeActiveExercise(idx) {
|
||||
// Clear the work callback before indexes can shift. This also protects a confirmation sheet
|
||||
// that was opened first and confirmed after a timed hold started.
|
||||
useUI.getState().stopWork()
|
||||
useStore.getState().update(s => {
|
||||
if (!s.active || !Array.isArray(s.active.entries)) return
|
||||
if (idx < 0 || idx >= s.active.entries.length) return
|
||||
s.active.entries.splice(idx, 1)
|
||||
cleanupSg(s.active.entries)
|
||||
if (idx < s.active.cur) s.active.cur--
|
||||
if (s.active.cur >= s.active.entries.length) s.active.cur = Math.max(0, s.active.entries.length - 1)
|
||||
}, true)
|
||||
}
|
||||
|
||||
function ActiveWorkout() {
|
||||
const nav = useNavigate()
|
||||
const S = useStore(s => s.S)
|
||||
const update = useStore(s => s.update)
|
||||
const { startRest, stopRest } = useUI()
|
||||
const { startRest, stopRest, work } = useUI()
|
||||
const A = S.active
|
||||
const units = supersetUnits(A.entries)
|
||||
const cur = Math.min(A.cur, Math.max(0, A.entries.length - 1))
|
||||
const unit = A.entries.length ? unitOf(units, cur) : []
|
||||
const unitIdx = units.findIndex(u => u === unit)
|
||||
const isSuperset = unit.length > 1
|
||||
// Superset flow: keep the active exercise in view - completing a set scrolls to the
|
||||
// next exercise in the group, then back up to the first exercise of the next round.
|
||||
const exRefs = useRef({})
|
||||
const progressHighWater = useRef(A.entries.map(e => e.sets.filter(s => s.done).length))
|
||||
// The marks are index-keyed, and removing an exercise shifts every index above it down
|
||||
// (removeActiveExercise splices). Re-baseline whenever the list length changes, otherwise a
|
||||
// shifted exercise inherits its predecessor's mark and its real progress reads as a re-check.
|
||||
useEffect(() => {
|
||||
progressHighWater.current = A.entries.map(e => e.sets.filter(s => s.done).length)
|
||||
}, [A.entries.length])
|
||||
useEffect(() => {
|
||||
if (!isSuperset) return
|
||||
const el = exRefs.current[cur]
|
||||
if (el && typeof el.scrollIntoView === 'function') el.scrollIntoView({ behavior: 'smooth', block: 'nearest' })
|
||||
}, [cur, isSuperset, A.entries.length])
|
||||
|
||||
const total = A.entries.reduce((n, e) => n + e.sets.length, 0)
|
||||
const done = setsDoneActive(A)
|
||||
@@ -218,6 +250,38 @@ function ActiveWorkout() {
|
||||
const onPairPrev = !isSuperset && cur > 0 ? () => pairAt(cur - 1, cur) : null
|
||||
const onPairNext = !isSuperset && cur < A.entries.length - 1 ? () => pairAt(cur, cur + 1) : null
|
||||
|
||||
// Remove a whole exercise from the session. The confirmation always asks first; in a
|
||||
// superset it asks WHICH exercise of the group to remove.
|
||||
const removeExercise = removeActiveExercise
|
||||
const confirmRemoveExercise = idx => {
|
||||
const e = A.entries[idx]
|
||||
if (!e) return
|
||||
const hasDone = (e.sets || []).some(s => s.done)
|
||||
confirmSheet({
|
||||
title: t('Remove {0}?', exOr(e.id).n),
|
||||
message: hasDone
|
||||
? t('The sets you logged for this exercise in this session will be lost.')
|
||||
: t('This removes the exercise from your current session.'),
|
||||
confirmText: t('Remove'), danger: true, onConfirm: () => removeExercise(idx)
|
||||
})
|
||||
}
|
||||
const removeExerciseSheet = () => {
|
||||
if (unit.length > 1) {
|
||||
useUI.getState().openSheet(close => (
|
||||
<div>
|
||||
<h3>{t('Remove exercise')}</h3>
|
||||
<div className="muted small" style={{ marginBottom: 12 }}>{t('Which exercise in this superset do you want to remove?')}</div>
|
||||
<div className="list">
|
||||
{unit.map(idx => <div key={idx} className="item" onClick={() => { close(); confirmRemoveExercise(idx) }}>
|
||||
<div className="grow"><div className="tt">{exOr(A.entries[idx]?.id).n}</div></div>
|
||||
<Icon name="chevronRight" />
|
||||
</div>)}
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
} else confirmRemoveExercise(cur)
|
||||
}
|
||||
|
||||
// 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
|
||||
// checks the set off through the normal path, so rest, supersets and the finish prompt all
|
||||
@@ -234,15 +298,13 @@ function ActiveWorkout() {
|
||||
const m = modeAt(idx)
|
||||
const cardioEntry = m === 'cardio'
|
||||
const isLastUnit = unitIdx >= units.length - 1
|
||||
let askTop = false, exJustDone = false, workoutDone = false
|
||||
let askTop = false, exJustDone = false, workoutDone = false, checked = false
|
||||
mutEntry(idx, e => {
|
||||
e.sets[i].done = !e.sets[i].done
|
||||
checked = e.sets[i].done
|
||||
if (e.sets[i].done) {
|
||||
beep(S.sound, 1040, 0.12); vibrate(30)
|
||||
const isLastExInUnit = idx === unit[unit.length - 1]
|
||||
const unitDone = unit.every(ui => (ui === idx ? e : A.entries[ui]).sets.every(x => x.done))
|
||||
if (isLastExInUnit && !unitDone) startRest(S.restSec)
|
||||
else if (unitDone) stopRest()
|
||||
if (unitDone && isLastUnit) workoutDone = true // last exercise's last set → done
|
||||
// Only loaded reps training has a "working weight" worth confirming — a bodyweight
|
||||
// plank has nothing to put in that slider, and neither does a set of push-ups
|
||||
@@ -257,6 +319,43 @@ function ActiveWorkout() {
|
||||
else if (workoutDone) workoutCompleteSheet()
|
||||
else if (exJustDone && cardioEntry) useUI.getState().toast(t('Cardio logged'))
|
||||
else if (exJustDone && m === 'time') useUI.getState().toast(t('Hold logged'))
|
||||
|
||||
// Only progress beyond this exercise's high-water mark may navigate or change rest. This
|
||||
// prevents an uncheck/re-check of finished work from replaying the flow side effects.
|
||||
const fresh = useStore.getState().S.active
|
||||
if (fresh && checked && fresh.entries[idx]) {
|
||||
const progress = setProgressHighWater(fresh.entries[idx], progressHighWater.current[idx] || 0)
|
||||
progressHighWater.current[idx] = progress.highWater
|
||||
if (!progress.isNew) return
|
||||
|
||||
const freshUnits = supersetUnits(fresh.entries)
|
||||
const freshUnit = freshUnits.find(u => u.includes(idx))
|
||||
const freshUnitIdx = freshUnits.indexOf(freshUnit)
|
||||
const freshLastUnit = freshUnitIdx >= freshUnits.length - 1
|
||||
const freshUnitDone = freshUnit?.every(ui => fresh.entries[ui].sets.every(x => x.done))
|
||||
|
||||
// Singleton units are ordinary exercises: preserve their historical between-set rest,
|
||||
// while final sets finish quietly and never enter superset navigation.
|
||||
if (freshUnitDone) stopRest()
|
||||
if (!freshUnit || freshUnit.length <= 1) {
|
||||
if (!freshUnitDone) startRest(S.restSec)
|
||||
return
|
||||
}
|
||||
|
||||
const step = supersetFlowStep(fresh.entries, freshUnit, idx)
|
||||
if (!step) return
|
||||
if (step.unitDone) {
|
||||
if (!freshLastUnit) {
|
||||
const nextUnit = freshUnits[freshUnitIdx + 1]
|
||||
// The top-weight sheet's explicit "Just close" path owns the choice not to advance.
|
||||
if (!askTop && nextUnit?.length) update(s => { if (s.active) s.active.cur = nextUnit[0] })
|
||||
startRest(S.restSec)
|
||||
}
|
||||
} else {
|
||||
if (step.nextIdx != null) update(s => { if (s.active) s.active.cur = step.nextIdx })
|
||||
if (step.roundDone) startRest(S.restSec)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Live-presence heartbeat so the admin dashboard can show who's training now. Signed-in only —
|
||||
@@ -302,7 +401,7 @@ function ActiveWorkout() {
|
||||
<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">
|
||||
{unit.map((idx, k) => <div key={idx} ref={el => { exRefs.current[idx] = el }} className="ss-ex" data-exidx={idx}>
|
||||
{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)} onAddWarmup={() => addWarmup(idx)} onRemoveSetAt={i => removeSetAt(idx, i)} onStartTimed={i => startTimed(idx, i)} />
|
||||
@@ -333,6 +432,12 @@ function ActiveWorkout() {
|
||||
s.active.cur = s.active.entries.length - 1
|
||||
}), null, routine, seed)
|
||||
})} icon="plus">{t('Add exercise')}</Button>
|
||||
{A.entries.length > 0 && <>
|
||||
<div style={{ height: 6 }} />
|
||||
<div style={{ display: 'flex', justifyContent: 'center' }}>
|
||||
<Button size="sm" icon="minus" style={{ color: 'var(--red)' }} disabled={!!work} onClick={removeExerciseSheet}>{t('Remove exercise')}</Button>
|
||||
</div>
|
||||
</>}
|
||||
<div style={{ height: 10 }} />
|
||||
{(() => {
|
||||
const exDone = A.entries.filter(e => e.sets.length && e.sets.every(s => s.done)).length
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
// @vitest-environment happy-dom
|
||||
import React, { act } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import { MemoryRouter } from 'react-router-dom'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import Workout, { removeActiveExercise } from './Workout.jsx'
|
||||
import { DEF, useStore } from '../store/useStore.js'
|
||||
import { useUI } from '../store/useUI.js'
|
||||
|
||||
vi.mock('../lib/sound.js', () => ({ beep: vi.fn(), vibrate: vi.fn() }))
|
||||
vi.mock('../lib/api.js', () => ({ api: vi.fn(() => Promise.resolve({})) }))
|
||||
|
||||
globalThis.IS_REACT_ACT_ENVIRONMENT = true
|
||||
const clone = value => JSON.parse(JSON.stringify(value))
|
||||
const entry = (id, sg) => ({
|
||||
id,
|
||||
...(sg ? { sg } : {}),
|
||||
target: { sets: 1, reps: 1 },
|
||||
sets: [{ w: 0, r: 1, done: false }]
|
||||
})
|
||||
|
||||
let root
|
||||
let container
|
||||
|
||||
function setActive(entries, cur = 0) {
|
||||
const S = clone(DEF)
|
||||
S.active = {
|
||||
id: 'remove-test', d: '2026-08-11', start: Date.now(), routineId: null,
|
||||
name: 'Remove test', bw: null, cur, entries
|
||||
}
|
||||
useStore.setState({ S, user: null })
|
||||
}
|
||||
|
||||
function renderWorkout(entries) {
|
||||
setActive(entries)
|
||||
container = document.createElement('div')
|
||||
document.body.appendChild(container)
|
||||
root = createRoot(container)
|
||||
act(() => root.render(<MemoryRouter><Workout /></MemoryRouter>))
|
||||
}
|
||||
|
||||
function removeButton() {
|
||||
return [...container.querySelectorAll('button')].find(button => button.textContent.includes('Remove exercise'))
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
localStorage.clear()
|
||||
useUI.getState().stopRest()
|
||||
useUI.getState().stopWork()
|
||||
useUI.setState({ sheets: [], toastMsg: '', timer: null, work: null })
|
||||
useStore.setState({ S: clone(DEF), user: null })
|
||||
root = null
|
||||
container = null
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
if (root) act(() => root.unmount())
|
||||
if (container) container.remove()
|
||||
useUI.getState().stopRest()
|
||||
useUI.getState().stopWork()
|
||||
vi.clearAllTimers()
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
describe('active-session exercise removal', () => {
|
||||
it('disables removal for the whole duration of a timed hold', () => {
|
||||
renderWorkout([entry('1001')])
|
||||
expect(removeButton()).toBeTruthy()
|
||||
expect(removeButton().disabled).toBe(false)
|
||||
|
||||
act(() => useUI.getState().startWork(30, 'Hold', vi.fn()))
|
||||
|
||||
expect(removeButton().disabled).toBe(true)
|
||||
})
|
||||
|
||||
it('cancels a pending timed callback before indexes shift and cleans a one-member group', () => {
|
||||
setActive([entry('1001', 'sg-1'), entry('1002', 'sg-1'), entry('1003')], 1)
|
||||
expect(useStore.getState().S.active.cur).toBe(1)
|
||||
const wrongWrite = vi.fn(elapsed => {
|
||||
useStore.getState().update(s => { s.active.entries[0].sets[0].sec = elapsed })
|
||||
})
|
||||
useUI.getState().startWork(5, 'Hold', wrongWrite)
|
||||
|
||||
removeActiveExercise(0)
|
||||
vi.advanceTimersByTime(10_000)
|
||||
|
||||
const active = useStore.getState().S.active
|
||||
expect(useUI.getState().work).toBeNull()
|
||||
expect(wrongWrite).not.toHaveBeenCalled()
|
||||
expect(active.entries.map(e => e.id)).toEqual(['1002', '1003'])
|
||||
expect(active.cur).toBe(0)
|
||||
expect(active.entries[0].sg).toBeUndefined()
|
||||
expect(active.entries[0].sets[0].sec).toBeUndefined()
|
||||
})
|
||||
|
||||
it('hides the remove control for an empty freestyle session', () => {
|
||||
renderWorkout([])
|
||||
expect(removeButton()).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('remove-exercise locale coverage', () => {
|
||||
const required = [
|
||||
'Remove {0}?',
|
||||
'The sets you logged for this exercise in this session will be lost.',
|
||||
'This removes the exercise from your current session.',
|
||||
'Remove',
|
||||
'Which exercise in this superset do you want to remove?'
|
||||
]
|
||||
const packs = import.meta.glob('../locales/*.js', { eager: true, import: 'default' })
|
||||
|
||||
it('defines every new prompt in all eleven locale packs', () => {
|
||||
expect(Object.keys(packs)).toHaveLength(11)
|
||||
Object.entries(packs).forEach(([path, pack]) => {
|
||||
required.forEach(key => expect(pack, `${path} is missing ${key}`).toHaveProperty(key))
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('remove-exercise edge cases', () => {
|
||||
it('removing the last remaining exercise leaves an empty, coherent session', () => {
|
||||
setActive([entry('a')], 0)
|
||||
act(() => { removeActiveExercise(0) })
|
||||
const A = useStore.getState().S.active
|
||||
expect(A.entries).toHaveLength(0)
|
||||
expect(A.cur).toBe(0)
|
||||
})
|
||||
|
||||
it('removing one half of a two-member superset dissolves the group', () => {
|
||||
setActive([entry('a', 'g1'), entry('b', 'g1'), entry('c')], 0)
|
||||
act(() => { removeActiveExercise(1) })
|
||||
const A = useStore.getState().S.active
|
||||
expect(A.entries.map(e => e.id)).toEqual(['a', 'c'])
|
||||
// A superset of one is not a superset.
|
||||
expect(A.entries[0].sg).toBeUndefined()
|
||||
})
|
||||
|
||||
it('removing an entry below the active one keeps cur on the same exercise', () => {
|
||||
setActive([entry('a'), entry('b'), entry('c')], 2)
|
||||
act(() => { removeActiveExercise(0) })
|
||||
const A = useStore.getState().S.active
|
||||
expect(A.entries.map(e => e.id)).toEqual(['b', 'c'])
|
||||
expect(A.entries[A.cur].id).toBe('c')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,185 @@
|
||||
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 Workout from './Workout.jsx'
|
||||
|
||||
const mocks = vi.hoisted(() => {
|
||||
const state = {
|
||||
S: null,
|
||||
startRest: vi.fn(),
|
||||
stopRest: vi.fn(),
|
||||
topWeightSheet: vi.fn(),
|
||||
}
|
||||
state.storeSnapshot = () => ({
|
||||
S: state.S,
|
||||
user: null,
|
||||
update: mut => mut(state.S),
|
||||
})
|
||||
state.uiSnapshot = () => ({
|
||||
work: null,
|
||||
startRest: state.startRest,
|
||||
stopRest: state.stopRest,
|
||||
startWork: vi.fn(),
|
||||
toast: vi.fn(),
|
||||
})
|
||||
return state
|
||||
})
|
||||
|
||||
vi.mock('../store/useStore.js', () => {
|
||||
const useStore = selector => selector(mocks.storeSnapshot())
|
||||
useStore.getState = mocks.storeSnapshot
|
||||
return { useStore }
|
||||
})
|
||||
vi.mock('../store/useUI.js', () => {
|
||||
const useUI = selector => selector ? selector(mocks.uiSnapshot()) : mocks.uiSnapshot()
|
||||
useUI.getState = mocks.uiSnapshot
|
||||
return { useUI }
|
||||
})
|
||||
vi.mock('react-router-dom', () => ({ useNavigate: () => () => {} }))
|
||||
vi.mock('../sheets.jsx', () => ({
|
||||
startFlow: vi.fn(),
|
||||
exercisePicker: vi.fn(),
|
||||
exConfigSheet: vi.fn(),
|
||||
exerciseDetailSheet: vi.fn(),
|
||||
topWeightSheet: mocks.topWeightSheet,
|
||||
finishWorkout: vi.fn(),
|
||||
workoutCompleteSheet: vi.fn(),
|
||||
confirmSheet: vi.fn(),
|
||||
}))
|
||||
vi.mock('../components/Media.jsx', () => ({ default: () => null }))
|
||||
// api.js reads navigator.userAgent at module scope. This file installs its own DOM inside the
|
||||
// tests rather than declaring a vitest environment, so it must not depend on an ambient one.
|
||||
vi.mock('../lib/api.js', () => ({
|
||||
api: vi.fn(() => Promise.resolve({})),
|
||||
IS_APPLE: false, IS_ANDROID: false, BIO: 'biometrics',
|
||||
}))
|
||||
|
||||
let dom
|
||||
let root
|
||||
let container
|
||||
|
||||
function exercise(id, sets, extra = {}) {
|
||||
return {
|
||||
id,
|
||||
target: { mode: 'reps', reps: 5, weight: 60, bodyweight: false },
|
||||
sets: sets.map(done => ({ w: 60, r: 5, done })),
|
||||
...extra,
|
||||
}
|
||||
}
|
||||
|
||||
function workout(entries, cur = 0) {
|
||||
return {
|
||||
unit: 'kg', restSec: 90, sound: false, effort: 'none', gifSize: 'full',
|
||||
workouts: [], exWeights: {}, routines: [],
|
||||
active: { id: 'active', name: 'Test workout', start: Date.now(), cur, entries },
|
||||
}
|
||||
}
|
||||
|
||||
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', 'Blob']) globalThis[key] = dom[key]
|
||||
globalThis.IS_REACT_ACT_ENVIRONMENT = true
|
||||
container = document.getElementById('root')
|
||||
root = createRoot(container)
|
||||
}
|
||||
|
||||
async function mount(entries, cur = 0) {
|
||||
mocks.S = workout(entries, cur)
|
||||
installDom()
|
||||
await act(async () => { root.render(React.createElement(Workout)) })
|
||||
}
|
||||
|
||||
async function unmount() {
|
||||
if (!root) return
|
||||
await act(async () => { root.unmount() })
|
||||
root = null
|
||||
container = null
|
||||
dom = null
|
||||
}
|
||||
|
||||
async function toggleSet(index) {
|
||||
const checkbox = container.querySelectorAll('[role="checkbox"]')[index]
|
||||
expect(checkbox).toBeTruthy()
|
||||
await act(async () => { checkbox.dispatchEvent(new dom.Event('click', { bubbles: true })) })
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
await unmount()
|
||||
})
|
||||
|
||||
describe('Workout set completion flow', () => {
|
||||
it('starts rest after a non-final ordinary set, but stops rest without restarting it on the final set', async () => {
|
||||
await mount([exercise('plain-bench', [false, false, false])])
|
||||
await toggleSet(0)
|
||||
|
||||
expect(mocks.startRest).toHaveBeenCalledOnce()
|
||||
expect(mocks.startRest).toHaveBeenCalledWith(90)
|
||||
expect(mocks.stopRest).not.toHaveBeenCalled()
|
||||
|
||||
await unmount()
|
||||
vi.clearAllMocks()
|
||||
await mount([exercise('plain-treadmill', [false], {
|
||||
target: { mode: 'cardio', min: 20, speed: 8 },
|
||||
})])
|
||||
await toggleSet(0)
|
||||
|
||||
expect(mocks.stopRest).toHaveBeenCalledOnce()
|
||||
expect(mocks.startRest).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('leaves a completed superset selected while its top-weight sheet owns the advance choice', async () => {
|
||||
const group = 'superset-1'
|
||||
await mount([
|
||||
exercise('superset-a', [true, true, true], { sg: group, asked: true }),
|
||||
exercise('superset-b', [true, true, false], { sg: group }),
|
||||
exercise('next-exercise', [false, false, false]),
|
||||
], 1)
|
||||
await toggleSet(5)
|
||||
|
||||
expect(mocks.topWeightSheet).toHaveBeenCalledWith(1)
|
||||
expect(mocks.S.active.cur).toBe(1)
|
||||
expect(mocks.startRest).toHaveBeenCalledWith(90)
|
||||
})
|
||||
})
|
||||
|
||||
describe('superset flow survives an exercise being removed mid-session', () => {
|
||||
// removeActiveExercise splices A.entries, shifting every index above the removal down.
|
||||
// The high-water marks are index-keyed, so without re-baselining the shifted exercise
|
||||
// inherits its predecessor's mark and its next completed set reads as an uncheck/re-check
|
||||
// — no advance, and no rest at the end of the round.
|
||||
it('still advances and rests for sets completed after a removal', async () => {
|
||||
// warm(2 sets, both done) ahead of a bench/row superset with nothing done yet.
|
||||
await mount([
|
||||
exercise('warm', [true, true]),
|
||||
exercise('bench', [false, false], { sg: 'g1' }),
|
||||
exercise('row', [false, false], { sg: 'g1' }),
|
||||
], 1)
|
||||
|
||||
// Drop the first exercise: bench moves 1 -> 0, row moves 2 -> 1.
|
||||
// Stale marks would be [2, 0, 0] against entries that are now [bench, row].
|
||||
await act(async () => {
|
||||
mocks.S.active.entries.splice(0, 1)
|
||||
mocks.S.active.cur = 0
|
||||
root.render(React.createElement(Workout))
|
||||
})
|
||||
mocks.startRest.mockClear()
|
||||
|
||||
// First member of the group: real progress, so the flow advances to the partner.
|
||||
await toggleSet(0)
|
||||
await act(async () => { root.render(React.createElement(Workout)) })
|
||||
expect(mocks.S.active.cur).toBe(1)
|
||||
|
||||
// Partner closes the round (each still has a second set), which is what starts the rest.
|
||||
await toggleSet(2)
|
||||
expect(mocks.startRest).toHaveBeenCalledWith(90)
|
||||
})
|
||||
})
|
||||
@@ -15,6 +15,36 @@ COPY frontend/ ./
|
||||
RUN npm run build
|
||||
|
||||
FROM nginx:alpine
|
||||
COPY web/nginx.conf /etc/nginx/conf.d/default.conf
|
||||
ARG VERSION=dev
|
||||
ARG VCS_REF=dev
|
||||
ARG BUILD_DATE=unknown
|
||||
|
||||
LABEL maintainer="Duarte Santos https://github.com/DuarteSantos8" \
|
||||
org.opencontainers.image.title="opengym-web" \
|
||||
org.opencontainers.image.description="Frontend for Self-hosted gym & body-weight tracker — plan routines, log workouts (supersets & cardio too), track your weight and progress, passkey login. Your data, your server." \
|
||||
org.opencontainers.image.source="https://github.com/DuarteSantos8/openGym" \
|
||||
org.opencontainers.image.url="https://ghcr.io/duartesantos8/opengym-web" \
|
||||
org.opencontainers.image.documentation="https://github.com/DuarteSantos8/openGym#readme" \
|
||||
org.opencontainers.image.licenses="AGPL-3.0-or-later" \
|
||||
org.opencontainers.image.version=$VERSION \
|
||||
org.opencontainers.image.revision=$VCS_REF \
|
||||
org.opencontainers.image.created=$BUILD_DATE
|
||||
|
||||
COPY web/nginx.conf.template /etc/nginx/templates/default.conf.template
|
||||
COPY --from=build /app/dist /usr/share/nginx/html
|
||||
# exercise media (img/gif) is mounted at runtime from the media volume
|
||||
|
||||
# Set Default ENVs for nginx
|
||||
ENV NGINX_PORT=80
|
||||
ENV BACKEND=api
|
||||
ENV PORT=3000
|
||||
|
||||
# Probe the port nginx was actually told to listen on (NGINX_PORT is configurable, so a
|
||||
# hardcoded http://localhost/ breaks on any instance that changed it), and address it as
|
||||
# 127.0.0.1: envsubst rewrites the conf after the image's IPv6 script, so nginx ends up
|
||||
# listening on IPv4 only while "localhost" resolves to ::1 first.
|
||||
HEALTHCHECK --interval=5m \
|
||||
--timeout=5s \
|
||||
--retries=3 \
|
||||
CMD wget --spider -q "http://127.0.0.1:${NGINX_PORT}/" || exit 1
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
# openGym — standalone web server: serves the static app AND proxies /api to the backend,
|
||||
# so the whole app lives on ONE origin (required for WebAuthn / passkeys).
|
||||
server {
|
||||
listen 80;
|
||||
listen ${NGINX_PORT};
|
||||
root /usr/share/nginx/html;
|
||||
index index.html;
|
||||
|
||||
# API → backend container
|
||||
location /api/ {
|
||||
proxy_pass http://api:3000;
|
||||
proxy_pass http://${BACKEND}:${PORT};
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
@@ -48,8 +48,10 @@
|
||||
<p>Then friends wanted in. That brought passkey profiles — sign in with your fingerprint,
|
||||
no passwords, everyone's data separate — and sync, so the log survives any phone.
|
||||
Somewhere along the way the little page got rewritten into a proper React app, learned
|
||||
12 languages, grew a muscle map, importers for FitNotes, Strong, Hevy and Apple Health,
|
||||
and finally became a native Android app you can install from this site.</p>
|
||||
12 languages, grew a muscle map that reads three ways — where the volume went, what is
|
||||
still recovering, and what each muscle is actually strong at — plus importers for
|
||||
FitNotes, Strong, Hevy and Apple Health, and finally became a native Android app you can
|
||||
install from this site.</p>
|
||||
|
||||
<p>In July 2026 I open-sourced the whole thing under the <b>AGPL</b>. The license is the
|
||||
point, not a footnote: your training data should be yours, the software that holds it
|
||||
|
||||
@@ -39,6 +39,7 @@
|
||||
<a href="#android">Android</a>
|
||||
<a href="#iphone">iPhone</a>
|
||||
<a href="#selfhost">Self-hosting</a>
|
||||
<a href="#mcp">Ask an AI</a>
|
||||
<a href="#import">Import your history</a>
|
||||
<a href="#backup">Backups</a>
|
||||
<a href="#build">Build it yourself</a>
|
||||
@@ -90,6 +91,28 @@ docker compose up -d</code></pre>
|
||||
examples and the invite-only/admin options, is in
|
||||
<a href="https://github.com/DuarteSantos8/openGym/blob/main/docs/SELF_HOSTING.md" rel="noopener">docs/SELF_HOSTING.md</a>.</div>
|
||||
|
||||
<h3>Settings worth knowing about</h3>
|
||||
<p>All of these live in <code>.env</code>; the defaults are what you get if you touch nothing.</p>
|
||||
<table class="cfg">
|
||||
<tr><td><code>RP_ID</code> / <code>ORIGIN</code></td><td>The domain passkeys are bound to, and the full URL you serve from. The two must agree, or sign-in fails.</td></tr>
|
||||
<tr><td><code>WEB_PORT</code></td><td>Host port for the web UI. Default <code>8080</code>.</td></tr>
|
||||
<tr><td><code>INVITE_ONLY</code></td><td>Set <code>1</code> and new profiles need an invite code you generate.</td></tr>
|
||||
<tr><td><code>ALLOW_GUEST</code></td><td>Set <code>0</code> to remove <b>Continue without account</b>, so everyone using the instance has a profile.</td></tr>
|
||||
<tr><td><code>ADMIN_UIDS</code></td><td>Which user ids get the admin dashboard.</td></tr>
|
||||
<tr><td><code>SESSION_DAYS</code></td><td>How long a sign-in lasts. Default <code>90</code>.</td></tr>
|
||||
<tr><td><code>BACKEND</code> / <code>PORT</code> / <code>NGINX_PORT</code></td><td>For fitting openGym into a stack that already has an <code>api</code> service, or putting it behind your own proxy on another port. The web container renders its nginx config at start-up, so these work on a prebuilt image.</td></tr>
|
||||
</table>
|
||||
|
||||
<h2 id="mcp">Ask an AI about your training</h2>
|
||||
<p>openGym ships an optional <b>MCP server</b>: a small read-only bridge that lets a client
|
||||
like Claude Desktop or Cursor answer questions from your actual log — <i>"what did I bench
|
||||
last week?"</i>, <i>"which muscle have I not trained this month?"</i>, <i>"what's my
|
||||
estimated 1RM on squats?"</i></p>
|
||||
<p>It runs on your machine, is spawned by the client, and reads your exported data directly.
|
||||
Nothing is sent anywhere, and it is <b>not part of the Docker build</b> — if you don't use
|
||||
an AI assistant, it simply isn't there. Setup is a few lines of client config:
|
||||
<a href="https://github.com/DuarteSantos8/openGym/blob/main/mcp/README.md" rel="noopener">mcp/README.md</a>.</p>
|
||||
|
||||
<h2 id="import">Import your training history</h2>
|
||||
<p>Coming from another tracker? <b>Settings → Data → Import from another app</b> reads:</p>
|
||||
<ul>
|
||||
|
||||
@@ -68,12 +68,12 @@
|
||||
<div class="feat"><div class="ic">🏋️</div><h3>1,324 exercises</h3><p>Searchable library with animated demos, filterable by body part and the equipment you actually own — plus your own custom exercises.</p></div>
|
||||
<div class="feat"><div class="ic">🗓️</div><h3>Weekly plan</h3><p>A routine per weekday, and any day can be rescheduled when life happens — without touching the plan.</p></div>
|
||||
<div class="feat"><div class="ic">⚖️</div><h3>Body weight & goal</h3><p>Interactive chart with your goal line; every change is colored by whether it moves toward it.</p></div>
|
||||
<div class="feat"><div class="ic">💪</div><h3>Muscle map</h3><p>A body diagram shaded by how much work each muscle got — and which ones got nothing.</p></div>
|
||||
<div class="feat"><div class="ic">💪</div><h3>Muscle map, three ways</h3><p>A body diagram read as <b>balance</b> (where the volume went, and which muscles got nothing), <b>fatigue</b> (what is still recovering, weighted by how hard each set was) or <b>strength</b> (how long since you trained it — and the exercises behind it, with their estimated 1RM).</p></div>
|
||||
<div class="feat"><div class="ic">🟩</div><h3>Activity heatmap</h3><p>A GitHub-style year view of your training time. Streaks included.</p></div>
|
||||
<div class="feat"><div class="ic">📈</div><h3>Progression that follows a rule</h3><p>Linear, Greyskull LP, double progression or added time — per routine, overridable per exercise. Your weights are already right when the session opens, and every target tells you why.</p></div>
|
||||
<div class="feat"><div class="ic">⏱️</div><h3>Timed sets</h3><p>Planks, hangs and carries are logged by time, with a timer for the set itself. Stop early and it logs what you actually held.</p></div>
|
||||
<div class="feat"><div class="ic">🧮</div><h3>Estimated 1RM</h3><p>Per exercise, from your best eligible set — and it names which one. Won't guess above 12 reps.</p></div>
|
||||
<div class="feat"><div class="ic">🔗</div><h3>Supersets & cardio</h3><p>Pair exercises back-to-back with one rest, and log time + speed where weight × reps makes no sense.</p></div>
|
||||
<div class="feat"><div class="ic">🔗</div><h3>Supersets & cardio</h3><p>Plan them, or pair two exercises mid-session and unpair them again. Work the group back-to-back with one rest per round — and log time + speed where weight × reps makes no sense.</p></div>
|
||||
<div class="feat"><div class="ic">📤</div><h3>Share a plan</h3><p>Send someone your routines as a small file — no workouts, no weigh-ins — or print it as a clean PDF. Importing merges, never overwrites.</p></div>
|
||||
<div class="feat"><div class="ic">🎯</div><h3>Effort per set</h3><p>Rate a set as RIR or RPE — whichever scale you already think in. Optional, and every set keeps the scale it was logged with.</p></div>
|
||||
<div class="feat"><div class="ic">☀️</div><h3>Screen stays awake</h3><p>No unlocking the phone between sets. The screen stays lit while a workout runs, and lets go the moment you finish.</p></div>
|
||||
@@ -81,6 +81,8 @@
|
||||
<div class="feat"><div class="ic">🌍</div><h3>12 languages</h3><p>Full UI translation, exercise instructions in 10 languages, loaded on demand.</p></div>
|
||||
<div class="feat"><div class="ic">🔑</div><h3>Passkeys, not passwords</h3><p>Self-hosted profiles sign in with Face ID / fingerprint. Each person's data stays their own.</p></div>
|
||||
<div class="feat"><div class="ic">🎨</div><h3>Designed, not assembled</h3><p>Light & dark themes, 8 accent colors, a hand-drawn icon set. Looks the same on every phone.</p></div>
|
||||
<div class="feat"><div class="ic">🔥</div><h3>Warm-up sets</h3><p>Mark the ramp-up rows as warm-ups and they stay out of your 1RM, your progression and the fatigue map — present in the session, absent from the numbers.</p></div>
|
||||
<div class="feat"><div class="ic">🤖</div><h3>Ask an AI about your training</h3><p>An optional MCP server lets a client like Claude Desktop read your history in your own words — <i>"what did I bench last week?"</i>. Read-only, runs on your machine, not in the Docker build.</p></div>
|
||||
<div class="feat"><div class="ic">📦</div><h3>Yours to keep</h3><p>One-tap JSON export and import. Your training log is a file you own, not a row in someone's cloud.</p></div>
|
||||
</div>
|
||||
</div></section>
|
||||
@@ -126,7 +128,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.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">v1.2.6 · 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>
|
||||
|
||||
@@ -167,3 +167,14 @@ footer { border-top: 1px solid var(--line); margin-top: 70px; padding: 30px 0 46
|
||||
.nav-in { gap: 12px; }
|
||||
header.hero { padding-top: 52px; }
|
||||
}
|
||||
|
||||
/* config table on the docs page */
|
||||
table.cfg { width: 100%; border-collapse: collapse; margin: 1rem 0 1.4rem; font-size: .95rem; }
|
||||
table.cfg td { padding: .55rem .7rem; border-top: 1px solid var(--line, #24303f); vertical-align: top; }
|
||||
table.cfg tr:first-child td { border-top: 0; }
|
||||
table.cfg td:first-child { white-space: nowrap; width: 1%; padding-right: 1.2rem; }
|
||||
@media (max-width: 620px) {
|
||||
table.cfg td { display: block; border-top: 0; padding: .15rem .7rem; }
|
||||
table.cfg td:first-child { white-space: normal; width: auto; padding-top: .7rem; border-top: 1px solid var(--line, #24303f); }
|
||||
table.cfg tr:first-child td:first-child { border-top: 0; }
|
||||
}
|
||||