Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c2e41937cb | ||
|
|
6dfb36c46a | ||
|
|
c588d219ba | ||
|
|
f94fa7c0e3 | ||
|
|
4b25a80356 | ||
|
|
19a441d93e | ||
|
|
e69673d3cd | ||
|
|
5de5147c5e | ||
|
|
9007aeefb6 | ||
|
|
71b22b3216 | ||
|
|
5bf149e60b | ||
|
|
c17632ea3d | ||
|
|
aac6b185ec | ||
|
|
3b720b0332 | ||
|
|
8fe980343d | ||
|
|
8323e06819 | ||
|
|
55b9dcb864 | ||
|
|
76a2d3b7a5 | ||
|
|
09baee49a7 | ||
|
|
374f6bdadc | ||
|
|
32c9a2380d | ||
|
|
9976b7a278 | ||
|
|
d4169690a6 | ||
|
|
55de70ad23 | ||
|
|
f860edd24a | ||
|
|
329eed4ce0 | ||
|
|
5d7e13361c | ||
|
|
274a0276e0 | ||
|
|
1ba378b632 | ||
|
|
0e00e1029c | ||
|
|
011a3f7790 | ||
|
|
4e842b00e1 | ||
|
|
f3ba7de479 | ||
|
|
57f04febbe | ||
|
|
23a5b6c228 | ||
|
|
ed666df237 | ||
|
|
a95104b675 | ||
|
|
edde72f9cb | ||
|
|
237d1c5cf2 | ||
|
|
b42d2baa6e | ||
|
|
f32c4d0b73 | ||
|
|
528cb70a79 | ||
|
|
a7d7f5c24b | ||
|
|
fe585097c8 | ||
|
|
d8c734a2b6 | ||
|
|
087ce34674 | ||
|
|
157ca90f3b | ||
|
|
15c29029c1 | ||
|
|
030a609427 | ||
|
|
8bbf59c001 | ||
|
|
b29a3f6bb0 | ||
|
|
bee9b64b78 | ||
|
|
35181af2aa | ||
|
|
01072ef5e3 | ||
|
|
86ac937d5d | ||
|
|
9cc645c755 | ||
|
|
cbb3630423 | ||
|
|
0109857249 | ||
|
|
edb3e42c43 | ||
|
|
577c86b487 | ||
|
|
13ed730a0c | ||
|
|
7e60ac20f2 | ||
|
|
06a1e0a709 | ||
|
|
d99f0ef2f1 | ||
|
|
d0075eeddf | ||
|
|
86f3476f5f | ||
|
|
9daf637044 | ||
|
|
b2b3577744 | ||
|
|
84e98425cc | ||
|
|
941d911fa9 | ||
|
|
5b5d65b63e | ||
|
|
6c91adefcd | ||
|
|
d1cede21d3 | ||
|
|
9af028bde3 | ||
|
|
eeee4b461c | ||
|
|
551b072c54 | ||
|
|
e007f76d43 | ||
|
|
e28345dd13 | ||
|
|
ba412cb36d | ||
|
|
f554b6b004 | ||
|
|
09949686c2 | ||
|
|
7c69e57b4f | ||
|
|
663e0b3987 | ||
|
|
5a0345c905 | ||
|
|
1e86d6ace2 | ||
|
|
a5e360cde5 | ||
|
|
00b4f543a3 | ||
|
|
4afffcb248 | ||
|
|
c33ff15d9d | ||
|
|
8de55ce0d9 | ||
|
|
aefb13b544 | ||
|
|
7354b1ca0c | ||
|
|
f5562febca | ||
|
|
1f40230727 | ||
|
|
de65e1099a | ||
|
|
be2fb2dd1d | ||
|
|
611987545a | ||
|
|
accc3c1038 | ||
|
|
1574811af0 | ||
|
|
b45dbca2a6 | ||
|
|
3a120df205 | ||
|
|
051a37abbf | ||
|
|
8440cf3546 | ||
|
|
b0d176aba3 | ||
|
|
42ac8c8513 | ||
|
|
f232b5ba7e | ||
|
|
caaf61d91e | ||
|
|
6aaf2a3eea | ||
|
|
4143ab8676 | ||
|
|
92914dea43 | ||
|
|
fadeb17b6c |
No files matched your search
@@ -33,9 +33,46 @@ RP_NAME=openGym
|
||||
# generate the codes from the admin dashboard):
|
||||
#
|
||||
# INVITE_ONLY=1
|
||||
#
|
||||
# Remove the "Continue without account" button, so a profile is the only way in.
|
||||
# Guest mode keeps everything in the browser and never touches this server, but
|
||||
# on an instance meant for a known set of people it is still the wrong front
|
||||
# door. Anyone already inside as a guest is signed out on their next visit; the
|
||||
# data they made stays in that browser. Defaults to on (guests allowed):
|
||||
#
|
||||
# ALLOW_GUEST=0
|
||||
|
||||
# ── Session length (optional) ──────────────────────────────────────────────
|
||||
# How long a sign-in lasts, in days. Default 90 — long enough that people who
|
||||
# train regularly never see a login screen, short enough that a stolen cookie
|
||||
# doesn't stay good forever. Lower it for an instance on the open internet,
|
||||
# raise it for a private one. Only affects new sign-ins; cookies already handed
|
||||
# out keep the lifetime they were issued with. Users can end every session on
|
||||
# every device themselves with "Sign out everywhere" in Settings.
|
||||
#
|
||||
# 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
|
||||
@@ -0,0 +1,60 @@
|
||||
name: Bug report
|
||||
description: Something in openGym is broken or not working as expected
|
||||
labels: ["bug"]
|
||||
body:
|
||||
- type: textarea
|
||||
id: what-happened
|
||||
attributes:
|
||||
label: What did you do?
|
||||
description: Steps to reproduce, as precisely as you can.
|
||||
placeholder: |
|
||||
1. Go to '...'
|
||||
2. Click on '...'
|
||||
3. See error
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: expected
|
||||
attributes:
|
||||
label: What did you expect to happen?
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: actual
|
||||
attributes:
|
||||
label: What happened instead?
|
||||
description: Include error messages, console output, or screenshots if you have them.
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: dropdown
|
||||
id: setup
|
||||
attributes:
|
||||
label: How are you running openGym?
|
||||
options:
|
||||
- Self-hosted (docker compose)
|
||||
- Frontend dev server (npm run dev)
|
||||
- Other / not sure
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: input
|
||||
id: environment
|
||||
attributes:
|
||||
label: Browser & OS
|
||||
placeholder: e.g. Safari 17 on iOS 18, Chrome 126 on Android
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: checkboxes
|
||||
id: passkey
|
||||
attributes:
|
||||
label: Is this about login / passkeys?
|
||||
description: >
|
||||
Most login issues are an `RP_ID`/`ORIGIN` mismatch — check your `.env` against the
|
||||
domain you're accessing openGym from before reporting. See the
|
||||
[self-hosting guide](../../docs/SELF_HOSTING.md).
|
||||
options:
|
||||
- label: Yes, this is a login/passkey issue and I've already checked RP_ID/ORIGIN
|
||||
@@ -0,0 +1,14 @@
|
||||
# gitea.com has no Discussions, so questions and ideas are issues here — labelled, so they
|
||||
# are not mistaken for agreed-on work. Blank issues stay off: the forms ask for the two
|
||||
# things that otherwise cost a round-trip every time (how it is running, and RP_ID/ORIGIN).
|
||||
blank_issues_enabled: false
|
||||
contact_links:
|
||||
- name: Self-hosting guide
|
||||
url: https://gitea.com/DuarteSantos/openGym/src/branch/main/docs/SELF_HOSTING.md
|
||||
about: Passkey login failing, reverse proxies, HTTPS, Docker — most login trouble is an RP_ID/ORIGIN mismatch and is answered here.
|
||||
- name: Contributing guide
|
||||
url: https://gitea.com/DuarteSantos/openGym/src/branch/main/CONTRIBUTING.md
|
||||
about: Project layout, dev setup and guidelines before you open a PR.
|
||||
- name: Changelog
|
||||
url: https://gitea.com/DuarteSantos/openGym/src/branch/main/CHANGELOG.md
|
||||
about: What changed in each release, newest first.
|
||||
@@ -0,0 +1,29 @@
|
||||
name: Feature request
|
||||
description: Suggest an idea or improvement for openGym
|
||||
labels: ["enhancement"]
|
||||
body:
|
||||
- type: textarea
|
||||
id: problem
|
||||
attributes:
|
||||
label: What problem does this solve?
|
||||
description: What are you trying to do that openGym doesn't support today?
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: proposal
|
||||
attributes:
|
||||
label: Proposed approach
|
||||
description: How would you like it to work? Rough ideas are fine.
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: checkboxes
|
||||
id: deps
|
||||
attributes:
|
||||
label: Dependencies
|
||||
description: >
|
||||
openGym is intentionally dependency-light — new packages (front or back) are a hard
|
||||
sell. See [CONTRIBUTING.md](../../CONTRIBUTING.md).
|
||||
options:
|
||||
- label: This doesn't require adding a new dependency
|
||||
@@ -0,0 +1,86 @@
|
||||
# Publishes the two images to the gitea.com container registry, replacing GHCR.
|
||||
#
|
||||
# Images land at gitea.com/duartesantos/opengym-{api,web} and are what
|
||||
# `docker compose pull` fetches.
|
||||
#
|
||||
# As on GitHub, a *published release* is the trigger, never a bare tag push: the
|
||||
# versioning rule consolidates unreleased tags, and a deleted tag does not delete
|
||||
# the image tags it already pushed — dependency bots then read the orphan as a
|
||||
# newer series (that was issue #87 on the old repo).
|
||||
#
|
||||
# Needs one repository secret: PACKAGES_TOKEN — a gitea.com token with
|
||||
# write:package scope (Settings → Applications → Generate New Token). The built-in
|
||||
# token cannot write packages.
|
||||
name: Publish Docker images
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
release:
|
||||
types: [published]
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
include:
|
||||
- image: api
|
||||
context: ./api
|
||||
file: ./api/Dockerfile
|
||||
- image: web
|
||||
context: .
|
||||
file: ./web/Dockerfile
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Lowercase owner (registry names must be lowercase)
|
||||
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@v3
|
||||
- uses: docker/setup-buildx-action@v3
|
||||
|
||||
- uses: docker/login-action@v3
|
||||
with:
|
||||
registry: gitea.com
|
||||
username: ${{ github.repository_owner }}
|
||||
password: ${{ secrets.PACKAGES_TOKEN }}
|
||||
|
||||
- uses: docker/metadata-action@v5
|
||||
id: meta
|
||||
with:
|
||||
images: gitea.com/${{ steps.repo.outputs.owner }}/opengym-${{ matrix.image }}
|
||||
tags: |
|
||||
type=raw,value=latest,enable={{is_default_branch}}
|
||||
type=semver,pattern={{version}}
|
||||
type=semver,pattern={{major}}.{{minor}}
|
||||
|
||||
# No cache-from/to: the GHCR copy used type=gha, which is a GitHub-hosted
|
||||
# service and is not there on gitea.com's runners.
|
||||
- uses: docker/build-push-action@v6
|
||||
with:
|
||||
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 }}
|
||||
@@ -0,0 +1,38 @@
|
||||
# Same suite as .github/workflows/test.yml, run by gitea.com's Actions runners.
|
||||
# The GitHub copy is kept for the day that account comes back; this one is what
|
||||
# actually gates contributions today.
|
||||
name: Tests
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
paths:
|
||||
- 'frontend/**'
|
||||
- 'mcp/**'
|
||||
- '.gitea/workflows/test.yml'
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- 'frontend/**'
|
||||
- 'mcp/**'
|
||||
- '.gitea/workflows/test.yml'
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
group: test-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
# node:22-alpine in web/Dockerfile and api/Dockerfile — CI must match production.
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 22
|
||||
cache: npm
|
||||
cache-dependency-path: frontend/package-lock.json
|
||||
- run: npm ci
|
||||
working-directory: frontend
|
||||
- run: npm test
|
||||
working-directory: frontend
|
||||
@@ -0,0 +1,5 @@
|
||||
# Puts a "Sponsor" button on the repo header. The GitHub entry only works once the account is
|
||||
# enrolled in GitHub Sponsors (github.com/sponsors — identity check, Stripe payout account and
|
||||
# a tax form); until then the button is simply not shown.
|
||||
github: DuarteSantos8
|
||||
buy_me_a_coffee: duartesantos
|
||||
@@ -1,5 +1,14 @@
|
||||
blank_issues_enabled: false
|
||||
contact_links:
|
||||
- name: Questions & contributing
|
||||
- name: Question or self-hosting help
|
||||
url: https://github.com/DuarteSantos8/openGym/discussions/categories/q-a
|
||||
about: Login/passkey trouble, reverse proxies, Docker, "how do I…" — ask in Q&A, not in an issue.
|
||||
- name: Idea or feature request to talk through
|
||||
url: https://github.com/DuarteSantos8/openGym/discussions/categories/ideas
|
||||
about: Not sure it belongs in the app yet? Float it in Ideas first — issues are for agreed work.
|
||||
- name: Show your setup
|
||||
url: https://github.com/DuarteSantos8/openGym/discussions/categories/show-and-tell
|
||||
about: Running openGym somewhere interesting, or built something on top of it? Show it off.
|
||||
- name: Contributing guide
|
||||
url: https://github.com/DuarteSantos8/openGym/blob/main/CONTRIBUTING.md
|
||||
about: Read the project layout, dev setup, and guidelines before opening an issue.
|
||||
about: Project layout, dev setup and guidelines before you open a PR.
|
||||
@@ -0,0 +1,102 @@
|
||||
# Dependency updates, deliberately quiet.
|
||||
#
|
||||
# openGym is dependency-light on purpose: the frontend is React + Router + Zustand, and api/
|
||||
# has two runtime dependencies. A default Dependabot setup would still open a PR per package
|
||||
# per week, which on a solo project means the alerts stop being read — the opposite of what
|
||||
# this is for. So: monthly, everything in an ecosystem grouped into a single PR, and a low
|
||||
# cap on open PRs. Security advisories are unaffected by any of this; GitHub raises those
|
||||
# regardless of schedule.
|
||||
#
|
||||
# Only manifests that actually exist here are listed. Deliberately NOT covered:
|
||||
# - gradle (frontend/android) and cocoapods (frontend/ios) — Capacitor generates those shells
|
||||
# and pins the native versions to the @capacitor/* npm packages. Bumping them independently
|
||||
# desyncs the two and breaks the mobile build; they follow the npm update instead.
|
||||
version: 2
|
||||
|
||||
updates:
|
||||
# Frontend app — frontend/package.json
|
||||
- package-ecosystem: npm
|
||||
directory: /frontend
|
||||
schedule:
|
||||
interval: monthly
|
||||
open-pull-requests-limit: 3
|
||||
groups:
|
||||
# Routine bumps arrive as one PR. Runtime and build tooling move together anyway (a Vite
|
||||
# bump usually wants its plugin bumped), and splitting them doubles the review without
|
||||
# splitting the risk.
|
||||
frontend:
|
||||
patterns: ['*']
|
||||
update-types: ['minor', 'patch']
|
||||
# Majors get their own PR. The first grouped run bundled a Capacitor 7 → 8 migration in
|
||||
# with six siblings, where it read as housekeeping — and CI would have gone green on it,
|
||||
# because the test workflow builds the web app and never touches the mobile flavour. A
|
||||
# major that lands alone is at least obviously a decision.
|
||||
frontend-major:
|
||||
patterns: ['*']
|
||||
update-types: ['major']
|
||||
ignore:
|
||||
# Capacitor 8 needs Node >= 22 (its own `engines` field) and the build host is on 20, and
|
||||
# `frontend/android` + `frontend/ios` are committed, so a major also means migrating the
|
||||
# native projects — Gradle/AGP, the Podfile. That is a deliberate piece of work, not a
|
||||
# dependency bump. Drop this ignore once the build host is on Node 22 and you want it.
|
||||
- dependency-name: '@capacitor/*'
|
||||
update-types: ['version-update:semver-major']
|
||||
|
||||
# Backend — api/package.json (@simplewebauthn/server, web-push)
|
||||
- package-ecosystem: npm
|
||||
directory: /api
|
||||
schedule:
|
||||
interval: monthly
|
||||
open-pull-requests-limit: 3
|
||||
groups:
|
||||
api:
|
||||
patterns: ['*']
|
||||
update-types: ['minor', 'patch']
|
||||
# Two dependencies, but one of them verifies passkeys — a major there is worth reading on
|
||||
# its own rather than alongside anything else.
|
||||
api-major:
|
||||
patterns: ['*']
|
||||
update-types: ['major']
|
||||
|
||||
# Base images — api/Dockerfile (node:22-alpine)
|
||||
- package-ecosystem: docker
|
||||
directory: /api
|
||||
schedule:
|
||||
interval: monthly
|
||||
open-pull-requests-limit: 1
|
||||
ignore:
|
||||
# Odd-numbered Node majors are "Current", never LTS — they stop getting fixes in about
|
||||
# six months. Dependabot's first run offered 22 → 25, which for something other people
|
||||
# self-host is a stability downgrade for nothing. Even majors (22 → 24 → 26) still get
|
||||
# proposed, which is the move actually worth reviewing.
|
||||
- dependency-name: node
|
||||
versions: ['25.x', '27.x', '29.x', '31.x', '33.x']
|
||||
|
||||
# Base images — web/Dockerfile (node:22-alpine build stage + nginx:alpine)
|
||||
- package-ecosystem: docker
|
||||
directory: /web
|
||||
schedule:
|
||||
interval: monthly
|
||||
open-pull-requests-limit: 1
|
||||
ignore:
|
||||
- dependency-name: node
|
||||
versions: ['25.x', '27.x', '29.x', '31.x', '33.x']
|
||||
|
||||
# Workflow actions — everything under .github/workflows/
|
||||
- package-ecosystem: github-actions
|
||||
directory: /
|
||||
schedule:
|
||||
interval: monthly
|
||||
open-pull-requests-limit: 2
|
||||
groups:
|
||||
# These are all first-party actions/* and docker/* pinned to a major tag; they update
|
||||
# in lockstep and none of them is worth a PR of its own.
|
||||
actions:
|
||||
patterns: ['*']
|
||||
update-types: ['minor', 'patch']
|
||||
# Action majors are usually a runner or Node-version change and usually harmless — but
|
||||
# these workflows publish the ghcr images and deploy the live demo, so the blast radius
|
||||
# is real. Separate PR, so a failure has an obvious cause.
|
||||
actions-major:
|
||||
patterns: ['*']
|
||||
update-types: ['major']
|
||||
@@ -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:
|
||||
@@ -23,22 +28,35 @@ jobs:
|
||||
context: .
|
||||
file: ./web/Dockerfile
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
- name: Lowercase owner (registry names must be lowercase)
|
||||
id: repo
|
||||
run: echo "owner=$(echo '${{ github.repository_owner }}' | tr '[:upper:]' '[:lower:]')" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- uses: docker/setup-qemu-action@v3
|
||||
- uses: docker/setup-buildx-action@v3
|
||||
- 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/login-action@v3
|
||||
- uses: docker/setup-qemu-action@v4
|
||||
- uses: docker/setup-buildx-action@v4
|
||||
|
||||
- uses: docker/login-action@v4.6.0
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- uses: docker/metadata-action@v5
|
||||
- uses: docker/metadata-action@v6
|
||||
id: meta
|
||||
with:
|
||||
images: ghcr.io/${{ steps.repo.outputs.owner }}/opengym-${{ matrix.image }}
|
||||
@@ -47,11 +65,15 @@ jobs:
|
||||
type=semver,pattern={{version}}
|
||||
type=semver,pattern={{major}}.{{minor}}
|
||||
|
||||
- uses: docker/build-push-action@v6
|
||||
- uses: docker/build-push-action@v7
|
||||
with:
|
||||
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 }}
|
||||
|
||||
@@ -30,8 +30,8 @@ jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
- uses: actions/checkout@v7
|
||||
- uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version: 22
|
||||
cache: npm
|
||||
@@ -44,8 +44,8 @@ jobs:
|
||||
VITE_DEMO: '1'
|
||||
VITE_IMG_BASE: ${{ env.DATASET }}/images/
|
||||
VITE_GIF_BASE: ${{ env.DATASET }}/videos/
|
||||
- uses: actions/configure-pages@v5
|
||||
- uses: actions/upload-pages-artifact@v3
|
||||
- uses: actions/configure-pages@v6
|
||||
- uses: actions/upload-pages-artifact@v5
|
||||
with:
|
||||
path: frontend/dist
|
||||
|
||||
@@ -57,4 +57,4 @@ jobs:
|
||||
url: ${{ steps.deploy.outputs.page_url }}
|
||||
steps:
|
||||
- id: deploy
|
||||
uses: actions/deploy-pages@v4
|
||||
uses: actions/deploy-pages@v5
|
||||
@@ -0,0 +1,74 @@
|
||||
# Runs on pull requests too — the other two workflows only fire on push to main, so
|
||||
# contributed changes used to reach main without anything ever having been run.
|
||||
name: Tests
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
paths:
|
||||
- 'frontend/**'
|
||||
- 'mcp/**'
|
||||
- '.github/workflows/test.yml'
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- 'frontend/**'
|
||||
- 'mcp/**'
|
||||
- '.github/workflows/test.yml'
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: test-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
# node:22-alpine in web/Dockerfile and api/Dockerfile — CI must match production.
|
||||
- uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version: 22
|
||||
cache: npm
|
||||
cache-dependency-path: frontend/package-lock.json
|
||||
- run: npm ci
|
||||
working-directory: frontend
|
||||
- run: npm test
|
||||
working-directory: frontend
|
||||
# A broken import or bad JSX fails the build long before any test covers it.
|
||||
- run: npm run build
|
||||
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
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
- uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version: 22
|
||||
cache: npm
|
||||
cache-dependency-path: mcp/package-lock.json
|
||||
- run: npm ci
|
||||
working-directory: mcp
|
||||
- run: npm test
|
||||
working-directory: mcp
|
||||
# The one check the vitest suite structurally cannot make. The MCP server is a bare node
|
||||
# process, but vitest runs its tests through Vite — import.meta.glob, .jsx imports and
|
||||
# ?raw all resolve happily there. That is how a Vite-only import reached a shared lib
|
||||
# module with 33 green tests standing over a server that died on startup.
|
||||
- run: npm run check:node-loadable
|
||||
working-directory: mcp
|
||||
@@ -13,3 +13,4 @@ frontend/dist/
|
||||
node_modules/
|
||||
*.log
|
||||
.DS_Store
|
||||
node_modules
|
||||
@@ -1,5 +1,362 @@
|
||||
# Changelog
|
||||
|
||||
## v1.2.8 — 2026-08-22
|
||||
|
||||
A housekeeping release, and two things worth reading even if you skip the rest. openGym has moved
|
||||
to **gitea.com** — the GitHub account it lived on was suspended, and everything you click to
|
||||
self-host pointed there. And the exercise media's licence is now stated correctly: the images and
|
||||
animations are © Gym visual, not CC, which matters if you redistribute them.
|
||||
|
||||
### The project moved to gitea.com
|
||||
|
||||
- 🏠 **openGym now lives at <https://gitea.com/DuarteSantos/openGym>.** The GitHub account
|
||||
was suspended on 2026-08-19 and took the repository, the GHCR images, the Pages demo and
|
||||
Discussions with it. `docker compose` now pulls `gitea.com/duartesantos/opengym-{api,web}`; the
|
||||
README, `SECURITY.md`, `CONTRIBUTING.md` and the self-hosting docs point at the new home; issue
|
||||
forms, tests and the image publish run as Gitea Actions. **If you self-host, re-pull:** the old
|
||||
`ghcr.io` images are gone and will not update again.
|
||||
- Gitea has no Discussions, so questions and ideas are labelled issues — or the Discord, which
|
||||
is where most of it happens now: <https://discord.gg/e62jY6fwVb>.
|
||||
- Old issue and PR numbers in the entries below stay as plain text. They point at a dead repo and
|
||||
do not match the numbering here.
|
||||
|
||||
### The exercise media is © Gym visual — not CC
|
||||
|
||||
- ⚖️ **openGym described the exercise dataset as "CC". That was wrong**, and it is now
|
||||
corrected everywhere it appeared (README, `NOTICE.md`, the website, the in-app credit, the
|
||||
compose file and `scripts/fetch-media.sh`). Upstream
|
||||
[hasaneyldrm/exercises-dataset](https://github.com/hasaneyldrm/exercises-dataset) licenses its two
|
||||
halves differently: the exercise **metadata and instruction text are MIT**, while the **images and
|
||||
animations are © [Gym visual](https://gymvisual.com/)**, used under that dataset's terms with
|
||||
permission that is not transferable.
|
||||
- **Nothing changes for using openGym.** It never shipped that media — not in the repository,
|
||||
not in its history, not in the images or the APK; your instance downloads it from upstream on
|
||||
first run, and the media step now prints where it comes from and under what terms.
|
||||
- **It does change what you may do with the media.** Reusing the images or animations — in
|
||||
openGym or anywhere else, commercially or not — needs your own licence from Gym visual. See
|
||||
[NOTICE.md](NOTICE.md).
|
||||
|
||||
### Fixes
|
||||
|
||||
- ⬅️ **The back gesture no longer quits the app** (Android). The packaged app never listened for
|
||||
the system back event at all — Capacitor leaves that to `@capacitor/app`, which was not
|
||||
installed — so a back swipe went straight past the WebView and finished the activity from
|
||||
wherever you were. The per-sheet history entries added in [#63] only ever did anything in a
|
||||
browser tab. Back now dismisses the open sheet, then walks back through the screens you came
|
||||
from, and only leaves the app after a second press at the root ("Press back again to exit").
|
||||
A sheet that is locked mid-task still swallows back, as it does in the browser.
|
||||
|
||||
### The website counts visits; the app still counts nothing
|
||||
|
||||
- 📊 **<https://opengym.duarte-santos.ch> now runs self-hosted, cookieless
|
||||
[Umami](https://umami.is/)** — page views for the landing, about and docs pages, no cookies,
|
||||
no third-party service.
|
||||
- 🔒 **Your instance does not.** The frontend only gets an analytics tag when
|
||||
`VITE_UMAMI_SRC` *and* `VITE_UMAMI_ID` are set at build time, which they are not in any published
|
||||
image or in a plain `npm run build`. A self-hosted openGym remains telemetry-free, as advertised.
|
||||
|
||||
## 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
|
||||
still recovering from it. Plus: a freestyle session no longer starts from blanks, the rest timer
|
||||
can reach you in another app, and a self-hosted instance can insist that everyone using it has an
|
||||
account.
|
||||
|
||||
### The muscle map, read as recovery (#44)
|
||||
|
||||
- 🔥 **A `Balance | Fatigue | Strength` switch on the Stats muscle card.** Balance is the map you
|
||||
already had and is untouched. Fatigue shades each muscle by how much of the recent training it
|
||||
is still carrying; Strength shades it by how long it has been since you trained it at all, with
|
||||
the weeks-since count spelled out underneath.
|
||||
- **Fatigue is volume-sensitive and fades smoothly.** A hard twelve-set chest day starts near the
|
||||
top and takes about six days to read ready again; a single set barely registers and is gone in
|
||||
two. It decays continuously on a 36-hour half-life rather than expiring at a window edge, so the
|
||||
map never flips from "fatigued" to "ready" between one look and the next.
|
||||
- **Strength holds for two weeks, then decays toward a floor.** A muscle you have not trained in
|
||||
months reads detrained rather than absent, which is the state that actually tells you something.
|
||||
- Both views are pure functions over your existing history — no new stored data, no schema change,
|
||||
nothing sent anywhere.
|
||||
|
||||
### The rest timer can reach you in another app (#49)
|
||||
|
||||
- ⏰ **A system notification when rest is over**, on top of the beep, for when you have switched to
|
||||
another tab or app mid-session. Permission is asked the first time a rest starts, and everything
|
||||
degrades quietly where notifications are unsupported or refused.
|
||||
- It goes through the service worker where the browser requires that — which is most phones — and
|
||||
falls back to the direct API elsewhere. No new dependencies; the existing server push path is
|
||||
untouched.
|
||||
|
||||
### Rows now strain the rear delts (#51)
|
||||
|
||||
- **Four row variations gained rear-deltoid secondaries** — barbell, dumbbell, inverted and cable
|
||||
seated rows — so the muscle map spreads their load the way the lift actually does. The overrides
|
||||
live in a small table that survives a regeneration of the exercise dataset rather than being
|
||||
edited into the generated data.
|
||||
|
||||
### An instance can require an account (#42)
|
||||
|
||||
- 🔒 **`ALLOW_GUEST=0` removes the "Continue without account" button.** Guest mode keeps everything
|
||||
in the browser and never touches the server — no account, no sync, nothing the admin dashboard
|
||||
can see — so on an instance meant for a known set of people it was a door leading nowhere
|
||||
useful, and until now there was no way to close it.
|
||||
- **It also ends guest sessions that already exist.** Guests never authenticate, so there is no
|
||||
request for the server to start refusing; the switch reaches someone already inside on their
|
||||
next visit, when the app checks the config and returns them to the login screen. Their data is
|
||||
not deleted — it stays in that browser, and moves into a real profile if they create one on the
|
||||
same device.
|
||||
- **A server it cannot reach is not a server that said no.** The button is only withdrawn on an
|
||||
explicit `allow_guest: false`; a failed config request, or a server too old to send the flag at
|
||||
all, leaves guest mode exactly as it was. An instance that is merely offline for a moment does
|
||||
not lock out everyone who never made an account.
|
||||
- **Default is on, so nothing changes for existing instances.** Set it alongside `INVITE_ONLY=1`:
|
||||
invite-only governs who may *create a profile* and says nothing about the guest button, which
|
||||
never creates one.
|
||||
|
||||
### Freestyle sessions start where you left off
|
||||
|
||||
- 🏋️ **Adding an exercise to an empty workout now prefills it from the last time you trained
|
||||
it** — the same number of sets, with each row's reps and weight carried across by position.
|
||||
Cardio brings its duration and speed, a hold brings its seconds. Until now every row opened on
|
||||
the config-sheet defaults, so the first thing a freestyle session asked of you was to retype
|
||||
what you already did last week.
|
||||
- **The config sheet agrees with the rows it is about to create.** It opens on the last target you
|
||||
actually trained rather than the generic default, so the set count you confirm is the set count
|
||||
you get.
|
||||
- **Planned sessions are untouched.** A routine-driven workout still runs the progression logic and
|
||||
still applies its prescription; only the freestyle path — which has no prescription to apply —
|
||||
reads from history instead.
|
||||
|
||||
Contributed by [@Space-Hermes](https://github.com/Space-Hermes) in
|
||||
[#50](https://github.com/DuarteSantos8/openGym/pull/50).
|
||||
|
||||
### Pair exercises into a superset mid-session (#64)
|
||||
|
||||
- 🔗 **"Make superset with previous / next" on each exercise card.** Two exercises paired in the
|
||||
session collapse into a single *Superset* card — do them back-to-back, rest once at the end —
|
||||
with an **Unpair** button in the header. No planning ahead required; pair them when you decide
|
||||
to, in the workout.
|
||||
- **Groups are any size.** Pairing the end of one group to the start of another merges them, and
|
||||
the header wording stays correct past two exercises.
|
||||
- **Unpairing cleans up after itself.** A group reduced to one exercise is dissolved rather than
|
||||
left as a superset of one, and the pairing helpers never mutate the running session.
|
||||
- Session-only by design: pairings drive the workout, and history stores the sets.
|
||||
|
||||
Contributed by [@Space-Hermes](https://github.com/Space-Hermes) in
|
||||
[#64](https://github.com/DuarteSantos8/openGym/pull/64).
|
||||
|
||||
### The muscle map stops rewriting the catalogue (#67)
|
||||
|
||||
- **The curated secondary-muscle additions are now an overlay, not a mutation.** The four row
|
||||
exercises that strain the rear delts used to get that written into the shared exercise dataset
|
||||
at import time, which meant export, print and import saw a catalogue that had been edited
|
||||
underneath them. They are derived at the read points instead, so the dataset stays pristine.
|
||||
- The detail sheet's tag row reads through the same overlay, so those muscles still show where
|
||||
they always did.
|
||||
|
||||
Contributed by [@Space-Hermes](https://github.com/Space-Hermes) in
|
||||
[#67](https://github.com/DuarteSantos8/openGym/pull/67).
|
||||
|
||||
### Fixes
|
||||
|
||||
- 🖼️ **Exercise images and animations were blank on the routine screen** ([#79]). The media paths
|
||||
were relative, and `/plan/r/:id` is the app's only two-segment route — so the browser asked for
|
||||
`/plan/r/img/…` and got a 404 with nothing in the console to say why. Every other screen was
|
||||
fine, which is what made it look like a one-screen mystery. Reported with the root cause already
|
||||
found, by [@lemi1000](https://github.com/lemi1000).
|
||||
- 📥 **Imports mapped more of what other apps export** ([#74]). Treadmill, Goblet Squat, Cycling and
|
||||
Cable Core Pallof Press arrived as *custom* exercises rather than catalogue ones — no word
|
||||
overlap could reach the names openGym stores them under. Those and their neighbours are now in
|
||||
the alias table. Already-imported history stays custom; new imports resolve. Reported by
|
||||
[@KiloOscarSix](https://github.com/KiloOscarSix).
|
||||
- **A progression edge case that could loop forever** ([#60]). An entry left with nothing but
|
||||
warm-up rows seeded the set-growth loop from a warm-up, which could never satisfy its own exit
|
||||
condition. It leaves the entry alone instead. Contributed by
|
||||
[@Space-Hermes](https://github.com/Space-Hermes).
|
||||
- Documented that `VITE_IMG_BASE` / `VITE_GIF_BASE` are build-time values, so setting them next to
|
||||
`docker compose` does nothing on a prebuilt image.
|
||||
|
||||
[#79]: https://github.com/DuarteSantos8/openGym/issues/79
|
||||
[#74]: https://github.com/DuarteSantos8/openGym/issues/74
|
||||
[#60]: https://github.com/DuarteSantos8/openGym/pull/60
|
||||
|
||||
## v1.2.5 — 2026-08-04
|
||||
|
||||
Nothing in the app itself changed. This release adds an optional side door: a small server that
|
||||
lets an AI assistant you already run — Claude Desktop, Cursor, Cline — answer questions about
|
||||
your own training, off the same files your instance already writes. If you don't use one, this
|
||||
release is invisible to you.
|
||||
|
||||
### Ask an AI about your training, without the data leaving your box (#19)
|
||||
|
||||
- 🤖 **An MCP server (`mcp/`)** — opt-in, read-only, and not part of the Docker build. Your LLM
|
||||
client spawns it as a local process, it reads `./data` directly, and it exits when the client
|
||||
disconnects. No new container, no extra auth on the api, no third-party service, nothing over
|
||||
the network. *"What did I bench last week?", "what's my estimated 1RM on deadlift?", "which
|
||||
muscles have I been neglecting?"*
|
||||
- **The answers match the Stats screen because they are the same numbers.** The server calls the
|
||||
very functions in `frontend/src/lib/` the app already computes with, rather than reimplementing
|
||||
them. Eight tools: routines, the week plan, workouts, one session in detail, body weight,
|
||||
estimated 1RM and muscle balance.
|
||||
- **Read-only on purpose.** Logging a workout from an assistant needs a long-lived token the api
|
||||
does not have yet, plus a lock against the web UI's read-modify-write. Until both exist, the
|
||||
server answers questions and does nothing else. It never reads passkey material, VAPID keys or
|
||||
session state — only the profile it was pointed at.
|
||||
- `docker-compose.yml` is untouched and nothing new enters the image, so an instance that ignores
|
||||
this ships exactly what it shipped before. Setup is in [mcp/README.md](mcp/README.md).
|
||||
|
||||
### Under the hood
|
||||
|
||||
- The pure half of `i18n.js` — the language state, the constants, the readers — moved into
|
||||
`i18n-core.js`, so the helpers under `frontend/src/lib/` can be loaded by a plain Node process
|
||||
and not only by Vite. `i18n.js` keeps the Vite-only parts (the locale-pack loader, the React
|
||||
hook) and re-exports the rest, so nothing that imports it had to change.
|
||||
- The shared lib modules that only need `t` now take it from the core directly. A Vite-only
|
||||
import inside a shared module is invisible under vitest, which transforms it, and fatal to the
|
||||
MCP server, which does not — so the shared half stays clear of the bundler half by
|
||||
construction rather than by remembering to.
|
||||
- `npm run check:node-loadable` in `mcp/` walks the server's import graph under a bare `node`,
|
||||
which is the one thing the test suite cannot do from inside Vite. CI runs it, alongside the
|
||||
MCP tests — neither had ever run there before.
|
||||
|
||||
The MCP server was contributed by [@Pengboi](https://github.com/Pengboi) — the first feature in
|
||||
openGym written by someone other than me. Thank you.
|
||||
|
||||
## v1.2.4 — 2026-08-01
|
||||
|
||||
The effort ratings you have been recording since v1.2.3 now answer questions, and bodyweight
|
||||
training stops being treated as barbell training with the weight left at zero. Plus: creating a
|
||||
profile from Settings works on an invite-only instance, which it never has.
|
||||
|
||||
### The effort ratings, read back as statistics
|
||||
|
||||
v1.2.3 let you rate how hard a set was. Nothing then read that rating back — it lived in the set
|
||||
label and nowhere else. Stats now answers the question the number was recorded for.
|
||||
|
||||
- 📊 **An Effort card in Stats** over 30d / 90d / 1Y / all time: average effort, the share of sets
|
||||
taken close to failure, and — always alongside them — how much of your training was rated at
|
||||
all. Rating is optional and off by default, so a partly rated history is normal; an average
|
||||
without its denominator would quietly speak for sets you never rated.
|
||||
- **Week by week.** The weekly average with that week's set count in the tooltip, because the
|
||||
pair is the reading: volume up with effort up is fatigue accumulating, volume up with effort
|
||||
flat is the adaptation you were training for. Weeks resting on a single rated set are dropped
|
||||
rather than drawn.
|
||||
- **Where the sets land.** The spread across the scale, not just the middle of it. Half your sets
|
||||
at failure and half in warm-up territory average out to a healthy-looking number; this is the
|
||||
chart that shows it.
|
||||
- 🔥 **Hard-sets mode on the muscle map.** The same body diagram, counting only sets taken near
|
||||
failure — "where did the stimulus go" rather than "where did the volume go". A muscle can lead
|
||||
on set count and still never be trained hard.
|
||||
- **Effort on the exercise curve.** Each session's dot on the top-set chart fills in as less is
|
||||
left in the tank, so the same weight moved with more in reserve stops reading as a flat line.
|
||||
Exercises with enough ratings also get an Effort curve of their own.
|
||||
- **One history, whichever scale you use.** Everything aggregates internally in RIR and converts
|
||||
back for display, so a history that mixes your own RIR logs with imported RPE averages as one
|
||||
series instead of two half-empty ones. RIR charts count downward on the axis, so harder sets
|
||||
sit higher.
|
||||
- Translated into all 12 UI languages.
|
||||
|
||||
### Bodyweight training, logged the way it is done
|
||||
|
||||
A push-up has no weight to type, and the app asked for one anyway — every set, on a quarter of
|
||||
the catalogue. Three reports (#31, #32, #33) turned out to be the same gap: the app assumed
|
||||
progress lived in the load. It doesn't, for the exercises most people actually start with.
|
||||
|
||||
- 💪 **Exercises know they are bodyweight.** Seeded from the equipment the dataset already
|
||||
records, so push-ups, pull-ups, dips and 300-odd others arrive marked. The weight column is
|
||||
not shown, the set row is one stepper instead of two, and the "confirm your working weight"
|
||||
prompt at the end of an exercise stops asking about a weight that was never there. (#32)
|
||||
- **Added weight when there is any.** A dip belt or a weighted vest is entered once in the
|
||||
exercise settings and reads as an addition — "+10 × 8", not "10×8" — everywhere it is shown
|
||||
back. With load on the belt the normal progression rules take over again, because now there
|
||||
is something to add.
|
||||
- 📈 **Reps and sets are the progression.** Clean session, one more rep. Set a top of the range
|
||||
and reaching it adds a set and starts the reps over instead of climbing forever; at six sets
|
||||
it says what it should have said all along, which is that it is time for weight or a harder
|
||||
variation. No ceiling set keeps the old behaviour exactly. (#33)
|
||||
- ↔️ **Reps per side.** For lunges, single-arm rows and every other unilateral movement. You
|
||||
log what you did — 16, the total — and the app shows the split, "8 per side", so the set in
|
||||
front of you is unambiguous without the rep count meaning one thing here and another there.
|
||||
The target steps in twos, 16 → 18 → 20, because half of an odd total is a rep one side never
|
||||
gets. (#31)
|
||||
- Both settings travel with a shared plan, and are written to a plan file only when they
|
||||
disagree with the catalogue — every existing plan, workout and backup is read unchanged and
|
||||
none of it needs migrating.
|
||||
- Translated into all 12 UI languages.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Creating a profile from Settings on an invite-only instance.** The sign-in screen asks for
|
||||
the invite code when the server needs one; the same registration reached from Settings never
|
||||
did, so it was refused with nothing on screen explaining why. It now asks on the same terms.
|
||||
- **A long value no longer runs through its own label** in a settings row — "Follow the routine
|
||||
(Linear progression)" overlapped "Rule" rather than shortening itself.
|
||||
|
||||
## v1.2.3 — 2026-07-31
|
||||
|
||||
How hard a set was, in whichever of the two scales you already think in — and the ratings your
|
||||
|
||||
@@ -12,6 +12,9 @@ api/ backend — server.js (Node, no framework), one dependency (@simplewe
|
||||
web/ multi-stage Dockerfile (builds frontend → nginx) + nginx.conf (serves app, proxies /api).
|
||||
media/ exercise img/gif (gitignored, fetched at runtime).
|
||||
docs/ self-hosting guide.
|
||||
mcp/ optional Model Context Protocol server — read-only stdio bridge for LLM apps
|
||||
(Claude Desktop, Cursor, …) to query a user's workouts/1RM/muscle balance. Not in
|
||||
the Docker build; only runs when an LLM client spawns it. See mcp/README.md.
|
||||
```
|
||||
|
||||
## Running for development
|
||||
@@ -28,7 +31,8 @@ cd frontend && npm test
|
||||
## Guidelines
|
||||
|
||||
- **Keep it dependency-light.** The frontend uses React + Router + Zustand and nothing else;
|
||||
new deps (front or back) are a hard sell. `api/` has exactly one dependency — keep it that way.
|
||||
new deps (front or back) are a hard sell. `api/` has two (`@simplewebauthn/server` for passkeys,
|
||||
`web-push` for notifications) — keep it near that.
|
||||
- **Match the style.** Small components, clear names, comments only where the "why" isn't obvious.
|
||||
State lives in the Zustand store (`src/store`); pure helpers in `src/lib`.
|
||||
- **Don't commit** the exercise media (`media/`) or `data/` — they're gitignored.
|
||||
@@ -47,6 +51,19 @@ cd frontend && npm test
|
||||
`src/lib/progression.js` — the policy interface is already there
|
||||
- Accessibility passes on the workout and chart screens
|
||||
|
||||
## Where to ask what
|
||||
|
||||
| You have | Goes to |
|
||||
| --- | --- |
|
||||
| A question, or self-hosting that won't behave | [An issue labelled `question`](https://gitea.com/DuarteSantos/openGym/issues) |
|
||||
| An idea you're not sure about yet | [An issue labelled `idea`](https://gitea.com/DuarteSantos/openGym/issues) |
|
||||
| A reproducible bug | [Issues](https://gitea.com/DuarteSantos/openGym/issues) |
|
||||
| A change you've already built | A pull request |
|
||||
|
||||
gitea.com has no Discussions, so questions and ideas are issues too — just labelled, so nobody
|
||||
mistakes a question for agreed-on work. An answered question is worth more than the same answer
|
||||
in a chat log: the next person searching "passkey login fails behind my reverse proxy" finds it.
|
||||
|
||||
## Reporting bugs
|
||||
|
||||
Open an issue with: what you did, what you expected, what happened, and your browser/OS. If it's
|
||||
|
||||
@@ -46,11 +46,54 @@ SOFTWARE.
|
||||
|
||||
## Exercise data & media
|
||||
|
||||
The exercise names, instructions (English in `frontend/src/lib/exercises-data.js`, other
|
||||
languages in `frontend/src/instr/`, regenerated via `scripts/build-instructions.mjs`), images
|
||||
and animations (fetched into `media/` at build time) come from
|
||||
[**hasaneyldrm/exercises-dataset**](https://github.com/hasaneyldrm/exercises-dataset)
|
||||
and are **not** covered by openGym's AGPL license — they remain under that dataset's own terms.
|
||||
The media files are not distributed in this repository; they are downloaded from the upstream
|
||||
source on first run. If you redistribute openGym with the media included, review the upstream
|
||||
license first.
|
||||
Both come from [**hasaneyldrm/exercises-dataset**](https://github.com/hasaneyldrm/exercises-dataset),
|
||||
and that dataset licenses them differently. Neither is covered by openGym's AGPL license.
|
||||
|
||||
### Metadata & instruction text — MIT
|
||||
|
||||
The exercise names, attributes and instructions (English in `frontend/src/lib/exercises-data.js`,
|
||||
other languages in `frontend/src/instr/`, regenerated via `scripts/build-instructions.mjs`) are
|
||||
MIT-licensed, reproduced below.
|
||||
|
||||
```
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Hasan Emir Yıldırım
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation and data files (the "Software"),
|
||||
to deal in the Software without restriction, including without limitation the
|
||||
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
|
||||
sell copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
```
|
||||
|
||||
### Images & animations — © Gym visual, not MIT and not AGPL
|
||||
|
||||
> **© Gym visual — https://gymvisual.com/**
|
||||
|
||||
The exercise thumbnails (180×180) and animations are **© [Gym visual](https://gymvisual.com/)**.
|
||||
They are in the upstream dataset with the rights holder's written permission, granted to that
|
||||
dataset; that permission is **not transferable**. Their use is governed by Gym visual's
|
||||
[Terms & Conditions](https://gymvisual.com/content/3-terms-and-conditions-of-use) — not by the MIT
|
||||
license above, and not by openGym's AGPL.
|
||||
|
||||
**openGym does not redistribute this media.** It is not in this repository, not in its history,
|
||||
and not in the published Docker images or the Android APK. A self-hosted instance downloads it
|
||||
from the upstream source on first `docker compose up`; the mobile and demo builds load it from a
|
||||
CDN at runtime.
|
||||
|
||||
If you want to reuse the media — in openGym or anywhere else, commercially or not — **obtain your
|
||||
own license from Gym visual first**, and keep the `© Gym visual — https://gymvisual.com/`
|
||||
attribution intact wherever it appears.
|
||||
@@ -19,9 +19,9 @@ No account on someone else's server, no subscription, no ads. Just `docker compo
|
||||

|
||||

|
||||
<br>
|
||||

|
||||
[](https://github.com/DuarteSantos8/openGym/stargazers)
|
||||
[](https://github.com/DuarteSantos8/openGym/issues)
|
||||

|
||||
[](https://gitea.com/DuarteSantos/openGym/stars)
|
||||
[](https://gitea.com/DuarteSantos/openGym/issues)
|
||||
|
||||
</div>
|
||||
|
||||
@@ -39,11 +39,11 @@ No account on someone else's server, no subscription, no ads. Just `docker compo
|
||||
|
||||
<div align="center">
|
||||
|
||||
### [🌐 opengym.duarte-santos.ch](https://opengym.duarte-santos.ch) · [▶ Try the live demo](https://duartesantos8.github.io/openGym/)
|
||||
### [🌐 opengym.duarte-santos.ch](https://opengym.duarte-santos.ch) · [📦 Source on gitea.com](https://gitea.com/DuarteSantos/openGym)
|
||||
|
||||
No signup, nothing to install — it runs entirely in your browser on example data.<br>
|
||||
<sub>There's no server behind the demo, so passkey sign-in, sync across devices and the
|
||||
admin dashboard only exist in a self-hosted instance.</sub>
|
||||
Screenshots, docs and the APK download live on the site.<br>
|
||||
<sub>The browser demo was hosted on GitHub Pages and is offline while that account is
|
||||
suspended — self-host it (below) or sideload the Android app to try it for real.</sub>
|
||||
|
||||
</div>
|
||||
|
||||
@@ -61,24 +61,30 @@ 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
|
||||
- 📥 **Bring your history with you** — import from **FitNotes** (Android and iOS), **Strong** and **Hevy**, or body weight straight out of an **Apple Health** export. Exercise names are matched against the library and anything unrecognised becomes one of your own exercises, so nothing in the file is dropped
|
||||
- 📦 **Yours to keep** — one-tap JSON export/import, guest mode, **no telemetry**
|
||||
- 🤖 **Ask an AI about your training** (optional) — an [MCP server](mcp/README.md) lets a client like Claude Desktop or Cursor read your history in your own words: *"what did I bench last week?"*. Read-only, spawned locally by the client, nothing leaves your box. Not in the Docker build — if you don't use an AI assistant, it isn't there
|
||||
- 📱 **Standalone Android app** — the whole tracker as a sideloadable APK: no account, no server, data on the phone, native workout reminders ([download](https://opengym.duarte-santos.ch))
|
||||
|
||||
## Quick start (self-host)
|
||||
@@ -86,7 +92,7 @@ as a home-screen app, passkey sign-in, offline support, sync across your phone a
|
||||
You need [Docker](https://docs.docker.com/get-docker/) with Compose.
|
||||
|
||||
```bash
|
||||
git clone https://github.com/DuarteSantos8/openGym
|
||||
git clone https://gitea.com/DuarteSantos/openGym
|
||||
cd openGym
|
||||
cp .env.example .env
|
||||
docker compose pull # grab prebuilt images (amd64 + arm64) — skip to build from source instead
|
||||
@@ -94,8 +100,17 @@ docker compose up -d
|
||||
```
|
||||
|
||||
Open **http://localhost:8080**, tap **Create profile**, and you're in. First launch downloads
|
||||
the exercise media (~140 MB) once. Prefer building the images yourself instead of pulling from
|
||||
`ghcr.io`? Drop the `pull` step and run `docker compose up -d --build` — you don't need Node or
|
||||
the exercise media (~140 MB) once.
|
||||
|
||||
> **About that media:** it comes from
|
||||
> [hasaneyldrm/exercises-dataset](https://github.com/hasaneyldrm/exercises-dataset), whose
|
||||
> metadata and instruction text are MIT — but whose images and animations are
|
||||
> **© [Gym visual](https://gymvisual.com/)**, used under that dataset's terms and *not* under
|
||||
> openGym's AGPL. openGym ships none of it: your instance downloads it from upstream. Reusing it
|
||||
> yourself, commercially or not, needs your own licence from Gym visual — see
|
||||
> [NOTICE.md](NOTICE.md).
|
||||
Prefer building the images yourself instead of pulling from
|
||||
`gitea.com`? Drop the `pull` step and run `docker compose up -d --build` — you don't need Node or
|
||||
a build step locally either way.
|
||||
|
||||
> Want it reachable from your phone over the internet with passkeys? You'll need an HTTPS
|
||||
@@ -130,7 +145,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
|
||||
@@ -149,11 +164,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
|
||||
|
||||
@@ -173,7 +196,8 @@ Rough, community-driven — ideas and PRs welcome:
|
||||
## Tech
|
||||
|
||||
React 19 + Vite (React Router, Zustand) · Node (no framework) · nginx · Docker Compose ·
|
||||
WebAuthn · exercise data from [hasaneyldrm/exercises-dataset](https://github.com/hasaneyldrm/exercises-dataset).
|
||||
WebAuthn · exercise data from [hasaneyldrm/exercises-dataset](https://github.com/hasaneyldrm/exercises-dataset)
|
||||
(MIT metadata and instructions; media © Gym visual — see [License](#license)).
|
||||
No database server, no cloud dependencies — the frontend builds inside Docker, so self-hosting
|
||||
stays a one-command `docker compose up`.
|
||||
|
||||
@@ -182,15 +206,54 @@ lives in pure functions under `frontend/src/lib/` with tests next to them: `npm
|
||||
`frontend/`. Vitest is a dev dependency; the app itself ships no runtime dependencies beyond
|
||||
React, the router and Zustand.
|
||||
|
||||
The same pure helpers power an optional MCP server (`mcp/`) that lets an LLM client like
|
||||
Claude Desktop read your data over stdio — see [mcp/README.md](mcp/README.md). Opt-in, not
|
||||
in the Docker build.
|
||||
|
||||
## Community
|
||||
|
||||
- **[Issues](https://gitea.com/DuarteSantos/openGym/issues)** — bugs, questions, self-hosting
|
||||
help and ideas. gitea.com has no Discussions, so it all lives in one tracker: label a question
|
||||
`question` and an idea `idea`, and it gets treated as one rather than as agreed-on work.
|
||||
- **Login trouble?** Most of it is an `RP_ID`/`ORIGIN` mismatch — check
|
||||
[docs/SELF_HOSTING.md](docs/SELF_HOSTING.md) before opening an issue.
|
||||
- **Pull requests** — [open one on gitea.com](https://gitea.com/DuarteSantos/openGym/pulls); see
|
||||
[CONTRIBUTING.md](CONTRIBUTING.md).
|
||||
|
||||
> **On the GitHub repo:** `github.com/DuarteSantos8/openGym` is offline because the account was
|
||||
> suspended. gitea.com is the home of the project until that is resolved — same history, same
|
||||
> tags, same releases. Old GitHub issue and PR numbers in [CHANGELOG.md](CHANGELOG.md) are kept
|
||||
> as plain references; they don't map onto gitea's numbering.
|
||||
|
||||
## Contributing
|
||||
|
||||
Issues and PRs welcome — see [CONTRIBUTING.md](CONTRIBUTING.md). Good first issues: more starter
|
||||
plans, exercise-data languages, import from other trackers. **A ⭐ helps more people find it.**
|
||||
|
||||
openGym is free and stays free: AGPL, no subscription, no paid tier, nothing held back for
|
||||
sponsors. If it replaced a paid tracker for you and you want to chip in, the Sponsor button at the
|
||||
top of the page is there — a star, a bug report or a PR is worth just as much.
|
||||
|
||||
<a href="https://buymeacoffee.com/duartesantos" target="_blank">
|
||||
<img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png"
|
||||
alt="Buy Me A Coffee"
|
||||
style="height: 60px !important;width: 217px !important;">
|
||||
</a>
|
||||
|
||||
## License
|
||||
|
||||
[GNU AGPL v3.0](LICENSE) — free and open source. You can self-host, use, modify and share it;
|
||||
if you run a modified version as a network service, you must offer that version's source under
|
||||
the same license. Nobody can turn openGym into a closed, proprietary product.
|
||||
**openGym's own code** is [GNU AGPL v3.0](LICENSE) — free and open source. You can self-host,
|
||||
use, modify and share it; if you run a modified version as a network service, you must offer that
|
||||
version's source under the same license. Nobody can turn openGym into a closed, proprietary
|
||||
product.
|
||||
|
||||
Exercise images/GIFs are fetched from the upstream dataset and keep their own terms — see [NOTICE.md](NOTICE.md).
|
||||
**Third-party content is not, and openGym cannot sublicense it.** The exercise metadata and
|
||||
instruction text come from
|
||||
[hasaneyldrm/exercises-dataset](https://github.com/hasaneyldrm/exercises-dataset) under the
|
||||
**MIT** license. The exercise images and animations are **© [Gym visual](https://gymvisual.com/)**
|
||||
and are used under that dataset's terms — openGym does not redistribute them (your instance
|
||||
fetches them at first run) and does not relicense them under the AGPL. To reuse that media
|
||||
yourself, get your own licence from Gym visual
|
||||
([terms](https://gymvisual.com/content/3-terms-and-conditions-of-use)).
|
||||
|
||||
Full third-party notices, including the body-diagram geometry: **[NOTICE.md](NOTICE.md)**.
|
||||
@@ -0,0 +1,148 @@
|
||||
# Security policy
|
||||
|
||||
openGym is a self-hosted app: you run the server, you hold the data. This file says which
|
||||
versions get fixes, how to report something privately, and — the part most people actually
|
||||
need — what the app protects you from and what it doesn't.
|
||||
|
||||
## Supported versions
|
||||
|
||||
Only the **latest release**. Releases are semver tags (`v1.0.0` → `v1.2.3`, see
|
||||
[CHANGELOG.md](CHANGELOG.md)); there is no LTS or maintenance branch and older tags are never
|
||||
patched. A fix ships in the next release and in the `latest` images on gitea.com.
|
||||
|
||||
Updating a self-hosted instance:
|
||||
|
||||
```bash
|
||||
git pull && docker compose pull && docker compose up -d
|
||||
```
|
||||
|
||||
## Reporting a vulnerability
|
||||
|
||||
The project moved to gitea.com, which has no private-advisory feature. So: open an issue on
|
||||
<https://gitea.com/DuarteSantos/openGym/issues> saying only *"I need a private channel for a
|
||||
security report"* — no details, no repro, no version — and you'll get an address to send it to
|
||||
within a couple of days.
|
||||
|
||||
> The GitHub repo and its private vulnerability reporting are gone with the suspended account;
|
||||
> `github.com/DuarteSantos8/openGym/security/advisories/new` no longer resolves.
|
||||
|
||||
Please don't put a working exploit in a public issue if it can be used against other people's
|
||||
instances. Everything else (a crash you can only trigger on your own box, a scanner warning)
|
||||
is fine as a normal issue.
|
||||
|
||||
Useful in a report: the version or commit, whether you're running the prebuilt images or a
|
||||
source build, your `RP_ID`/`ORIGIN` and what sits in front of the app, steps to reproduce, and
|
||||
what an attacker gets out of it.
|
||||
|
||||
**On response times:** this is a hobby project maintained by one person alongside school. There
|
||||
is no SLA and no bounty. Expect days rather than hours, and longer during exam periods. If a
|
||||
week goes by with no reply, comment on the advisory thread — it's more likely to be a missed
|
||||
notification than a decision. If a report goes unfixed and you want to disclose publicly, say so
|
||||
in the thread; there's no objection, and no request to sit on it indefinitely.
|
||||
|
||||
## In scope
|
||||
|
||||
- **`api/server.js`** — forging or replaying a session cookie, bypassing passkey verification,
|
||||
reading or writing another user's data through `/api/data`, reaching `/api/admin/*` without
|
||||
being an admin, or creating a profile without a valid code while `INVITE_ONLY=1`.
|
||||
- **Frontend** — XSS in the React app, or anything that lets a page on another origin read or
|
||||
change a signed-in user's data.
|
||||
- **Shipped deployment config** — `docker-compose.yml`, `web/nginx.conf`, the two Dockerfiles:
|
||||
a default that exposes something a self-hoster wouldn't expect to be exposed.
|
||||
- **The published images** `gitea.com/duartesantos/opengym-api` and `-web`.
|
||||
|
||||
## Out of scope
|
||||
|
||||
- Anything that already assumes access to the host, to `./data`, or to the Docker socket. The
|
||||
operator is trusted by design — see the security model below.
|
||||
- Admins reading their users' workout history. That is the documented purpose of the admin
|
||||
dashboard, not a leak.
|
||||
- **Missing rate limiting**, brute force, or "I sent 100k requests and it got slow". The app
|
||||
has no rate limiting at all and doesn't pretend to; that belongs in the reverse proxy you put
|
||||
in front of it. Genuine amplification (one small request causing unbounded work) *is* in scope.
|
||||
- **Missing security headers** (CSP, HSTS, X-Frame-Options) — `web/nginx.conf` sets none; TLS
|
||||
and headers are the reverse proxy's job. A concrete attack that headers would have stopped is
|
||||
still worth reporting.
|
||||
- Instances served over plain `http://` on a LAN IP. Unsupported: passkeys don't work there and
|
||||
the session cookie isn't marked `Secure`.
|
||||
- Scanner output with no working exploit, and `npm audit` findings in build-time
|
||||
devDependencies (Vite, Vitest, Capacitor CLI) that never reach a running instance.
|
||||
- The GitHub Pages demo build — it has no backend at all, everything stays in that browser.
|
||||
- Third-party content: the exercise image/GIF dataset and the CDN it's fetched from.
|
||||
|
||||
## Security model
|
||||
|
||||
Read this before hosting openGym for anyone other than yourself.
|
||||
|
||||
### What it does
|
||||
|
||||
- **Passkeys only.** No passwords, no email addresses, no reset flow. Registration and login are
|
||||
verified server-side by `@simplewebauthn/server` against `expectedOrigin: ORIGIN` and
|
||||
`expectedRPID: RP_ID`, and the authenticator's signature counter is stored and updated on every
|
||||
login (`api/server.js:292-318`, `api/server.js:338-358`).
|
||||
- **Sessions are a signed cookie.** `gymsid` carries `<uid>:<expiry>:<version>` plus an
|
||||
HMAC-SHA256 tag over it, compared in constant time (`api/server.js:148-161`). The key is 32
|
||||
random bytes generated on first run and written to `./data/secret` with mode `0600`
|
||||
(`api/server.js:34-36`). The cookie is `HttpOnly` and `SameSite=Lax`, and gets `Secure` **only
|
||||
when `ORIGIN` starts with `https:`** (`api/server.js:29`, `api/server.js:198-201`).
|
||||
- **Any user can end every session they have.** `POST /api/logout/all` increments that account's
|
||||
session version, and every authenticated request checks the version in the cookie against the
|
||||
one on the user record (`api/server.js:167`, `api/server.js:187-188`), so every cookie ever
|
||||
issued for the account — on every device, including a copy someone walked off with — stops
|
||||
verifying at once. Passkeys are untouched; signing back in works immediately.
|
||||
- **Data is isolated per user by the session's uid.** `GET`/`PUT /api/data` only ever touch
|
||||
`state-<uid>.json` for the caller (`api/server.js:375-392`); no route lets a normal user name
|
||||
another user.
|
||||
- **Disabling an account takes effect immediately.** Every authenticated request and every login
|
||||
is rejected for a disabled user (`api/server.js:184`, `api/server.js:357`).
|
||||
|
||||
### What it does not do
|
||||
|
||||
- **Nothing in `./data` is encrypted.** It holds `db.json` (users, passkey public keys, push
|
||||
subscriptions, invite codes), one `state-<uid>.json` per user with their complete workout
|
||||
history and body-weight log, `secret`, and `vapid.json`. Anyone who can read that folder — you,
|
||||
whoever holds the backups, whoever gets into the host — can read every user's data, and with
|
||||
`secret` can mint a valid session cookie for any account. **If you host openGym for other
|
||||
people, they are trusting you exactly as much as they'd trust any server operator.**
|
||||
- **Admins can read everything.** A user listed in `ADMIN_UIDS` (or flagged `admin: true` in
|
||||
`db.json`) gets every user's full history and body weight, can disable accounts, and can create
|
||||
or revoke invite codes (`api/server.js:460-540`). Off by default — a fresh instance has no admin.
|
||||
- **Sessions can't be revoked one device at a time.** Revocation is per *account*, not per
|
||||
session: `POST /api/logout/all` kills all of them at once and there is no device list to pick
|
||||
from. `POST /api/logout` on its own only clears the cookie in that one browser
|
||||
(`api/server.js:361`) — a copy taken beforehand keeps working. Sessions last **90 days** by
|
||||
default, settable with `SESSION_DAYS` (`api/server.js:26`); each cookie carries the lifetime it
|
||||
was issued with, so changing the setting doesn't reach cookies that are already out. Deleting
|
||||
`./data/secret` and restarting still works as the instance-wide reset, and disabling an account
|
||||
still locks out one user completely.
|
||||
- **CSRF protection is `SameSite=Lax` and nothing else.** There are no CSRF tokens.
|
||||
- **User verification is preferred, not required.** Both handshakes pass
|
||||
`requireUserVerification: false` (`api/server.js:297`, `api/server.js:343`), so a passkey
|
||||
released without a biometric or PIN is still accepted. In practice: unlocked device ≈ account
|
||||
access.
|
||||
- **One passkey per profile, and no recovery.** Every successful registration creates a *new*
|
||||
profile (`api/server.js:309-319`); there is no route to attach a second passkey to an existing
|
||||
one, and no email or reset path. Lose the passkey and that profile is unreachable — only direct
|
||||
surgery on `./data` gets it back.
|
||||
- **Disabling someone isn't a ban.** They can still register a fresh profile with a new passkey
|
||||
unless `INVITE_ONLY=1` is set.
|
||||
- **HTTPS is required and the app doesn't provide it.** The API container speaks plain HTTP and
|
||||
nginx listens on `:80` (`web/nginx.conf`); TLS is your reverse proxy's job. Without it,
|
||||
browsers won't do passkeys at all (except on `http://localhost`) and the session cookie is sent
|
||||
in the clear.
|
||||
- **No rate limiting anywhere.** Nothing throttles logins, registrations or writes, and
|
||||
`POST /api/register/options` still answers whether an invite code is valid
|
||||
(`api/server.js:272`), so an invite-only instance on the open internet should have a rate limit
|
||||
in front of it. New invite codes are 16 hex characters — 64 bits (`api/server.js:525`) — which
|
||||
makes guessing one impractical even unthrottled; codes generated by earlier versions are 8
|
||||
characters / 32 bits and still work, so revoke and reissue any that are still unused. The only
|
||||
hard limit
|
||||
in the app is a 5 MB request body (`api/server.js:27`).
|
||||
- **A few endpoints answer without a session:** `/api/health` (which includes the total user
|
||||
count), `/api/config` (whether invite-only is on), `/api/push/public-key`, and the
|
||||
register/login handshakes.
|
||||
- **Changing `RP_ID` invalidates every existing passkey.** They were bound to the old hostname
|
||||
and will fail verification against the new one. The data stays on disk but is unreachable until
|
||||
each user registers again — as a *new* profile. Choose your hostname before anyone registers.
|
||||
- **Guest mode never reaches the backend.** That data lives unencrypted in the browser's
|
||||
`localStorage` and is gone when the browser storage is cleared.
|
||||
@@ -1,8 +1,32 @@
|
||||
FROM node:22-alpine
|
||||
|
||||
ARG VERSION=dev
|
||||
ARG VCS_REF=dev
|
||||
ARG BUILD_DATE=unknown
|
||||
|
||||
LABEL maintainer="Duarte Santos https://gitea.com/DuarteSantos" \
|
||||
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://gitea.com/DuarteSantos/openGym" \
|
||||
org.opencontainers.image.url="https://gitea.com/DuarteSantos/-/packages/container/opengym-api" \
|
||||
org.opencontainers.image.documentation="https://gitea.com/DuarteSantos/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.3",
|
||||
"version": "1.2.8",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "server.js",
|
||||
|
||||
@@ -19,7 +19,16 @@ const RP_NAME = process.env.RP_NAME || 'openGym';
|
||||
// code the admin generates. Both default off so a fresh self-hosted instance stays open.
|
||||
const ADMIN_UIDS = (process.env.ADMIN_UIDS || '').split(',').map(s => s.trim()).filter(Boolean);
|
||||
const INVITE_ONLY = /^(1|true|yes|on)$/i.test(process.env.INVITE_ONLY || '');
|
||||
const SESSION_DAYS = 365;
|
||||
// Guest mode ("Continue without account") keeps everything in the browser and never touches this
|
||||
// server — but on an instance meant for a known set of people, an entrance nobody can walk back
|
||||
// out of is still the wrong front door (#42). Default ON, so existing instances are unchanged;
|
||||
// the polarity is inverted from INVITE_ONLY because the safe default here is the permissive one.
|
||||
const ALLOW_GUEST = !/^(0|false|no|off)$/i.test(process.env.ALLOW_GUEST || '');
|
||||
// 90 days keeps someone who trains a few times a week permanently signed in without a stolen
|
||||
// cookie staying good for a year. Overridable because a family instance and one on the open
|
||||
// internet don't want the same number. Only affects cookies minted from now on — the expiry is
|
||||
// baked into each cookie when it's issued, so lowering this never cuts an existing session short.
|
||||
const SESSION_DAYS = Math.max(1, +(process.env.SESSION_DAYS || 90) || 90);
|
||||
const MAX_BODY = 5 * 1024 * 1024;
|
||||
// Secure cookies require HTTPS; over plain http://localhost the flag would drop the cookie
|
||||
const SECURE = /^https:/i.test(ORIGIN) ? ' Secure;' : '';
|
||||
@@ -155,9 +164,15 @@ function verifySig(token) {
|
||||
} catch { return null; }
|
||||
return payload;
|
||||
}
|
||||
function makeSession(uid) {
|
||||
// Session payload is `<uid>:<expiry>:<version>`, where the version is the user's `sv` counter.
|
||||
// Bumping `sv` (POST /api/logout/all) makes every cookie ever handed out for that account stop
|
||||
// verifying, which is the only revocation there was before short of deleting ./data/secret and
|
||||
// signing out the whole instance. Cookies minted before `sv` existed have no third field and are
|
||||
// read as version 0, matching a user who has never bumped — they stay valid until they expire.
|
||||
const sessionVersion = user => user.sv || 0;
|
||||
function makeSession(user) {
|
||||
const exp = Date.now() + SESSION_DAYS * 86400000;
|
||||
return sign(uid + ':' + exp);
|
||||
return sign(user.id + ':' + exp + ':' + sessionVersion(user));
|
||||
}
|
||||
function readSession(req) {
|
||||
const cookies = Object.fromEntries((req.headers.cookie || '').split(';').map(c => {
|
||||
@@ -167,10 +182,15 @@ function readSession(req) {
|
||||
if (!tok) return null;
|
||||
const payload = verifySig(tok);
|
||||
if (!payload) return null;
|
||||
const [uid, exp] = payload.split(':');
|
||||
const [uid, exp, ver] = payload.split(':');
|
||||
if (!uid || +exp < Date.now()) return null;
|
||||
const user = db.users.find(u => u.id === uid) || null;
|
||||
if (user && user.disabled) return null; // disabled accounts are locked out everywhere
|
||||
if (!user) return null;
|
||||
if (user.disabled) return null; // disabled accounts are locked out everywhere
|
||||
// Missing third field = pre-versioning cookie = version 0. Anything non-numeric is a malformed
|
||||
// payload (it still had to pass the HMAC, so this is belt-and-braces) and is refused outright.
|
||||
const claimed = ver === undefined ? 0 : Number(ver);
|
||||
if (!Number.isInteger(claimed) || claimed !== sessionVersion(user)) return null;
|
||||
return user;
|
||||
}
|
||||
// Guard for /api/admin/* — resolves the caller and 401/403s if they aren't an admin.
|
||||
@@ -180,8 +200,8 @@ function requireAdmin(req, res) {
|
||||
if (!isAdmin(user)) { json(res, 403, { error: 'forbidden' }); return null; }
|
||||
return user;
|
||||
}
|
||||
function sessionCookie(uid) {
|
||||
return `gymsid=${makeSession(uid)}; Path=/; Max-Age=${SESSION_DAYS * 86400}; HttpOnly;${SECURE} SameSite=Lax`;
|
||||
function sessionCookie(user) {
|
||||
return `gymsid=${makeSession(user)}; Path=/; Max-Age=${SESSION_DAYS * 86400}; HttpOnly;${SECURE} SameSite=Lax`;
|
||||
}
|
||||
const clearCookie = `gymsid=; Path=/; Max-Age=0; HttpOnly;${SECURE} SameSite=Lax`;
|
||||
|
||||
@@ -241,7 +261,7 @@ const routes = {
|
||||
'GET /api/health': async (req, res) => json(res, 200, { ok: true, users: db.users.length }),
|
||||
|
||||
// Public config the login screen needs before anyone is signed in.
|
||||
'GET /api/config': async (req, res) => json(res, 200, { invite_only: INVITE_ONLY }),
|
||||
'GET /api/config': async (req, res) => json(res, 200, { invite_only: INVITE_ONLY, allow_guest: ALLOW_GUEST }),
|
||||
|
||||
'GET /api/me': async (req, res) => {
|
||||
const user = readSession(req);
|
||||
@@ -301,7 +321,7 @@ const routes = {
|
||||
transports: body.credential?.response?.transports || []
|
||||
});
|
||||
saveDb();
|
||||
json(res, 200, { user: { id: user.id, name: user.name, admin: isAdmin(user) } }, { 'Set-Cookie': sessionCookie(user.id) });
|
||||
json(res, 200, { user: { id: user.id, name: user.name, admin: isAdmin(user) } }, { 'Set-Cookie': sessionCookie(user) });
|
||||
},
|
||||
|
||||
'POST /api/login/options': async (req, res) => {
|
||||
@@ -340,11 +360,23 @@ const routes = {
|
||||
const user = db.users.find(u => u.id === cred.userId);
|
||||
if (!user) return json(res, 500, { error: 'user missing' });
|
||||
if (user.disabled) return json(res, 403, { error: 'this account has been disabled' });
|
||||
json(res, 200, { user: { id: user.id, name: user.name, admin: isAdmin(user) } }, { 'Set-Cookie': sessionCookie(user.id) });
|
||||
json(res, 200, { user: { id: user.id, name: user.name, admin: isAdmin(user) } }, { 'Set-Cookie': sessionCookie(user) });
|
||||
},
|
||||
|
||||
'POST /api/logout': async (req, res) => json(res, 200, { ok: true }, { 'Set-Cookie': clearCookie }),
|
||||
|
||||
// "Sign out everywhere" — bumps this user's session version, which invalidates every cookie
|
||||
// ever issued for the account, on every device, including a copy someone else walked off with.
|
||||
// The caller's own cookie is cleared here too, so the browser doing it doesn't sit on a token
|
||||
// it no longer accepts. Passkeys are untouched: signing back in works immediately.
|
||||
'POST /api/logout/all': async (req, res) => {
|
||||
const user = readSession(req);
|
||||
if (!user) return json(res, 401, { error: 'not signed in' });
|
||||
user.sv = sessionVersion(user) + 1;
|
||||
saveDb();
|
||||
json(res, 200, { ok: true }, { 'Set-Cookie': clearCookie });
|
||||
},
|
||||
|
||||
'GET /api/data': async (req, res) => {
|
||||
const user = readSession(req);
|
||||
if (!user) return json(res, 401, { error: 'not signed in' });
|
||||
@@ -491,7 +523,11 @@ const routes = {
|
||||
const admin = requireAdmin(req, res); if (!admin) return;
|
||||
const body = await readBody(req);
|
||||
let code;
|
||||
do { code = crypto.randomBytes(4).toString('hex').toUpperCase(); } while (db.invites.some(i => i.code === code));
|
||||
// 16 hex chars = 64 bits, up from 8 chars / 32 bits. The app has no rate limiting by design
|
||||
// (that's the reverse proxy's job) and /api/register/options tells a caller whether a code is
|
||||
// good, so the code itself has to be the thing that isn't worth guessing. Codes already in
|
||||
// db.json keep working — validation is an exact string compare, never a length or format check.
|
||||
do { code = crypto.randomBytes(8).toString('hex').toUpperCase(); } while (db.invites.some(i => i.code === code));
|
||||
const invite = { code, note: String(body.note || '').slice(0, 60), createdBy: admin.id, created: new Date().toISOString() };
|
||||
db.invites.push(invite);
|
||||
saveDb();
|
||||
|
||||
|
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 |
@@ -2,7 +2,10 @@ name: opengym
|
||||
|
||||
services:
|
||||
# One-time: download the exercise images + GIFs into ./media (skipped if already there).
|
||||
# ~140 MB, from github.com/hasaneyldrm/exercises-dataset (CC).
|
||||
# ~140 MB, from github.com/hasaneyldrm/exercises-dataset. That dataset is MIT for the
|
||||
# metadata and instruction text, but the images and GIFs are © Gym visual
|
||||
# (https://gymvisual.com/) and are used under the dataset's terms — openGym neither
|
||||
# redistributes nor relicenses them. See NOTICE.md.
|
||||
media:
|
||||
image: alpine/git
|
||||
volumes:
|
||||
@@ -13,6 +16,14 @@ services:
|
||||
- |
|
||||
if [ -z "$$(ls -A /out/img 2>/dev/null)" ]; then
|
||||
echo "↓ Downloading exercise media (~140 MB, one time)…"
|
||||
echo " Source: github.com/hasaneyldrm/exercises-dataset"
|
||||
echo " Metadata and instruction text: MIT."
|
||||
echo " Images and animations: © Gym visual — https://gymvisual.com/"
|
||||
echo " They are used under that dataset's terms, not openGym's AGPL, and are"
|
||||
echo " downloaded from upstream — openGym does not redistribute them."
|
||||
echo " Terms: https://gymvisual.com/content/3-terms-and-conditions-of-use"
|
||||
echo " Reusing this media yourself, commercially or not, needs your own licence"
|
||||
echo " from Gym visual. Details in NOTICE.md."
|
||||
git clone --depth 1 https://github.com/hasaneyldrm/exercises-dataset /tmp/ds
|
||||
cp /tmp/ds/images/*.jpg /out/img/ && cp /tmp/ds/videos/*.gif /out/gif/
|
||||
echo "✓ Exercise media ready ($$(ls /out/img | wc -l) images)."
|
||||
@@ -24,12 +35,14 @@ services:
|
||||
# Passkey auth + per-user data (Node, no framework).
|
||||
# image: prebuilt (docker compose pull). build: from source (docker compose up --build).
|
||||
api:
|
||||
image: ghcr.io/duartesantos8/opengym-api:latest
|
||||
image: gitea.com/duartesantos/opengym-api:latest
|
||||
build: ./api
|
||||
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
|
||||
@@ -37,7 +50,7 @@ services:
|
||||
# Builds the React frontend (multi-stage) and serves it, proxying /api → api
|
||||
# and the exercise media from the shared volume. Single origin for passkeys.
|
||||
web:
|
||||
image: ghcr.io/duartesantos8/opengym-web:latest
|
||||
image: gitea.com/duartesantos/opengym-web:latest
|
||||
build:
|
||||
context: .
|
||||
dockerfile: web/Dockerfile
|
||||
@@ -48,7 +61,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://gitea.com/DuarteSantos/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 pull # prebuilt images from gitea.com (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.
|
||||
@@ -90,11 +90,12 @@ Visit `https://gym.example.com`, create your profile, and add it to your home sc
|
||||
Anyone who can reach the URL can create their own profile — each gets isolated data. That's the
|
||||
default: open signup, no admin.
|
||||
|
||||
If you'd rather control who gets in, two optional settings in `.env` turn that around:
|
||||
If you'd rather control who gets in, three optional settings in `.env` turn that around:
|
||||
|
||||
```bash
|
||||
ADMIN_UIDS=youruserid # comma-separated; these users get the admin dashboard
|
||||
INVITE_ONLY=1 # new profiles need an invite code
|
||||
ALLOW_GUEST=0 # remove "Continue without account"
|
||||
```
|
||||
|
||||
Register your own passkey profile first, then find your id in `./data/db.json` under `users[].id`
|
||||
@@ -104,10 +105,43 @@ out and locked out everywhere until you re-enable it), and — with `INVITE_ONLY
|
||||
revoking invite codes. Existing accounts keep working when you switch invite-only on. Admin access
|
||||
is gated by your passkey and enforced server-side, so it needs no separate login.
|
||||
|
||||
`INVITE_ONLY=1` and `ALLOW_GUEST=0` answer different questions and are usually set together.
|
||||
Invite-only controls who may *create a profile*; it says nothing about the **Continue without
|
||||
account** button, which never creates one. Guest mode keeps everything in that browser and never
|
||||
talks to the server — there is no account, no sync and nothing for the admin dashboard to show —
|
||||
so on an instance meant for a known set of people it is a door that leads nowhere useful. With
|
||||
`ALLOW_GUEST=0` the button is gone, and anyone already using the app as a guest is returned to the
|
||||
login screen on their next visit. Their data is not deleted: it stays in that browser and comes
|
||||
back if you ever switch guests on again, or moves into a real profile if they create one on the
|
||||
same device.
|
||||
|
||||
Prefer to keep the whole thing off the open internet? A VPN or an auth proxy (Authelia, Cloudflare
|
||||
Access…) in front still works, and composes with the above.
|
||||
|
||||
## 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`:
|
||||
|
||||
@@ -118,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.
|
||||
@@ -135,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:
|
||||
|
||||
@@ -164,6 +202,17 @@ 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. |
|
||||
|
||||
### `VITE_IMG_BASE` / `VITE_GIF_BASE` are build-time, not run-time
|
||||
|
||||
These two are read by Vite when the frontend is **compiled**, so their values are baked into
|
||||
the shipped JavaScript bundle. Setting them in the `.env` next to `docker compose` has no
|
||||
effect on an already-built image — the bundle has already made up its mind.
|
||||
|
||||
They are only useful if you build the frontend yourself (`docker compose up -d --build`, or a
|
||||
`npm run build` with the variables exported). If you need to redirect media on a prebuilt
|
||||
image, do it in your reverse proxy instead.
|
||||
@@ -7,8 +7,8 @@ android {
|
||||
applicationId "ch.duartesantos.opengym"
|
||||
minSdkVersion rootProject.ext.minSdkVersion
|
||||
targetSdkVersion rootProject.ext.targetSdkVersion
|
||||
versionCode 4
|
||||
versionName "1.2.3"
|
||||
versionCode 9
|
||||
versionName "1.2.8"
|
||||
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
||||
aaptOptions {
|
||||
// Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps.
|
||||
|
||||
@@ -9,6 +9,7 @@ android {
|
||||
|
||||
apply from: "../capacitor-cordova-android-plugins/cordova.variables.gradle"
|
||||
dependencies {
|
||||
implementation project(':capacitor-app')
|
||||
implementation project(':capacitor-filesystem')
|
||||
implementation project(':capacitor-local-notifications')
|
||||
implementation project(':capacitor-share')
|
||||
|
||||
@@ -2,6 +2,9 @@
|
||||
include ':capacitor-android'
|
||||
project(':capacitor-android').projectDir = new File('../node_modules/@capacitor/android/capacitor')
|
||||
|
||||
include ':capacitor-app'
|
||||
project(':capacitor-app').projectDir = new File('../node_modules/@capacitor/app/android')
|
||||
|
||||
include ':capacitor-filesystem'
|
||||
project(':capacitor-filesystem').projectDir = new File('../node_modules/@capacitor/filesystem/android')
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@ install! 'cocoapods', :disable_input_output_paths => true
|
||||
def capacitor_pods
|
||||
pod 'Capacitor', :path => '../../node_modules/@capacitor/ios'
|
||||
pod 'CapacitorCordova', :path => '../../node_modules/@capacitor/ios'
|
||||
pod 'CapacitorApp', :path => '../../node_modules/@capacitor/app'
|
||||
pod 'CapacitorFilesystem', :path => '../../node_modules/@capacitor/filesystem'
|
||||
pod 'CapacitorLocalNotifications', :path => '../../node_modules/@capacitor/local-notifications'
|
||||
pod 'CapacitorShare', :path => '../../node_modules/@capacitor/share'
|
||||
|
||||
@@ -1,21 +1,22 @@
|
||||
{
|
||||
"name": "opengym-frontend",
|
||||
"version": "1.2.3",
|
||||
"version": "1.2.7",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "opengym-frontend",
|
||||
"version": "1.2.3",
|
||||
"version": "1.2.7",
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"dependencies": {
|
||||
"@capacitor/app": "^7.1.2",
|
||||
"@capacitor/core": "^7.6.8",
|
||||
"@capacitor/filesystem": "^7.1.8",
|
||||
"@capacitor/local-notifications": "^7.0.7",
|
||||
"@capacitor/share": "^7.0.4",
|
||||
"react": "^19.2.7",
|
||||
"react-dom": "^19.2.7",
|
||||
"react-router-dom": "^7.18.1",
|
||||
"react-router-dom": "^7.18.2",
|
||||
"zustand": "^5.0.14"
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -24,6 +25,8 @@
|
||||
"@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"
|
||||
}
|
||||
@@ -60,6 +63,14 @@
|
||||
"@capacitor/core": "^7.6.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@capacitor/app": {
|
||||
"version": "7.1.2",
|
||||
"resolved": "https://registry.npmjs.org/@capacitor/app/-/app-7.1.2.tgz",
|
||||
"integrity": "sha512-d4I/oF/PRu4megL7/IGKYfe5j7yzSON1FRFgq6kH+m5kH6g7V+wyjHRLauCzGNjdRx4S+nWOumINds0qcRBtKg==",
|
||||
"peerDependencies": {
|
||||
"@capacitor/core": ">=7.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@capacitor/assets": {
|
||||
"version": "3.0.5",
|
||||
"resolved": "https://registry.npmjs.org/@capacitor/assets/-/assets-3.0.5.tgz",
|
||||
@@ -1264,6 +1275,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",
|
||||
@@ -2070,6 +2098,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",
|
||||
@@ -2504,6 +2545,7 @@
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/cookie/-/cookie-1.1.1.tgz",
|
||||
"integrity": "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
@@ -2593,6 +2635,12 @@
|
||||
"url": "https://github.com/sponsors/fb55"
|
||||
}
|
||||
},
|
||||
"node_modules/cssom": {
|
||||
"version": "0.5.0",
|
||||
"resolved": "https://registry.npmjs.org/cssom/-/cssom-0.5.0.tgz",
|
||||
"integrity": "sha512-iKuQcq+NdHqlAcwUY0o/HL69XQrUaQdMjmStJ8JFmUaiiQErlhrmuigkg/CU4E2J0IyUKUrMAgl36TvN67MqTw==",
|
||||
"dev": true
|
||||
},
|
||||
"node_modules/dargs": {
|
||||
"version": "7.0.0",
|
||||
"resolved": "https://registry.npmjs.org/dargs/-/dargs-7.0.0.tgz",
|
||||
@@ -3267,6 +3315,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",
|
||||
@@ -3336,6 +3416,98 @@
|
||||
"integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==",
|
||||
"dev": true
|
||||
},
|
||||
"node_modules/html-escaper": {
|
||||
"version": "3.0.3",
|
||||
"resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-3.0.3.tgz",
|
||||
"integrity": "sha512-RuMffC89BOWQoY0WKGpIhn5gX3iI54O6nRA0yC124NYVtzjmFWBIiFd8M0x+ZdX0P9R4lADg1mgP8C7PxGOWuQ==",
|
||||
"dev": true
|
||||
},
|
||||
"node_modules/htmlparser2": {
|
||||
"version": "10.1.0",
|
||||
"resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-10.1.0.tgz",
|
||||
"integrity": "sha512-VTZkM9GWRAtEpveh7MSF6SjjrpNVNNVJfFup7xTY3UpFtm67foy9HDVXneLtFVt4pMz5kZtgNcvCniNFb1hlEQ==",
|
||||
"dev": true,
|
||||
"funding": [
|
||||
"https://github.com/fb55/htmlparser2?sponsor=1",
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/fb55"
|
||||
}
|
||||
],
|
||||
"dependencies": {
|
||||
"domelementtype": "^2.3.0",
|
||||
"domhandler": "^5.0.3",
|
||||
"domutils": "^3.2.2",
|
||||
"entities": "^7.0.1"
|
||||
}
|
||||
},
|
||||
"node_modules/htmlparser2/node_modules/dom-serializer": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-2.0.0.tgz",
|
||||
"integrity": "sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg==",
|
||||
"dev": true,
|
||||
"dependencies": {
|
||||
"domelementtype": "^2.3.0",
|
||||
"domhandler": "^5.0.2",
|
||||
"entities": "^4.2.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/cheeriojs/dom-serializer?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/htmlparser2/node_modules/dom-serializer/node_modules/entities": {
|
||||
"version": "4.5.0",
|
||||
"resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz",
|
||||
"integrity": "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==",
|
||||
"dev": true,
|
||||
"engines": {
|
||||
"node": ">=0.12"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/fb55/entities?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/htmlparser2/node_modules/domhandler": {
|
||||
"version": "5.0.3",
|
||||
"resolved": "https://registry.npmjs.org/domhandler/-/domhandler-5.0.3.tgz",
|
||||
"integrity": "sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w==",
|
||||
"dev": true,
|
||||
"dependencies": {
|
||||
"domelementtype": "^2.3.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 4"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/fb55/domhandler?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/htmlparser2/node_modules/domutils": {
|
||||
"version": "3.2.2",
|
||||
"resolved": "https://registry.npmjs.org/domutils/-/domutils-3.2.2.tgz",
|
||||
"integrity": "sha512-6kZKyUajlDuqlHKVX1w7gyslj9MPIXzIFiz/rGu35uC1wMi+kMhQwGhl4lt9unC9Vb9INnY9Z3/ZA3+FhASLaw==",
|
||||
"dev": true,
|
||||
"dependencies": {
|
||||
"dom-serializer": "^2.0.0",
|
||||
"domelementtype": "^2.3.0",
|
||||
"domhandler": "^5.0.3"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/fb55/domutils?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/htmlparser2/node_modules/entities": {
|
||||
"version": "7.0.1",
|
||||
"resolved": "https://registry.npmjs.org/entities/-/entities-7.0.1.tgz",
|
||||
"integrity": "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==",
|
||||
"dev": true,
|
||||
"engines": {
|
||||
"node": ">=0.12"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/fb55/entities?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/ieee754": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz",
|
||||
@@ -3825,6 +3997,171 @@
|
||||
"integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==",
|
||||
"dev": true
|
||||
},
|
||||
"node_modules/linkedom": {
|
||||
"version": "0.18.13",
|
||||
"resolved": "https://registry.npmjs.org/linkedom/-/linkedom-0.18.13.tgz",
|
||||
"integrity": "sha512-ES/o9qotMpzpN2MHs+Iq/JcVoOj8Fa5wiQYrTdFpvAnwXL0g66XHHUc9WUMk6nAlBtGsFQ24ne+SYnvnaQ2FSw==",
|
||||
"dev": true,
|
||||
"dependencies": {
|
||||
"css-select": "^7.0.0",
|
||||
"cssom": "^0.5.0",
|
||||
"html-escaper": "^3.0.3",
|
||||
"htmlparser2": "^10.1.0",
|
||||
"uhyphen": "^0.2.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=16"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"canvas": ">= 2"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"canvas": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/linkedom/node_modules/boolbase": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/boolbase/-/boolbase-2.0.0.tgz",
|
||||
"integrity": "sha512-DkVaaQHymRhpYEYo9x1oo7Q7B0Y6KJUsjm3c9eTyFDby4MHLBTwZ6ZDWBel5zrYxj1WsZgC5oLpiz+93MluXeA==",
|
||||
"dev": true,
|
||||
"engines": {
|
||||
"node": ">=20.19.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/fb55"
|
||||
}
|
||||
},
|
||||
"node_modules/linkedom/node_modules/css-select": {
|
||||
"version": "7.0.0",
|
||||
"resolved": "https://registry.npmjs.org/css-select/-/css-select-7.0.0.tgz",
|
||||
"integrity": "sha512-snmjEVXy+1LnwXdxhYvTMj1d9tOh4HxkA1YmoayVBeeyR2C14Pum7fcxJIm4SswYspVy866eYNwlH6xC3/VH5g==",
|
||||
"dev": true,
|
||||
"dependencies": {
|
||||
"boolbase": "^2.0.0",
|
||||
"css-what": "^8.0.0",
|
||||
"domhandler": "^6.0.1",
|
||||
"domutils": "^4.0.2",
|
||||
"nth-check": "^3.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.19.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/fb55"
|
||||
}
|
||||
},
|
||||
"node_modules/linkedom/node_modules/css-what": {
|
||||
"version": "8.0.0",
|
||||
"resolved": "https://registry.npmjs.org/css-what/-/css-what-8.0.0.tgz",
|
||||
"integrity": "sha512-DH0Bqq3DNp5tdOReuNyAA+Ev4Y2GS5FMbZpeTLP6C4CDi0h5nL0BmUPChXw3o/qbHLDWHl49sbNqQVY7bMSDdw==",
|
||||
"dev": true,
|
||||
"engines": {
|
||||
"node": ">=20.19.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/fb55"
|
||||
}
|
||||
},
|
||||
"node_modules/linkedom/node_modules/dom-serializer": {
|
||||
"version": "3.1.1",
|
||||
"resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-3.1.1.tgz",
|
||||
"integrity": "sha512-4MEa38/QexBob6gFNwu+EGdWvhJ1OKuNwdYY3Y3NyeWDQfnGeDYQUDfIRzWu5B5gsv03so2Uxd28YC6zrsx3Lw==",
|
||||
"dev": true,
|
||||
"dependencies": {
|
||||
"domelementtype": "^3.0.0",
|
||||
"domhandler": "^6.0.0",
|
||||
"entities": "^8.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.19.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/cheeriojs/dom-serializer?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/linkedom/node_modules/domelementtype": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-3.0.0.tgz",
|
||||
"integrity": "sha512-umCQid3jKbDmVjx8jGaW7uUykm4DEUeyV21hPxNMo2nV955DhUThwqyOIDtreepP31hl84X7G5U9ZfsWvIB3Pg==",
|
||||
"dev": true,
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/fb55"
|
||||
}
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=20.19.0"
|
||||
}
|
||||
},
|
||||
"node_modules/linkedom/node_modules/domhandler": {
|
||||
"version": "6.0.1",
|
||||
"resolved": "https://registry.npmjs.org/domhandler/-/domhandler-6.0.1.tgz",
|
||||
"integrity": "sha512-gYzvtM72ZtxQO0T048kd6HWSbbGCNOUwcnfQ01cqIJ4X2IYKFFHZ5mKvrQETcFXxsRObZulDaKmy//R7TPtsBg==",
|
||||
"dev": true,
|
||||
"dependencies": {
|
||||
"domelementtype": "^3.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.19.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/fb55/domhandler?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/linkedom/node_modules/domutils": {
|
||||
"version": "4.0.2",
|
||||
"resolved": "https://registry.npmjs.org/domutils/-/domutils-4.0.2.tgz",
|
||||
"integrity": "sha512-qI4JLRKnSzqFqr7hAlS5xQDusBCjKSEG4t4+7aNrIQMHBcsC2TGEhuyABJdYkgSewL57PNLYEiibY2iPKhKpaA==",
|
||||
"dev": true,
|
||||
"dependencies": {
|
||||
"dom-serializer": "^3.0.0",
|
||||
"domelementtype": "^3.0.0",
|
||||
"domhandler": "^6.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.19.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/fb55/domutils?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/linkedom/node_modules/entities": {
|
||||
"version": "8.0.0",
|
||||
"resolved": "https://registry.npmjs.org/entities/-/entities-8.0.0.tgz",
|
||||
"integrity": "sha512-zwfzJecQ/Uej6tusMqwAqU/6KL2XaB2VZ2Jg54Je6ahNBGNH6Ek6g3jjNCF0fG9EWQKGZNddNjU5F1ZQn/sBnA==",
|
||||
"dev": true,
|
||||
"engines": {
|
||||
"node": ">=20.19.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/fb55/entities?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/linkedom/node_modules/nth-check": {
|
||||
"version": "3.0.1",
|
||||
"resolved": "https://registry.npmjs.org/nth-check/-/nth-check-3.0.1.tgz",
|
||||
"integrity": "sha512-GX0gsdbGVCgnRgbeGaubfjpBXyYRWOOCVeYh08bSQvDZqxz5ndXs1OTfAt/h36G1xvI94YIspsI0sVFqAV9+RQ==",
|
||||
"dev": true,
|
||||
"dependencies": {
|
||||
"boolbase": "^2.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.19.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/fb55/nth-check?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/load-json-file": {
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmjs.org/load-json-file/-/load-json-file-4.0.0.tgz",
|
||||
@@ -4757,9 +5094,10 @@
|
||||
}
|
||||
},
|
||||
"node_modules/react-router": {
|
||||
"version": "7.18.1",
|
||||
"resolved": "https://registry.npmjs.org/react-router/-/react-router-7.18.1.tgz",
|
||||
"integrity": "sha512-GDLgg3i3uM0aeJO3Fm+TCS+sDQ7gu12T6x0qdTEzcwqEfleci7JwugVNIF3U//0FWKnJT7ptG+20B2jfDqnZAg==",
|
||||
"version": "7.18.2",
|
||||
"resolved": "https://registry.npmjs.org/react-router/-/react-router-7.18.2.tgz",
|
||||
"integrity": "sha512-aUVMjFm3GAPTTZL7oYr5E7ETiqfQCHRLH+B+5afnICvf0r7kkK4eR6SMuwbSTJw/7t+12khT/Kahij49fqOCIg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"cookie": "^1.0.1",
|
||||
"set-cookie-parser": "^2.6.0"
|
||||
@@ -4778,11 +5116,12 @@
|
||||
}
|
||||
},
|
||||
"node_modules/react-router-dom": {
|
||||
"version": "7.18.1",
|
||||
"resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-7.18.1.tgz",
|
||||
"integrity": "sha512-KaZh+X/6UtEp28x51AUYZDMg9NGoz2ja3dNHa+ta/tk40vCzKhQ/RypCWBMLbmDr6//E24Vv5uPsrqXFozdkAg==",
|
||||
"version": "7.18.2",
|
||||
"resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-7.18.2.tgz",
|
||||
"integrity": "sha512-AIKJ/jgGlFb3EbfCXk5Gzshiwt+l3mqbCrNjmEWMMjqQxNJ3svBa6bgzFyCC2Sw3RA0VWF1kg3uQf2OFhxb8hw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"react-router": "7.18.1"
|
||||
"react-router": "7.18.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.0.0"
|
||||
@@ -5201,7 +5540,8 @@
|
||||
"node_modules/set-cookie-parser": {
|
||||
"version": "2.7.2",
|
||||
"resolved": "https://registry.npmjs.org/set-cookie-parser/-/set-cookie-parser-2.7.2.tgz",
|
||||
"integrity": "sha512-oeM1lpU/UvhTxw+g3cIfxXHyJRc/uidd3yK1P242gzHds0udQBYzs3y8j4gCCW+ZJ7ad0yctld8RYO+bdurlvw=="
|
||||
"integrity": "sha512-oeM1lpU/UvhTxw+g3cIfxXHyJRc/uidd3yK1P242gzHds0udQBYzs3y8j4gCCW+ZJ7ad0yctld8RYO+bdurlvw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/sharp": {
|
||||
"version": "0.32.6",
|
||||
@@ -5882,6 +6222,12 @@
|
||||
"node": ">=0.8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/uhyphen": {
|
||||
"version": "0.2.0",
|
||||
"resolved": "https://registry.npmjs.org/uhyphen/-/uhyphen-0.2.0.tgz",
|
||||
"integrity": "sha512-qz3o9CHXmJJPGBdqzab7qAYuW8kQGKNEuoHFYrBwV6hWIMcpAmxDLXojcHfFr9US1Pe6zUswEIJIbLI610fuqA==",
|
||||
"dev": true
|
||||
},
|
||||
"node_modules/undici-types": {
|
||||
"version": "8.3.0",
|
||||
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.3.0.tgz",
|
||||
@@ -6125,6 +6471,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",
|
||||
@@ -6201,6 +6557,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.3",
|
||||
"version": "1.2.8",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
@@ -9,17 +9,19 @@
|
||||
"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": {
|
||||
"@capacitor/app": "^7.1.2",
|
||||
"@capacitor/core": "^7.6.8",
|
||||
"@capacitor/filesystem": "^7.1.8",
|
||||
"@capacitor/local-notifications": "^7.0.7",
|
||||
"@capacitor/share": "^7.0.4",
|
||||
"react": "^19.2.7",
|
||||
"react-dom": "^19.2.7",
|
||||
"react-router-dom": "^7.18.1",
|
||||
"react-router-dom": "^7.18.2",
|
||||
"zustand": "^5.0.14"
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -28,6 +30,8 @@
|
||||
"@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,57 @@
|
||||
#!/usr/bin/env node
|
||||
// Guards the one invariant every locale in src/locales/ shares: the same key set.
|
||||
// English is the source language and has no locale file, so a key that exists in only
|
||||
// some locales falls back to English silently, mid-sentence, with nothing failing
|
||||
// anywhere. This catches that at review time instead of in the app.
|
||||
//
|
||||
// node scripts/check-locales.mjs
|
||||
//
|
||||
// The reference is the union of all locales, not one blessed file: a key added to a
|
||||
// single locale then flags the other ten instead of passing unnoticed.
|
||||
|
||||
import { readdirSync } from 'node:fs'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { fileURLToPath, pathToFileURL } from 'node:url'
|
||||
|
||||
const localesDir = join(dirname(fileURLToPath(import.meta.url)), '..', 'src', 'locales')
|
||||
const files = readdirSync(localesDir).filter(f => f.endsWith('.js')).sort()
|
||||
|
||||
if (!files.length) {
|
||||
console.error(`No locale files found in ${localesDir}`)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const locales = new Map()
|
||||
for (const file of files) {
|
||||
const { default: dict } = await import(pathToFileURL(join(localesDir, file)).href)
|
||||
if (!dict || typeof dict !== 'object') {
|
||||
console.error(`${file}: no default-exported object`)
|
||||
process.exit(1)
|
||||
}
|
||||
locales.set(file.replace(/\.js$/, ''), new Set(Object.keys(dict)))
|
||||
}
|
||||
|
||||
// How many locales carry each key — 1 means the key was added to a single file only,
|
||||
// which is the usual shape of the bug and worth naming separately from plain gaps.
|
||||
const seen = new Map()
|
||||
for (const keys of locales.values()) for (const k of keys) seen.set(k, (seen.get(k) || 0) + 1)
|
||||
const union = [...seen.keys()]
|
||||
|
||||
let failed = false
|
||||
for (const [lang, keys] of locales) {
|
||||
const missing = union.filter(k => !keys.has(k))
|
||||
const orphans = union.filter(k => keys.has(k) && seen.get(k) === 1)
|
||||
if (missing.length || orphans.length) {
|
||||
failed = true
|
||||
console.error(`\n${lang}.js: ${keys.size}/${union.length} keys`)
|
||||
for (const k of missing) console.error(` missing: ${JSON.stringify(k)}`)
|
||||
for (const k of orphans) console.error(` only here: ${JSON.stringify(k)}`)
|
||||
}
|
||||
}
|
||||
|
||||
if (failed) {
|
||||
console.error('\nLocale key sets differ. Every locale must carry the same keys.')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
console.log(`${locales.size} locales, ${union.length} keys each — in sync.`)
|
||||
@@ -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',
|
||||
)
|
||||
@@ -6,6 +6,7 @@ import { bindUI } from './components/ui.jsx'
|
||||
import { ACCENTS } from './lib/format.js'
|
||||
import { setLang, useLang } from './lib/i18n.js'
|
||||
import { setNav } from './lib/nav.js'
|
||||
import { initBackButton } from './lib/back.js'
|
||||
import { useWakeLock } from './lib/wakelock.js'
|
||||
import { startFlow } from './sheets.jsx'
|
||||
import Icon from './components/Icon.jsx'
|
||||
@@ -92,5 +93,11 @@ function Shell() {
|
||||
export default function App() {
|
||||
const boot = useStore(s => s.boot)
|
||||
useEffect(() => { boot() }, [boot])
|
||||
// Android system back — sheet, then page, then press-again-to-exit (see lib/back.js)
|
||||
useEffect(() => {
|
||||
let stop = null, gone = false
|
||||
initBackButton().then(fn => { if (gone) fn(); else stop = fn })
|
||||
return () => { gone = true; stop?.() }
|
||||
}, [])
|
||||
return <HashRouter><Shell /></HashRouter>
|
||||
}
|
||||
@@ -47,11 +47,13 @@ function View({ view, levels, onMuscle, selected }) {
|
||||
/**
|
||||
* <BodyMap load={{ chest: 12, … }} body="male" />
|
||||
* `load` is effective sets per muscle (see lib/muscles.js); shading is relative to
|
||||
* the hardest-worked muscle in that same load, so it always reads as a balance.
|
||||
* the hardest-worked muscle in that same load, so it always reads as a balance. Pass ordered
|
||||
* `{ at, level, exclusive? }` `thresholds` for a fixed absolute scale (recovery views use this
|
||||
* to keep their semantic bands stable); omitting it preserves the balance behavior.
|
||||
*/
|
||||
export default function BodyMap({ load = {}, body = 'male', onMuscle, selected, className = '' }) {
|
||||
export default function BodyMap({ load = {}, thresholds, body = 'male', onMuscle, selected, className = '' }) {
|
||||
const paths = useBodyPaths()
|
||||
const levels = levelsOf(load)
|
||||
const levels = levelsOf(load, thresholds)
|
||||
const g = paths && (paths[body] || paths.male)
|
||||
return (
|
||||
<div className={'bodymap ' + className}>
|
||||
|
||||
@@ -4,8 +4,15 @@ import { t } from '../lib/i18n.js'
|
||||
|
||||
const W = 340 // viewBox width; the svg stretches to its container, height comes from `h`
|
||||
|
||||
// points: [{ t: ms, y: num, d?: iso }] sorted by t. opts: { h, unit, color, axes, goal }
|
||||
export default function LineChart({ points, h = 150, unit = '', color = 'var(--acc)', axes = true, goal = null }) {
|
||||
// points: [{ t: ms, y: num, d?: iso, m?: 0..1, note?: str }] sorted by t.
|
||||
// m marks the point — a second reading carried by the same dot (bigger and more solid =
|
||||
// more of it). Used for effort on the weight curve, where the two belong on one line:
|
||||
// the same weight with less left in the tank is not the same session.
|
||||
// note extra text for that point's tooltip.
|
||||
// opts: { h, unit, color, axes, goal, invert }
|
||||
// invert flips the y axis, for a scale that counts down as it gets harder (RIR). Without it
|
||||
// a curve of reps-in-reserve reads upside down, with the hardest sets at the floor.
|
||||
export default function LineChart({ points, h = 150, unit = '', color = 'var(--acc)', axes = true, goal = null, invert = false }) {
|
||||
const svgRef = useRef(null)
|
||||
const wrapRef = useRef(null)
|
||||
const tipRef = useRef(null)
|
||||
@@ -42,7 +49,10 @@ export default function LineChart({ points, h = 150, unit = '', color = 'var(--a
|
||||
const pad = (ymax - ymin) * 0.12; ymin -= pad; ymax += pad
|
||||
const t0 = pts[0].t, t1 = pts[pts.length - 1].t || t0 + 1
|
||||
const X = t => (t1 === t0 ? (P.l + W - P.r) / 2 : P.l + (t - t0) / (t1 - t0) * (W - P.l - P.r))
|
||||
const Y = y => P.t + (1 - (y - ymin) / (ymax - ymin)) * (H - P.t - P.b)
|
||||
const Y = y => {
|
||||
const f = (y - ymin) / (ymax - ymin)
|
||||
return P.t + (invert ? f : 1 - f) * (H - P.t - P.b)
|
||||
}
|
||||
|
||||
const gridlines = []
|
||||
if (axes) {
|
||||
@@ -81,7 +91,8 @@ export default function LineChart({ points, h = 150, unit = '', color = 'var(--a
|
||||
const poly = pts.map(p => X(p.t).toFixed(1) + ',' + Y(p.y).toFixed(1)).join(' ')
|
||||
const last = pts[pts.length - 1]
|
||||
const gid = 'g' + Math.round(t0 % 1e7) + '_' + H
|
||||
const hoverPts = (single ? [points[0]] : points).map(p => ({ x: X(p.t), y: Y(p.y), iso: p.d || isoOf(new Date(p.t)), v: p.y }))
|
||||
const hoverPts = (single ? [points[0]] : points).map(p => ({ x: X(p.t), y: Y(p.y), iso: p.d || isoOf(new Date(p.t)), v: p.y, note: p.note }))
|
||||
const marked = points.some(p => p.m != null)
|
||||
|
||||
const onMove = e => {
|
||||
const c = e.touches ? e.touches[0] : e
|
||||
@@ -111,6 +122,8 @@ export default function LineChart({ points, h = 150, unit = '', color = 'var(--a
|
||||
</>}
|
||||
<polygon points={`${P.l},${H - P.b} ${poly} ${X(last.t).toFixed(1)},${H - P.b}`} fill={`url(#${gid})`} />
|
||||
<polyline points={poly} fill="none" stroke={color} strokeWidth="2.5" strokeLinejoin="round" strokeLinecap="round" />
|
||||
{marked && pts.map((p, i) => (p.m == null ? null :
|
||||
<circle key={'m' + i} cx={X(p.t)} cy={Y(p.y)} r={2.4 + p.m * 3} fill={color} opacity={0.3 + p.m * 0.7} />))}
|
||||
<circle cx={X(last.t)} cy={Y(last.y)} r="4" fill={color} />
|
||||
{hover && <g>
|
||||
<line className="cvl" x1={hover.x} y1={P.t} x2={hover.x} y2={H - P.b} stroke="var(--label-3)" strokeWidth="1" strokeDasharray="3 3" />
|
||||
@@ -119,7 +132,7 @@ export default function LineChart({ points, h = 150, unit = '', color = 'var(--a
|
||||
</g>}
|
||||
</svg>
|
||||
{hover && <div className="ctip" ref={tipRef}>
|
||||
{fmtDate(hover.iso, true)} · {fmtNum(hover.v)}{unit ? ' ' + unit : ''}
|
||||
{fmtDate(hover.iso, true)} · {fmtNum(hover.v)}{unit ? ' ' + unit : ''}{hover.note ? ' · ' + hover.note : ''}
|
||||
</div>}
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -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)
|
||||
})
|
||||
})
|
||||
@@ -233,7 +233,11 @@ h4.sec{
|
||||
.lrow-m{flex:1;min-width:0;display:flex;flex-direction:column;gap:1px}
|
||||
.lrow-t{font-size:17px;letter-spacing:-.012em;line-height:1.25}
|
||||
.lrow-s{font-size:13px;color:var(--label-2);line-height:1.3}
|
||||
.lrow-v{color:var(--label-2);font-size:17px;letter-spacing:-.012em;flex:none}
|
||||
/* flex:none would let a long value ("Follow the routine (Linear progression)") run straight
|
||||
through the title next to it, since the title's column is already free to shrink to nothing.
|
||||
Letting the value shrink and ellipsise instead keeps the two out of each other's way. */
|
||||
.lrow-v{color:var(--label-2);font-size:17px;letter-spacing:-.012em;flex:0 1 auto;min-width:0;
|
||||
overflow:hidden;text-overflow:ellipsis;white-space:nowrap;text-align:right}
|
||||
.lrow-c{color:var(--label);font-size:15px;flex:none;--icon-stroke:2.4}
|
||||
.lrow-k{color:var(--acc);font-size:17px;flex:none;--icon-stroke:2.4}
|
||||
.lrow.danger,.lrow.danger .lrow-t{color:var(--red)}
|
||||
@@ -555,6 +559,9 @@ h4.sec{
|
||||
.setrow+.setrow::before{
|
||||
content:'';position:absolute;left:32px;right:0;top:0;height:var(--hair);background:var(--sep);
|
||||
}
|
||||
.setph{margin:8px 0 2px;font-size:11px;letter-spacing:.08em;text-transform:uppercase;color:var(--dim);display:flex;align-items:center;gap:10px}
|
||||
.setph::after{content:'';flex:1;height:1px;background:var(--sep)}
|
||||
.setsep{height:1px;background:var(--sep);margin:9px 0}
|
||||
.setrow .n{
|
||||
width:24px;height:24px;border-radius:50%;background:var(--surface-2);color:var(--label-2);
|
||||
display:flex;align-items:center;justify-content:center;font-size:12px;font-weight:500;flex:none;
|
||||
@@ -773,6 +780,18 @@ h4.sec{
|
||||
.bm-m.l2{fill:color-mix(in srgb,var(--acc) 56%,var(--bm-base))}
|
||||
.bm-m.l3{fill:color-mix(in srgb,var(--acc) 78%,var(--bm-base))}
|
||||
.bm-m.l4{fill:var(--acc)}
|
||||
/* Fatigue view: attention ramp - fatigued muscles highlighted (owner tweak 2026-08-06) */
|
||||
.hm-fatigue .bm-m.l4{fill:var(--red)}
|
||||
.hm-fatigue .bm-m.l3{fill:var(--orange)}
|
||||
.hm-fatigue .bm-m.l2{fill:var(--yellow)}
|
||||
.hm-fatigue .bm-m.l1{fill:color-mix(in srgb,var(--yellow) 32%,var(--bm-base))}
|
||||
.hm-fatigue .hm-c.l4{background:var(--red)}
|
||||
.hm-fatigue .hm-c.l3{background:var(--orange)}
|
||||
.hm-fatigue .hm-c.l2{background:var(--yellow)}
|
||||
/* Strength view: top band pops gold (owner tweak 2026-08-06) */
|
||||
.hm-strength .bm-m.l4{fill:var(--yellow);filter:drop-shadow(0 0 1.5px var(--yellow))}
|
||||
.hm-strength .hm-c.l4{background:var(--yellow)}
|
||||
|
||||
.bm-m.sel{stroke:var(--label);stroke-width:7}
|
||||
.bodymap.tappable .bm-m{cursor:pointer}
|
||||
/* A hairline in the surface colour separates neighbouring muscles; the artwork has no
|
||||
@@ -784,6 +803,9 @@ h4.sec{
|
||||
.mrow .bar{width:74px;height:5px;border-radius:3px;background:var(--surface-2);flex:none;overflow:hidden}
|
||||
.mrow .bar i{display:block;height:100%;background:var(--acc);border-radius:3px}
|
||||
.mrow .v{font-size:12px;color:var(--label-2);min-width:52px;text-align:right;flex:none}
|
||||
/* A headline number inside a card — tile weight without a tile around it, for the pair of
|
||||
readings at the top of the effort card. */
|
||||
.stat-v{font-size:26px;font-weight:600;letter-spacing:-.026em;line-height:1.1}
|
||||
.mchips{display:flex;flex-wrap:wrap;gap:6px;margin-top:4px}
|
||||
.mchip{font-size:12px;padding:4px 9px;border-radius:99px;background:var(--surface-2);color:var(--label-2)}
|
||||
.mchip.miss{background:color-mix(in srgb,var(--orange) 16%,transparent);color:var(--orange)}
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
// Android system back (the gesture and the hardware/nav button are the same event).
|
||||
//
|
||||
// Capacitor's BridgeActivity does not handle back at all — without a JS listener the
|
||||
// activity simply finishes, so a back swipe quit the app from anywhere, whatever the
|
||||
// WebView history said. That made the sheet history entries from #63 dead weight in the
|
||||
// packaged app: they only ever worked in a browser tab, where the browser walks history
|
||||
// itself.
|
||||
//
|
||||
// Once a `backButton` listener exists, the plugin stops falling through to finish() —
|
||||
// back can then ONLY leave the app through App.exitApp(), which is why the last step is
|
||||
// an explicit press-again-to-exit rather than a silent no-op.
|
||||
import { MOBILE } from './mobile.js'
|
||||
import { useUI } from '../store/useUI.js'
|
||||
import { t } from './i18n.js'
|
||||
|
||||
// How long a first back press stays armed as "press again to exit" (the toast shows 2.2s).
|
||||
export const EXIT_WINDOW = 2000
|
||||
|
||||
// What a back press means, given what is on screen. Pure, so the table below is testable.
|
||||
export function decideBack({ top, canGoBack, exitArmed }) {
|
||||
if (top) return top.locked ? 'ignore' : 'sheet' // a locked sheet swallows back on purpose
|
||||
if (canGoBack) return 'history' // a page/tab we pushed ourselves
|
||||
return exitArmed ? 'exit' : 'arm-exit'
|
||||
}
|
||||
|
||||
export function makeBackHandler({ getSheets, closeSheet, toast, goBack, exit, now = Date.now }) {
|
||||
let armedAt = -Infinity
|
||||
return (ev = {}) => {
|
||||
const sheets = getSheets()
|
||||
const action = decideBack({
|
||||
top: sheets[sheets.length - 1],
|
||||
canGoBack: !!ev.canGoBack,
|
||||
exitArmed: now() - armedAt < EXIT_WINDOW,
|
||||
})
|
||||
if (action !== 'arm-exit') armedAt = -Infinity
|
||||
if (action === 'sheet') closeSheet(sheets[sheets.length - 1].id)
|
||||
else if (action === 'history') goBack()
|
||||
else if (action === 'arm-exit') { armedAt = now(); toast(t('Press back again to exit')) }
|
||||
else if (action === 'exit') exit()
|
||||
return action
|
||||
}
|
||||
}
|
||||
|
||||
// Registers the listener for the native shell. No-op in web builds, where the browser
|
||||
// (or the PWA shell) walks history on its own and there is no plugin to talk to.
|
||||
export async function initBackButton() {
|
||||
if (!MOBILE) return () => {}
|
||||
try {
|
||||
const { App } = await import('@capacitor/app')
|
||||
const handler = makeBackHandler({
|
||||
getSheets: () => useUI.getState().sheets,
|
||||
closeSheet: id => useUI.getState().closeSheet(id),
|
||||
toast: msg => useUI.getState().toast(msg),
|
||||
goBack: () => window.history.back(),
|
||||
exit: () => App.exitApp(),
|
||||
})
|
||||
const sub = await App.addListener('backButton', handler)
|
||||
return () => sub.remove()
|
||||
} catch (e) {
|
||||
return () => {} // no plugin (older install): leave back to the default behaviour
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { decideBack, makeBackHandler, EXIT_WINDOW } from './back.js'
|
||||
|
||||
// Back on Android has to serve three layers with one event: the sheet stack on top, the
|
||||
// page history under it, and — because a registered listener stops the plugin from ever
|
||||
// finishing the activity itself — a deliberate way out of the app at the bottom.
|
||||
describe('decideBack', () => {
|
||||
it('dismisses the top sheet before touching history', () => {
|
||||
expect(decideBack({ top: { id: 's1' }, canGoBack: true, exitArmed: false })).toBe('sheet')
|
||||
})
|
||||
|
||||
it('lets a locked sheet swallow the press', () => {
|
||||
expect(decideBack({ top: { id: 's1', locked: true }, canGoBack: true, exitArmed: true })).toBe('ignore')
|
||||
})
|
||||
|
||||
it('walks history when nothing is open', () => {
|
||||
expect(decideBack({ top: undefined, canGoBack: true, exitArmed: false })).toBe('history')
|
||||
})
|
||||
|
||||
it('arms the exit at the bottom of the stack, and exits on the second press', () => {
|
||||
expect(decideBack({ top: undefined, canGoBack: false, exitArmed: false })).toBe('arm-exit')
|
||||
expect(decideBack({ top: undefined, canGoBack: false, exitArmed: true })).toBe('exit')
|
||||
})
|
||||
})
|
||||
|
||||
function harness() {
|
||||
const calls = { closed: [], toasts: [], back: 0, exit: 0 }
|
||||
let sheets = []
|
||||
let now = 1000
|
||||
const handler = makeBackHandler({
|
||||
getSheets: () => sheets,
|
||||
closeSheet: id => { calls.closed.push(id); sheets = sheets.filter(s => s.id !== id) },
|
||||
toast: m => calls.toasts.push(m),
|
||||
goBack: () => { calls.back++ },
|
||||
exit: () => { calls.exit++ },
|
||||
now: () => now,
|
||||
})
|
||||
return { calls, handler, setSheets: s => { sheets = s }, tick: ms => { now += ms } }
|
||||
}
|
||||
|
||||
describe('makeBackHandler', () => {
|
||||
it('closes stacked sheets one press at a time', () => {
|
||||
const h = harness()
|
||||
h.setSheets([{ id: 'a' }, { id: 'b' }])
|
||||
expect(h.handler({ canGoBack: true })).toBe('sheet')
|
||||
expect(h.handler({ canGoBack: true })).toBe('sheet')
|
||||
expect(h.calls.closed).toEqual(['b', 'a'])
|
||||
expect(h.calls.back).toBe(0)
|
||||
})
|
||||
|
||||
it('does not close a locked sheet, and does not arm the exit behind it', () => {
|
||||
const h = harness()
|
||||
h.setSheets([{ id: 'a', locked: true }])
|
||||
expect(h.handler({ canGoBack: false })).toBe('ignore')
|
||||
expect(h.calls.closed).toEqual([])
|
||||
expect(h.calls.toasts).toEqual([])
|
||||
expect(h.calls.exit).toBe(0)
|
||||
})
|
||||
|
||||
it('goes back a page while the WebView still has app history', () => {
|
||||
const h = harness()
|
||||
expect(h.handler({ canGoBack: true })).toBe('history')
|
||||
expect(h.calls.back).toBe(1)
|
||||
expect(h.calls.exit).toBe(0)
|
||||
})
|
||||
|
||||
// The whole point of the fix: one press at the root must never be the end of the app.
|
||||
it('warns once, then exits on a second press inside the window', () => {
|
||||
const h = harness()
|
||||
expect(h.handler({ canGoBack: false })).toBe('arm-exit')
|
||||
expect(h.calls.toasts).toHaveLength(1)
|
||||
expect(h.calls.exit).toBe(0)
|
||||
h.tick(EXIT_WINDOW - 1)
|
||||
expect(h.handler({ canGoBack: false })).toBe('exit')
|
||||
expect(h.calls.exit).toBe(1)
|
||||
})
|
||||
|
||||
it('re-arms rather than exiting once the window has passed', () => {
|
||||
const h = harness()
|
||||
h.handler({ canGoBack: false })
|
||||
h.tick(EXIT_WINDOW + 1)
|
||||
expect(h.handler({ canGoBack: false })).toBe('arm-exit')
|
||||
expect(h.calls.exit).toBe(0)
|
||||
expect(h.calls.toasts).toHaveLength(2)
|
||||
})
|
||||
|
||||
// A sheet opened (or a page pushed) after the warning means the user is still using the
|
||||
// app — the next back belongs to that sheet, and the one after must warn again.
|
||||
it('disarms the exit as soon as another press does real work', () => {
|
||||
const h = harness()
|
||||
h.handler({ canGoBack: false })
|
||||
h.setSheets([{ id: 'a' }])
|
||||
expect(h.handler({ canGoBack: true })).toBe('sheet')
|
||||
expect(h.handler({ canGoBack: false })).toBe('arm-exit')
|
||||
expect(h.calls.exit).toBe(0)
|
||||
})
|
||||
|
||||
it('treats a missing event payload as no history', () => {
|
||||
const h = harness()
|
||||
expect(h.handler()).toBe('arm-exit')
|
||||
})
|
||||
})
|
||||
@@ -11,4 +11,4 @@
|
||||
// lands in a self-hosted bundle.
|
||||
export const DEMO = import.meta.env.VITE_DEMO === '1'
|
||||
export const DEMO_SEEDED = 'gym_demo_seeded_v1'
|
||||
export const REPO = 'https://github.com/DuarteSantos8/openGym'
|
||||
export const REPO = 'https://gitea.com/DuarteSantos/openGym'
|
||||
@@ -2,6 +2,7 @@
|
||||
// out of the bundle self-hosters ship.
|
||||
import { isoOf, uid } from './format.js'
|
||||
import { starterRoutines } from './starter.js'
|
||||
import { modeOf } from './history.js'
|
||||
|
||||
// Starting weight and weekly increment per exercise of the starter plan (kg).
|
||||
// Chest dips are body-weight only here, so they log reps at 0 added weight.
|
||||
@@ -14,6 +15,30 @@ const WEEKS = 12 // how much history to fabricate
|
||||
const BW_FROM = 82.4, BW_TO = 78.3 // body-weight trend across those weeks
|
||||
const TARGET_W = 77
|
||||
|
||||
// --- Effort -----------------------------------------------------------------------------
|
||||
// The demo has to show the effort stats, not just the volume ones, so the history carries
|
||||
// ratings. Flat ratings would draw a flat trend and prove nothing, so this fabricates the
|
||||
// shape the charts exist to make visible: a block grinding toward failure, a deload jumping
|
||||
// back off it, another block going a little deeper than the first.
|
||||
const DELOAD_WEEK = 5
|
||||
// Reps left in the tank the block is aiming for, by week.
|
||||
const weekTarget = wk =>
|
||||
wk === DELOAD_WEEK ? 4.5
|
||||
: wk < DELOAD_WEEK ? 2.8 - wk * 0.3
|
||||
: 2.6 - (wk - DELOAD_WEEK - 1) * 0.26
|
||||
// Leg day is trained further from failure than the upper body — deliberate, so the muscle
|
||||
// map's "hard sets" mode shows a different picture from its all-sets mode.
|
||||
const EASY = new Set(['0043', '0085', '0739', '0585', '0586'])
|
||||
// One exercise nobody ever rates: partial coverage is the normal case (rating is optional and
|
||||
// off by default), and it shows the per-exercise Effort toggle correctly staying away.
|
||||
const NEVER_RATED = '0605'
|
||||
const UNRATED = 0.1 // …plus this share of the remaining sets, at random
|
||||
// The first weeks are logged in RPE, as if they came out of another app before the profile
|
||||
// switched to RIR. A set is never rewritten (see history.js), so the stats have to average a
|
||||
// mixed history as one series — the demo should be showing that, not hiding it.
|
||||
const RPE_UNTIL = 3
|
||||
const clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v))
|
||||
|
||||
// Deterministic PRNG — the demo should look the same on every visit and in screenshots.
|
||||
function rng(seed) {
|
||||
let a = seed >>> 0
|
||||
@@ -26,9 +51,14 @@ function rng(seed) {
|
||||
}
|
||||
const round = (w, step) => Math.round(w / step) * step
|
||||
const at = (date, h, m) => { const d = new Date(date); d.setHours(h, m, 0, 0); return d.getTime() }
|
||||
// The Monday of a date. The effort trend is plotted per calendar week, so the training block
|
||||
// has to run on calendar weeks too — a deload counted off the first day of the history would
|
||||
// straddle two points and average itself away in both.
|
||||
const monday = date => { const d = new Date(date); d.setDate(d.getDate() - ((d.getDay() + 6) % 7)); d.setHours(12, 0, 0, 0); return +d }
|
||||
|
||||
// A full example profile: 12 weeks of Mon/Wed/Fri sessions on the starter plan, with linear
|
||||
// progression, the odd missed session, and twice-weekly weigh-ins trending toward the goal.
|
||||
// progression, the odd missed session, twice-weekly weigh-ins trending toward the goal, and
|
||||
// per-set effort ratings on most (not all) of it.
|
||||
export function buildDemoState() {
|
||||
const rnd = rng(20260723)
|
||||
const [push, pull, legs] = starterRoutines()
|
||||
@@ -61,15 +91,35 @@ export function buildDemoState() {
|
||||
if (iso === isoOf(today) && nowH < 18) continue // leave today's session to try out, unless it's already evening
|
||||
|
||||
const prs = []
|
||||
const entries = routine.ex.map(cfg => {
|
||||
const blockWk = Math.round((monday(day) - monday(start)) / (7 * 86400000))
|
||||
const rir0 = weekTarget(blockWk)
|
||||
const scale = blockWk < RPE_UNTIL ? 'rpe' : 'rir'
|
||||
const entries = routine.ex.map((cfg, exIdx) => {
|
||||
const [base, inc] = PROG[cfg.id] || [20, 0.5]
|
||||
const step = base >= 40 ? 2.5 : 1.25
|
||||
const w = base ? Math.max(step, round(base + inc * weekIdx, step)) : 0
|
||||
// The deload pulls the weight back too — effort dropping on its own would look like the
|
||||
// same session suddenly got easy.
|
||||
const back = blockWk === DELOAD_WEEK ? 0.88 : 1
|
||||
const w = base ? Math.max(step, round((base + inc * weekIdx) * back, step)) : 0
|
||||
const rateable = modeOf(cfg) === 'reps' && cfg.id !== NEVER_RATED
|
||||
const sets = []
|
||||
for (let i = 0; i < cfg.sets; i++) {
|
||||
// last set is where reps usually start slipping
|
||||
const drop = i === cfg.sets - 1 && rnd() < 0.55 ? (rnd() < 0.4 ? 2 : 1) : 0
|
||||
sets.push({ w, r: Math.max(4, cfg.reps - drop), done: true })
|
||||
const s = { w, r: Math.max(4, cfg.reps - drop), done: true }
|
||||
const rir = clamp(round(rir0
|
||||
+ (cfg.sets - 1 - i) * 0.6 // a first set sits further from failure than a last
|
||||
- exIdx * 0.12 // …and fatigue accumulates across the session
|
||||
+ (EASY.has(cfg.id) ? 1.2 : 0)
|
||||
- (drop ? 0.5 : 0) // reps slipping is the set that ran out of room
|
||||
+ (rnd() - 0.5), 0.5), 0, 6)
|
||||
if (rateable && rnd() > UNRATED) {
|
||||
// RPE's floor of 6 is a convention about which sets are worth rating, so an easy
|
||||
// set logged in RPE genuinely loses the distance it was from failure.
|
||||
if (scale === 'rpe') s.rpe = clamp(10 - rir, 6, 10)
|
||||
else s.rir = rir
|
||||
}
|
||||
sets.push(s)
|
||||
}
|
||||
if (w > (best[cfg.id] || 0)) { best[cfg.id] = w; prs.push(cfg.id) }
|
||||
exWeights[cfg.id] = { w: Math.max(w, exWeights[cfg.id]?.w || 0), d: iso }
|
||||
@@ -103,6 +153,9 @@ export function buildDemoState() {
|
||||
week: { 1: push.id, 3: pull.id, 5: legs.id },
|
||||
dayPlan,
|
||||
workouts, bodyweight, exWeights,
|
||||
targetW: TARGET_W
|
||||
targetW: TARGET_W,
|
||||
// The history is rated, so the demo turns the column on and the stats get a scale to
|
||||
// label their aggregates with instead of guessing one (see displayScale).
|
||||
effort: 'rir'
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
// The demo build is the only openGym most people ever see, so its seeded history has to
|
||||
// exercise the stats it is there to show off — including the effort card, which renders as
|
||||
// dashes on a history that is rated too thinly or not at all.
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { buildDemoState } from './demoSeed.js'
|
||||
import {
|
||||
effortSummary, effortWeeks, effortHistogram, hasEffort, displayScale, avgRir,
|
||||
rirOf, isHardSet, MIN_RATED, HARD_RIR
|
||||
} from './effort.js'
|
||||
import { effortOf, modeOf } from './history.js'
|
||||
|
||||
const S = buildDemoState()
|
||||
const eachSet = fn => S.workouts.forEach(w => w.entries.forEach(e => e.sets.forEach(s => fn(s, w, e))))
|
||||
const sum = effortSummary(S, 0) // 0 = the whole history
|
||||
|
||||
describe('demo seed — effort', () => {
|
||||
it('rates enough of the history to clear every guard in the effort stats', () => {
|
||||
expect(hasEffort(S)).toBe(true)
|
||||
expect(sum.done).toBeGreaterThan(400)
|
||||
expect(sum.rated).toBeGreaterThan(MIN_RATED * 20)
|
||||
expect(sum.avg).not.toBeNull()
|
||||
expect(sum.hardPct).not.toBeNull()
|
||||
// Somewhere between "everything is a grinder" and "nothing ever gets close".
|
||||
expect(sum.hardPct).toBeGreaterThan(0.3)
|
||||
expect(sum.hardPct).toBeLessThan(0.9)
|
||||
})
|
||||
|
||||
it('leaves coverage partial, because that is the normal case the UI states a denominator for', () => {
|
||||
const cov = sum.rated / sum.done
|
||||
expect(cov).toBeGreaterThan(0.7)
|
||||
expect(cov).toBeLessThan(0.95)
|
||||
})
|
||||
|
||||
it('never rates a set that has no reps to leave in the tank', () => {
|
||||
eachSet((s, w, e) => {
|
||||
if (rirOf(s) != null) expect(modeOf({ ...(e.target || {}), id: e.id })).toBe('reps')
|
||||
})
|
||||
})
|
||||
|
||||
it('leaves one exercise unrated throughout, so the per-exercise Effort toggle is absent for it', () => {
|
||||
const rated = {}
|
||||
eachSet((s, w, e) => { rated[e.id] = (rated[e.id] || 0) + (rirOf(s) != null ? 1 : 0) })
|
||||
const ids = Object.keys(rated)
|
||||
expect(ids.filter(id => rated[id] === 0)).toEqual(['0605'])
|
||||
// …while the rest carry enough rated sessions for a curve of their own (needs 3).
|
||||
ids.filter(id => id !== '0605').forEach(id => {
|
||||
const sessions = S.workouts.filter(w => {
|
||||
const en = w.entries.find(e => e.id === id)
|
||||
return en && avgRir(en.sets.filter(s => s.done)) != null
|
||||
})
|
||||
expect(sessions.length).toBeGreaterThanOrEqual(3)
|
||||
})
|
||||
})
|
||||
|
||||
it('labels the aggregates in the scale the profile logs', () => {
|
||||
expect(effortOf(S)).toBe('rir')
|
||||
expect(displayScale(S)).toBe('rir')
|
||||
// The oldest block is written in RPE, as if imported — the stats have to average the mix.
|
||||
let rir = 0, rpe = 0
|
||||
eachSet(s => { if (s.rir != null) rir++; else if (s.rpe != null) rpe++ })
|
||||
expect(rir).toBeGreaterThan(0)
|
||||
expect(rpe).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('draws a weekly trend with a point for every week of the history', () => {
|
||||
const wks = effortWeeks(S, 0)
|
||||
expect(wks.length).toBeGreaterThanOrEqual(10)
|
||||
wks.forEach(w => { expect(w.n).toBeGreaterThanOrEqual(2); expect(w.sets).toBeGreaterThanOrEqual(w.n) })
|
||||
// Sorted oldest first, one point per calendar week.
|
||||
expect(wks.map(w => w.t)).toEqual([...wks.map(w => w.t)].sort((a, b) => a - b))
|
||||
expect(new Set(wks.map(w => w.t)).size).toBe(wks.length)
|
||||
})
|
||||
|
||||
it('makes the deload visible as a genuinely easier week', () => {
|
||||
const wks = effortWeeks(S, 0)
|
||||
const easiest = wks.reduce((a, b) => (b.rir > a.rir ? b : a))
|
||||
const rest = wks.filter(w => w !== easiest)
|
||||
const restAvg = rest.reduce((a, w) => a + w.rir, 0) / rest.length
|
||||
expect(easiest.rir - restAvg).toBeGreaterThan(1) // a step, not noise
|
||||
// and the blocks around it grind toward failure rather than sitting flat
|
||||
const hardest = wks.reduce((a, b) => (b.rir < a.rir ? b : a))
|
||||
expect(easiest.rir - hardest.rir).toBeGreaterThan(1.5)
|
||||
expect(hardest.t).toBeGreaterThan(easiest.t) // the deepest week comes after it
|
||||
})
|
||||
|
||||
it('spreads across the scale instead of piling onto one bucket', () => {
|
||||
const hist = effortHistogram(S, 0)
|
||||
expect(hist.reduce((n, b) => n + b.n, 0)).toBe(sum.rated)
|
||||
expect(hist.filter(b => b.pct > 0.05).length).toBeGreaterThan(2)
|
||||
expect(Math.max(...hist.map(b => b.pct))).toBeLessThan(0.6)
|
||||
// both ends occupied: sets taken to (or near) failure and sets left well short of it
|
||||
expect(hist[0].n + hist[1].n).toBeGreaterThan(0)
|
||||
expect(hist[hist.length - 1].n).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('has hard sets to filter the muscle map by', () => {
|
||||
let hard = 0
|
||||
eachSet(s => { if (isHardSet(s)) hard++ })
|
||||
expect(hard).toBe(sum.hard)
|
||||
expect(hard).toBeGreaterThan(50)
|
||||
eachSet(s => { if (isHardSet(s)) expect(rirOf(s)).toBeLessThanOrEqual(HARD_RIR) })
|
||||
})
|
||||
|
||||
it('is deterministic — two builds produce the same ratings', () => {
|
||||
const b = buildDemoState()
|
||||
const flat = st => st.workouts.map(w => w.entries.map(e => e.sets.map(s => `${s.w}x${s.r}/${s.rir ?? ''}/${s.rpe ?? ''}`).join(',')).join('|')).join(';')
|
||||
expect(flat(b)).toBe(flat(S))
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,140 @@
|
||||
// Effort as a statistic: one internal scale, both display scales.
|
||||
//
|
||||
// A set carries either `rir` or `rpe` and is never rewritten — switching the setting changes
|
||||
// what new sets ask for, nothing else (see history.js). For a *chart* that is a problem: a
|
||||
// history that mixes the two (own logs in RIR, an imported file in RPE) would draw two
|
||||
// half-empty series. So everything aggregates in RIR and is converted back for display.
|
||||
// RIR is the internal unit because it has a real zero — a set taken to failure — where RPE's
|
||||
// floor of 6 is only a convention about which sets are worth rating. RPE 8 == RIR 2.
|
||||
import { EFFORT, effortOf } from './history.js'
|
||||
import { weekKey } from './format.js'
|
||||
import { 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
|
||||
// separates working sets from the ones left in the warm-up range.
|
||||
export const HARD_RIR = 3
|
||||
// Below this many rated sets an average is noise. Showing "RIR 1.0" off a single set reads
|
||||
// like a finding when it is one tap, so the callers show a dash instead.
|
||||
export const MIN_RATED = 5
|
||||
|
||||
/** A set's effort in RIR, or null when it was never rated. 0 is a rating, not "empty". */
|
||||
export const rirOf = s =>
|
||||
!s ? null : s.rir != null ? s.rir : s.rpe != null ? 10 - s.rpe : null
|
||||
|
||||
/** RIR → the scale being displayed. The reverse of rirOf, for one number. */
|
||||
export const toScale = (kind, rir) =>
|
||||
rir == null ? null : Math.round((kind === 'rpe' ? 10 - rir : rir) * 10) / 10
|
||||
|
||||
/**
|
||||
* Which scale to *label* aggregates with. The profile's own setting wins; a profile that
|
||||
* logs nothing itself but carries rated history (the imported-from-Hevy case) is shown the
|
||||
* scale that history is actually written in, rather than an RIR it has never seen.
|
||||
*/
|
||||
export function displayScale(S) {
|
||||
const k = effortOf(S)
|
||||
if (EFFORT[k]) return k
|
||||
let rir = 0, rpe = 0
|
||||
eachDoneSet(S, s => { if (s.rir != null) rir++; else if (s.rpe != null) rpe++ })
|
||||
return rpe > rir ? 'rpe' : 'rir'
|
||||
}
|
||||
export const scaleName = kind => EFFORT[kind].hd
|
||||
|
||||
// Every finished set in the profile, oldest first. `fn` gets the set plus the workout it
|
||||
// belongs to, which is what the windowed and per-week views need.
|
||||
function eachDoneSet(S, fn) {
|
||||
;(S.workouts || []).forEach(w =>
|
||||
(w.entries || []).forEach(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
|
||||
// history means for every caller here.
|
||||
const inWindow = (w, days) =>
|
||||
!days || (w.start || new Date(w.d).getTime()) > Date.now() - days * 86400000
|
||||
|
||||
export const avgRir = sets => {
|
||||
const vs = (sets || []).map(rirOf).filter(v => v != null)
|
||||
return vs.length ? vs.reduce((a, b) => a + b, 0) / vs.length : null
|
||||
}
|
||||
|
||||
/**
|
||||
* The headline numbers for a window: how hard, how much of it was hard, and — the part that
|
||||
* keeps the rest honest — how much of the training was rated at all. Effort is optional and
|
||||
* off by default, so partial coverage is the normal case; an average without its denominator
|
||||
* would quietly speak for sets that were never rated.
|
||||
*/
|
||||
export function effortSummary(S, days) {
|
||||
let done = 0, rated = 0, sum = 0, hard = 0
|
||||
eachDoneSet(S, (s, w) => {
|
||||
if (!inWindow(w, days)) return
|
||||
done++
|
||||
const r = rirOf(s)
|
||||
if (r == null) return
|
||||
rated++; sum += r
|
||||
if (r <= HARD_RIR) hard++
|
||||
})
|
||||
return {
|
||||
done, rated, hard,
|
||||
avg: rated >= MIN_RATED ? sum / rated : null,
|
||||
hardPct: rated >= MIN_RATED ? hard / rated : null
|
||||
}
|
||||
}
|
||||
|
||||
/** Does this profile hold any rated set at all? Decides whether the effort UI exists. */
|
||||
export function hasEffort(S) {
|
||||
let any = false
|
||||
eachDoneSet(S, s => { if (!any && rirOf(s) != null) any = true })
|
||||
return any
|
||||
}
|
||||
|
||||
/**
|
||||
* Average effort per calendar week, with the week's set count alongside: the pair is the
|
||||
* point. Volume up with effort up is fatigue accumulating; volume up with effort flat is the
|
||||
* adaptation you were training for. Weeks with a single rated set are dropped rather than
|
||||
* drawn — one tap should not become a peak in the curve.
|
||||
*/
|
||||
export function effortWeeks(S, days) {
|
||||
const wk = new Map()
|
||||
eachDoneSet(S, (s, w) => {
|
||||
if (!inWindow(w, days)) return
|
||||
const k = weekKey(w.d)
|
||||
let e = wk.get(k)
|
||||
if (!e) wk.set(k, e = { k, t: mondayOf(w.d), sum: 0, n: 0, sets: 0 })
|
||||
e.sets++
|
||||
const r = rirOf(s)
|
||||
if (r != null) { e.sum += r; e.n++ }
|
||||
})
|
||||
return [...wk.values()].filter(e => e.n >= 2).sort((a, b) => a.t - b.t)
|
||||
.map(e => ({ t: e.t, rir: e.sum / e.n, n: e.n, sets: e.sets }))
|
||||
}
|
||||
// The Monday of an ISO date, as ms — the x position a week's point sits at.
|
||||
function mondayOf(iso) {
|
||||
const d = new Date(iso + 'T12:00:00')
|
||||
d.setDate(d.getDate() - ((d.getDay() + 6) % 7))
|
||||
d.setHours(12, 0, 0, 0)
|
||||
return +d
|
||||
}
|
||||
|
||||
/**
|
||||
* How the rated sets spread across the scale, in whole steps with everything past the top
|
||||
* bucket collapsed into it. This is the chart that answers "am I training too far from
|
||||
* failure, or leaving nothing for the next session" — an average alone hides both, because
|
||||
* half the sets at 0 and half at 4 average to a healthy-looking 2.
|
||||
*/
|
||||
export const BUCKETS = 4 // 0,1,2,3 and a "4+" tail
|
||||
export function effortHistogram(S, days) {
|
||||
const bins = new Array(BUCKETS + 1).fill(0)
|
||||
let rated = 0
|
||||
eachDoneSet(S, (s, w) => {
|
||||
if (!inWindow(w, days)) return
|
||||
const r = rirOf(s)
|
||||
if (r == null) return
|
||||
rated++
|
||||
bins[Math.min(BUCKETS, Math.max(0, Math.floor(r)))]++
|
||||
})
|
||||
return bins.map((n, i) => ({ rir: i, tail: i === BUCKETS, n, pct: rated ? n / rated : 0 }))
|
||||
}
|
||||
|
||||
/** A set that counts as hard — the filter behind the muscle map's "hard sets" mode. */
|
||||
export const isHardSet = s => { const r = rirOf(s); return r != null && r <= HARD_RIR }
|
||||
@@ -0,0 +1,186 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import {
|
||||
rirOf, toScale, displayScale, avgRir, effortSummary, hasEffort, effortWeeks,
|
||||
effortHistogram, isHardSet, HARD_RIR, MIN_RATED
|
||||
} from './effort.js'
|
||||
import { isoOf } from './format.js'
|
||||
|
||||
const daysAgo = n => { const d = new Date(); d.setDate(d.getDate() - n); return d }
|
||||
// One workout on a day, with the sets given. Everything here is a finished set unless a set
|
||||
// says otherwise, because that is what the stats read.
|
||||
const W = (n, sets) => {
|
||||
const d = daysAgo(n)
|
||||
return { id: 'w' + n, d: isoOf(d), start: +d, entries: [{ id: '0025', sets: sets.map(s => ({ w: 60, r: 8, done: true, ...s })) }] }
|
||||
}
|
||||
const S = (...workouts) => ({ workouts })
|
||||
|
||||
describe('rirOf', () => {
|
||||
it('reads RIR straight and RPE as its mirror — RPE 8 is RIR 2', () => {
|
||||
expect(rirOf({ rir: 2 })).toBe(2)
|
||||
expect(rirOf({ rpe: 8 })).toBe(2)
|
||||
expect(rirOf({ rpe: 9.5 })).toBe(0.5)
|
||||
})
|
||||
|
||||
it('keeps a rated 0 and rejects everything that only looks like one', () => {
|
||||
expect(rirOf({ rir: 0 })).toBe(0) // taken to failure — a rating, not "empty"
|
||||
expect(rirOf({ rpe: 10 })).toBe(0)
|
||||
expect(rirOf({})).toBe(null)
|
||||
expect(rirOf({ rir: null })).toBe(null)
|
||||
expect(rirOf(null)).toBe(null)
|
||||
})
|
||||
|
||||
it('prefers the scale the set itself was logged on when a file wrote both', () => {
|
||||
expect(rirOf({ rir: 3, rpe: 9 })).toBe(3)
|
||||
})
|
||||
})
|
||||
|
||||
describe('toScale', () => {
|
||||
it('converts back to whichever scale is on screen', () => {
|
||||
expect(toScale('rir', 2)).toBe(2)
|
||||
expect(toScale('rpe', 2)).toBe(8)
|
||||
expect(toScale('rpe', 0)).toBe(10)
|
||||
expect(toScale('rir', null)).toBe(null)
|
||||
})
|
||||
|
||||
it('does not let the round trip produce float dust', () => {
|
||||
expect(toScale('rpe', 10 - 7.5)).toBe(7.5)
|
||||
})
|
||||
})
|
||||
|
||||
describe('displayScale', () => {
|
||||
it('follows the profile setting when it has one', () => {
|
||||
expect(displayScale({ effort: 'rpe', workouts: [] })).toBe('rpe')
|
||||
expect(displayScale({ effort: 'rir', workouts: [] })).toBe('rir')
|
||||
})
|
||||
|
||||
it('shows an unrated profile the scale its imported history is written in', () => {
|
||||
// Effort off, but a file brought RPE with it: labelling that history "RIR" would show a
|
||||
// number the profile has never entered and mean the opposite of what it says.
|
||||
expect(displayScale({ effort: 'none', ...S(W(3, [{ rpe: 8 }, { rpe: 9 }])) })).toBe('rpe')
|
||||
expect(displayScale({ effort: 'none', ...S(W(3, [{ rir: 2 }])) })).toBe('rir')
|
||||
expect(displayScale({ effort: 'none', workouts: [] })).toBe('rir')
|
||||
})
|
||||
})
|
||||
|
||||
describe('avgRir', () => {
|
||||
it('averages the rated sets and ignores the rest', () => {
|
||||
expect(avgRir([{ rir: 1 }, { rir: 3 }])).toBe(2)
|
||||
expect(avgRir([{ rir: 1 }, {}, { rpe: 7 }])).toBe(2) // RPE 7 = RIR 3
|
||||
})
|
||||
|
||||
it('is null rather than 0 when nothing was rated', () => {
|
||||
expect(avgRir([{}, { rir: null }])).toBe(null)
|
||||
expect(avgRir([])).toBe(null)
|
||||
expect(avgRir(null)).toBe(null)
|
||||
})
|
||||
})
|
||||
|
||||
describe('effortSummary', () => {
|
||||
const st = S(
|
||||
W(2, [{ rir: 1 }, { rir: 3 }, { rir: 2 }]),
|
||||
W(4, [{ rir: 0 }, { rpe: 6 }, {}]), // RPE 6 = RIR 4, one set unrated
|
||||
W(40, [{ rir: 5 }, { rir: 5 }])
|
||||
)
|
||||
|
||||
it('counts rated sets against every finished set, not against itself', () => {
|
||||
const r = effortSummary(st, 0)
|
||||
expect(r.done).toBe(8)
|
||||
expect(r.rated).toBe(7)
|
||||
})
|
||||
|
||||
it('leaves unrated sets out of the average instead of reading them as failure', () => {
|
||||
const r = effortSummary(S(W(2, [{ rir: 4 }, {}, {}, {}, {}, {}])), 0)
|
||||
expect(r.rated).toBe(1)
|
||||
expect(r.avg).toBe(null) // one rating is not an average
|
||||
})
|
||||
|
||||
it('waits for a real sample before reporting a number', () => {
|
||||
const few = S(W(2, new Array(MIN_RATED - 1).fill({ rir: 2 })))
|
||||
expect(effortSummary(few, 0).avg).toBe(null)
|
||||
const enough = S(W(2, new Array(MIN_RATED).fill({ rir: 2 })))
|
||||
expect(effortSummary(enough, 0).avg).toBe(2)
|
||||
})
|
||||
|
||||
it('counts the sets taken close to failure', () => {
|
||||
const r = effortSummary(st, 0)
|
||||
expect(r.hard).toBe(4) // 1, 3, 2, 0 — the 4 and the two 5s are not
|
||||
expect(r.hardPct).toBeCloseTo(4 / 7)
|
||||
})
|
||||
|
||||
it('honours the window', () => {
|
||||
const r = effortSummary(st, 7)
|
||||
expect(r.rated).toBe(5) // the 40-day-old session is out
|
||||
expect(effortSummary(st, 3).rated).toBe(3)
|
||||
})
|
||||
|
||||
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', () => {
|
||||
it('decides whether the effort UI exists at all', () => {
|
||||
expect(hasEffort(S(W(2, [{ rir: 0 }])))).toBe(true)
|
||||
expect(hasEffort(S(W(2, [{ rpe: 8 }])))).toBe(true)
|
||||
expect(hasEffort(S(W(2, [{}, { rir: null }])))).toBe(false)
|
||||
expect(hasEffort({ workouts: [] })).toBe(false)
|
||||
})
|
||||
|
||||
it('ignores sets that were never finished', () => {
|
||||
expect(hasEffort(S(W(2, [{ rir: 2, done: false }])))).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('effortWeeks', () => {
|
||||
it('averages per calendar week and carries the week volume alongside', () => {
|
||||
const pts = effortWeeks(S(W(1, [{ rir: 1 }, { rir: 3 }, {}])), 0)
|
||||
expect(pts).toHaveLength(1)
|
||||
expect(pts[0].rir).toBe(2)
|
||||
expect(pts[0].n).toBe(2) // rated
|
||||
expect(pts[0].sets).toBe(3) // trained
|
||||
})
|
||||
|
||||
it('drops a week that rests on a single tap', () => {
|
||||
expect(effortWeeks(S(W(1, [{ rir: 1 }])), 0)).toEqual([])
|
||||
})
|
||||
|
||||
it('comes back oldest first, whatever order the workouts arrived in', () => {
|
||||
const pts = effortWeeks(S(W(2, [{ rir: 1 }, { rir: 1 }]), W(30, [{ rir: 3 }, { rir: 3 }])), 0)
|
||||
expect(pts.map(p => p.rir)).toEqual([3, 1])
|
||||
expect(pts[0].t).toBeLessThan(pts[1].t)
|
||||
})
|
||||
})
|
||||
|
||||
describe('effortHistogram', () => {
|
||||
it('bins by whole steps and collapses the far end into a tail', () => {
|
||||
const h = effortHistogram(S(W(2, [{ rir: 0 }, { rir: 1.5 }, { rir: 4 }, { rir: 7 }])), 0)
|
||||
expect(h.map(b => b.n)).toEqual([1, 1, 0, 0, 2])
|
||||
expect(h[4].tail).toBe(true)
|
||||
expect(h[0].pct).toBe(0.25)
|
||||
})
|
||||
|
||||
it('is all zeroes, not NaN, when nothing is rated', () => {
|
||||
const h = effortHistogram(S(W(2, [{}])), 0)
|
||||
expect(h.every(b => b.n === 0 && b.pct === 0)).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('isHardSet', () => {
|
||||
it('draws the line at the effort that actually drives adaptation', () => {
|
||||
expect(isHardSet({ rir: HARD_RIR })).toBe(true)
|
||||
expect(isHardSet({ rir: HARD_RIR + 0.5 })).toBe(false)
|
||||
expect(isHardSet({ rpe: 10 })).toBe(true)
|
||||
expect(isHardSet({})).toBe(false) // unrated is not hard, and not easy either
|
||||
})
|
||||
})
|
||||
@@ -1,7 +1,27 @@
|
||||
import { EXDB } from './exercises-data.js'
|
||||
import { t } from './i18n.js'
|
||||
import { t } from './i18n-core.js'
|
||||
|
||||
export { EXDB }
|
||||
|
||||
// The generated dataset already supplies secondary muscles for most exercises. Keep the
|
||||
// handful of conservative catalogue additions that are useful to the muscle map here so a
|
||||
// dataset refresh does not erase them. Values follow the dataset's existing alias vocabulary.
|
||||
const SECONDARY_ADDITIONS = {
|
||||
'0027': ['rear deltoids'], // barbell bent over row
|
||||
'0293': ['rear deltoids'], // dumbbell bent over row
|
||||
'0499': ['rear deltoids'], // inverted row
|
||||
'0861': ['rear deltoids'], // cable seated row
|
||||
}
|
||||
|
||||
// Secondary muscles for an exercise, with the small conservative additions applied as an
|
||||
// overlay. The raw dataset is never mutated - consumers that want the pristine catalogue
|
||||
// (export, print, import) keep reading EXDB untouched, while the muscle map sees the
|
||||
// enriched list. Values follow the dataset's existing alias vocabulary.
|
||||
export const smOf = ex => {
|
||||
const base = Array.isArray(ex?.sm) ? ex.sm : (ex?.sm ? [ex.sm] : [])
|
||||
return [...new Set([...base, ...(SECONDARY_ADDITIONS[ex?.id] || [])])]
|
||||
}
|
||||
|
||||
export const EXIDX = {}
|
||||
EXDB.forEach(e => { EXIDX[e.id] = e })
|
||||
export const BODYPARTS = [...new Set(EXDB.map(e => e.bp))].sort()
|
||||
@@ -28,15 +48,29 @@ export const allExercises = st => [...(st.customEx || []), ...EXDB]
|
||||
|
||||
// Media normally sits next to the app (img/ and gif/, mounted into the web container).
|
||||
// A build can point them somewhere else — the demo build pulls them off a CDN instead of
|
||||
// shipping ~140 MB of images into the deployment.
|
||||
const IMG_BASE = import.meta.env.VITE_IMG_BASE || 'img/'
|
||||
const GIF_BASE = import.meta.env.VITE_GIF_BASE || 'gif/'
|
||||
// shipping ~140 MB of images into the deployment. `import.meta.env` is undefined in plain
|
||||
// Node; the guard keeps this module loadable without Vite.
|
||||
// The defaults are absolute on purpose (issue #79). A bare 'img/' resolves against the
|
||||
// current document's directory, so on the one two-segment route in the app, /plan/r/:id,
|
||||
// every request went to /plan/r/img/… and 404'd — and nginx's extension block has no
|
||||
// try_files, so it 404s rather than falling through to index.html, leaving a blank image
|
||||
// and nothing in the console.
|
||||
const ENV = import.meta.env || {}
|
||||
const IMG_BASE = ENV.VITE_IMG_BASE || '/img/'
|
||||
const GIF_BASE = ENV.VITE_GIF_BASE || '/gif/'
|
||||
export const imgSrc = ex => IMG_BASE + ex.img
|
||||
export const gifSrc = ex => GIF_BASE + ex.gif
|
||||
|
||||
// Cardio exercises log time + speed instead of weight × reps.
|
||||
export const isCardio = idOrEx => (typeof idOrEx === 'string' ? EXIDX[idOrEx] : idOrEx)?.bp === 'cardio'
|
||||
|
||||
// Exercises the dataset already knows carry no external load (issue #32) — a quarter of the
|
||||
// catalogue. This seeds the `bw` flag on a fresh config so a push-up never asks for a weight
|
||||
// nobody was going to enter. It is only the default: the flag lives on the config, so a dip
|
||||
// done with a belt can turn it off and a custom exercise can turn it on.
|
||||
export const isBodyweightEq = idOrEx =>
|
||||
(typeof idOrEx === 'string' ? EXIDX[idOrEx] : idOrEx)?.eq === 'body weight'
|
||||
|
||||
// An id that resolves to nothing — a plan file built against a different exercise dataset,
|
||||
// a custom exercise deleted on another device before the sync arrived — still has to
|
||||
// render. A placeholder keeps it visible (and removable) instead of taking the whole view
|
||||
|
||||
@@ -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,5 +1,5 @@
|
||||
// Formatting + date helpers (ported from the vanilla app, unit taken from the store where needed).
|
||||
import { dateLocale, t } from './i18n.js'
|
||||
import { dateLocale, t } from './i18n-core.js'
|
||||
export const todayISO = () => {
|
||||
const d = new Date()
|
||||
return d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0')
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
/**
|
||||
* Whether "Continue without account" may be offered, given the public config from /api/config.
|
||||
*
|
||||
* Guest mode is allowed unless the server has *positively* said otherwise. That asymmetry is the
|
||||
* whole point: a config we could not fetch — offline, server restarting, request failed — is not
|
||||
* the same answer as `allow_guest: false`, and treating it as one would lock people out of an
|
||||
* instance whose admin never disabled anything. An instance that really did disable guests says
|
||||
* so on the next successful boot, and the session is ended then (see useStore.boot).
|
||||
*
|
||||
* Older servers predate the flag and send no `allow_guest` at all; they mean "allowed".
|
||||
*
|
||||
* @param {{allow_guest?: boolean}|null|undefined} config Parsed /api/config body, or null.
|
||||
* @returns {boolean} true when the guest entrance may be shown and used.
|
||||
*/
|
||||
export const guestAllowed = config => !(config && config.allow_guest === false)
|
||||
@@ -0,0 +1,36 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { guestAllowed } from './guest.js'
|
||||
|
||||
// The flag is the easy half. The half worth pinning down is what happens when the server did not
|
||||
// answer: a failed config fetch must not be read as "guests are disabled", or an instance that is
|
||||
// merely unreachable locks out everyone who never made an account (#42).
|
||||
describe('guestAllowed', () => {
|
||||
it('allows guests when the server says so', () => {
|
||||
expect(guestAllowed({ allow_guest: true })).toBe(true)
|
||||
})
|
||||
|
||||
it('refuses guests only on an explicit false', () => {
|
||||
expect(guestAllowed({ allow_guest: false })).toBe(false)
|
||||
})
|
||||
|
||||
it('allows guests when the config could not be fetched', () => {
|
||||
expect(guestAllowed(null)).toBe(true)
|
||||
expect(guestAllowed(undefined)).toBe(true)
|
||||
})
|
||||
|
||||
it('allows guests against a server too old to send the flag', () => {
|
||||
expect(guestAllowed({ invite_only: true })).toBe(true)
|
||||
})
|
||||
|
||||
// A missing key and a falsy-but-not-false value are different things. Only `false` — what the
|
||||
// server actually serialises — closes the door; anything else stays open rather than guessing.
|
||||
it('does not treat other falsy values as a refusal', () => {
|
||||
for (const v of [0, '', null, undefined, NaN]) {
|
||||
expect(guestAllowed({ allow_guest: v })).toBe(true)
|
||||
}
|
||||
})
|
||||
|
||||
it('treats the string "false" as the misconfiguration it is, not as a refusal', () => {
|
||||
expect(guestAllowed({ allow_guest: 'false' })).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -1,6 +1,21 @@
|
||||
// Pure helpers over the state object S (ported 1:1 from the vanilla app).
|
||||
import { todayISO, isoOf, weekKey, fmtNum } from './format.js'
|
||||
import { isCardio } from './exercises.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
|
||||
// gets dragged along behind it.
|
||||
import { t } from './i18n-core.js'
|
||||
|
||||
// How an exercise is logged (issue #16). This used to be derived from the body part alone,
|
||||
// which meant a plank or a farmer's carry could only be timed by filing it under cardio.
|
||||
@@ -17,6 +32,28 @@ export function modeOf(cfg) {
|
||||
}
|
||||
export const isTimed = cfg => modeOf(cfg) === 'time'
|
||||
|
||||
// Two flags that ride on top of a mode rather than making new ones (issues #31/#32), because
|
||||
// "bodyweight" and "per side" are true of a rep set and of a timed hold alike:
|
||||
// bodyweight — the exercise carries no load of its own, so `w` means *added* weight and is
|
||||
// asked for only once you say there is some. Seeded from the equipment field.
|
||||
// Spelled out rather than `bw`, which a workout already uses for the weigh-in
|
||||
// it was logged at — two different things one letter apart is a bug waiting.
|
||||
// side — the exercise is unilateral. You still log what you did: 16, the total across
|
||||
// both sides. The split is derived for planning ("8 per side"), never entered
|
||||
// — a number that sometimes means one side and sometimes both is the thing
|
||||
// that made this ambiguous in the first place, and one rep count that always
|
||||
// means the same thing beats two that need a legend.
|
||||
// Both are absent on every plan, workout and backup written before they existed, and absent
|
||||
// reads as false, so nothing needs migrating.
|
||||
export const isBw = cfg => (cfg && cfg.bodyweight != null ? !!cfg.bodyweight : isBodyweightEq(cfg && cfg.id))
|
||||
export const isPerSide = cfg => !!(cfg && cfg.side)
|
||||
// What one side did, for display only. Half of an odd total is shown as it falls (8.5) rather
|
||||
// than rounded away: it means the sides were not even, which is worth seeing.
|
||||
export const sideReps = reps => (reps || 0) / 2
|
||||
// Unilateral work moves in pairs, so its rep target steps by two — 16, 18, 20 — and a total
|
||||
// that stayed odd would put a rep on one side and not the other.
|
||||
export const repStep = cfg => (isPerSide(cfg) ? 2 : 1)
|
||||
|
||||
// mm:ss for a work duration — seconds alone read badly past a minute ("90 s" vs "1:30").
|
||||
export function fmtSec(sec) {
|
||||
const n = Math.max(0, Math.round(Number(sec) || 0))
|
||||
@@ -69,27 +106,43 @@ const effortTail = s => {
|
||||
// One-line summary of a logged set. `cfg` carries the mode when the caller has it (a routine
|
||||
// entry or a workout entry); passing an id alone keeps the old body-part behaviour.
|
||||
export function setLabel(id, s, cfg) {
|
||||
const mode = modeOf(cfg || { id })
|
||||
const c = cfg || { id }
|
||||
const mode = modeOf(c)
|
||||
if (mode === 'cardio') return `${s.min || 0} min @ ${fmtNum(s.speed || 0)} km/h`
|
||||
if (mode === 'time') return fmtSec(s.sec) + (s.w > 0 ? ` · ${fmtNum(s.w)}` : '')
|
||||
return `${fmtNum(s.w || 0)}×${s.r || 0}` + effortTail(s)
|
||||
// Bodyweight reads as what you did — "12", or "+10 × 12" once there is a belt involved —
|
||||
// rather than "0×12", which says a set was performed with no weight and means nothing.
|
||||
// A per-side set needs no mark here: the number logged is the total, the same as every
|
||||
// other set in the app.
|
||||
const reps = s.r || 0
|
||||
if (isBw({ ...c, id: c.id ?? id })) {
|
||||
const load = s.w > 0 ? `+${fmtNum(s.w)} × ` : ''
|
||||
return `${load}${reps}` + effortTail(s)
|
||||
}
|
||||
return `${fmtNum(s.w || 0)}×${reps}` + effortTail(s)
|
||||
}
|
||||
// Default config for a freshly added exercise.
|
||||
export function defaultConfig(id, mode) {
|
||||
const m = mode || modeOf({ id })
|
||||
if (m === 'cardio') return { sets: 1, min: 20, speed: 8 }
|
||||
if (m === 'time') return { sets: 3, sec: 45, weight: 0, mode: 'time' }
|
||||
return { sets: 3, reps: 10, weight: 0, mode: 'reps' }
|
||||
// Written only when it is true, so a barbell config is byte-for-byte what it was before
|
||||
// the flag existed and a plan file gains nothing it does not need.
|
||||
const bw = isBodyweightEq(id) ? { bodyweight: true } : {}
|
||||
if (m === 'time') return { sets: 3, sec: 45, weight: 0, mode: 'time', ...bw }
|
||||
return { sets: 3, reps: 10, weight: 0, mode: 'reps', ...bw }
|
||||
}
|
||||
// One-line summary of a planned exercise ("3 × 10 · 60 kg"), shared by the routine editor
|
||||
// and the plan export so a mode is described the same way everywhere.
|
||||
export function exLine(cfg, unit) {
|
||||
const mode = modeOf(cfg)
|
||||
const n = cfg.sets || 1
|
||||
const load = cfg.weight ? ' · ' + fmtNum(cfg.weight) + ' ' + unit : ''
|
||||
// Added weight reads as added: "+10 kg" on a dip belt, "60 kg" on a barbell.
|
||||
const load = cfg.weight ? ' · ' + (isBw(cfg) ? '+' : '') + fmtNum(cfg.weight) + ' ' + unit : ''
|
||||
if (mode === 'cardio') return `${n} × ${cfg.min || 20} min @ ${fmtNum(cfg.speed || 8)} km/h`
|
||||
if (mode === 'time') return `${n} × ${fmtSec(cfg.sec || 45)}${load}`
|
||||
return `${n} × ${cfg.reps}${load}`
|
||||
// This is the line with room for it, so the split is spelled out: "3 × 16 · 8/side".
|
||||
const split = isPerSide(cfg) ? ' · ' + t('{0}/side', fmtNum(sideReps(cfg.reps))) : ''
|
||||
return `${n} × ${cfg.reps}${load}${split}`
|
||||
}
|
||||
|
||||
// Drop superset ids that no longer have an adjacent partner (after unlink/reorder/remove).
|
||||
@@ -99,6 +152,60 @@ export function cleanupSg(ex) {
|
||||
})
|
||||
}
|
||||
|
||||
// Return the contiguous run around an entry that shares its superset id. A repeated id in a
|
||||
// separated part of the list is deliberately not included: the display semantics are adjacent
|
||||
// entries sharing one id, not every entry that happens to carry that id.
|
||||
function contiguousSgGroup(items, idx) {
|
||||
const sg = items[idx]?.sg
|
||||
if (!sg) return [idx]
|
||||
let first = idx
|
||||
let last = idx
|
||||
while (first > 0 && items[first - 1]?.sg === sg) first--
|
||||
while (last + 1 < items.length && items[last + 1]?.sg === sg) last++
|
||||
return Array.from({ length: last - first + 1 }, (_, i) => first + i)
|
||||
}
|
||||
|
||||
function freshSg(items, first, second) {
|
||||
const base = `sg-${Math.min(first, second)}-${Math.max(first, second)}`
|
||||
let sg = base
|
||||
let n = 2
|
||||
while (items.some(e => e.sg === sg)) sg = `${base}-${n++}`
|
||||
return sg
|
||||
}
|
||||
|
||||
// Purely pair two adjacent entries. Existing contiguous groups on either side are merged, so
|
||||
// pairing the end of one group with the start of another produces one display unit. A caller can
|
||||
// provide a group id (useful when restoring a known id); otherwise an existing id is preferred,
|
||||
// with a deterministic unused id for two previously ungrouped entries.
|
||||
export function pairAdjacent(items, first, second, groupId) {
|
||||
if (!Array.isArray(items)) throw new TypeError('Superset entries must be an array')
|
||||
if (!Number.isInteger(first) || !Number.isInteger(second) || !items[first] || !items[second]) {
|
||||
throw new RangeError('Superset entry indexes are invalid')
|
||||
}
|
||||
if (Math.abs(first - second) !== 1) throw new RangeError('Superset entries must be adjacent')
|
||||
|
||||
const next = items.map(e => ({ ...e }))
|
||||
const left = Math.min(first, second)
|
||||
const right = Math.max(first, second)
|
||||
const group = groupId || next[left].sg || next[right].sg || freshSg(next, left, right)
|
||||
const members = new Set([...contiguousSgGroup(next, left), ...contiguousSgGroup(next, right)])
|
||||
members.forEach(i => { next[i].sg = group })
|
||||
return next
|
||||
}
|
||||
|
||||
// Remove one entry from its superset and clean any ids that no longer have an adjacent partner.
|
||||
// This is pure so the active workout can replace its entries atomically through the store.
|
||||
export function unpairSuperset(items, idx) {
|
||||
if (!Array.isArray(items)) throw new TypeError('Superset entries must be an array')
|
||||
if (!Number.isInteger(idx) || !items[idx]) throw new RangeError('Superset entry index is invalid')
|
||||
const next = items.map(e => ({ ...e }))
|
||||
delete next[idx].sg
|
||||
next.forEach((e, i) => {
|
||||
if (e.sg && !(next[i - 1]?.sg === e.sg || next[i + 1]?.sg === e.sg)) delete e.sg
|
||||
})
|
||||
return next
|
||||
}
|
||||
|
||||
export function lastEntryFor(S, exId) {
|
||||
for (let i = S.workouts.length - 1; i >= 0; i--) {
|
||||
const en = S.workouts[i].entries.find(e => e.id === exId)
|
||||
@@ -109,13 +216,25 @@ export function lastEntryFor(S, exId) {
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
// A freestyle exercise starts with the last target the user actually trained, rather than the
|
||||
// generic config sheet defaults used when there is no history. The set rows themselves are still
|
||||
// built by buildSets(), which copies each completed set by position; only the target shape and
|
||||
// number of rows need to be seeded here so the config sheet and the rows agree.
|
||||
export function freestyleConfig(S, cfg) {
|
||||
const last = lastEntryFor(S, cfg.id)
|
||||
if (!last) return { ...cfg }
|
||||
return {
|
||||
...cfg,
|
||||
...(last.target || {}),
|
||||
id: cfg.id,
|
||||
sets: Math.max(1, last.sets.length)
|
||||
}
|
||||
}
|
||||
export function bestWeightFor(S, exId) {
|
||||
let best = 0
|
||||
S.workouts.forEach(w => w.entries.forEach(e => {
|
||||
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
|
||||
}
|
||||
@@ -130,10 +249,11 @@ export function effectiveRoutine(S, iso) {
|
||||
const id = effectiveRoutineId(S, iso)
|
||||
return id ? S.routines.find(r => r.id === id) || null : null
|
||||
}
|
||||
export function buildSets(S, cfg) {
|
||||
export function buildSets(S, cfg, options = {}) {
|
||||
const last = lastEntryFor(S, cfg.id)
|
||||
const n = Math.max(1, cfg.sets || 1)
|
||||
const mode = modeOf(cfg)
|
||||
const preferLast = !!options.preferLast
|
||||
const sets = []
|
||||
// Last time's set at the same position, falling back to its final set when the plan grew.
|
||||
const prevAt = i => (last ? (last.sets[i] || last.sets[last.sets.length - 1]) : null)
|
||||
@@ -159,13 +279,17 @@ export function buildSets(S, cfg) {
|
||||
for (let i = 0; i < n; i++) {
|
||||
const prev = prevAt(i)
|
||||
const usable = prev && prev.r > 0 ? prev : null
|
||||
const w = conf && conf.w > 0 ? conf.w : (usable ? usable.w : cfg.weight)
|
||||
// Planned sessions may use the confirmed working weight, while freestyle should reproduce
|
||||
// the load of each matching set when that option is requested.
|
||||
const w = preferLast && usable ? usable.w : (conf && conf.w > 0 ? conf.w : (usable ? usable.w : cfg.weight))
|
||||
sets.push({ w, r: usable ? usable.r : cfg.reps, done: false })
|
||||
}
|
||||
return sets
|
||||
}
|
||||
export function workoutVolume(w) {
|
||||
let v = 0
|
||||
// No special case for unilateral work: a per-side set logs its total, so both sides are
|
||||
// already in the rep count that arrives here.
|
||||
w.entries.forEach(e => e.sets.forEach(s => { if (s.done) v += (s.w || 0) * (s.r || 0) }))
|
||||
return v
|
||||
}
|
||||
@@ -207,3 +331,100 @@ export function streakWeeks(S) {
|
||||
}
|
||||
return streak
|
||||
}
|
||||
|
||||
/**
|
||||
* Cascade a weight change forward: following sets of the same warm-up flag that are still
|
||||
* undone take the new value (null deletes the key). Done sets are never rewritten.
|
||||
*/
|
||||
export function cascadeWeight(rows, from, value) {
|
||||
const warm = isWarmupRow(rows[from])
|
||||
const next = rows.slice()
|
||||
for (let j = from + 1; j < next.length; j++) {
|
||||
if (isWarmupRow(next[j]) === warm && !next[j].done) {
|
||||
if (value == null) delete next[j].w
|
||||
else next[j].w = value
|
||||
}
|
||||
}
|
||||
return next
|
||||
}
|
||||
|
||||
/** Insert a warm-up row before the first work row, copying the preceding warm-up's values. */
|
||||
export function insertWarmupRow(rows, mode, target) {
|
||||
const firstWork = rows.findIndex(x => !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, phase: 'warmup', warmup: true }
|
||||
: mode === 'time'
|
||||
? { sec: l ? l.sec : (target.sec || 45), w: l ? (l.w || 0) : (target.weight || 0), done: false, phase: 'warmup', warmup: true }
|
||||
: { w: l ? l.w : 0, r: l ? l.r : target.reps, done: false, phase: 'warmup', warmup: true }
|
||||
const next = rows.slice()
|
||||
next.splice(at, 0, warm)
|
||||
return next
|
||||
}
|
||||
|
||||
/** Remove the row at `i`, never emptying the entry below one row. */
|
||||
export function removeRowAt(rows, i) {
|
||||
if (rows.length <= 1) return rows.slice()
|
||||
const next = rows.slice()
|
||||
next.splice(i, 1)
|
||||
return next
|
||||
}
|
||||
|
||||
/** Completed non-warm-up sets across a workout's entries. */
|
||||
export function workSetsDone(w) {
|
||||
return (w?.entries || []).reduce(
|
||||
(n, e) => n + (e.sets || []).filter(s => s.done && !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,10 +1,13 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { modeOf, isTimed, fmtSec, setLabel, defaultConfig, buildSets, exLine, workoutVolume, effortOf, stepEffort, capEffort } 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.
|
||||
const CARDIO = EXDB.find(e => e.bp === 'cardio').id
|
||||
const LIFT = EXDB.find(e => e.bp !== 'cardio').id
|
||||
// A *loaded* lift: the catalogue's first non-cardio entry is a sit-up, which since issue #32
|
||||
// defaults to bodyweight and would quietly send every label test down the other path.
|
||||
const LIFT = EXDB.find(e => e.bp !== 'cardio' && e.eq !== 'body weight').id
|
||||
const BW = EXDB.find(e => e.eq === 'body weight').id
|
||||
|
||||
describe('modeOf', () => {
|
||||
it('falls back to the body part when a plan has no mode — every existing plan keeps working', () => {
|
||||
@@ -255,9 +258,73 @@ describe('defaultConfig', () => {
|
||||
expect(defaultConfig(CARDIO)).toEqual({ sets: 1, min: 20, speed: 8 })
|
||||
expect(defaultConfig(LIFT, 'time')).toEqual({ sets: 3, sec: 45, weight: 0, mode: 'time' })
|
||||
})
|
||||
it('seeds the bodyweight flag from the catalogue, and only when it is true', () => {
|
||||
expect(defaultConfig(BW)).toEqual({ sets: 3, reps: 10, weight: 0, mode: 'reps', bodyweight: true })
|
||||
expect(defaultConfig(BW, 'time')).toEqual({ sets: 3, sec: 45, weight: 0, mode: 'time', bodyweight: true })
|
||||
expect('bodyweight' in defaultConfig(LIFT)).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
/* ---------- bodyweight and per side (issues #31/#32/#33) ---------- */
|
||||
|
||||
describe('isBw', () => {
|
||||
it('defaults from the catalogue so an existing plan needs no flag', () => {
|
||||
expect(isBw({ id: BW })).toBe(true)
|
||||
expect(isBw({ id: LIFT })).toBe(false)
|
||||
})
|
||||
it('lets the config win in both directions — a belt on a dip, a flag on a machine', () => {
|
||||
expect(isBw({ id: BW, bodyweight: false })).toBe(false)
|
||||
expect(isBw({ id: LIFT, bodyweight: true })).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('sideReps', () => {
|
||||
it('halves the logged total, because the total is what was logged', () => {
|
||||
expect(sideReps(16)).toBe(8)
|
||||
expect(sideReps(0)).toBe(0)
|
||||
})
|
||||
it('shows an odd total as it falls rather than rounding the imbalance away', () => {
|
||||
expect(sideReps(17)).toBe(8.5)
|
||||
})
|
||||
})
|
||||
|
||||
describe('exLine — per side never reaches a timed hold', () => {
|
||||
it('ignores a stale side flag on a hold, which has no reps to split', () => {
|
||||
expect(exLine({ id: LIFT, sets: 3, sec: 45, mode: 'time', side: true }, 'kg')).toBe('3 × 0:45')
|
||||
})
|
||||
})
|
||||
|
||||
describe('repStep', () => {
|
||||
it('steps unilateral work in twos so the total stays splittable', () => {
|
||||
expect(repStep({ side: true })).toBe(2)
|
||||
expect(repStep({})).toBe(1)
|
||||
expect(repStep(null)).toBe(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('setLabel — bodyweight', () => {
|
||||
it('reads as reps alone, because "0×12" describes nothing', () => {
|
||||
expect(setLabel(BW, { w: 0, r: 12 }, { id: BW })).toBe('12')
|
||||
})
|
||||
it('spells out a belt as an addition', () => {
|
||||
expect(setLabel(BW, { w: 10, r: 8 }, { id: BW })).toBe('+10 × 8')
|
||||
})
|
||||
it('logs a per-side set as the plain total, like every other set in the app', () => {
|
||||
expect(setLabel(BW, { w: 0, r: 16 }, { id: BW, side: true })).toBe('16')
|
||||
expect(setLabel(LIFT, { w: 20, r: 16 }, { id: LIFT, side: true })).toBe('20×16')
|
||||
})
|
||||
it('keeps the effort tail', () => {
|
||||
expect(setLabel(BW, { w: 0, r: 12, rir: 2 }, { id: BW })).toBe('12 (RIR 2)')
|
||||
})
|
||||
})
|
||||
|
||||
describe('exLine', () => {
|
||||
it('shows the split where there is room for it, next to the total you log', () => {
|
||||
expect(exLine({ id: LIFT, sets: 3, reps: 16, side: true }, 'kg')).toBe('3 × 16 · 8/side')
|
||||
})
|
||||
it('marks added weight as added', () => {
|
||||
expect(exLine({ id: BW, sets: 3, reps: 8, weight: 10 }, 'kg')).toBe('3 × 8 · +10 kg')
|
||||
})
|
||||
it('summarises a planned exercise per mode', () => {
|
||||
expect(exLine({ id: LIFT, sets: 3, reps: 10 }, 'kg')).toBe('3 × 10')
|
||||
expect(exLine({ id: LIFT, sets: 3, reps: 10, weight: 60 }, 'kg')).toBe('3 × 10 · 60 kg')
|
||||
@@ -269,6 +336,80 @@ describe('exLine', () => {
|
||||
|
||||
const emptyS = { workouts: [], exWeights: {} }
|
||||
|
||||
describe('freestyleConfig', () => {
|
||||
it('inherits the last target and completed set count for a newly added exercise', () => {
|
||||
const S = {
|
||||
exWeights: {},
|
||||
workouts: [{
|
||||
d: '2026-01-01',
|
||||
entries: [{
|
||||
id: LIFT,
|
||||
target: { mode: 'reps', sets: 4, reps: 8, weight: 60, prog: 'linear' },
|
||||
sets: [
|
||||
{ w: 60, r: 8, done: true },
|
||||
{ w: 62.5, r: 7, done: true },
|
||||
{ w: 62.5, r: 6, done: true },
|
||||
{ w: 62.5, r: 5, done: true }
|
||||
]
|
||||
}]
|
||||
}]
|
||||
}
|
||||
const cfg = freestyleConfig(S, { id: LIFT, mode: 'reps', sets: 3, reps: 10, weight: 0 })
|
||||
|
||||
expect(cfg).toEqual({ id: LIFT, mode: 'reps', sets: 4, reps: 8, weight: 60, prog: 'linear' })
|
||||
expect(buildSets(S, cfg)).toEqual([
|
||||
{ w: 60, r: 8, done: false },
|
||||
{ w: 62.5, r: 7, done: false },
|
||||
{ w: 62.5, r: 6, done: false },
|
||||
{ w: 62.5, r: 5, done: false }
|
||||
])
|
||||
})
|
||||
|
||||
it('inherits the target for timed and cardio exercises too', () => {
|
||||
const timed = {
|
||||
exWeights: {},
|
||||
workouts: [{
|
||||
d: '2026-01-02',
|
||||
entries: [{
|
||||
id: LIFT,
|
||||
target: { mode: 'time', sets: 2, sec: 60, weight: 15 },
|
||||
sets: [{ sec: 55, w: 15, done: true }, { sec: 60, w: 17.5, done: true }]
|
||||
}]
|
||||
}]
|
||||
}
|
||||
const cardio = {
|
||||
exWeights: {},
|
||||
workouts: [{
|
||||
d: '2026-01-03',
|
||||
entries: [{
|
||||
id: CARDIO,
|
||||
target: { sets: 2, min: 30, speed: 7 },
|
||||
sets: [{ min: 28, speed: 7, done: true }, { min: 30, speed: 7.5, done: true }]
|
||||
}]
|
||||
}]
|
||||
}
|
||||
|
||||
const timedCfg = freestyleConfig(timed, { id: LIFT, mode: 'time', sets: 3, sec: 45, weight: 0 })
|
||||
expect(timedCfg).toEqual({ id: LIFT, mode: 'time', sets: 2, sec: 60, weight: 15 })
|
||||
expect(buildSets(timed, timedCfg)).toEqual([
|
||||
{ sec: 55, w: 15, done: false },
|
||||
{ sec: 60, w: 17.5, done: false }
|
||||
])
|
||||
|
||||
const cardioCfg = freestyleConfig(cardio, { id: CARDIO, sets: 1, min: 20, speed: 8 })
|
||||
expect(cardioCfg).toEqual({ id: CARDIO, sets: 2, min: 30, speed: 7 })
|
||||
expect(buildSets(cardio, cardioCfg)).toEqual([
|
||||
{ min: 28, speed: 7, done: false },
|
||||
{ min: 30, speed: 7.5, done: false }
|
||||
])
|
||||
})
|
||||
|
||||
it('keeps the supplied defaults when there is no completed matching workout', () => {
|
||||
const cfg = freestyleConfig(emptyS, { id: LIFT, mode: 'reps', sets: 3, reps: 10, weight: 50 })
|
||||
expect(cfg).toEqual({ id: LIFT, mode: 'reps', sets: 3, reps: 10, weight: 50 })
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildSets', () => {
|
||||
it('builds reps sets from the plan when there is no history', () => {
|
||||
expect(buildSets(emptyS, { id: LIFT, sets: 3, reps: 8, weight: 50 }))
|
||||
@@ -307,6 +448,14 @@ describe('buildSets', () => {
|
||||
const S = { exWeights: { [LIFT]: { w: 75 } }, workouts: [{ d: '2026-01-01', entries: [{ id: LIFT, sets: [{ w: 60, r: 10, done: true }] }] }] }
|
||||
expect(buildSets(S, { id: LIFT, sets: 1, reps: 8, weight: 50 })).toEqual([{ w: 75, r: 10, done: false }])
|
||||
})
|
||||
|
||||
it('can preserve each last set weight for freestyle instead of using the working-weight hint', () => {
|
||||
const S = { exWeights: { [LIFT]: { w: 75 } }, workouts: [{ d: '2026-01-01', entries: [{ id: LIFT, sets: [
|
||||
{ w: 60, r: 10, done: true }, { w: 62.5, r: 8, done: true }
|
||||
] }] }] }
|
||||
expect(buildSets(S, { id: LIFT, sets: 2, reps: 8, weight: 50 }, { preferLast: true }))
|
||||
.toEqual([{ w: 60, r: 10, done: false }, { w: 62.5, r: 8, done: false }])
|
||||
})
|
||||
})
|
||||
|
||||
describe('workoutVolume', () => {
|
||||
@@ -318,4 +467,220 @@ describe('workoutVolume', () => {
|
||||
] }
|
||||
expect(workoutVolume(w)).toBe(600)
|
||||
})
|
||||
|
||||
it('needs no per-side case — the logged reps are already both sides (issue #31)', () => {
|
||||
const w = { entries: [{ id: LIFT, target: { side: true }, sets: [{ w: 20, r: 16, done: true }] }] }
|
||||
expect(workoutVolume(w)).toBe(320)
|
||||
})
|
||||
|
||||
it('leaves an unloaded bodyweight set at zero volume rather than inventing a number', () => {
|
||||
const w = { entries: [{ id: BW, target: { bodyweight: true }, sets: [{ w: 0, r: 20, done: true }] }] }
|
||||
expect(workoutVolume(w)).toBe(0)
|
||||
})
|
||||
|
||||
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' }])
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
describe('session row helpers', () => {
|
||||
it('cascadeWeight propagates to same-flag undone rows and never rewrites done sets', () => {
|
||||
const rows = [
|
||||
{ warmup: true, w: 20, done: true },
|
||||
{ warmup: true, w: 20, done: false },
|
||||
{ w: 60, done: true },
|
||||
{ w: 60, done: false },
|
||||
{ w: 60, done: false },
|
||||
]
|
||||
const next = cascadeWeight(rows, 2, 62.5)
|
||||
expect(next[2].w).toBe(60) // done set untouched
|
||||
expect(next[3].w).toBe(62.5) // same flag (work), undone
|
||||
expect(next[4].w).toBe(62.5) // same flag (work), undone
|
||||
expect(next[1].w).toBe(20) // different flag (warm-up) untouched
|
||||
})
|
||||
|
||||
it('cascadeWeight deleting the weight removes the key from following undone rows only', () => {
|
||||
const rows = [
|
||||
{ w: 60, done: true },
|
||||
{ w: 60, done: false },
|
||||
{ w: 60, done: false },
|
||||
]
|
||||
const next = cascadeWeight(rows, 0, null)
|
||||
expect(next[0].w).toBe(60) // done set untouched
|
||||
expect('w' in next[1]).toBe(false)
|
||||
expect('w' in next[2]).toBe(false)
|
||||
})
|
||||
|
||||
it('insertWarmupRow inserts before the first work row and copies the last warm-up values', () => {
|
||||
const rows = [
|
||||
{ warmup: true, w: 20, r: 8, done: true },
|
||||
{ warmup: true, w: 30, r: 8, done: false },
|
||||
{ w: 60, r: 8, done: false },
|
||||
]
|
||||
const next = insertWarmupRow(rows, 'reps', { reps: 8 })
|
||||
expect(next.length).toBe(4)
|
||||
expect(next[2].warmup).toBe(true)
|
||||
expect(next[2].w).toBe(30) // copies the preceding warm-up
|
||||
expect(next[3].w).toBe(60) // work row still after the warm-up block
|
||||
})
|
||||
|
||||
it('removeRowAt never empties an entry below one row', () => {
|
||||
expect(removeRowAt([{ w: 60 }], 0).length).toBe(1)
|
||||
const rows = [{ w: 60 }, { w: 70 }]
|
||||
const next = removeRowAt(rows, 0)
|
||||
expect(next.length).toBe(1)
|
||||
expect(next[0].w).toBe(70)
|
||||
})
|
||||
})
|
||||
|
||||
// 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)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,44 @@
|
||||
// Runtime-agnostic core of the i18n module: state, constants and readers (t, dateLocale,
|
||||
// instrFor, getLang). Plain Node-loadable — the browser-only pieces (import.meta.glob lazy
|
||||
// loads, the React subscription hook) live in i18n.js and re-export from here.
|
||||
|
||||
export const LANGS = {
|
||||
en: 'English', de: 'Deutsch', es: 'Español', fr: 'Français', it: 'Italiano',
|
||||
pt: 'Português', pl: 'Polski', tr: 'Türkçe', ru: 'Русский', zh: '中文',
|
||||
ko: '한국어', hi: 'हिन्दी'
|
||||
}
|
||||
export const INSTR_LANGS = ['en', 'es', 'fr', 'it', 'tr', 'ru', 'zh', 'hi', 'pl', 'ko']
|
||||
export const DATE_LOCALES = {
|
||||
en: 'en-GB', de: 'de-DE', es: 'es-ES', fr: 'fr-FR', it: 'it-IT', pt: 'pt-PT',
|
||||
pl: 'pl-PL', tr: 'tr-TR', ru: 'ru-RU', zh: 'zh-CN', ko: 'ko-KR', hi: 'hi-IN'
|
||||
}
|
||||
|
||||
let lang = 'en' // set only by _setLangState, called from i18n.js setLang
|
||||
let dict = {} // current locale pack (empty = English fallback)
|
||||
let instr = null // { exId: [steps] } for the current language, null = English
|
||||
let version = 0 // bumped on every setLang; drives the React subscription selector
|
||||
|
||||
export const getLang = () => lang
|
||||
export const dateLocale = () => DATE_LOCALES[lang] || 'en-GB'
|
||||
export const getVersion = () => version
|
||||
|
||||
// Translate a source string; {0},{1}… are replaced with args (also on the English fallback).
|
||||
export function t(s, ...args) {
|
||||
let v = dict[s] || s
|
||||
for (let i = 0; i < args.length; i++) v = v.replaceAll('{' + i + '}', args[i])
|
||||
return v
|
||||
}
|
||||
|
||||
// Instructions for an exercise in the current language (English steps as fallback).
|
||||
export const instrFor = ex => (instr && instr[ex.id]) || ex.st || []
|
||||
|
||||
// Called by i18n.js's setLang once the locale pack has been loaded — kept here rather than
|
||||
// exported as setLang because loading packs requires import.meta.glob, which is Vite-only.
|
||||
// Both `dict` and `instr` may be null to reset to English.
|
||||
export function _setLangState(newLang, newDict, newInstr) {
|
||||
lang = LANGS[newLang] ? newLang : 'en'
|
||||
dict = lang === 'en' ? {} : (newDict || {})
|
||||
instr = lang === 'en' || !INSTR_LANGS.includes(lang) ? null : (newInstr || null)
|
||||
version++
|
||||
return version
|
||||
}
|
||||
@@ -1,56 +1,38 @@
|
||||
// Tiny dependency-free i18n. English source strings are the keys; locale files in
|
||||
// src/locales/ map them to translations and are lazy-loaded (Vite code-splits each
|
||||
// import.meta.glob entry), so the initial bundle stays English-only.
|
||||
// Exercise instructions come from separately generated packs in src/instr/ (one per
|
||||
// language, from the upstream dataset) — also lazy-loaded on language switch.
|
||||
// Browser-only shell of the i18n module. The runtime-agnostic state and readers live
|
||||
// in i18n-core.js (plain Node-loadable); this file adds the two pieces that genuinely need
|
||||
// the browser: `setLang` (which lazy-loads locale packs via import.meta.glob) and the React
|
||||
// subscription hook `useLang`.
|
||||
|
||||
import { useSyncExternalStore } from 'react'
|
||||
import {
|
||||
LANGS, INSTR_LANGS, DATE_LOCALES,
|
||||
getLang, dateLocale, t, instrFor, getVersion, _setLangState
|
||||
} from './i18n-core.js'
|
||||
|
||||
// UI languages. de/pt have no instruction pack upstream — instructions fall back to English.
|
||||
export const LANGS = {
|
||||
en: 'English', de: 'Deutsch', es: 'Español', fr: 'Français', it: 'Italiano',
|
||||
pt: 'Português', pl: 'Polski', tr: 'Türkçe', ru: 'Русский', zh: '中文',
|
||||
ko: '한국어', hi: 'हिन्दी'
|
||||
}
|
||||
export const INSTR_LANGS = ['en', 'es', 'fr', 'it', 'tr', 'ru', 'zh', 'hi', 'pl', 'ko']
|
||||
const DATE_LOCALES = {
|
||||
en: 'en-GB', de: 'de-DE', es: 'es-ES', fr: 'fr-FR', it: 'it-IT', pt: 'pt-PT',
|
||||
pl: 'pl-PL', tr: 'tr-TR', ru: 'ru-RU', zh: 'zh-CN', ko: 'ko-KR', hi: 'hi-IN'
|
||||
}
|
||||
export { LANGS, INSTR_LANGS, DATE_LOCALES, getLang, dateLocale, t, instrFor }
|
||||
|
||||
// Vite code-splits each locale pack into its own chunk via import.meta.glob; instructions use
|
||||
// the same mechanism in src/instr/. Both are lazy, so the production bundle ships English only.
|
||||
const localePacks = import.meta.glob('../locales/*.js')
|
||||
const instrPacks = import.meta.glob('../instr/*.js')
|
||||
|
||||
let lang = 'en'
|
||||
let dict = {}
|
||||
let instr = null // { exId: [steps] } for the current language, null = English
|
||||
let version = 0
|
||||
// React subscription bookkeeping — kept here, not in core, so core has zero React coupling.
|
||||
const subs = new Set()
|
||||
const notify = () => { version++; subs.forEach(f => f()) }
|
||||
|
||||
export const getLang = () => lang
|
||||
export const dateLocale = () => DATE_LOCALES[lang] || 'en-GB'
|
||||
|
||||
// Translate a source string; {0},{1}… are replaced with args (also on the English fallback).
|
||||
export function t(s, ...args) {
|
||||
let v = dict[s] || s
|
||||
for (let i = 0; i < args.length; i++) v = v.replaceAll('{' + i + '}', args[i])
|
||||
return v
|
||||
}
|
||||
// Instructions for an exercise in the current language (English steps as fallback).
|
||||
export const instrFor = ex => (instr && instr[ex.id]) || ex.st || []
|
||||
const notify = () => { subs.forEach(f => f()) }
|
||||
|
||||
export async function setLang(l) {
|
||||
if (!LANGS[l]) l = 'en'
|
||||
if (l === lang && version > 0) return
|
||||
lang = l
|
||||
if (l === getLang() && getVersion() > 0) return
|
||||
let dict = {}, instr = null
|
||||
try {
|
||||
dict = l === 'en' ? {} : (await localePacks['../locales/' + l + '.js']()).default
|
||||
instr = l === 'en' || !INSTR_LANGS.includes(l) ? null : (await instrPacks['../instr/' + l + '.js']()).default
|
||||
} catch (e) { dict = {}; instr = null }
|
||||
_setLangState(l, dict, instr)
|
||||
notify()
|
||||
}
|
||||
|
||||
// Re-renders the subscribing component (and its children) whenever the language changes.
|
||||
export function useLang() {
|
||||
return useSyncExternalStore(fn => { subs.add(fn); return () => subs.delete(fn) }, () => version)
|
||||
return useSyncExternalStore(fn => { subs.add(fn); return () => subs.delete(fn) }, getVersion)
|
||||
}
|
||||
@@ -20,6 +20,7 @@
|
||||
|
||||
import { EXDB, EXIDX } from './exercises.js'
|
||||
import { uid } from './format.js'
|
||||
import { isWarmupRow } from './workout-model.js'
|
||||
|
||||
/* ----------------------------------------------------------------- CSV ---- */
|
||||
|
||||
@@ -173,6 +174,17 @@ const ALIAS_EX = {
|
||||
'tricep pushdown': '0241', 'triceps pushdown': '0241', pushdown: '0241',
|
||||
skullcrusher: '0060', 'skull crusher': '0060', 'lying triceps extension': '0061',
|
||||
lunge: '0054', lunges: '0054', 'cable crossover': '1269', 'cable cross over': '1269',
|
||||
'goblet squat': '1760', 'dumbbell goblet squat': '1760', 'kettlebell goblet squat': '0534',
|
||||
// Reported in issue #74: these come out of Hevy under names no word-overlap can reach, so
|
||||
// they landed as custom exercises. The catalogue's cardio vocabulary is thin (29 of 1,324
|
||||
// entries), so each of these is the *only* candidate rather than the best of several.
|
||||
treadmill: '3666', 'treadmill walk': '3666', 'treadmill run': '3666',
|
||||
cycling: '2331', 'cross trainer': '2331', elliptical: '2141',
|
||||
'stationary bike': '2138', 'exercise bike': '2138', 'stepmill': '2311',
|
||||
// The catalogue has only band Pallof presses, so a cable one resolves to the band entry:
|
||||
// same movement, wrong equipment label, which beats leaving it uncategorised.
|
||||
'pallof press': '0979', 'cable pallof press': '0979', 'vertical pallof press': '1015',
|
||||
'cable core pallof press': '0979', 'core pallof press': '0979',
|
||||
}
|
||||
|
||||
let ALIAS_IDX = null
|
||||
@@ -334,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)
|
||||
@@ -357,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.
|
||||
@@ -405,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)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,50 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { matchExercise } from './import-csv.js'
|
||||
import { EXIDX } from './exercises.js'
|
||||
|
||||
// The names other apps actually export, and the catalogue entry each has to land on.
|
||||
// Everything here was reported as arriving in the app as a *custom* exercise (issue #74):
|
||||
// the alias table is the intended place to fix that, so these pin it.
|
||||
const MAPS = {
|
||||
Treadmill: '3666',
|
||||
'Goblet Squat': '1760',
|
||||
Cycling: '2331',
|
||||
'Cable Core Pallof Press': '0979',
|
||||
Elliptical: '2141',
|
||||
'Stationary Bike': '2138',
|
||||
}
|
||||
|
||||
describe('foreign exercise names resolve to the catalogue', () => {
|
||||
for (const [name, id] of Object.entries(MAPS)) {
|
||||
it(`maps "${name}" to ${id}`, () => {
|
||||
expect(matchExercise(name)).toBe(id)
|
||||
expect(EXIDX[id]).toBeTruthy() // an alias pointing at a dropped id is worse than no alias
|
||||
})
|
||||
}
|
||||
|
||||
// Equipment qualifiers must still beat the bare alias, or an import files years of
|
||||
// dumbbell work under the barbell lift.
|
||||
it('keeps the qualified variants distinct', () => {
|
||||
expect(matchExercise('Kettlebell Goblet Squat')).toBe('0534')
|
||||
expect(matchExercise('Dumbbell Goblet Squat')).toBe('1760')
|
||||
})
|
||||
|
||||
// The word-bag is order-insensitive, which is what lets one alias cover the two ways
|
||||
// exporters write the same movement.
|
||||
it('ignores word order and case', () => {
|
||||
expect(matchExercise('Squat (Barbell)')).toBe(matchExercise('Barbell Squat'))
|
||||
})
|
||||
|
||||
// Regression guard for the aliases added above: the common lifts must not have moved.
|
||||
it('leaves the established aliases alone', () => {
|
||||
expect(matchExercise('Bench Press')).toBe('0025')
|
||||
expect(matchExercise('Squat')).toBe('0043')
|
||||
expect(matchExercise('Barbell Row')).toBe('0027')
|
||||
expect(matchExercise('Deadlift')).toBe('0032')
|
||||
})
|
||||
|
||||
it('still refuses to guess', () => {
|
||||
expect(matchExercise('Some Movement I Invented')).toBe(null)
|
||||
expect(matchExercise('')).toBe(null)
|
||||
})
|
||||
})
|
||||
@@ -9,7 +9,7 @@
|
||||
//
|
||||
// Like the demo build, MOBILE is replaced at build time, so all of this folds away in
|
||||
// web bundles; the Capacitor plugins are only ever imported behind it.
|
||||
import { t } from './i18n.js'
|
||||
import { t } from './i18n-core.js'
|
||||
|
||||
export const MOBILE = import.meta.env.VITE_MOBILE === '1'
|
||||
|
||||
|
||||
@@ -7,7 +7,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 } 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)
|
||||
;(ex.sm || []).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,33 +190,61 @@ 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
|
||||
}
|
||||
|
||||
/** Load for finished workouts (only sets actually ticked off count). */
|
||||
export const loadOfWorkouts = workouts =>
|
||||
/**
|
||||
* Load for finished workouts (only sets actually ticked off count). `pick` narrows that
|
||||
* further — the map can then answer "where did the *hard* sets go", which is a different
|
||||
* question from where the sets went: a muscle can lead on volume and still never be trained
|
||||
* near failure.
|
||||
*/
|
||||
export const loadOfWorkouts = (workouts, pick) =>
|
||||
loadOf((workouts || []).flatMap(w =>
|
||||
(w.entries || []).map(e => ({ id: e.id, sets: (e.sets || []).filter(s => s.done).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).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, relative to the hardest-worked muscle in the same
|
||||
* window. Relative rather than absolute on purpose: the map answers "is my training
|
||||
* balanced", which only means anything as a comparison within one period.
|
||||
* Shade buckets 0–4 per muscle.
|
||||
*
|
||||
* With no `thresholds`, levels remain relative to the hardest-worked muscle in the same
|
||||
* window. This is the original balance-map behavior. When `thresholds` is supplied, levels
|
||||
* use an absolute scale instead: it is an ordered array of `{ at, level, exclusive? }` rules,
|
||||
* and the last matching rule wins. An exclusive rule matches values strictly greater than
|
||||
* `at`; otherwise the boundary is inclusive. Values below the first matching rule are l0.
|
||||
* Absolute rules let recovery views keep fixed semantic bands instead of renormalizing to the
|
||||
* strongest muscle on screen.
|
||||
*/
|
||||
export function levelsOf(load) {
|
||||
export function levelsOf(load, thresholds) {
|
||||
if (thresholds) {
|
||||
const lv = {}
|
||||
MUSCLES.forEach(m => {
|
||||
const value = Number(load[m] || 0)
|
||||
let level = 0
|
||||
for (const rule of thresholds) {
|
||||
const matches = rule.exclusive ? value > rule.at : value >= rule.at
|
||||
if (matches) level = Math.max(0, Math.min(4, rule.level))
|
||||
}
|
||||
lv[m] = level
|
||||
})
|
||||
return lv
|
||||
}
|
||||
|
||||
const max = Math.max(0, ...MUSCLES.map(m => load[m] || 0))
|
||||
const lv = {}
|
||||
MUSCLES.forEach(m => {
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { EXIDX, EXDB, smOf } from './exercises.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.
|
||||
describe('catalogue secondary muscles', () => {
|
||||
it('maps a bench press to chest, triceps and deltoids', () => {
|
||||
expect(musclesOf(EXIDX['0025'])).toMatchObject({
|
||||
chest: 1,
|
||||
triceps: 0.4,
|
||||
deltoids: 0.4,
|
||||
})
|
||||
})
|
||||
|
||||
it('maps a squat to glutes, quads and hamstrings', () => {
|
||||
expect(musclesOf(EXIDX['0043'])).toMatchObject({
|
||||
gluteal: 1,
|
||||
quadriceps: 0.4,
|
||||
hamstring: 0.4,
|
||||
})
|
||||
})
|
||||
|
||||
it('maps common row variations to the upper back, biceps and rear deltoids', () => {
|
||||
for (const id of ['0027', '0293', '0499', '0861']) {
|
||||
expect(musclesOf(EXIDX[id])).toMatchObject({
|
||||
'upper-back': 1,
|
||||
biceps: 0.4,
|
||||
deltoids: 0.4,
|
||||
})
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
describe('catalogue secondary additions', () => {
|
||||
it('enriches the muscle map without mutating the raw dataset', () => {
|
||||
const raw = EXDB.find(e => e.id === '0027')
|
||||
expect(raw.sm).not.toContain('rear deltoids')
|
||||
expect(smOf(raw)).toContain('rear deltoids')
|
||||
// the alias collapses onto the deltoids slug in the canonical muscle map
|
||||
expect(musclesOf(raw)).toHaveProperty('deltoids')
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
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) 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)) }
|
||||
})
|
||||
|
||||
@@ -146,3 +146,19 @@ describe('is1RMRecord', () => {
|
||||
expect(is1RMRecord(S, 'bench', { id: 'bench', sets: [{ w: 200, r: 5, done: false }] })).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
describe('warm-up sets and 1RM', () => {
|
||||
const ENTRY = { id: 'warm-test', sets: [
|
||||
{ w: 20, r: 8, done: true, warmup: true },
|
||||
{ w: 80, r: 5, done: true },
|
||||
] }
|
||||
|
||||
it('does not let a ticked-off warm-up set set or raise the estimated 1RM', () => {
|
||||
const working = { id: 'warm-test', sets: [{ w: 80, r: 5, done: true }] }
|
||||
expect(bestSetOf(ENTRY)).toEqual(bestSetOf(working))
|
||||
expect(best1RM({ workouts: [{ entries: [ENTRY] }] }, 'warm-test')).toEqual(
|
||||
best1RM({ workouts: [{ entries: [working] }] }, 'warm-test'),
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -8,10 +8,10 @@
|
||||
// 2. A clean, printable page (Save as PDF) where a single exercise never splits across
|
||||
// a page break — each exercise, and each routine that fits, stays in one place.
|
||||
|
||||
import { EXIDX } from './exercises.js'
|
||||
import { modeOf, fmtSec } from './history.js'
|
||||
import { EXIDX, isBodyweightEq } from './exercises.js'
|
||||
import { modeOf, fmtSec, isBw, isPerSide, sideReps } from './history.js'
|
||||
import { uid, todayISO, DAYN, fmtNum, exCount } from './format.js'
|
||||
import { t } from './i18n.js'
|
||||
import { t } from './i18n-core.js'
|
||||
|
||||
const PLAN_FMT = 1
|
||||
const WEEK_ORDER = [1, 2, 3, 4, 5, 6, 0] // Mon-first, matching the Plan screen
|
||||
@@ -33,11 +33,17 @@ function cleanEx(e) {
|
||||
if (e.reps != null) o.reps = e.reps
|
||||
if (e.weight) o.weight = e.weight
|
||||
}
|
||||
// How the exercise is logged travels too (issues #31/#32) — the bodyweight flag only when
|
||||
// it disagrees with the catalogue, since agreeing is what the other end already assumes.
|
||||
if (e.bodyweight != null && e.bodyweight !== isBodyweightEq(e.id)) o.bodyweight = e.bodyweight
|
||||
// Only on reps work — `side` counts reps, and a timed hold has none to split.
|
||||
if (e.side && mode !== 'time' && mode !== 'cardio') o.side = true
|
||||
// Progression settings travel with the plan — a shared Greyskull routine that arrives
|
||||
// without its rule is just a list of weights.
|
||||
if (e.prog) o.prog = e.prog
|
||||
if (e.inc > 0) o.inc = e.inc
|
||||
if (e.repsMin != null) o.repsMin = e.repsMin
|
||||
if (e.repsMax != null) o.repsMax = e.repsMax
|
||||
if (e.sg) o.sg = e.sg
|
||||
return o
|
||||
}
|
||||
@@ -145,7 +151,9 @@ function scheme(e, unit) {
|
||||
return sets > 1 ? `${sets} × ${body}` : body
|
||||
}
|
||||
let s = mode === 'time' ? `${sets} × ${fmtSec(e.sec || 45)}` : `${sets} × ${e.reps ?? 10}`
|
||||
if (e.weight) s += ` · ${fmtNum(e.weight)} ${unit}`
|
||||
if (e.weight) s += ` · ${isBw(e) ? '+' : ''}${fmtNum(e.weight)} ${unit}`
|
||||
// A printed plan is read at the rack, so the split earns its four characters.
|
||||
if (mode !== 'time' && isPerSide(e)) s += ` · ${t('{0}/side', fmtNum(sideReps(e.reps ?? 10)))}`
|
||||
return s
|
||||
}
|
||||
|
||||
|
||||
@@ -16,8 +16,9 @@
|
||||
// · fewer sets than prescribed → miss
|
||||
// So a session that fell apart can never advance the load as though it had succeeded.
|
||||
|
||||
import { modeOf } from './history.js'
|
||||
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']
|
||||
|
||||
@@ -60,6 +61,9 @@ export function defaultIncrement(exId, unit) {
|
||||
return heavy ? 5 : 2.5
|
||||
}
|
||||
export const DEFAULT_SEC_INCREMENT = 5
|
||||
// Where adding another set of push-ups stops being progress and starts being a way to spend
|
||||
// an evening. Past this the honest advice is load or a harder variation (issue #33).
|
||||
export const MAX_BW_SETS = 6
|
||||
|
||||
// The policy in force for one exercise: its own override, else the routine's default, else
|
||||
// the mode's default. Reps keeps behaving the way the app always did (all reps → add a step).
|
||||
@@ -98,7 +102,9 @@ function deloadTo(cur, step) {
|
||||
export function readSession(entry, fallback) {
|
||||
const target = (entry && entry.target) || fallback || {}
|
||||
const mode = modeOf({ ...target, id: entry && entry.id })
|
||||
const sets = (entry && entry.sets) || []
|
||||
// Warm-up rows are prep, not the session: one filtered read beats guarding every consumer
|
||||
// below (an undone warm-up otherwise poisons `ok` forever and its reps drag `low`/`count`).
|
||||
const sets = ((entry && entry.sets) || []).filter(s => !isWarmupRow(s))
|
||||
const planned = target.sets || sets.length
|
||||
const enough = sets.length >= planned
|
||||
|
||||
@@ -117,6 +123,7 @@ export function readSession(entry, fallback) {
|
||||
return {
|
||||
mode, goal, reps,
|
||||
weight: Math.max(0, ...sets.filter(s => s.done).map(s => s.w || 0)),
|
||||
count: reps.length, // the dimension bodyweight work grows (#33)
|
||||
low: reps.length ? Math.min(...reps) : 0,
|
||||
amrap: reps.length ? reps[reps.length - 1] : 0, // Greyskull's final set
|
||||
ok: goal > 0 && enough && reps.length > 0 && reps.every(r => r >= goal)
|
||||
@@ -128,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)) 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
|
||||
}
|
||||
@@ -179,14 +186,28 @@ export function nextPrescription(S, cfg, routine) {
|
||||
|
||||
const w = last.weight
|
||||
// Bodyweight work carries no external load, so there is nothing to add or take away —
|
||||
// "deload your push-ups to 2.5 kg" is not advice. Progress in reps instead. This runs
|
||||
// ahead of the individual policies because it is true for all of them; a rep range set on
|
||||
// top of it simply gets passed once you exceed it, which is the right moment to add load
|
||||
// or move to a harder variation anyway.
|
||||
// "deload your push-ups to 2.5 kg" is not advice. Progress in reps instead. This runs ahead
|
||||
// of the individual policies because it is true for all of them. Note the trigger is the
|
||||
// *logged* weight, not the `bw` flag: a dip done with a belt has a load to progress and
|
||||
// belongs on the normal policies, and a barbell lift logged at 0 has nothing to add to.
|
||||
if (w <= 0) {
|
||||
const goal = last.goal || cfg.reps || 0
|
||||
if (last.ok && goal > 0) return { policy, kind: 'up', weight: 0, reps: goal + 1, why: ['Bodyweight — every rep last time, so go for {0} this time.', goal + 1] }
|
||||
return { policy, kind: 'hold', weight: 0, reps: goal || undefined, why: ['Bodyweight — same target again until every set is clean.'] }
|
||||
if (!last.ok || goal <= 0) return { policy, kind: 'hold', weight: 0, reps: goal || undefined, why: ['Bodyweight — same target again until every set is clean.'] }
|
||||
// A ceiling turns "+1 rep forever" into a plan (issue #33). Past the top of the range the
|
||||
// reps go back to the bottom and a set is added instead, which is how bodyweight work
|
||||
// actually progresses once a set of 30 push-ups stops being a strength stimulus.
|
||||
const top = cfg.repsMax > 0 ? cfg.repsMax : 0
|
||||
if (top > 0 && goal >= top) {
|
||||
const sets = Math.max(1, cfg.sets || last.count || 1) + 1
|
||||
const bottom = Math.max(1, Math.min(cfg.reps || top, top))
|
||||
if (sets <= MAX_BW_SETS) return { policy, kind: 'up', weight: 0, reps: bottom, sets, why: ['{0} reps in every set — add a set and go back to {1}.', goal, bottom] }
|
||||
// Out of sets worth adding: more volume is no longer the answer, load or a harder
|
||||
// variation is — and that is a decision for a person, not a policy.
|
||||
return { policy, kind: 'hold', weight: 0, reps: goal, why: ['{0} sets of {1} — time to add weight or move to a harder variation.', sets - 1, goal] }
|
||||
}
|
||||
// Unilateral work steps by two, so the total stays even and both sides get the rep.
|
||||
const next = goal + repStep(cfg)
|
||||
return { policy, kind: 'up', weight: 0, reps: next, why: ['Bodyweight — every rep last time, so go for {0} this time.', next] }
|
||||
}
|
||||
if (policy === 'double') {
|
||||
const top = cfg.reps || last.goal || 10
|
||||
@@ -196,7 +217,7 @@ export function nextPrescription(S, cfg, routine) {
|
||||
const dw = deloadTo(w, inc)
|
||||
return { policy, kind: 'deload', weight: dw, reps: bottom, why: ['Stalled {0} sessions — deload to {1} {2}.', stalls, dw, unit] }
|
||||
}
|
||||
const aim = Math.min(top, Math.max(bottom, last.low + 1))
|
||||
const aim = Math.min(top, Math.max(bottom, last.low + repStep(cfg)))
|
||||
return { policy, kind: 'hold', weight: w, reps: aim, why: ['Same weight — aim for {0} reps this time.', aim] }
|
||||
}
|
||||
|
||||
@@ -231,12 +252,27 @@ export function nextPrescription(S, cfg, routine) {
|
||||
*/
|
||||
export function applyPrescription(sets, p) {
|
||||
if (!p || p.kind === 'off' || p.kind === 'first') return sets
|
||||
return sets.map(s => {
|
||||
if (s.done) return s
|
||||
const out = { ...s }
|
||||
if (p.weight != null) out.w = p.weight
|
||||
if (p.reps != null) out.r = p.reps
|
||||
if (p.sec != null) out.sec = p.sec
|
||||
return out
|
||||
const out = sets.map(s => {
|
||||
// Never rewrite a logged set, and never rewrite a warm-up: the prescription speaks to
|
||||
// the work rows only (a ticked warm-up falling through here would be the data-loss the
|
||||
// cascade fix removed, two files over).
|
||||
if (s.done || isWarmupRow(s)) return s
|
||||
const o = { ...s }
|
||||
if (p.weight != null) o.w = p.weight
|
||||
if (p.reps != null) o.r = p.reps
|
||||
if (p.sec != null) o.sec = p.sec
|
||||
return o
|
||||
})
|
||||
// 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 => !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 => !isWarmupRow(s)).length < p.sets) out.push({ ...seed, done: false })
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import {
|
||||
readSession, sessionsFor, stallCount, nextPrescription, applyPrescription,
|
||||
policyFor, defaultIncrement, POLICIES_FOR, DELOAD_AFTER
|
||||
policyFor, defaultIncrement, POLICIES_FOR, DELOAD_AFTER, MAX_BW_SETS
|
||||
} from './progression.js'
|
||||
import { EXDB } from './exercises.js'
|
||||
|
||||
@@ -189,6 +189,54 @@ describe('bodyweight exercises', () => {
|
||||
expect(p.reps).toBe(11)
|
||||
})
|
||||
|
||||
/* A ceiling turns "+1 rep forever" into a plan — issue #33. */
|
||||
it('climbs to the ceiling one rep at a time', () => {
|
||||
const p = nextPrescription(bw([[0, 10, 10, 10]]), { ...cfg, repsMax: 15 })
|
||||
expect(p.kind).toBe('up')
|
||||
expect(p.reps).toBe(11)
|
||||
expect(p.sets).toBeUndefined()
|
||||
})
|
||||
|
||||
it('adds a set and restarts the range once the ceiling is reached', () => {
|
||||
const at15 = hist(LIFT, [[0, 15, 15, 15]], { sets: 3, reps: 15 })
|
||||
const p = nextPrescription(at15, { ...cfg, reps: 10, repsMax: 15 })
|
||||
expect(p.kind).toBe('up')
|
||||
expect(p.sets).toBe(4)
|
||||
expect(p.reps).toBe(10)
|
||||
expect(p.weight).toBe(0)
|
||||
})
|
||||
|
||||
it('stops adding sets at the cap and says what to do instead', () => {
|
||||
const at15 = hist(LIFT, [[0, 15, 15, 15]], { sets: 3, reps: 15 })
|
||||
const p = nextPrescription(at15, { ...cfg, sets: MAX_BW_SETS, reps: 10, repsMax: 15 })
|
||||
expect(p.kind).toBe('hold')
|
||||
expect(p.sets).toBeUndefined()
|
||||
expect(p.why[0]).toMatch(/harder variation/)
|
||||
})
|
||||
|
||||
it('leaves a belted set to the normal policies — there is a load to add now', () => {
|
||||
const belted = hist(LIFT, [[10, 10, 10, 10]], { sets: 3, reps: 10 })
|
||||
const p = nextPrescription(belted, { ...cfg, bodyweight: true, repsMax: 15 })
|
||||
expect(p.kind).toBe('up')
|
||||
expect(p.weight).toBeGreaterThan(10)
|
||||
expect(p.sets).toBeUndefined()
|
||||
})
|
||||
|
||||
it('steps a unilateral total by two, so it lands on 16, 18, 20 (issue #31)', () => {
|
||||
const at16 = hist(LIFT, [[0, 16, 16, 16]], { sets: 3, reps: 16 })
|
||||
expect(nextPrescription(at16, { ...cfg, reps: 16, side: true }).reps).toBe(18)
|
||||
// and by one when it is not
|
||||
expect(nextPrescription(at16, { ...cfg, reps: 16 }).reps).toBe(17)
|
||||
})
|
||||
|
||||
it('keeps climbing reps forever when no ceiling was set — the old behaviour', () => {
|
||||
const at30 = hist(LIFT, [[0, 30, 30, 30]], { sets: 3, reps: 30 })
|
||||
const p = nextPrescription(at30, cfg)
|
||||
expect(p.kind).toBe('up')
|
||||
expect(p.reps).toBe(31)
|
||||
expect(p.sets).toBeUndefined()
|
||||
})
|
||||
|
||||
it('applies to every policy, not just linear', () => {
|
||||
for (const prog of ['linear', 'greyskull', 'double']) {
|
||||
const p = nextPrescription(bw([[0, 10, 10, 4], [0, 10, 10, 4], [0, 10, 10, 4]]), { ...cfg, prog })
|
||||
@@ -390,4 +438,88 @@ describe('applyPrescription', () => {
|
||||
const timed = [{ sec: 45, w: 0, done: false }]
|
||||
expect(applyPrescription(timed, { kind: 'up', sec: 50 })).toEqual([{ sec: 50, w: 0, done: false }])
|
||||
})
|
||||
|
||||
it('grows the list when the policy added a set (issue #33)', () => {
|
||||
const three = [{ w: 0, r: 10, done: false }, { w: 0, r: 10, done: false }, { w: 0, r: 10, done: false }]
|
||||
const out = applyPrescription(three, { kind: 'up', weight: 0, reps: 10, sets: 4 })
|
||||
expect(out).toHaveLength(4)
|
||||
expect(out[3]).toEqual({ w: 0, r: 10, done: false })
|
||||
})
|
||||
|
||||
it('never shrinks a session that has already logged sets', () => {
|
||||
expect(applyPrescription(sets, { kind: 'up', weight: 60, sets: 1 })).toHaveLength(sets.length)
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
describe('warm-up rows in session reads (round 3)', () => {
|
||||
it('readSession ignores warm-up rows for reps, count, low and ok', () => {
|
||||
// An undone warm-up (r 0) must not poison `ok` forever; its lighter reps must not
|
||||
// drag `low`/`count` - the warm-up is prep, the session is the work rows.
|
||||
const s = readSession({ id: LIFT, target: { sets: 2, reps: 5, mode: 'reps' }, sets: [
|
||||
{ w: 20, r: 8, done: true, warmup: true },
|
||||
{ w: 60, r: 5, done: true },
|
||||
{ w: 60, r: 6, done: true },
|
||||
] })
|
||||
expect(s.count).toBe(2)
|
||||
expect(s.low).toBe(5)
|
||||
expect(s.reps).toEqual([5, 6])
|
||||
expect(s.ok).toBe(true)
|
||||
})
|
||||
|
||||
it('readSession keeps an undone warm-up out of held/ok in time mode', () => {
|
||||
const s = readSession({ id: LIFT, target: { sets: 2, sec: 45, mode: 'time' }, sets: [
|
||||
{ sec: 45, done: true, warmup: true },
|
||||
{ sec: 45, done: true },
|
||||
{ sec: 30, done: true },
|
||||
] })
|
||||
expect(s.held).toEqual([45, 30])
|
||||
expect(s.ok).toBe(false) // the 30s work row is the miss, not the warm-up
|
||||
})
|
||||
|
||||
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)', () => {
|
||||
it('leaves a done warm-up exactly as logged', () => {
|
||||
const sets = [
|
||||
{ w: 20, r: 8, done: true, warmup: true },
|
||||
{ w: 60, r: 5, done: true },
|
||||
{ w: 60, r: 5, done: false },
|
||||
]
|
||||
const out = applyPrescription(sets, { kind: 'up', weight: 62.5, reps: 5 })
|
||||
expect(out[0]).toEqual({ w: 20, r: 8, done: true, warmup: true })
|
||||
expect(out[1]).toEqual({ w: 60, r: 5, done: true })
|
||||
expect(out[2]).toEqual({ w: 62.5, r: 5, done: false })
|
||||
})
|
||||
|
||||
it('grows the work rows, not the warm-up rows, when the policy adds sets', () => {
|
||||
const sets = [
|
||||
{ w: 20, r: 8, done: true, warmup: true },
|
||||
{ w: 60, r: 5, done: true },
|
||||
{ w: 60, r: 5, done: false },
|
||||
]
|
||||
const out = applyPrescription(sets, { kind: 'up', weight: 62.5, reps: 5, sets: 4 })
|
||||
expect(out.filter(s => !s.warmup)).toHaveLength(4) // 2 existing + 2 grown
|
||||
expect(out.filter(s => s.warmup)).toHaveLength(1) // warm-up untouched
|
||||
expect(out[0]).toEqual({ w: 20, r: 8, done: true, warmup: true })
|
||||
})
|
||||
|
||||
it('an all-warm-up entry terminates and stays untouched', () => {
|
||||
const sets = [
|
||||
{ w: 20, r: 8, done: true, warmup: true },
|
||||
{ w: 25, r: 6, done: true, warmup: true },
|
||||
]
|
||||
const out = applyPrescription(sets, { kind: 'up', weight: 62.5, reps: 5, sets: 4 })
|
||||
expect(out).toEqual(sets) // no work row to seed growth from - nothing grows, no loop
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,17 @@
|
||||
import { FATIGUE_STATES } from './recovery.js'
|
||||
|
||||
/**
|
||||
* Select the consumer-facing fatigue state for one numeric recovery value.
|
||||
* Values below .25 are ready, .25 through .5 are recovering, and values above .5 are fatigued.
|
||||
* Keeping this boundary selector in production code prevents views and tests from drifting apart.
|
||||
*
|
||||
* @param {number} value Numeric fatigue value from fatigueOf().
|
||||
* @returns {'ready'|'recovering'|'fatigued'} The stable state label for the UI.
|
||||
*/
|
||||
export function fatigueStateOf(value) {
|
||||
return value < 0.25
|
||||
? FATIGUE_STATES.READY
|
||||
: value <= 0.5
|
||||
? FATIGUE_STATES.RECOVERING
|
||||
: FATIGUE_STATES.FATIGUED
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { FATIGUE_STATES, fatigueOf, strengthOf } from './recovery.js'
|
||||
import { fatigueStateOf } from './recovery-view.js'
|
||||
import { MUSCLES, levelsOf } from './muscles.js'
|
||||
|
||||
const FATIGUE_BANDS = [
|
||||
{ at: 0, level: 4 },
|
||||
{ at: 0.25, level: 2 },
|
||||
{ at: 0.5, level: 0, exclusive: true },
|
||||
]
|
||||
const STRENGTH_BANDS = [
|
||||
{ at: 0.5, level: 0 },
|
||||
{ at: 0.625, level: 1 },
|
||||
{ at: 0.75, level: 2 },
|
||||
{ at: 0.875, level: 3 },
|
||||
{ at: 1, level: 4 },
|
||||
]
|
||||
|
||||
describe('production recovery view selectors', () => {
|
||||
it('preserves the relative balance scale when no thresholds are supplied', () => {
|
||||
const levels = levelsOf({ chest: 10, biceps: 5 })
|
||||
expect(levels.chest).toBe(4)
|
||||
expect(levels.biceps).toBe(2)
|
||||
})
|
||||
|
||||
it('uses the production fatigue selector at both approved boundaries', () => {
|
||||
expect(fatigueStateOf(0.2499)).toBe(FATIGUE_STATES.READY)
|
||||
expect(fatigueStateOf(0.25)).toBe(FATIGUE_STATES.RECOVERING)
|
||||
expect(fatigueStateOf(0.5)).toBe(FATIGUE_STATES.RECOVERING)
|
||||
expect(fatigueStateOf(0.5001)).toBe(FATIGUE_STATES.FATIGUED)
|
||||
})
|
||||
|
||||
it('renders fatigue bands on a fixed absolute scale rather than relative to the map maximum', () => {
|
||||
const levels = levelsOf({
|
||||
chest: 0.25,
|
||||
biceps: 0.6,
|
||||
triceps: 0.1,
|
||||
}, FATIGUE_BANDS)
|
||||
expect(levels.chest).toBe(2)
|
||||
expect(levels.biceps).toBe(0)
|
||||
expect(levels.triceps).toBe(4)
|
||||
})
|
||||
|
||||
it('renders strength on fixed .5-to-1 bands with full retention at l4', () => {
|
||||
const levels = levelsOf({ chest: 0.9, biceps: 1, triceps: 0.5 }, STRENGTH_BANDS)
|
||||
expect(levels.chest).toBe(3)
|
||||
expect(levels.biceps).toBe(4)
|
||||
expect(levels.triceps).toBe(0)
|
||||
})
|
||||
|
||||
it('keeps selectors tied to the same render-time clock', () => {
|
||||
const now = Date.UTC(2026, 0, 22)
|
||||
const workout = { start: now - 15 * 86400000, d: '2026-01-07', entries: [] }
|
||||
expect(strengthOf([workout], now).chest).toBe(0.5)
|
||||
expect(fatigueOf([workout], now).chest).toBe(0)
|
||||
expect(strengthOf([workout], now + 7 * 86400000).chest).toBe(0.5)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,365 @@
|
||||
import { EXIDX } from './exercises.js'
|
||||
import { MUSCLES, musclesOf } from './muscles.js'
|
||||
import { isWarmupRow } from './workout-model.js'
|
||||
|
||||
// A "normal" hard session for one muscle, in primary-set equivalents. The saturation curve
|
||||
// 1 - exp(-stimulus / REF) maps any session size onto [0,1) so volume raises the starting
|
||||
// fatigue level without ever pinning it, and the value can then fade asymptotically.
|
||||
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
|
||||
|
||||
/** Period after training during which retained strength remains at full value. */
|
||||
export const STRENGTH_FULL_MS = 1209600000
|
||||
|
||||
/** Exponential half-life for retained strength after the full-retention period. */
|
||||
export const STRENGTH_HALF_LIFE_MS = 2419200000
|
||||
|
||||
/** Minimum retained-strength value for an untrained or fully detrained muscle. */
|
||||
export const STRENGTH_FLOOR = 0.5
|
||||
|
||||
/**
|
||||
* Stable labels for consumer fatigue buckets: values below 0.25 are ready, values from 0.25
|
||||
* through 0.5 are recovering, and values above 0.5 are fatigued.
|
||||
*/
|
||||
export const FATIGUE_STATES = Object.freeze({
|
||||
READY: 'ready',
|
||||
RECOVERING: 'recovering',
|
||||
FATIGUED: 'fatigued',
|
||||
})
|
||||
|
||||
/**
|
||||
* Return exponential decay expressed as a fraction of one half-life.
|
||||
*
|
||||
* @param {number} ageMs Elapsed age of the stimulus in milliseconds.
|
||||
* @param {number} halfLifeMs Duration of one half-life in milliseconds.
|
||||
* @returns {number} Remaining fraction, using the exact `0.5 ** (age / halfLife)` formula.
|
||||
*/
|
||||
export function halfLifeDecay(ageMs, halfLifeMs) {
|
||||
return 0.5 ** (ageMs / halfLifeMs)
|
||||
}
|
||||
|
||||
// The v2 data contract has one timestamp per workout, not per set. Keep this fallback in one
|
||||
// place so fatigue and strength use exactly the same stimulus time as effort.js.
|
||||
function workoutTimestamp(workout) {
|
||||
const timestamp = workout?.start || new Date(workout?.d).getTime()
|
||||
return Number.isFinite(timestamp) ? timestamp : Number(timestamp)
|
||||
}
|
||||
|
||||
function emptyMuscleMap(value) {
|
||||
return Object.fromEntries(MUSCLES.map(slug => [slug, value]))
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
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 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]))
|
||||
|
||||
function fatigueValue(events, now) {
|
||||
if (!events.length) return 0
|
||||
events.sort((a, b) => a.timestamp - b.timestamp)
|
||||
|
||||
let value = 0
|
||||
let lastTimestamp = events[0].timestamp
|
||||
for (const event of events) {
|
||||
value *= halfLifeDecay(event.timestamp - lastTimestamp, FATIGUE_HALF_LIFE_MS)
|
||||
value += event.stimulus
|
||||
lastTimestamp = event.timestamp
|
||||
}
|
||||
value *= halfLifeDecay(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)
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate current per-muscle fatigue from completed sets in the recent window.
|
||||
*
|
||||
* Stimulus time is `workout.start`, falling back to the workout date `workout.d`. Each completed
|
||||
* set contributes the exercise's `musclesOf` weights; the scan is bounded to FATIGUE_SCAN_MS for
|
||||
* performance, not semantics. Stimuli are accumulated chronologically with a 36-hour half-life,
|
||||
* decayed to `now`, and normalised with the saturation curve 1 - exp(-v). 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, opts = {}) {
|
||||
const current = Number(now)
|
||||
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
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate retained per-muscle strength from the latest completed stimulus in all history.
|
||||
*
|
||||
* A muscle with no completed set starts at the 0.5 floor. After a completed set, strength is
|
||||
* 1.0 through 14 days old, then decays toward the floor with a 28-day half-life. Any later
|
||||
* completed set becomes the new latest stimulus and resets the 14-day full-retention period.
|
||||
* The result always contains every drawable muscle slug.
|
||||
*
|
||||
* @param {Array<object>} workouts Workout history with `start`/`d` and entry set arrays.
|
||||
* @param {number} now Current time in milliseconds; injected to keep this function deterministic.
|
||||
* @returns {Record<string, number>} Retained-strength values keyed by every drawable muscle slug.
|
||||
*/
|
||||
export function strengthOf(workouts, now, opts = {}) {
|
||||
const current = Number(now)
|
||||
const latest = Object.fromEntries(MUSCLES.map(slug => [slug, -Infinity]))
|
||||
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)
|
||||
if (!Number.isFinite(current)) return result
|
||||
for (const slug of MUSCLES) {
|
||||
const lastTimestamp = latest[slug]
|
||||
if (!Number.isFinite(lastTimestamp)) continue
|
||||
const age = current - lastTimestamp
|
||||
if (age <= STRENGTH_FULL_MS) {
|
||||
result[slug] = 1
|
||||
} else {
|
||||
result[slug] = Math.max(
|
||||
STRENGTH_FLOOR,
|
||||
halfLifeDecay(age - STRENGTH_FULL_MS, STRENGTH_HALF_LIFE_MS),
|
||||
)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* List muscles currently above the fatigued threshold.
|
||||
*
|
||||
* @param {Array<object>} workouts Workout history passed to {@link fatigueOf}.
|
||||
* @param {number} now Current time in milliseconds passed to {@link fatigueOf}.
|
||||
* @returns {string[]} Muscle slugs whose fatigue value is greater than 0.5, in `MUSCLES`
|
||||
* head-to-toe order.
|
||||
* @example
|
||||
* const avoid = fatiguedMuscles(workouts, now)
|
||||
*/
|
||||
export function fatiguedMuscles(workouts, now, opts = {}) {
|
||||
return Object.entries(fatigueOf(workouts, now, opts))
|
||||
.filter(([, value]) => value > 0.5)
|
||||
.map(([slug]) => slug)
|
||||
}
|
||||
|
||||
/**
|
||||
* List muscles whose retained strength is below full retention.
|
||||
*
|
||||
* @param {Array<object>} workouts Workout history passed to {@link strengthOf}.
|
||||
* @param {number} now Current time in milliseconds passed to {@link strengthOf}.
|
||||
* @returns {string[]} Muscle slugs whose retained strength is less than 1.0, in `MUSCLES`
|
||||
* head-to-toe order; never-trained muscles are included at the 0.5 floor.
|
||||
* @example
|
||||
* const targets = detrainedMuscles(workouts, now)
|
||||
*/
|
||||
export function detrainedMuscles(workouts, now, opts = {}) {
|
||||
return Object.entries(strengthOf(workouts, now, opts))
|
||||
.filter(([, value]) => value < 1)
|
||||
.map(([slug]) => slug)
|
||||
}
|
||||
@@ -0,0 +1,505 @@
|
||||
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,
|
||||
detrainedMuscles,
|
||||
fatiguedMuscles,
|
||||
fatigueOf,
|
||||
halfLifeDecay,
|
||||
strengthOf,
|
||||
} from './recovery.js'
|
||||
import { EXDB, registerCustom } from './exercises.js'
|
||||
import { MUSCLES, musclesOf } from './muscles.js'
|
||||
import { fatigueStateOf } from './recovery-view.js'
|
||||
|
||||
const HOUR = 60 * 60 * 1000
|
||||
const DAY = 24 * HOUR
|
||||
const NOW = Date.UTC(2026, 0, 1, 12)
|
||||
|
||||
// Keep fixtures tied to the shipped catalogue while making the expected stimulus explicit.
|
||||
const SINGLE = EXDB.find(ex => {
|
||||
const weights = musclesOf(ex)
|
||||
return ex.bp !== 'cardio' && Object.keys(weights).length === 1 && Object.values(weights)[0] === 1
|
||||
})
|
||||
const WEIGHTED = EXDB.find(ex => {
|
||||
const weights = musclesOf(ex)
|
||||
return ex.bp !== 'cardio' && Object.values(weights).includes(0.4)
|
||||
})
|
||||
if (!SINGLE || !WEIGHTED) throw new Error('recovery tests require single- and secondary-weight fixtures')
|
||||
|
||||
const SINGLE_WEIGHTS = musclesOf(SINGLE)
|
||||
const WEIGHTED_WEIGHTS = musclesOf(WEIGHTED)
|
||||
const SINGLE_SLUG = Object.keys(SINGLE_WEIGHTS)[0]
|
||||
const WEIGHTED_PRIMARY_SLUG = Object.keys(WEIGHTED_WEIGHTS).find(slug => WEIGHTED_WEIGHTS[slug] === 1)
|
||||
const SECONDARY_SLUG = Object.keys(WEIGHTED_WEIGHTS).find(slug => WEIGHTED_WEIGHTS[slug] === 0.4)
|
||||
if (!WEIGHTED_PRIMARY_SLUG || !SECONDARY_SLUG) throw new Error('recovery tests require weighted primary and secondary fixtures')
|
||||
|
||||
const workoutAt = (id, start, sets = [{ done: true }]) => ({
|
||||
d: new Date(start).toISOString(),
|
||||
start,
|
||||
entries: [{ id, sets: sets.map(set => ({ ...set })) }],
|
||||
})
|
||||
const 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, 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(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)
|
||||
expect(FATIGUE_STATES).toEqual({ READY: 'ready', RECOVERING: 'recovering', FATIGUED: 'fatigued' })
|
||||
expect(halfLifeDecay(FATIGUE_HALF_LIFE_MS, FATIGUE_HALF_LIFE_MS)).toBe(0.5)
|
||||
})
|
||||
})
|
||||
|
||||
describe('fatigueOf and strengthOf', () => {
|
||||
it('returns every muscle, ready/floor defaults, and hook defaults for empty history', () => {
|
||||
const fatigue = fatigueOf([], NOW)
|
||||
const strength = strengthOf([], NOW)
|
||||
|
||||
expect(Object.keys(fatigue)).toEqual(MUSCLES)
|
||||
expect(fatigue).toEqual(zeroFatigue())
|
||||
expect(Object.values(fatigue).map(fatigueStateOf)).toEqual(
|
||||
MUSCLES.map(() => FATIGUE_STATES.READY),
|
||||
)
|
||||
expect(Object.keys(strength)).toEqual(MUSCLES)
|
||||
expect(strength).toEqual(floorStrength())
|
||||
expect(fatiguedMuscles([], NOW)).toEqual([])
|
||||
expect(detrainedMuscles([], NOW)).toEqual(MUSCLES)
|
||||
})
|
||||
|
||||
it('applies one completed set to each of the exercise muscle weights', () => {
|
||||
const workouts = [doneWorkoutAt(WEIGHTED.id, NOW)]
|
||||
const fatigue = fatigueOf(workouts, NOW)
|
||||
const strength = strengthOf(workouts, NOW)
|
||||
|
||||
for (const slug of MUSCLES) {
|
||||
const weight = WEIGHTED_WEIGHTS[slug] || 0
|
||||
expect(fatigue[slug]).toBeCloseTo(1 - Math.exp(-V * weight / FATIGUE_REF_VOLUME), 10)
|
||||
expect(strength[slug]).toBe(weight ? 1 : STRENGTH_FLOOR)
|
||||
}
|
||||
// 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(-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 * 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]
|
||||
expect(old).toBeGreaterThan(0)
|
||||
expect(old).toBeLessThan(0.25)
|
||||
})
|
||||
|
||||
it('decays each weighted stimulus exactly at 36 hours and by sqrt-half at 18 hours', () => {
|
||||
for (const age of [FATIGUE_HALF_LIFE_MS, FATIGUE_HALF_LIFE_MS / 2]) {
|
||||
const fatigue = fatigueOf([doneWorkoutAt(WEIGHTED.id, NOW - age)], NOW)
|
||||
const expectedDecay = 0.5 ** (age / FATIGUE_HALF_LIFE_MS)
|
||||
for (const [slug, weight] of Object.entries(WEIGHTED_WEIGHTS)) {
|
||||
expect(fatigue[slug]).toBeCloseTo(
|
||||
1 - Math.exp(-V * weight * expectedDecay / FATIGUE_REF_VOLUME),
|
||||
10,
|
||||
)
|
||||
}
|
||||
if (age === FATIGUE_HALF_LIFE_MS) {
|
||||
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(-V * (0.5 ** 0.5) / FATIGUE_REF_VOLUME),
|
||||
10,
|
||||
)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
it('fades a 72-hour-old set below the ready threshold instead of hard-cutting', () => {
|
||||
const workouts = [doneWorkoutAt(SINGLE.id, NOW - 72 * HOUR)]
|
||||
const value = fatigueOf(workouts, NOW)[SINGLE_SLUG]
|
||||
expect(value).toBeGreaterThan(0)
|
||||
expect(value).toBeLessThan(0.25)
|
||||
expect(fatigueStateOf(value)).toBe(FATIGUE_STATES.READY)
|
||||
expect(strengthOf(workouts, NOW)[SINGLE_SLUG]).toBe(1)
|
||||
})
|
||||
|
||||
it('ignores sets whose done flag is false for both axes', () => {
|
||||
const workouts = [workoutAt(WEIGHTED.id, NOW, [{ done: false }])]
|
||||
expect(fatigueOf(workouts, NOW)).toEqual(zeroFatigue())
|
||||
expect(strengthOf(workouts, NOW)).toEqual(floorStrength())
|
||||
expect(fatiguedMuscles(workouts, NOW)).toEqual([])
|
||||
expect(detrainedMuscles(workouts, NOW)).toEqual(MUSCLES)
|
||||
})
|
||||
})
|
||||
|
||||
describe('fatigue state boundaries', () => {
|
||||
// Inverse of the saturation curve: raw stimulus needed to land exactly on a target level.
|
||||
const rawAt = target => -FATIGUE_REF_VOLUME * Math.log(1 - target)
|
||||
|
||||
it('classifies exactly .25 as recovering and .2499 as ready', () => {
|
||||
const weight = WEIGHTED_WEIGHTS[SECONDARY_SLUG]
|
||||
const sets = 4
|
||||
const valueAt = 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)
|
||||
}
|
||||
|
||||
expect(fatigueStateOf(valueAt(0.25))).toBe(FATIGUE_STATES.RECOVERING)
|
||||
expect(fatigueStateOf(valueAt(0.2499))).toBe(FATIGUE_STATES.READY)
|
||||
})
|
||||
|
||||
it('classifies exactly .5 as recovering, .5001 as fatigued, and hooks only fatigued muscles', () => {
|
||||
const sets = 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 * V / rawAt(0.5001)),
|
||||
sets,
|
||||
),
|
||||
]
|
||||
const half = fatigueOf(atHalf, NOW)[SINGLE_SLUG]
|
||||
const above = fatigueOf(aboveHalf, NOW)[SINGLE_SLUG]
|
||||
|
||||
expect(half).toBeCloseTo(0.4999, 10)
|
||||
expect(fatigueStateOf(stableFloat(half))).toBe(FATIGUE_STATES.RECOVERING)
|
||||
expect(fatiguedMuscles(atHalf, NOW)).toEqual([])
|
||||
expect(above).toBeCloseTo(0.5001, 10)
|
||||
expect(fatigueStateOf(stableFloat(above))).toBe(FATIGUE_STATES.FATIGUED)
|
||||
expect(fatiguedMuscles(aboveHalf, NOW)).toEqual([SINGLE_SLUG])
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
describe('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]
|
||||
|
||||
it('stays at full retention through 14 days and decays from 15 days by the 28-day half-life', () => {
|
||||
expect(strengthAt(STRENGTH_FULL_MS)).toBe(1)
|
||||
expect(strengthAt(15 * DAY)).toBeCloseTo(0.5 ** (1 / 28), 10)
|
||||
})
|
||||
|
||||
it('clamps the 42-day half-life point and later 56-day value at the .5 floor', () => {
|
||||
expect(strengthAt(42 * DAY)).toBe(0.5)
|
||||
expect(strengthAt(56 * DAY)).toBe(STRENGTH_FLOOR)
|
||||
})
|
||||
|
||||
it('resets retained strength when a later completed session retrains the muscle', () => {
|
||||
const workouts = [
|
||||
doneWorkoutAt(SINGLE.id, NOW - 20 * DAY),
|
||||
doneWorkoutAt(SINGLE.id, NOW),
|
||||
]
|
||||
expect(strengthOf(workouts, NOW)[SINGLE_SLUG]).toBe(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('accumulation and purity', () => {
|
||||
it('matches the saturated sum of independently decayed stimuli in chronological order', () => {
|
||||
const ages = [64 * HOUR, 40 * HOUR]
|
||||
const workouts = ages.map(age => doneWorkoutAt(SINGLE.id, NOW - age))
|
||||
const raw = ages.reduce(
|
||||
(sum, age) => sum + V * 0.5 ** (age / FATIGUE_HALF_LIFE_MS),
|
||||
0,
|
||||
)
|
||||
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)
|
||||
expect(fatigueOf([...workouts].reverse(), NOW)[SINGLE_SLUG]).toBeCloseTo(expected, 10)
|
||||
})
|
||||
|
||||
it('saturates without pinning and returns identical results without mutating inputs or sharing state', () => {
|
||||
const saturated = [doneWorkoutAt(SINGLE.id, NOW, 2)]
|
||||
expect(fatigueOf(saturated, NOW)[SINGLE_SLUG]).toBeCloseTo(
|
||||
1 - Math.exp(-2 * V / FATIGUE_REF_VOLUME),
|
||||
10,
|
||||
)
|
||||
expect(fatigueOf(saturated, NOW)[SINGLE_SLUG]).toBeLessThan(1)
|
||||
|
||||
const workouts = [
|
||||
doneWorkoutAt(SINGLE.id, NOW - 64 * HOUR),
|
||||
doneWorkoutAt(SINGLE.id, NOW - 40 * HOUR),
|
||||
]
|
||||
const before = JSON.parse(JSON.stringify(workouts))
|
||||
const firstFatigue = fatigueOf(workouts, NOW)
|
||||
const firstStrength = strengthOf(workouts, NOW)
|
||||
const secondFatigue = fatigueOf(workouts, NOW)
|
||||
const secondStrength = strengthOf(workouts, NOW)
|
||||
|
||||
expect(secondFatigue).toEqual(firstFatigue)
|
||||
expect(secondStrength).toEqual(firstStrength)
|
||||
expect(workouts).toEqual(before)
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
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
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -5,6 +5,13 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
|
||||
// otherwise the tests pass against a one-shot implementation that dies on the first tab switch.
|
||||
let requests, released, live, listeners, reject
|
||||
|
||||
// Node 21+ defines globalThis.navigator itself, as a getter with no setter — a plain
|
||||
// assignment throws under ESM's strict mode. defineProperty works on both that and the older
|
||||
// runtimes where the global simply doesn't exist. Production images are node:22-alpine, so
|
||||
// the tests have to run there too.
|
||||
const setNavigator = value =>
|
||||
Object.defineProperty(globalThis, 'navigator', { value, configurable: true, writable: true })
|
||||
|
||||
function fakeBrowser() {
|
||||
requests = 0; released = 0; live = null; reject = false
|
||||
listeners = new Set()
|
||||
@@ -13,7 +20,7 @@ function fakeBrowser() {
|
||||
addEventListener: (type, fn) => { if (type === 'visibilitychange') listeners.add(fn) },
|
||||
removeEventListener: (type, fn) => { if (type === 'visibilitychange') listeners.delete(fn) },
|
||||
}
|
||||
globalThis.navigator = {
|
||||
setNavigator({
|
||||
wakeLock: {
|
||||
request: async () => {
|
||||
requests++
|
||||
@@ -24,7 +31,7 @@ function fakeBrowser() {
|
||||
return s
|
||||
},
|
||||
},
|
||||
}
|
||||
})
|
||||
}
|
||||
const fire = () => listeners.forEach(fn => fn())
|
||||
const settle = () => new Promise(r => setTimeout(r, 0))
|
||||
@@ -42,7 +49,7 @@ afterEach(() => { delete globalThis.document; delete globalThis.navigator })
|
||||
|
||||
describe('wakeLockSupported', () => {
|
||||
it('is false when the browser has no wakeLock at all', () => {
|
||||
globalThis.navigator = {}
|
||||
setNavigator({})
|
||||
expect(wakeLockSupported()).toBe(false)
|
||||
})
|
||||
it('is true when it does', () => {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -3,6 +3,7 @@ export default {
|
||||
// --- generic ---
|
||||
'Confirm': 'Bestätigen',
|
||||
'Cancel': 'Abbrechen',
|
||||
'Press back again to exit': 'Zum Beenden erneut zurück drücken',
|
||||
'Delete': 'Löschen',
|
||||
'Save': 'Speichern',
|
||||
'Import': 'Importieren',
|
||||
@@ -94,6 +95,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',
|
||||
@@ -161,13 +167,15 @@ export default {
|
||||
'Last time you hit all reps — try {0}': 'Letztes Mal alle Wdh. geschafft — versuch {0}',
|
||||
'Weights bumped to {0}': 'Gewichte auf {0} erhöht',
|
||||
'Remove set': 'Satz entfernen',
|
||||
'Warm-up': 'Aufwärmen',
|
||||
'Add warm-up set': 'Aufwärmsatz hinzufügen',
|
||||
'Add set': 'Satz hinzufügen',
|
||||
'Cardio logged': 'Cardio eingetragen',
|
||||
'Discard workout?': 'Training verwerfen?',
|
||||
'The sets you logged in this session will be lost.': 'Die in dieser Einheit eingetragenen Sätze gehen verloren.',
|
||||
'Superset {0} / {1}': 'Supersatz {0} / {1}',
|
||||
'Exercise {0} / {1}': 'Übung {0} / {1}',
|
||||
'Superset · do these back-to-back, rest after both': 'Supersatz · direkt nacheinander, Pause erst danach',
|
||||
'Superset · do these back-to-back, rest when done': 'Supersatz · direkt nacheinander, Pause erst danach',
|
||||
'Freestyle workout — add your first exercise.': 'Freies Training — füge deine erste Übung hinzu.',
|
||||
'Finish workout early · {0} exercises': 'Training vorzeitig beenden · {0} Übungen',
|
||||
'Rest over — next set!': 'Pause vorbei — nächster Satz!',
|
||||
@@ -236,6 +244,7 @@ export default {
|
||||
'Sign in with passkey': 'Mit Passkey anmelden',
|
||||
'Create new profile': 'Neues Profil erstellen',
|
||||
"This browser doesn't support passkeys — you can still use openGym locally on this device.": 'Dieser Browser unterstützt keine Passkeys — du kannst openGym trotzdem lokal auf diesem Gerät nutzen.',
|
||||
"This browser doesn't support passkeys, and this instance requires an account. Try a browser or device with passkey support.": 'Dieser Browser unterstützt keine Passkeys, und dieser Server verlangt ein Konto. Probier einen Browser oder ein Gerät mit Passkey-Unterstützung.',
|
||||
'Continue without account': 'Ohne Konto fortfahren',
|
||||
'Passkeys use {0} — no passwords.': 'Passkeys nutzen {0} — keine Passwörter.',
|
||||
'Each profile keeps its own plan, workouts & body weight.': 'Jedes Profil hat seinen eigenen Plan, Trainings & Körpergewicht.',
|
||||
@@ -245,6 +254,12 @@ export default {
|
||||
'Sign out?': 'Abmelden?',
|
||||
'Your data is synced to your profile first, then cleared from this device.': 'Deine Daten werden erst mit dem Profil synchronisiert, dann von diesem Gerät entfernt.',
|
||||
'Sign out': 'Abmelden',
|
||||
'Sign out everywhere?': 'Überall abmelden?',
|
||||
'Signs this profile out on every device, including this one. Your passkeys keep working — sign in with them again anytime.': 'Meldet dieses Profil auf allen Geräten ab, auch auf diesem. Deine Passkeys bleiben gültig — du kannst dich damit jederzeit wieder anmelden.',
|
||||
'Sign out everywhere': 'Überall abmelden',
|
||||
'Ends this profile’s sessions on all your devices.': 'Beendet die Sitzungen dieses Profils auf all deinen Geräten.',
|
||||
'Signed out on all devices': 'Auf allen Geräten abgemeldet',
|
||||
'Could not sign out everywhere — you are still signed in.': 'Abmelden auf allen Geräten fehlgeschlagen — du bist weiterhin angemeldet.',
|
||||
'Guest mode — data lives only in this browser. Create a passkey profile to keep it safe and separate per person.': 'Gastmodus — Daten liegen nur in diesem Browser. Erstelle ein Passkey-Profil, um sie zu sichern und pro Person zu trennen.',
|
||||
'Create passkey profile': 'Passkey-Profil erstellen',
|
||||
'Passkeys not supported in this browser.': 'Passkeys werden in diesem Browser nicht unterstützt.',
|
||||
@@ -372,6 +387,15 @@ export default {
|
||||
'Admin dashboard': 'Admin-Dashboard',
|
||||
// --- muscle map ---
|
||||
'Muscle balance': 'Muskelbalance',
|
||||
'Fatigue': 'Ermüdung',
|
||||
'Ready': 'Bereit',
|
||||
'Recovering': 'In Erholung',
|
||||
'Fatigued': 'Ermüdet',
|
||||
'Fatigue shows how recently each muscle was trained. High means rest.': 'Die Ermüdung zeigt, wie lange das Training jedes Muskels zurückliegt. Ein hoher Wert bedeutet: Pause.',
|
||||
'Strength shows retained muscle strength. Train again to reset it.': 'Die Kraft zeigt, wie viel Muskelkraft erhalten ist. Trainiere erneut, um sie zurückzusetzen.',
|
||||
'full': 'voll',
|
||||
'floor': 'Minimum',
|
||||
'Weeks since training: {0}': 'Zuletzt vor {0} Wo. trainiert',
|
||||
'by sets worked': 'nach Sätzen',
|
||||
'Week': 'Woche',
|
||||
'not trained': 'nicht trainiert',
|
||||
@@ -531,4 +555,46 @@ export default {
|
||||
'Easy — warm-up territory': 'Locker — Aufwärmbereich',
|
||||
'RIR counts the reps you left; RPE reads the same effort off a 10-point scale — so RPE ≈ 10 − RIR. Pick the one you already think in.': 'RIR zählt die Wiederholungen, die du übrig lässt; RPE liest dieselbe Anstrengung auf einer 10er-Skala ab — also RPE ≈ 10 − RIR. Nimm die Skala, in der du ohnehin denkst.',
|
||||
'The highlighted row is where most working sets land. Sets you have already logged keep their own scale, and nothing else reads the value — progression and estimated 1RM are unaffected.': 'Die hervorgehobene Zeile ist der Bereich, in dem die meisten Arbeitssätze landen. Bereits protokollierte Sätze behalten ihre eigene Skala, und sonst liest den Wert nichts — Progression und geschätztes 1RM bleiben unberührt.',
|
||||
// --- effort in the stats ---
|
||||
'Effort': 'Anstrengung',
|
||||
'how close to failure': 'wie nah am Muskelversagen',
|
||||
'by hard sets': 'nach harten Sätzen',
|
||||
'Hard': 'Hart',
|
||||
'no hard sets': 'keine harten Sätze',
|
||||
'No hard sets in this period': 'Keine harten Sätze in diesem Zeitraum',
|
||||
'Every muscle group got at least one hard set in this period.': 'Jede Muskelgruppe hat in diesem Zeitraum mindestens einen harten Satz bekommen.',
|
||||
'No rated sets in this period.': 'Keine bewerteten Sätze in diesem Zeitraum.',
|
||||
'average effort': 'durchschnittliche Anstrengung',
|
||||
'at {0} {1} or harder': 'bei {0} {1} oder härter',
|
||||
'{0} of {1} finished sets rated': '{0} von {1} erledigten Sätzen bewertet',
|
||||
'Effort per set is switched off — turn it on in Settings to keep rating.': 'Anstrengung pro Satz ist ausgeschaltet — schalte sie in den Einstellungen ein, um weiter zu bewerten.',
|
||||
'Week by week': 'Woche für Woche',
|
||||
'Where the sets land': 'Wo die Sätze landen',
|
||||
'Most working sets belong close to failure without living there — half at the floor and half at the top average out to a healthy-looking middle.': 'Die meisten Arbeitssätze gehören nah ans Muskelversagen, ohne dort zu wohnen — die Hälfte ganz unten und die Hälfte ganz oben mittelt sich zu einem gesund aussehenden Mittelwert.',
|
||||
'Average effort per workout': 'Durchschnittliche Anstrengung pro Training',
|
||||
'A fuller dot means less left in the tank — the same weight at a lower {0} is progress the line alone does not show.': 'Ein vollerer Punkt heißt: weniger im Tank — dasselbe Gewicht bei niedrigerem {0} ist Fortschritt, den die Linie allein nicht zeigt.',
|
||||
// --- bodyweight & per side ---
|
||||
'Bodyweight': 'Körpergewicht',
|
||||
'No weight to enter — just log the reps.': 'Kein Gewicht einzutragen — nur die Wiederholungen.',
|
||||
'Ask for a weight on every set.': 'Bei jedem Satz nach dem Gewicht fragen.',
|
||||
'For dips or pull-ups with a belt. Progression then follows the weight.': 'Für Dips oder Klimmzüge mit Gürtel. Die Progression folgt dann dem Gewicht.',
|
||||
'Reps per side': 'Wiederholungen pro Seite',
|
||||
'For lunges, single-arm rows and the like.': 'Für Ausfallschritte, einarmiges Rudern und Ähnliches.',
|
||||
'Top of the range': 'Oberes Ende',
|
||||
'Reps climb by one whenever every set was clean. Set a ceiling to add sets instead of reps forever.': 'Die Wiederholungen steigen um eine, sobald jeder Satz sauber war. Setz ein oberes Ende, damit irgendwann ein Satz dazukommt statt immer mehr Wiederholungen.',
|
||||
'Reps climb to {0}, then a set is added and the reps start over. At {1} sets it asks you to add weight instead.': 'Die Wiederholungen steigen bis {0}, dann kommt ein Satz dazu und die Wiederholungen starten neu. Bei {1} Sätzen wird stattdessen nach Zusatzgewicht gefragt.',
|
||||
'Added ({0})': 'Zusatz ({0})',
|
||||
'{0}/side': '{0}/Seite',
|
||||
'{0} reps in every set — add a set and go back to {1}.': '{0} Wiederholungen in jedem Satz — ein Satz kommt dazu, zurück auf {1}.',
|
||||
'{0} sets of {1} — time to add weight or move to a harder variation.': '{0} Sätze mit {1} — Zeit für Zusatzgewicht oder eine schwerere Variante.',
|
||||
'{0} per side': '{0} pro Seite',
|
||||
'You still log the total: {0} is {1} per side.': 'Du trägst weiterhin die Gesamtzahl ein: {0} sind {1} pro Seite.',
|
||||
'{0} sets · {1} work': '{0} Sätze · {1} Arbeit',
|
||||
'Make superset with previous': 'Mit vorheriger Übung kombinieren',
|
||||
'Make superset with next': 'Mit nächster Übung kombinieren',
|
||||
'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'
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
export default {
|
||||
'Confirm': 'Confirmar',
|
||||
'Cancel': 'Cancelar',
|
||||
'Press back again to exit': 'Pulsa atrás otra vez para salir',
|
||||
'Delete': 'Eliminar',
|
||||
'Save': 'Guardar',
|
||||
'Import': 'Importar',
|
||||
@@ -90,6 +91,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',
|
||||
@@ -154,13 +160,15 @@ export default {
|
||||
'Last time you hit all reps — try {0}': 'La última vez completaste todas las reps — prueba {0}',
|
||||
'Weights bumped to {0}': 'Pesos subidos a {0}',
|
||||
'Remove set': 'Quitar serie',
|
||||
'Warm-up': 'Calentamiento',
|
||||
'Add warm-up set': 'Añadir serie de calentamiento',
|
||||
'Add set': 'Añadir serie',
|
||||
'Cardio logged': 'Cardio registrado',
|
||||
'Discard workout?': '¿Descartar entrenamiento?',
|
||||
'The sets you logged in this session will be lost.': 'Las series registradas en esta sesión se perderán.',
|
||||
'Superset {0} / {1}': 'Superserie {0} / {1}',
|
||||
'Exercise {0} / {1}': 'Ejercicio {0} / {1}',
|
||||
'Superset · do these back-to-back, rest after both': 'Superserie · hazlos seguidos, descansa después de ambos',
|
||||
'Superset · do these back-to-back, rest when done': 'Superserie · hazlos seguidos, descansa al final',
|
||||
'Freestyle workout — add your first exercise.': 'Entrenamiento libre — añade tu primer ejercicio.',
|
||||
'Finish workout early · {0} exercises': 'Terminar antes · {0} ejercicios',
|
||||
'Rest over — next set!': '¡Descanso terminado — siguiente serie!',
|
||||
@@ -223,6 +231,7 @@ export default {
|
||||
'Sign in with passkey': 'Iniciar sesión con passkey',
|
||||
'Create new profile': 'Crear perfil nuevo',
|
||||
"This browser doesn't support passkeys — you can still use openGym locally on this device.": 'Este navegador no admite passkeys — aun así puedes usar openGym localmente en este dispositivo.',
|
||||
"This browser doesn't support passkeys, and this instance requires an account. Try a browser or device with passkey support.": 'Este navegador no admite passkeys y este servidor requiere una cuenta. Prueba con un navegador o dispositivo compatible con passkeys.',
|
||||
'Continue without account': 'Continuar sin cuenta',
|
||||
'Passkeys use {0} — no passwords.': 'Las passkeys usan {0} — sin contraseñas.',
|
||||
'Each profile keeps its own plan, workouts & body weight.': 'Cada perfil guarda su propio plan, entrenamientos y peso corporal.',
|
||||
@@ -231,6 +240,12 @@ export default {
|
||||
'Sign out?': '¿Cerrar sesión?',
|
||||
'Your data is synced to your profile first, then cleared from this device.': 'Tus datos se sincronizan primero con tu perfil y luego se borran de este dispositivo.',
|
||||
'Sign out': 'Cerrar sesión',
|
||||
'Sign out everywhere?': '¿Cerrar sesión en todos los dispositivos?',
|
||||
'Signs this profile out on every device, including this one. Your passkeys keep working — sign in with them again anytime.': 'Cierra la sesión de este perfil en todos los dispositivos, incluido este. Tus passkeys siguen funcionando — puedes volver a iniciar sesión con ellas cuando quieras.',
|
||||
'Sign out everywhere': 'Cerrar sesión en todos los dispositivos',
|
||||
'Ends this profile’s sessions on all your devices.': 'Termina las sesiones de este perfil en todos tus dispositivos.',
|
||||
'Signed out on all devices': 'Sesión cerrada en todos los dispositivos',
|
||||
'Could not sign out everywhere — you are still signed in.': 'No se pudo cerrar la sesión en todos los dispositivos — sigues con la sesión iniciada.',
|
||||
'Guest mode — data lives only in this browser. Create a passkey profile to keep it safe and separate per person.': 'Modo invitado — los datos viven solo en este navegador. Crea un perfil con passkey para protegerlos y separarlos por persona.',
|
||||
'Create passkey profile': 'Crear perfil con passkey',
|
||||
'Passkeys not supported in this browser.': 'Passkeys no compatibles con este navegador.',
|
||||
@@ -354,6 +369,15 @@ export default {
|
||||
'Admin dashboard': 'Panel de administración',
|
||||
// --- muscle map ---
|
||||
'Muscle balance': 'Equilibrio muscular',
|
||||
'Fatigue': 'Fatiga',
|
||||
'Ready': 'Listo',
|
||||
'Recovering': 'En recuperación',
|
||||
'Fatigued': 'Fatigado',
|
||||
'Fatigue shows how recently each muscle was trained. High means rest.': 'La fatiga indica cuánto tiempo ha pasado desde el último entrenamiento de cada músculo. Un valor alto indica que toca descansar.',
|
||||
'Strength shows retained muscle strength. Train again to reset it.': 'La fuerza muestra cuánta fuerza muscular se conserva. Vuelve a entrenar para restablecerla.',
|
||||
'full': 'completo',
|
||||
'floor': 'mínimo',
|
||||
'Weeks since training: {0}': 'Último entrenamiento: hace {0} sem.',
|
||||
'by sets worked': 'por series trabajadas',
|
||||
'Week': 'Semana',
|
||||
'not trained': 'sin entrenar',
|
||||
@@ -513,4 +537,47 @@ export default {
|
||||
'Easy — warm-up territory': 'Fácil — zona de calentamiento',
|
||||
'RIR counts the reps you left; RPE reads the same effort off a 10-point scale — so RPE ≈ 10 − RIR. Pick the one you already think in.': 'El RIR cuenta las repeticiones que dejas; el RPE lee ese mismo esfuerzo en una escala de 10 — así que RPE ≈ 10 − RIR. Elige la que ya usas para pensar.',
|
||||
'The highlighted row is where most working sets land. Sets you have already logged keep their own scale, and nothing else reads the value — progression and estimated 1RM are unaffected.': 'La fila resaltada es donde cae la mayoría de las series efectivas. Las series ya registradas conservan su escala, y nada más lee el valor: la progresión y el 1RM estimado no cambian.',
|
||||
// --- effort in the stats ---
|
||||
'Effort': 'Esfuerzo',
|
||||
'how close to failure': 'qué tan cerca del fallo',
|
||||
'by hard sets': 'por series duras',
|
||||
'Hard': 'Duras',
|
||||
'no hard sets': 'sin series duras',
|
||||
'No hard sets in this period': 'Sin series duras en este periodo',
|
||||
'Every muscle group got at least one hard set in this period.': 'Todos los grupos musculares recibieron al menos una serie dura en este periodo.',
|
||||
'No rated sets in this period.': 'Ninguna serie valorada en este periodo.',
|
||||
'average effort': 'esfuerzo medio',
|
||||
'at {0} {1} or harder': 'a {0} {1} o más duro',
|
||||
'{0} of {1} finished sets rated': '{0} de {1} series completadas valoradas',
|
||||
'Effort per set is switched off — turn it on in Settings to keep rating.': 'El esfuerzo por serie está desactivado — actívalo en Ajustes para seguir valorando.',
|
||||
'Week by week': 'Semana a semana',
|
||||
'Where the sets land': 'Dónde caen las series',
|
||||
'Most working sets belong close to failure without living there — half at the floor and half at the top average out to a healthy-looking middle.': 'La mayoría de las series efectivas van cerca del fallo sin vivir allí — la mitad abajo y la mitad arriba dan una media que solo parece sana.',
|
||||
'Average effort per workout': 'Esfuerzo medio por entrenamiento',
|
||||
'A fuller dot means less left in the tank — the same weight at a lower {0} is progress the line alone does not show.': 'Un punto más lleno significa menos reserva — el mismo peso con un {0} más bajo es progreso que la línea por sí sola no muestra.',
|
||||
|
||||
// --- bodyweight & per side ---
|
||||
'Bodyweight': 'Peso corporal',
|
||||
'No weight to enter — just log the reps.': 'No hay peso que introducir — solo registra las reps.',
|
||||
'Ask for a weight on every set.': 'Pedir un peso en cada serie.',
|
||||
'For dips or pull-ups with a belt. Progression then follows the weight.': 'Para fondos o dominadas con cinturón. La progresión sigue entonces el peso.',
|
||||
'Reps per side': 'Reps por lado',
|
||||
'For lunges, single-arm rows and the like.': 'Para zancadas, remo a una mano y similares.',
|
||||
'Top of the range': 'Tope del rango',
|
||||
'Reps climb by one whenever every set was clean. Set a ceiling to add sets instead of reps forever.': 'Las reps suben de una en una cuando todas las series salen limpias. Fija un tope para añadir series en vez de reps para siempre.',
|
||||
'Reps climb to {0}, then a set is added and the reps start over. At {1} sets it asks you to add weight instead.': 'Las reps suben hasta {0}, luego se añade una serie y las reps vuelven a empezar. Con {1} series te pedirá añadir peso.',
|
||||
'Added ({0})': 'Extra ({0})',
|
||||
'{0}/side': '{0}/lado',
|
||||
'{0} reps in every set — add a set and go back to {1}.': '{0} reps en todas las series: añade una serie y vuelve a {1}.',
|
||||
'{0} sets of {1} — time to add weight or move to a harder variation.': '{0} series de {1}: toca añadir peso o pasar a una variante más difícil.',
|
||||
'{0} per side': '{0} por lado',
|
||||
'You still log the total: {0} is {1} per side.': 'Sigues registrando el total: {0} son {1} por lado.',
|
||||
'{0} sets · {1} work': '{0} series · {1} trabajo',
|
||||
'Make superset with previous': 'Hacer superserie con anterior',
|
||||
'Make superset with next': 'Hacer superserie con siguiente',
|
||||
'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'
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
export default {
|
||||
'Confirm': 'Confirmer',
|
||||
'Cancel': 'Annuler',
|
||||
'Press back again to exit': 'Appuyez de nouveau pour quitter',
|
||||
'Delete': 'Supprimer',
|
||||
'Save': 'Enregistrer',
|
||||
'Import': 'Importer',
|
||||
@@ -90,6 +91,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',
|
||||
@@ -154,13 +160,15 @@ export default {
|
||||
'Last time you hit all reps — try {0}': 'Toutes les reps réussies la dernière fois — essaie {0}',
|
||||
'Weights bumped to {0}': 'Poids montés à {0}',
|
||||
'Remove set': 'Retirer une série',
|
||||
'Warm-up': 'Échauffement',
|
||||
'Add warm-up set': 'Ajouter une série d’échauffement',
|
||||
'Add set': 'Ajouter une série',
|
||||
'Cardio logged': 'Cardio noté',
|
||||
'Discard workout?': 'Abandonner la séance ?',
|
||||
'The sets you logged in this session will be lost.': 'Les séries notées dans cette session seront perdues.',
|
||||
'Superset {0} / {1}': 'Superset {0} / {1}',
|
||||
'Exercise {0} / {1}': 'Exercice {0} / {1}',
|
||||
'Superset · do these back-to-back, rest after both': 'Superset · enchaîne-les, repos après les deux',
|
||||
'Superset · do these back-to-back, rest when done': 'Superset · enchaîne-les, repos à la fin',
|
||||
'Freestyle workout — add your first exercise.': 'Séance libre — ajoute ton premier exercice.',
|
||||
'Finish workout early · {0} exercises': 'Terminer plus tôt · {0} exercices',
|
||||
'Rest over — next set!': 'Repos fini — série suivante !',
|
||||
@@ -223,6 +231,7 @@ export default {
|
||||
'Sign in with passkey': 'Se connecter avec une passkey',
|
||||
'Create new profile': 'Créer un nouveau profil',
|
||||
"This browser doesn't support passkeys — you can still use openGym locally on this device.": 'Ce navigateur ne prend pas en charge les passkeys — tu peux quand même utiliser openGym localement sur cet appareil.',
|
||||
"This browser doesn't support passkeys, and this instance requires an account. Try a browser or device with passkey support.": 'Ce navigateur ne prend pas en charge les passkeys, et ce serveur exige un compte. Essaie un navigateur ou un appareil compatible avec les passkeys.',
|
||||
'Continue without account': 'Continuer sans compte',
|
||||
'Passkeys use {0} — no passwords.': 'Les passkeys utilisent {0} — pas de mots de passe.',
|
||||
'Each profile keeps its own plan, workouts & body weight.': 'Chaque profil garde son plan, ses séances et son poids corporel.',
|
||||
@@ -231,6 +240,12 @@ export default {
|
||||
'Sign out?': 'Se déconnecter ?',
|
||||
'Your data is synced to your profile first, then cleared from this device.': 'Tes données sont d’abord synchronisées avec ton profil, puis effacées de cet appareil.',
|
||||
'Sign out': 'Se déconnecter',
|
||||
'Sign out everywhere?': 'Se déconnecter partout ?',
|
||||
'Signs this profile out on every device, including this one. Your passkeys keep working — sign in with them again anytime.': 'Déconnecte ce profil sur tous les appareils, y compris celui-ci. Tes passkeys restent valides — tu peux te reconnecter avec elles à tout moment.',
|
||||
'Sign out everywhere': 'Se déconnecter partout',
|
||||
'Ends this profile’s sessions on all your devices.': 'Met fin aux sessions de ce profil sur tous tes appareils.',
|
||||
'Signed out on all devices': 'Déconnecté sur tous les appareils',
|
||||
'Could not sign out everywhere — you are still signed in.': 'Impossible de se déconnecter partout — tu es toujours connecté.',
|
||||
'Guest mode — data lives only in this browser. Create a passkey profile to keep it safe and separate per person.': 'Mode invité — les données ne vivent que dans ce navigateur. Crée un profil passkey pour les protéger et les séparer par personne.',
|
||||
'Create passkey profile': 'Créer un profil passkey',
|
||||
'Passkeys not supported in this browser.': 'Passkeys non prises en charge par ce navigateur.',
|
||||
@@ -354,6 +369,15 @@ export default {
|
||||
'Admin dashboard': 'Tableau d’administration',
|
||||
// --- muscle map ---
|
||||
'Muscle balance': 'Équilibre musculaire',
|
||||
'Fatigue': 'Fatigue',
|
||||
'Ready': 'Prêt',
|
||||
'Recovering': 'En récupération',
|
||||
'Fatigued': 'Fatigué',
|
||||
'Fatigue shows how recently each muscle was trained. High means rest.': 'La fatigue indique à quand remonte le dernier entraînement de chaque muscle. Un niveau élevé signifie qu’il est temps de se reposer.',
|
||||
'Strength shows retained muscle strength. Train again to reset it.': 'La force indique combien de force musculaire est conservée. Entraîne-toi à nouveau pour la réinitialiser.',
|
||||
'full': 'complet',
|
||||
'floor': 'plancher',
|
||||
'Weeks since training: {0}': 'Dernier entraînement : il y a {0} sem.',
|
||||
'by sets worked': 'par séries effectuées',
|
||||
'Week': 'Semaine',
|
||||
'not trained': 'non travaillé',
|
||||
@@ -513,4 +537,47 @@ export default {
|
||||
'Easy — warm-up territory': 'Facile — zone d’échauffement',
|
||||
'RIR counts the reps you left; RPE reads the same effort off a 10-point scale — so RPE ≈ 10 − RIR. Pick the one you already think in.': 'Le RIR compte les répétitions qu’il te restait ; le RPE lit le même effort sur une échelle de 10 — donc RPE ≈ 10 − RIR. Prends celle dans laquelle tu penses déjà.',
|
||||
'The highlighted row is where most working sets land. Sets you have already logged keep their own scale, and nothing else reads the value — progression and estimated 1RM are unaffected.': 'La ligne mise en avant est celle où tombent la plupart des séries de travail. Les séries déjà enregistrées gardent leur échelle, et rien d’autre ne lit la valeur — la progression et le 1RM estimé ne changent pas.',
|
||||
// --- effort in the stats ---
|
||||
'Effort': 'Effort',
|
||||
'how close to failure': 'à quel point près de l’échec',
|
||||
'by hard sets': 'par séries dures',
|
||||
'Hard': 'Dures',
|
||||
'no hard sets': 'aucune série dure',
|
||||
'No hard sets in this period': 'Aucune série dure sur cette période',
|
||||
'Every muscle group got at least one hard set in this period.': 'Chaque groupe musculaire a eu au moins une série dure sur cette période.',
|
||||
'No rated sets in this period.': 'Aucune série notée sur cette période.',
|
||||
'average effort': 'effort moyen',
|
||||
'at {0} {1} or harder': 'à {0} {1} ou plus dur',
|
||||
'{0} of {1} finished sets rated': '{0} séries notées sur {1} terminées',
|
||||
'Effort per set is switched off — turn it on in Settings to keep rating.': 'L’effort par série est désactivé — active-le dans les Réglages pour continuer à noter.',
|
||||
'Week by week': 'Semaine par semaine',
|
||||
'Where the sets land': 'Où tombent les séries',
|
||||
'Most working sets belong close to failure without living there — half at the floor and half at the top average out to a healthy-looking middle.': 'La plupart des séries de travail se placent près de l’échec sans y vivre — la moitié tout en bas et la moitié tout en haut donnent une moyenne qui n’a l’air saine que sur le papier.',
|
||||
'Average effort per workout': 'Effort moyen par séance',
|
||||
'A fuller dot means less left in the tank — the same weight at a lower {0} is progress the line alone does not show.': 'Un point plus plein veut dire moins de réserve — le même poids à un {0} plus bas, c’est un progrès que la ligne seule ne montre pas.',
|
||||
|
||||
// --- bodyweight & per side ---
|
||||
'Bodyweight': 'Poids du corps',
|
||||
'No weight to enter — just log the reps.': 'Pas de poids à saisir — note simplement les répétitions.',
|
||||
'Ask for a weight on every set.': 'Demander un poids à chaque série.',
|
||||
'For dips or pull-ups with a belt. Progression then follows the weight.': 'Pour les dips ou les tractions avec une ceinture. La progression suit alors le poids.',
|
||||
'Reps per side': 'Reps par côté',
|
||||
'For lunges, single-arm rows and the like.': 'Pour les fentes, les rowings à un bras et compagnie.',
|
||||
'Top of the range': 'Haut de la fourchette',
|
||||
'Reps climb by one whenever every set was clean. Set a ceiling to add sets instead of reps forever.': 'Les répétitions montent d’une dès que toutes les séries sont propres. Fixe un plafond pour ajouter une série au lieu de monter les répétitions sans fin.',
|
||||
'Reps climb to {0}, then a set is added and the reps start over. At {1} sets it asks you to add weight instead.': 'Les répétitions montent jusqu’à {0}, puis une série est ajoutée et les répétitions repartent du bas. À {1} séries, c’est du poids qu’il te demande d’ajouter.',
|
||||
'Added ({0})': 'Ajouté ({0})',
|
||||
'{0}/side': '{0}/côté',
|
||||
'{0} reps in every set — add a set and go back to {1}.': '{0} répétitions sur toutes les séries — une série en plus, retour à {1}.',
|
||||
'{0} sets of {1} — time to add weight or move to a harder variation.': '{0} séries de {1} — il est temps d’ajouter du poids ou de passer à une variante plus dure.',
|
||||
'{0} per side': '{0} par côté',
|
||||
'You still log the total: {0} is {1} per side.': 'Tu notes toujours le total : {0}, c’est {1} par côté.',
|
||||
'{0} sets · {1} work': '{0} séries · {1} travail',
|
||||
'Make superset with previous': 'Faire un superset avec le précédent',
|
||||
'Make superset with next': 'Faire un superset avec le suivant',
|
||||
'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'
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
export default {
|
||||
'Confirm': 'पुष्टि करें',
|
||||
'Cancel': 'रद्द करें',
|
||||
'Press back again to exit': 'बाहर निकलने के लिए फिर से बैक दबाएँ',
|
||||
'Delete': 'हटाएँ',
|
||||
'Save': 'सहेजें',
|
||||
'Import': 'आयात करें',
|
||||
@@ -90,6 +91,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} आराम के लिए सेट',
|
||||
@@ -154,13 +160,15 @@ export default {
|
||||
'Last time you hit all reps — try {0}': 'पिछली बार सारे रेप्स पूरे किए — {0} आज़माएँ',
|
||||
'Weights bumped to {0}': 'वज़न बढ़ाकर {0} किया',
|
||||
'Remove set': 'सेट हटाएँ',
|
||||
'Warm-up': 'वार्म-अप',
|
||||
'Add warm-up set': 'वार्म-अप सेट जोड़ें',
|
||||
'Add set': 'सेट जोड़ें',
|
||||
'Cardio logged': 'कार्डियो दर्ज हुआ',
|
||||
'Discard workout?': 'वर्कआउट छोड़ें?',
|
||||
'The sets you logged in this session will be lost.': 'इस सत्र में दर्ज किए सेट खो जाएँगे।',
|
||||
'Superset {0} / {1}': 'सुपरसेट {0} / {1}',
|
||||
'Exercise {0} / {1}': 'व्यायाम {0} / {1}',
|
||||
'Superset · do these back-to-back, rest after both': 'सुपरसेट · इन्हें लगातार करें, दोनों के बाद आराम',
|
||||
'Superset · do these back-to-back, rest when done': 'सुपरसेट · इन्हें लगातार करें, अंत में आराम',
|
||||
'Freestyle workout — add your first exercise.': 'फ्रीस्टाइल वर्कआउट — पहला व्यायाम जोड़ें।',
|
||||
'Finish workout early · {0} exercises': 'जल्दी समाप्त करें · {0} व्यायाम',
|
||||
'Rest over — next set!': 'आराम खत्म — अगला सेट!',
|
||||
@@ -223,6 +231,7 @@ export default {
|
||||
'Sign in with passkey': 'पासकी से साइन इन करें',
|
||||
'Create new profile': 'नई प्रोफ़ाइल बनाएँ',
|
||||
"This browser doesn't support passkeys — you can still use openGym locally on this device.": 'यह ब्राउज़र पासकी सपोर्ट नहीं करता — फिर भी आप इस डिवाइस पर openGym लोकली इस्तेमाल कर सकते हैं।',
|
||||
"This browser doesn't support passkeys, and this instance requires an account. Try a browser or device with passkey support.": 'यह ब्राउज़र पासकी सपोर्ट नहीं करता, और इस सर्वर के लिए खाता ज़रूरी है। पासकी सपोर्ट वाला ब्राउज़र या डिवाइस आज़माएँ।',
|
||||
'Continue without account': 'बिना खाते के जारी रखें',
|
||||
'Passkeys use {0} — no passwords.': 'पासकी {0} का उपयोग करती हैं — कोई पासवर्ड नहीं।',
|
||||
'Each profile keeps its own plan, workouts & body weight.': 'हर प्रोफ़ाइल की अपनी योजना, वर्कआउट और वज़न होते हैं।',
|
||||
@@ -231,6 +240,12 @@ export default {
|
||||
'Sign out?': 'साइन आउट करें?',
|
||||
'Your data is synced to your profile first, then cleared from this device.': 'डेटा पहले प्रोफ़ाइल से सिंक होता है, फिर इस डिवाइस से हटता है।',
|
||||
'Sign out': 'साइन आउट',
|
||||
'Sign out everywhere?': 'हर जगह साइन आउट करें?',
|
||||
'Signs this profile out on every device, including this one. Your passkeys keep working — sign in with them again anytime.': 'इस डिवाइस सहित सभी डिवाइस पर इस प्रोफ़ाइल को साइन आउट करता है। आपकी पासकी काम करती रहेंगी — उनसे कभी भी दोबारा साइन इन करें।',
|
||||
'Sign out everywhere': 'हर जगह साइन आउट करें',
|
||||
'Ends this profile’s sessions on all your devices.': 'आपके सभी डिवाइस पर इस प्रोफ़ाइल के सेशन खत्म करता है।',
|
||||
'Signed out on all devices': 'सभी डिवाइस पर साइन आउट हो गया',
|
||||
'Could not sign out everywhere — you are still signed in.': 'हर जगह साइन आउट नहीं हो सका — आप अभी भी साइन इन हैं।',
|
||||
'Guest mode — data lives only in this browser. Create a passkey profile to keep it safe and separate per person.': 'गेस्ट मोड — डेटा केवल इस ब्राउज़र में रहता है। सुरक्षित रखने और हर व्यक्ति के लिए अलग रखने हेतु पासकी प्रोफ़ाइल बनाएँ।',
|
||||
'Create passkey profile': 'पासकी प्रोफ़ाइल बनाएँ',
|
||||
'Passkeys not supported in this browser.': 'इस ब्राउज़र में पासकी समर्थित नहीं।',
|
||||
@@ -354,6 +369,15 @@ export default {
|
||||
'Admin dashboard': 'एडमिन डैशबोर्ड',
|
||||
// --- muscle map ---
|
||||
'Muscle balance': 'मांसपेशी संतुलन',
|
||||
'Fatigue': 'थकान',
|
||||
'Ready': 'तैयार',
|
||||
'Recovering': 'पुनर्प्राप्ति में',
|
||||
'Fatigued': 'थकी हुई',
|
||||
'Fatigue shows how recently each muscle was trained. High means rest.': 'थकान बताती है कि हर मांसपेशी की ट्रेनिंग कितनी हाल की है। अधिक थकान होने पर आराम करें।',
|
||||
'Strength shows retained muscle strength. Train again to reset it.': 'शक्ति बताती है कि मांसपेशियों की कितनी ताकत बनी हुई है। इसे रीसेट करने के लिए फिर से ट्रेन करें।',
|
||||
'full': 'पूर्ण',
|
||||
'floor': 'न्यूनतम',
|
||||
'Weeks since training: {0}': 'पिछला व्यायाम: {0} सप्ताह पहले',
|
||||
'by sets worked': 'सेट के अनुसार',
|
||||
'Week': 'सप्ताह',
|
||||
'not trained': 'प्रशिक्षित नहीं',
|
||||
@@ -513,4 +537,47 @@ export default {
|
||||
'Easy — warm-up territory': 'आसान — वॉर्म-अप का दायरा',
|
||||
'RIR counts the reps you left; RPE reads the same effort off a 10-point scale — so RPE ≈ 10 − RIR. Pick the one you already think in.': 'RIR बचे हुए रेप्स गिनता है; RPE उसी मेहनत को 10 के पैमाने पर पढ़ता है — यानी RPE ≈ 10 − RIR. वही चुनें जिसमें आप पहले से सोचते हैं।',
|
||||
'The highlighted row is where most working sets land. Sets you have already logged keep their own scale, and nothing else reads the value — progression and estimated 1RM are unaffected.': 'हाइलाइट की गई पंक्ति वह है जहाँ ज़्यादातर वर्किंग सेट आते हैं। पहले दर्ज किए सेट अपना पैमाना बनाए रखते हैं, और इस मान को और कुछ नहीं पढ़ता — प्रोग्रेशन और अनुमानित 1RM अछूते रहते हैं।',
|
||||
// --- effort in the stats ---
|
||||
'Effort': 'मेहनत',
|
||||
'how close to failure': 'फेलियर के कितने पास',
|
||||
'by hard sets': 'कठिन सेट के हिसाब से',
|
||||
'Hard': 'कठिन',
|
||||
'no hard sets': 'कोई कठिन सेट नहीं',
|
||||
'No hard sets in this period': 'इस अवधि में कोई कठिन सेट नहीं',
|
||||
'Every muscle group got at least one hard set in this period.': 'इस अवधि में हर मांसपेशी समूह को कम से कम एक कठिन सेट मिला।',
|
||||
'No rated sets in this period.': 'इस अवधि में कोई आँका गया सेट नहीं।',
|
||||
'average effort': 'औसत मेहनत',
|
||||
'at {0} {1} or harder': '{0} {1} या उससे कठिन',
|
||||
'{0} of {1} finished sets rated': '{1} पूरे किए सेट में से {0} आँके गए',
|
||||
'Effort per set is switched off — turn it on in Settings to keep rating.': 'हर सेट की मेहनत बंद है — आँकना जारी रखने के लिए सेटिंग्स में चालू करें।',
|
||||
'Week by week': 'हफ़्ते दर हफ़्ते',
|
||||
'Where the sets land': 'सेट कहाँ गिरते हैं',
|
||||
'Most working sets belong close to failure without living there — half at the floor and half at the top average out to a healthy-looking middle.': 'ज़्यादातर वर्किंग सेट फेलियर के पास होने चाहिए, पर वहीं बसे नहीं — आधे सबसे नीचे और आधे सबसे ऊपर मिलकर एक ऐसा औसत बनाते हैं जो सिर्फ़ देखने में सेहतमंद लगता है।',
|
||||
'Average effort per workout': 'हर वर्कआउट की औसत मेहनत',
|
||||
'A fuller dot means less left in the tank — the same weight at a lower {0} is progress the line alone does not show.': 'ज़्यादा भरा बिंदु मतलब टंकी में कम बचा — वही वज़न कम {0} पर उठाना वह प्रगति है जो अकेली लाइन नहीं दिखाती।',
|
||||
|
||||
// --- bodyweight & per side ---
|
||||
'Bodyweight': 'बॉडीवेट',
|
||||
'No weight to enter — just log the reps.': 'कोई वज़न नहीं डालना — बस रेप्स दर्ज करें।',
|
||||
'Ask for a weight on every set.': 'हर सेट पर वज़न पूछें।',
|
||||
'For dips or pull-ups with a belt. Progression then follows the weight.': 'बेल्ट के साथ डिप्स या पुल-अप्स के लिए। फिर प्रोग्रेशन वज़न के हिसाब से चलता है।',
|
||||
'Reps per side': 'प्रति तरफ़ रेप्स',
|
||||
'For lunges, single-arm rows and the like.': 'लंजेस, सिंगल-आर्म रो और ऐसे व्यायामों के लिए।',
|
||||
'Top of the range': 'रेंज का ऊपरी सिरा',
|
||||
'Reps climb by one whenever every set was clean. Set a ceiling to add sets instead of reps forever.': 'हर सेट साफ़ रहने पर रेप्स एक-एक बढ़ते हैं। ऊपरी सीमा तय करें ताकि रेप्स हमेशा बढ़ने के बजाय एक सेट जुड़ जाए।',
|
||||
'Reps climb to {0}, then a set is added and the reps start over. At {1} sets it asks you to add weight instead.': 'रेप्स {0} तक बढ़ते हैं, फिर एक सेट जुड़ता है और रेप्स दोबारा शुरू होते हैं। {1} सेट पर यह वज़न बढ़ाने को कहता है।',
|
||||
'Added ({0})': 'अतिरिक्त ({0})',
|
||||
'{0}/side': '{0}/तरफ़',
|
||||
'{0} reps in every set — add a set and go back to {1}.': 'हर सेट में {0} रेप्स — एक सेट जोड़ें और वापस {1} पर।',
|
||||
'{0} sets of {1} — time to add weight or move to a harder variation.': '{1} रेप्स के {0} सेट — अब वज़न बढ़ाने या किसी कठिन वैरिएशन पर जाने का समय।',
|
||||
'{0} per side': 'प्रति तरफ़ {0}',
|
||||
'You still log the total: {0} is {1} per side.': 'आप कुल ही दर्ज करते हैं: {0} यानी प्रति तरफ़ {1}।',
|
||||
'{0} sets · {1} work': '{0} सेट · {1} काम',
|
||||
'Make superset with previous': 'पिछले के साथ सुपरसेट',
|
||||
'Make superset with next': 'अगले के साथ सुपरसेट',
|
||||
'primary': 'प्राथमिक',
|
||||
'secondary': 'द्वितीयक',
|
||||
'No exercises with an estimated 1RM yet.': 'अभी तक अनुमानित 1RM वाला कोई व्यायाम नहीं।',
|
||||
'Tap a muscle to see its exercises.': 'व्यायाम देखने के लिए किसी मांसपेशी पर टैप करें।',
|
||||
'Unpair': 'अलग करें'
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
export default {
|
||||
'Confirm': 'Conferma',
|
||||
'Cancel': 'Annulla',
|
||||
'Press back again to exit': 'Premi di nuovo indietro per uscire',
|
||||
'Delete': 'Elimina',
|
||||
'Save': 'Salva',
|
||||
'Import': 'Importa',
|
||||
@@ -90,6 +91,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',
|
||||
@@ -154,13 +160,15 @@ export default {
|
||||
'Last time you hit all reps — try {0}': "L'ultima volta hai completato tutte le rip. — prova {0}",
|
||||
'Weights bumped to {0}': 'Pesi aumentati a {0}',
|
||||
'Remove set': 'Rimuovi serie',
|
||||
'Warm-up': 'Riscaldamento',
|
||||
'Add warm-up set': 'Aggiungi serie di riscaldamento',
|
||||
'Add set': 'Aggiungi serie',
|
||||
'Cardio logged': 'Cardio registrato',
|
||||
'Discard workout?': 'Scartare allenamento?',
|
||||
'The sets you logged in this session will be lost.': 'Le serie registrate in questa sessione andranno perse.',
|
||||
'Superset {0} / {1}': 'Superset {0} / {1}',
|
||||
'Exercise {0} / {1}': 'Esercizio {0} / {1}',
|
||||
'Superset · do these back-to-back, rest after both': 'Superset · falli uno dopo l’altro, riposo dopo entrambi',
|
||||
'Superset · do these back-to-back, rest when done': 'Superset · falli uno dopo l’altro, riposo alla fine',
|
||||
'Freestyle workout — add your first exercise.': 'Allenamento libero — aggiungi il primo esercizio.',
|
||||
'Finish workout early · {0} exercises': 'Termina in anticipo · {0} esercizi',
|
||||
'Rest over — next set!': 'Riposo finito — prossima serie!',
|
||||
@@ -223,6 +231,7 @@ export default {
|
||||
'Sign in with passkey': 'Accedi con passkey',
|
||||
'Create new profile': 'Crea nuovo profilo',
|
||||
"This browser doesn't support passkeys — you can still use openGym locally on this device.": 'Questo browser non supporta le passkey — puoi comunque usare openGym localmente su questo dispositivo.',
|
||||
"This browser doesn't support passkeys, and this instance requires an account. Try a browser or device with passkey support.": 'Questo browser non supporta le passkey e questo server richiede un account. Prova un browser o un dispositivo che supporti le passkey.',
|
||||
'Continue without account': 'Continua senza account',
|
||||
'Passkeys use {0} — no passwords.': 'Le passkey usano {0} — niente password.',
|
||||
'Each profile keeps its own plan, workouts & body weight.': 'Ogni profilo ha il proprio piano, allenamenti e peso corporeo.',
|
||||
@@ -231,6 +240,12 @@ export default {
|
||||
'Sign out?': 'Uscire?',
|
||||
'Your data is synced to your profile first, then cleared from this device.': 'I dati vengono prima sincronizzati col profilo, poi rimossi da questo dispositivo.',
|
||||
'Sign out': 'Esci',
|
||||
'Sign out everywhere?': 'Uscire ovunque?',
|
||||
'Signs this profile out on every device, including this one. Your passkeys keep working — sign in with them again anytime.': 'Esce da questo profilo su tutti i dispositivi, incluso questo. Le tue passkey restano valide — puoi rientrare con loro quando vuoi.',
|
||||
'Sign out everywhere': 'Esci ovunque',
|
||||
'Ends this profile’s sessions on all your devices.': 'Chiude le sessioni di questo profilo su tutti i tuoi dispositivi.',
|
||||
'Signed out on all devices': 'Uscito da tutti i dispositivi',
|
||||
'Could not sign out everywhere — you are still signed in.': 'Impossibile uscire ovunque — sei ancora connesso.',
|
||||
'Guest mode — data lives only in this browser. Create a passkey profile to keep it safe and separate per person.': 'Modalità ospite — i dati vivono solo in questo browser. Crea un profilo passkey per proteggerli e separarli per persona.',
|
||||
'Create passkey profile': 'Crea profilo passkey',
|
||||
'Passkeys not supported in this browser.': 'Passkey non supportate in questo browser.',
|
||||
@@ -354,6 +369,15 @@ export default {
|
||||
'Admin dashboard': 'Pannello di amministrazione',
|
||||
// --- muscle map ---
|
||||
'Muscle balance': 'Equilibrio muscolare',
|
||||
'Fatigue': 'Fatica',
|
||||
'Ready': 'Pronto',
|
||||
'Recovering': 'In recupero',
|
||||
'Fatigued': 'Affaticato',
|
||||
'Fatigue shows how recently each muscle was trained. High means rest.': 'La fatica mostra quanto è recente l’allenamento di ogni muscolo. Un valore alto significa che serve riposo.',
|
||||
'Strength shows retained muscle strength. Train again to reset it.': 'La forza mostra quanta forza muscolare hai mantenuto. Allenati di nuovo per reimpostarla.',
|
||||
'full': 'pieno',
|
||||
'floor': 'minimo',
|
||||
'Weeks since training: {0}': 'Ultimo allenamento: {0} sett. fa',
|
||||
'by sets worked': 'per serie svolte',
|
||||
'Week': 'Settimana',
|
||||
'not trained': 'non allenato',
|
||||
@@ -513,4 +537,47 @@ export default {
|
||||
'Easy — warm-up territory': 'Facile — zona riscaldamento',
|
||||
'RIR counts the reps you left; RPE reads the same effort off a 10-point scale — so RPE ≈ 10 − RIR. Pick the one you already think in.': 'Il RIR conta le ripetizioni che ti restavano; l’RPE legge lo stesso sforzo su una scala da 10 — quindi RPE ≈ 10 − RIR. Scegli quella con cui già ragioni.',
|
||||
'The highlighted row is where most working sets land. Sets you have already logged keep their own scale, and nothing else reads the value — progression and estimated 1RM are unaffected.': 'La riga evidenziata è dove finisce la maggior parte delle serie di lavoro. Le serie già registrate mantengono la loro scala, e nient’altro legge il valore: progressione e 1RM stimato non cambiano.',
|
||||
// --- effort in the stats ---
|
||||
'Effort': 'Sforzo',
|
||||
'how close to failure': 'quanto vicino al cedimento',
|
||||
'by hard sets': 'per serie dure',
|
||||
'Hard': 'Dure',
|
||||
'no hard sets': 'nessuna serie dura',
|
||||
'No hard sets in this period': 'Nessuna serie dura in questo periodo',
|
||||
'Every muscle group got at least one hard set in this period.': 'Ogni gruppo muscolare ha avuto almeno una serie dura in questo periodo.',
|
||||
'No rated sets in this period.': 'Nessuna serie valutata in questo periodo.',
|
||||
'average effort': 'sforzo medio',
|
||||
'at {0} {1} or harder': 'a {0} {1} o più duro',
|
||||
'{0} of {1} finished sets rated': '{0} di {1} serie completate valutate',
|
||||
'Effort per set is switched off — turn it on in Settings to keep rating.': 'Lo sforzo per serie è disattivato — attivalo nelle Impostazioni per continuare a valutare.',
|
||||
'Week by week': 'Settimana per settimana',
|
||||
'Where the sets land': 'Dove cadono le serie',
|
||||
'Most working sets belong close to failure without living there — half at the floor and half at the top average out to a healthy-looking middle.': 'La maggior parte delle serie di lavoro sta vicino al cedimento senza viverci — metà in fondo e metà in cima danno una media che sembra sana solo all’apparenza.',
|
||||
'Average effort per workout': 'Sforzo medio per allenamento',
|
||||
'A fuller dot means less left in the tank — the same weight at a lower {0} is progress the line alone does not show.': 'Un punto più pieno significa meno riserva — lo stesso peso con un {0} più basso è progresso che la linea da sola non mostra.',
|
||||
|
||||
// --- bodyweight & per side ---
|
||||
'Bodyweight': 'Corpo libero',
|
||||
'No weight to enter — just log the reps.': 'Nessun peso da inserire — registra solo le ripetizioni.',
|
||||
'Ask for a weight on every set.': 'Chiedi un peso a ogni serie.',
|
||||
'For dips or pull-ups with a belt. Progression then follows the weight.': 'Per dip o trazioni con la cintura. La progressione segue poi il peso.',
|
||||
'Reps per side': 'Ripetizioni per lato',
|
||||
'For lunges, single-arm rows and the like.': 'Per affondi, rematori a un braccio e simili.',
|
||||
'Top of the range': 'Massimo dell\'intervallo',
|
||||
'Reps climb by one whenever every set was clean. Set a ceiling to add sets instead of reps forever.': 'Le ripetizioni salgono di una ogni volta che tutte le serie sono pulite. Imposta un massimo per aggiungere serie invece di ripetizioni all\'infinito.',
|
||||
'Reps climb to {0}, then a set is added and the reps start over. At {1} sets it asks you to add weight instead.': 'Le ripetizioni salgono fino a {0}, poi viene aggiunta una serie e le ripetizioni ripartono da capo. A {1} serie ti chiede invece di aggiungere peso.',
|
||||
'Added ({0})': 'Aggiunto ({0})',
|
||||
'{0}/side': '{0}/lato',
|
||||
'{0} reps in every set — add a set and go back to {1}.': '{0} ripetizioni in ogni serie — aggiungi una serie e torna a {1}.',
|
||||
'{0} sets of {1} — time to add weight or move to a harder variation.': '{0} serie da {1} — è ora di aggiungere peso o passare a una variante più difficile.',
|
||||
'{0} per side': '{0} per lato',
|
||||
'You still log the total: {0} is {1} per side.': 'Registri sempre il totale: {0} sono {1} per lato.',
|
||||
'{0} sets · {1} work': '{0} serie · {1} lavoro',
|
||||
'Make superset with previous': 'Superset con il precedente',
|
||||
'Make superset with next': 'Superset con il successivo',
|
||||
'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'
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
export default {
|
||||
'Confirm': '확인',
|
||||
'Cancel': '취소',
|
||||
'Press back again to exit': '뒤로를 한 번 더 누르면 종료됩니다',
|
||||
'Delete': '삭제',
|
||||
'Save': '저장',
|
||||
'Import': '가져오기',
|
||||
@@ -90,6 +91,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}을(를) 휴식일로 설정',
|
||||
@@ -154,13 +160,15 @@ export default {
|
||||
'Last time you hit all reps — try {0}': '지난번에 모든 횟수를 채웠어요 — {0}에 도전해 보세요',
|
||||
'Weights bumped to {0}': '무게를 {0}(으)로 올렸어요',
|
||||
'Remove set': '세트 빼기',
|
||||
'Warm-up': '워밍업',
|
||||
'Add warm-up set': '워밍업 세트 추가',
|
||||
'Add set': '세트 추가',
|
||||
'Cardio logged': '유산소 기록됨',
|
||||
'Discard workout?': '운동을 버릴까요?',
|
||||
'The sets you logged in this session will be lost.': '이 세션에서 기록한 세트가 사라집니다.',
|
||||
'Superset {0} / {1}': '슈퍼세트 {0} / {1}',
|
||||
'Exercise {0} / {1}': '운동 {0} / {1}',
|
||||
'Superset · do these back-to-back, rest after both': '슈퍼세트 · 연달아 수행하고, 둘 다 끝난 뒤 휴식',
|
||||
'Superset · do these back-to-back, rest when done': '슈퍼세트 · 연달아 수행하고, 전부 끝난 뒤 휴식',
|
||||
'Freestyle workout — add your first exercise.': '자유 운동 — 첫 운동을 추가하세요.',
|
||||
'Finish workout early · {0} exercises': '일찍 마치기 · 운동 {0}개',
|
||||
'Rest over — next set!': '휴식 끝 — 다음 세트!',
|
||||
@@ -223,6 +231,7 @@ export default {
|
||||
'Sign in with passkey': '패스키로 로그인',
|
||||
'Create new profile': '새 프로필 만들기',
|
||||
"This browser doesn't support passkeys — you can still use openGym locally on this device.": '이 브라우저는 패스키를 지원하지 않아요 — 그래도 이 기기에서 openGym을 로컬로 사용할 수 있습니다.',
|
||||
"This browser doesn't support passkeys, and this instance requires an account. Try a browser or device with passkey support.": '이 브라우저는 패스키를 지원하지 않고, 이 서버는 계정이 필요합니다. 패스키를 지원하는 브라우저나 기기를 사용해 보세요.',
|
||||
'Continue without account': '계정 없이 계속',
|
||||
'Passkeys use {0} — no passwords.': '패스키는 {0}을(를) 사용합니다 — 비밀번호 없음.',
|
||||
'Each profile keeps its own plan, workouts & body weight.': '프로필마다 자신의 계획, 운동, 체중을 보관합니다.',
|
||||
@@ -231,6 +240,12 @@ export default {
|
||||
'Sign out?': '로그아웃할까요?',
|
||||
'Your data is synced to your profile first, then cleared from this device.': '데이터를 먼저 프로필에 동기화한 뒤 이 기기에서 지웁니다.',
|
||||
'Sign out': '로그아웃',
|
||||
'Sign out everywhere?': '모든 기기에서 로그아웃할까요?',
|
||||
'Signs this profile out on every device, including this one. Your passkeys keep working — sign in with them again anytime.': '이 기기를 포함해 모든 기기에서 이 프로필을 로그아웃합니다. 패스키는 그대로 사용할 수 있어 언제든 다시 로그인할 수 있습니다.',
|
||||
'Sign out everywhere': '모든 기기에서 로그아웃',
|
||||
'Ends this profile’s sessions on all your devices.': '모든 기기에서 이 프로필의 세션을 종료합니다.',
|
||||
'Signed out on all devices': '모든 기기에서 로그아웃했습니다',
|
||||
'Could not sign out everywhere — you are still signed in.': '모든 기기에서 로그아웃하지 못했습니다 — 아직 로그인 상태입니다.',
|
||||
'Guest mode — data lives only in this browser. Create a passkey profile to keep it safe and separate per person.': '게스트 모드 — 데이터가 이 브라우저에만 저장됩니다. 패스키 프로필을 만들어 안전하게 보관하고 사람별로 분리하세요.',
|
||||
'Create passkey profile': '패스키 프로필 만들기',
|
||||
'Passkeys not supported in this browser.': '이 브라우저는 패스키를 지원하지 않습니다.',
|
||||
@@ -354,6 +369,15 @@ export default {
|
||||
'Admin dashboard': '관리자 대시보드',
|
||||
// --- muscle map ---
|
||||
'Muscle balance': '근육 균형',
|
||||
'Fatigue': '피로',
|
||||
'Ready': '준비됨',
|
||||
'Recovering': '회복 중',
|
||||
'Fatigued': '피로함',
|
||||
'Fatigue shows how recently each muscle was trained. High means rest.': '피로도는 각 근육을 얼마나 최근에 운동했는지 보여줍니다. 높을수록 휴식이 필요합니다.',
|
||||
'Strength shows retained muscle strength. Train again to reset it.': '근력은 근육에 남아 있는 힘을 보여줍니다. 다시 운동하면 값이 초기화됩니다.',
|
||||
'full': '완전',
|
||||
'floor': '최소',
|
||||
'Weeks since training: {0}': '마지막 운동: {0}주 전',
|
||||
'by sets worked': '세트 수 기준',
|
||||
'Week': '이번 주',
|
||||
'not trained': '훈련 안 함',
|
||||
@@ -513,4 +537,47 @@ export default {
|
||||
'Easy — warm-up territory': '가벼움 — 웜업 구간',
|
||||
'RIR counts the reps you left; RPE reads the same effort off a 10-point scale — so RPE ≈ 10 − RIR. Pick the one you already think in.': 'RIR은 남긴 횟수를 세고, RPE는 같은 노력을 10점 척도로 읽습니다 — 즉 RPE ≈ 10 − RIR. 평소에 쓰던 쪽을 고르세요.',
|
||||
'The highlighted row is where most working sets land. Sets you have already logged keep their own scale, and nothing else reads the value — progression and estimated 1RM are unaffected.': '강조된 줄은 대부분의 본세트가 들어가는 구간입니다. 이미 기록한 세트는 원래 척도를 그대로 유지하며, 이 값을 읽는 곳은 없습니다 — 프로그레션과 예상 1RM은 영향을 받지 않습니다.',
|
||||
// --- effort in the stats ---
|
||||
'Effort': '강도',
|
||||
'how close to failure': '실패 지점에 얼마나 가까운지',
|
||||
'by hard sets': '힘든 세트 기준',
|
||||
'Hard': '힘든 세트',
|
||||
'no hard sets': '힘든 세트 없음',
|
||||
'No hard sets in this period': '이 기간에 힘든 세트 없음',
|
||||
'Every muscle group got at least one hard set in this period.': '이 기간에 모든 근육군이 최소 한 세트는 힘들게 훈련했습니다.',
|
||||
'No rated sets in this period.': '이 기간에 평가된 세트가 없습니다.',
|
||||
'average effort': '평균 강도',
|
||||
'at {0} {1} or harder': '{0} {1} 이상',
|
||||
'{0} of {1} finished sets rated': '완료한 {1}세트 중 {0}세트 평가됨',
|
||||
'Effort per set is switched off — turn it on in Settings to keep rating.': '세트당 강도가 꺼져 있습니다 — 계속 평가하려면 설정에서 켜세요.',
|
||||
'Week by week': '주별 변화',
|
||||
'Where the sets land': '세트가 몰리는 곳',
|
||||
'Most working sets belong close to failure without living there — half at the floor and half at the top average out to a healthy-looking middle.': '대부분의 본세트는 실패 지점 가까이에 있어야 하지만 거기 머물면 안 됩니다 — 절반은 바닥에 절반은 꼭대기에 있으면 평균만 건강해 보입니다.',
|
||||
'Average effort per workout': '운동당 평균 강도',
|
||||
'A fuller dot means less left in the tank — the same weight at a lower {0} is progress the line alone does not show.': '점이 진할수록 남은 여력이 적다는 뜻입니다 — 같은 무게를 더 낮은 {0}로 든 것은 선만 봐서는 알 수 없는 발전입니다.',
|
||||
|
||||
// --- bodyweight & per side ---
|
||||
'Bodyweight': '맨몸 운동',
|
||||
'No weight to enter — just log the reps.': '입력할 무게 없음 — 횟수만 기록합니다.',
|
||||
'Ask for a weight on every set.': '세트마다 무게를 물어봅니다.',
|
||||
'For dips or pull-ups with a belt. Progression then follows the weight.': '벨트를 차고 하는 딥스나 풀업용. 그러면 점진적 증가가 무게를 따라갑니다.',
|
||||
'Reps per side': '한쪽당 횟수',
|
||||
'For lunges, single-arm rows and the like.': '런지, 한팔 로우 같은 운동용.',
|
||||
'Top of the range': '범위 상한',
|
||||
'Reps climb by one whenever every set was clean. Set a ceiling to add sets instead of reps forever.': '모든 세트가 깔끔하면 횟수가 하나씩 올라갑니다. 상한을 정하면 횟수를 계속 늘리는 대신 세트를 추가합니다.',
|
||||
'Reps climb to {0}, then a set is added and the reps start over. At {1} sets it asks you to add weight instead.': '횟수가 {0}회까지 오르면 세트가 하나 추가되고 횟수는 처음부터 다시 시작합니다. {1}세트가 되면 대신 무게를 올리라고 안내합니다.',
|
||||
'Added ({0})': '추가 ({0})',
|
||||
'{0}/side': '한쪽 {0}회',
|
||||
'{0} reps in every set — add a set and go back to {1}.': '모든 세트 {0}회 달성 — 세트를 추가하고 {1}회로 돌아갑니다.',
|
||||
'{0} sets of {1} — time to add weight or move to a harder variation.': '{1}회 {0}세트 — 이제 무게를 올리거나 더 어려운 동작으로 넘어가세요.',
|
||||
'{0} per side': '한쪽당 {0}회',
|
||||
'You still log the total: {0} is {1} per side.': '기록은 그대로 합계로 합니다: {0}회는 한쪽당 {1}회입니다.',
|
||||
'{0} sets · {1} work': '{0} 세트 · {1} 작업',
|
||||
'Make superset with previous': '이전 운동과 슈퍼셋',
|
||||
'Make superset with next': '다음 운동과 슈퍼셋',
|
||||
'primary': '주동',
|
||||
'secondary': '보조',
|
||||
'No exercises with an estimated 1RM yet.': '추정 1RM이 있는 운동이 아직 없습니다.',
|
||||
'Tap a muscle to see its exercises.': '근육을 눌러 해당 운동을 확인하세요.',
|
||||
'Unpair': '분리'
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
export default {
|
||||
'Confirm': 'Potwierdź',
|
||||
'Cancel': 'Anuluj',
|
||||
'Press back again to exit': 'Naciśnij wstecz ponownie, aby wyjść',
|
||||
'Delete': 'Usuń',
|
||||
'Save': 'Zapisz',
|
||||
'Import': 'Importuj',
|
||||
@@ -90,6 +91,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',
|
||||
@@ -154,13 +160,15 @@ export default {
|
||||
'Last time you hit all reps — try {0}': 'Ostatnio zrobiłeś wszystkie powtórzenia — spróbuj {0}',
|
||||
'Weights bumped to {0}': 'Ciężary podniesione do {0}',
|
||||
'Remove set': 'Usuń serię',
|
||||
'Warm-up': 'Rozgrzewka',
|
||||
'Add warm-up set': 'Dodaj serię rozgrzewkową',
|
||||
'Add set': 'Dodaj serię',
|
||||
'Cardio logged': 'Cardio zapisane',
|
||||
'Discard workout?': 'Odrzucić trening?',
|
||||
'The sets you logged in this session will be lost.': 'Serie zapisane w tej sesji zostaną utracone.',
|
||||
'Superset {0} / {1}': 'Superseria {0} / {1}',
|
||||
'Exercise {0} / {1}': 'Ćwiczenie {0} / {1}',
|
||||
'Superset · do these back-to-back, rest after both': 'Superseria · rób jedno po drugim, odpocznij po obu',
|
||||
'Superset · do these back-to-back, rest when done': 'Superseria · rób jedno po drugim, odpocznij na końcu',
|
||||
'Freestyle workout — add your first exercise.': 'Trening dowolny — dodaj pierwsze ćwiczenie.',
|
||||
'Finish workout early · {0} exercises': 'Zakończ wcześniej · {0} ćwiczeń',
|
||||
'Rest over — next set!': 'Koniec przerwy — następna seria!',
|
||||
@@ -223,6 +231,7 @@ export default {
|
||||
'Sign in with passkey': 'Zaloguj się passkey',
|
||||
'Create new profile': 'Utwórz nowy profil',
|
||||
"This browser doesn't support passkeys — you can still use openGym locally on this device.": 'Ta przeglądarka nie obsługuje passkey — mimo to możesz używać openGym lokalnie na tym urządzeniu.',
|
||||
"This browser doesn't support passkeys, and this instance requires an account. Try a browser or device with passkey support.": 'Ta przeglądarka nie obsługuje passkey, a ten serwer wymaga konta. Spróbuj przeglądarki lub urządzenia z obsługą passkey.',
|
||||
'Continue without account': 'Kontynuuj bez konta',
|
||||
'Passkeys use {0} — no passwords.': 'Passkey używa: {0} — bez haseł.',
|
||||
'Each profile keeps its own plan, workouts & body weight.': 'Każdy profil ma własny plan, treningi i masę ciała.',
|
||||
@@ -231,6 +240,12 @@ export default {
|
||||
'Sign out?': 'Wylogować?',
|
||||
'Your data is synced to your profile first, then cleared from this device.': 'Dane najpierw synchronizują się z profilem, potem są usuwane z urządzenia.',
|
||||
'Sign out': 'Wyloguj',
|
||||
'Sign out everywhere?': 'Wylogować wszędzie?',
|
||||
'Signs this profile out on every device, including this one. Your passkeys keep working — sign in with them again anytime.': 'Wylogowuje ten profil na wszystkich urządzeniach, także na tym. Twoje passkey nadal działają — możesz się nimi zalogować w każdej chwili.',
|
||||
'Sign out everywhere': 'Wyloguj wszędzie',
|
||||
'Ends this profile’s sessions on all your devices.': 'Kończy sesje tego profilu na wszystkich Twoich urządzeniach.',
|
||||
'Signed out on all devices': 'Wylogowano na wszystkich urządzeniach',
|
||||
'Could not sign out everywhere — you are still signed in.': 'Nie udało się wylogować wszędzie — nadal jesteś zalogowany.',
|
||||
'Guest mode — data lives only in this browser. Create a passkey profile to keep it safe and separate per person.': 'Tryb gościa — dane żyją tylko w tej przeglądarce. Utwórz profil passkey, aby je zabezpieczyć i rozdzielić na osoby.',
|
||||
'Create passkey profile': 'Utwórz profil passkey',
|
||||
'Passkeys not supported in this browser.': 'Passkey nieobsługiwane w tej przeglądarce.',
|
||||
@@ -354,6 +369,15 @@ export default {
|
||||
'Admin dashboard': 'Panel administratora',
|
||||
// --- muscle map ---
|
||||
'Muscle balance': 'Równowaga mięśniowa',
|
||||
'Fatigue': 'Zmęczenie',
|
||||
'Ready': 'Gotowe',
|
||||
'Recovering': 'W regeneracji',
|
||||
'Fatigued': 'Zmęczony',
|
||||
'Fatigue shows how recently each muscle was trained. High means rest.': 'Zmęczenie pokazuje, jak niedawno trenowano każdą partię mięśni. Wysoki poziom oznacza potrzebę odpoczynku.',
|
||||
'Strength shows retained muscle strength. Train again to reset it.': 'Siła pokazuje, ile siły mięśniowej pozostało. Ponowny trening przywraca jej poziom wyjściowy.',
|
||||
'full': 'pełna',
|
||||
'floor': 'minimum',
|
||||
'Weeks since training: {0}': 'Trening: {0} tyg. temu',
|
||||
'by sets worked': 'wg serii',
|
||||
'Week': 'Tydzień',
|
||||
'not trained': 'nietrenowane',
|
||||
@@ -513,4 +537,47 @@ export default {
|
||||
'Easy — warm-up territory': 'Lekko — poziom rozgrzewki',
|
||||
'RIR counts the reps you left; RPE reads the same effort off a 10-point scale — so RPE ≈ 10 − RIR. Pick the one you already think in.': 'RIR liczy powtórzenia, które zostały w zapasie; RPE odczytuje ten sam wysiłek w skali 10 — czyli RPE ≈ 10 − RIR. Wybierz tę, w której już myślisz.',
|
||||
'The highlighted row is where most working sets land. Sets you have already logged keep their own scale, and nothing else reads the value — progression and estimated 1RM are unaffected.': 'Wyróżniony wiersz to miejsce, w które trafia większość serii roboczych. Zapisane wcześniej serie zachowują swoją skalę, a wartości nic więcej nie czyta — progresja i szacowany 1RM pozostają bez zmian.',
|
||||
// --- effort in the stats ---
|
||||
'Effort': 'Wysiłek',
|
||||
'how close to failure': 'jak blisko upadku',
|
||||
'by hard sets': 'wg ciężkich serii',
|
||||
'Hard': 'Ciężkie',
|
||||
'no hard sets': 'brak ciężkich serii',
|
||||
'No hard sets in this period': 'Brak ciężkich serii w tym okresie',
|
||||
'Every muscle group got at least one hard set in this period.': 'Każda grupa mięśniowa dostała w tym okresie co najmniej jedną ciężką serię.',
|
||||
'No rated sets in this period.': 'Brak ocenionych serii w tym okresie.',
|
||||
'average effort': 'średni wysiłek',
|
||||
'at {0} {1} or harder': 'przy {0} {1} lub ciężej',
|
||||
'{0} of {1} finished sets rated': 'ocenione serie: {0} z {1} ukończonych',
|
||||
'Effort per set is switched off — turn it on in Settings to keep rating.': 'Wysiłek na serię jest wyłączony — włącz go w Ustawieniach, aby dalej oceniać.',
|
||||
'Week by week': 'Tydzień po tygodniu',
|
||||
'Where the sets land': 'Gdzie lądują serie',
|
||||
'Most working sets belong close to failure without living there — half at the floor and half at the top average out to a healthy-looking middle.': 'Większość serii roboczych należy blisko upadku, ale nie na nim — połowa na dole i połowa na górze uśrednia się do zdrowo wyglądającego środka.',
|
||||
'Average effort per workout': 'Średni wysiłek na trening',
|
||||
'A fuller dot means less left in the tank — the same weight at a lower {0} is progress the line alone does not show.': 'Pełniejsza kropka znaczy mniej zapasu — ten sam ciężar przy niższym {0} to postęp, którego sama linia nie pokazuje.',
|
||||
|
||||
// --- bodyweight & per side ---
|
||||
'Bodyweight': 'Masa własna',
|
||||
'No weight to enter — just log the reps.': 'Nie podajesz ciężaru — zapisujesz tylko powtórzenia.',
|
||||
'Ask for a weight on every set.': 'Pytaj o ciężar przy każdej serii.',
|
||||
'For dips or pull-ups with a belt. Progression then follows the weight.': 'Do dipów albo podciągania z pasem. Progresja idzie wtedy za ciężarem.',
|
||||
'Reps per side': 'Powtórzenia na stronę',
|
||||
'For lunges, single-arm rows and the like.': 'Do wykroków, wiosłowania jednorącz i podobnych.',
|
||||
'Top of the range': 'Górna granica zakresu',
|
||||
'Reps climb by one whenever every set was clean. Set a ceiling to add sets instead of reps forever.': 'Powtórzenia rosną o jedno, gdy każda seria jest czysta. Ustaw górną granicę, aby zamiast powtórzeń w nieskończoność dochodziły serie.',
|
||||
'Reps climb to {0}, then a set is added and the reps start over. At {1} sets it asks you to add weight instead.': 'Powtórzenia rosną do {0}, potem dochodzi seria, a powtórzenia zaczynają od nowa. Przy {1} seriach aplikacja poprosi zamiast tego o dodanie ciężaru.',
|
||||
'Added ({0})': 'Dodane ({0})',
|
||||
'{0}/side': '{0}/str.',
|
||||
'{0} reps in every set — add a set and go back to {1}.': 'Wszystkie serie po {0} powt. — dodaj serię i wróć do {1}.',
|
||||
'{0} sets of {1} — time to add weight or move to a harder variation.': '{0} × {1} powt. — czas dodać ciężar albo przejść na trudniejszy wariant.',
|
||||
'{0} per side': '{0} na stronę',
|
||||
'You still log the total: {0} is {1} per side.': 'Nadal zapisujesz łączną liczbę: {0} to {1} na stronę.',
|
||||
'{0} sets · {1} work': '{0} serii · {1} praca',
|
||||
'Make superset with previous': 'Połącz z poprzednim',
|
||||
'Make superset with next': 'Połącz z następnym',
|
||||
'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'
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
export default {
|
||||
'Confirm': 'Confirmar',
|
||||
'Cancel': 'Cancelar',
|
||||
'Press back again to exit': 'Prima novamente para sair',
|
||||
'Delete': 'Eliminar',
|
||||
'Save': 'Guardar',
|
||||
'Import': 'Importar',
|
||||
@@ -90,6 +91,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',
|
||||
@@ -154,13 +160,15 @@ export default {
|
||||
'Last time you hit all reps — try {0}': 'Da última vez completaste todas as reps — tenta {0}',
|
||||
'Weights bumped to {0}': 'Pesos aumentados para {0}',
|
||||
'Remove set': 'Remover série',
|
||||
'Warm-up': 'Aquecimento',
|
||||
'Add warm-up set': 'Adicionar série de aquecimento',
|
||||
'Add set': 'Adicionar série',
|
||||
'Cardio logged': 'Cardio registado',
|
||||
'Discard workout?': 'Descartar treino?',
|
||||
'The sets you logged in this session will be lost.': 'As séries registadas nesta sessão vão perder-se.',
|
||||
'Superset {0} / {1}': 'Supersérie {0} / {1}',
|
||||
'Exercise {0} / {1}': 'Exercício {0} / {1}',
|
||||
'Superset · do these back-to-back, rest after both': 'Supersérie · faz seguidos, descansa depois de ambos',
|
||||
'Superset · do these back-to-back, rest when done': 'Supersérie · faz seguidos, descansa no final',
|
||||
'Freestyle workout — add your first exercise.': 'Treino livre — adiciona o teu primeiro exercício.',
|
||||
'Finish workout early · {0} exercises': 'Terminar mais cedo · {0} exercícios',
|
||||
'Rest over — next set!': 'Descanso terminado — próxima série!',
|
||||
@@ -223,6 +231,7 @@ export default {
|
||||
'Sign in with passkey': 'Entrar com passkey',
|
||||
'Create new profile': 'Criar novo perfil',
|
||||
"This browser doesn't support passkeys — you can still use openGym locally on this device.": 'Este navegador não suporta passkeys — ainda assim podes usar o openGym localmente neste dispositivo.',
|
||||
"This browser doesn't support passkeys, and this instance requires an account. Try a browser or device with passkey support.": 'Este navegador não suporta passkeys e este servidor exige uma conta. Experimenta um navegador ou dispositivo com suporte a passkeys.',
|
||||
'Continue without account': 'Continuar sem conta',
|
||||
'Passkeys use {0} — no passwords.': 'As passkeys usam {0} — sem palavras-passe.',
|
||||
'Each profile keeps its own plan, workouts & body weight.': 'Cada perfil guarda o seu plano, treinos e peso corporal.',
|
||||
@@ -231,6 +240,12 @@ export default {
|
||||
'Sign out?': 'Terminar sessão?',
|
||||
'Your data is synced to your profile first, then cleared from this device.': 'Os teus dados são primeiro sincronizados com o perfil e depois apagados deste dispositivo.',
|
||||
'Sign out': 'Terminar sessão',
|
||||
'Sign out everywhere?': 'Terminar sessão em todos os dispositivos?',
|
||||
'Signs this profile out on every device, including this one. Your passkeys keep working — sign in with them again anytime.': 'Termina a sessão deste perfil em todos os dispositivos, incluindo este. As tuas passkeys continuam a funcionar — podes voltar a entrar com elas quando quiseres.',
|
||||
'Sign out everywhere': 'Terminar sessão em todos os dispositivos',
|
||||
'Ends this profile’s sessions on all your devices.': 'Termina as sessões deste perfil em todos os teus dispositivos.',
|
||||
'Signed out on all devices': 'Sessão terminada em todos os dispositivos',
|
||||
'Could not sign out everywhere — you are still signed in.': 'Não foi possível terminar a sessão em todos os dispositivos — continuas com sessão iniciada.',
|
||||
'Guest mode — data lives only in this browser. Create a passkey profile to keep it safe and separate per person.': 'Modo convidado — os dados vivem só neste navegador. Cria um perfil com passkey para os proteger e separar por pessoa.',
|
||||
'Create passkey profile': 'Criar perfil com passkey',
|
||||
'Passkeys not supported in this browser.': 'Passkeys não suportadas neste navegador.',
|
||||
@@ -354,6 +369,15 @@ export default {
|
||||
'Admin dashboard': 'Painel de administração',
|
||||
// --- muscle map ---
|
||||
'Muscle balance': 'Equilíbrio muscular',
|
||||
'Fatigue': 'Fadiga',
|
||||
'Ready': 'Pronto',
|
||||
'Recovering': 'Em recuperação',
|
||||
'Fatigued': 'Fatigado',
|
||||
'Fatigue shows how recently each muscle was trained. High means rest.': 'A fadiga mostra há quanto tempo cada músculo foi treinado. Um nível elevado significa que é preciso descansar.',
|
||||
'Strength shows retained muscle strength. Train again to reset it.': 'A força mostra quanta força muscular se mantém. Treina novamente para repor o valor.',
|
||||
'full': 'completo',
|
||||
'floor': 'mínimo',
|
||||
'Weeks since training: {0}': 'Treino: há {0} sem.',
|
||||
'by sets worked': 'por séries trabalhadas',
|
||||
'Week': 'Semana',
|
||||
'not trained': 'sem treino',
|
||||
@@ -513,4 +537,47 @@ export default {
|
||||
'Easy — warm-up territory': 'Fácil — zona de aquecimento',
|
||||
'RIR counts the reps you left; RPE reads the same effort off a 10-point scale — so RPE ≈ 10 − RIR. Pick the one you already think in.': 'O RIR conta as repetições que deixaste; o RPE lê o mesmo esforço numa escala de 10 — ou seja, RPE ≈ 10 − RIR. Escolhe aquela em que já pensas.',
|
||||
'The highlighted row is where most working sets land. Sets you have already logged keep their own scale, and nothing else reads the value — progression and estimated 1RM are unaffected.': 'A linha destacada é onde cai a maioria das séries de trabalho. As séries já registadas mantêm a sua escala, e mais nada lê o valor — a progressão e o 1RM estimado não mudam.',
|
||||
// --- effort in the stats ---
|
||||
'Effort': 'Esforço',
|
||||
'how close to failure': 'quão perto da falha',
|
||||
'by hard sets': 'por séries duras',
|
||||
'Hard': 'Duras',
|
||||
'no hard sets': 'sem séries duras',
|
||||
'No hard sets in this period': 'Sem séries duras neste período',
|
||||
'Every muscle group got at least one hard set in this period.': 'Todos os grupos musculares tiveram pelo menos uma série dura neste período.',
|
||||
'No rated sets in this period.': 'Nenhuma série avaliada neste período.',
|
||||
'average effort': 'esforço médio',
|
||||
'at {0} {1} or harder': 'a {0} {1} ou mais duro',
|
||||
'{0} of {1} finished sets rated': '{0} de {1} séries concluídas avaliadas',
|
||||
'Effort per set is switched off — turn it on in Settings to keep rating.': 'O esforço por série está desligado — liga-o nas Definições para continuares a avaliar.',
|
||||
'Week by week': 'Semana a semana',
|
||||
'Where the sets land': 'Onde caem as séries',
|
||||
'Most working sets belong close to failure without living there — half at the floor and half at the top average out to a healthy-looking middle.': 'A maioria das séries de trabalho fica perto da falha sem viver lá — metade no fundo e metade no topo dão uma média que só parece saudável.',
|
||||
'Average effort per workout': 'Esforço médio por treino',
|
||||
'A fuller dot means less left in the tank — the same weight at a lower {0} is progress the line alone does not show.': 'Um ponto mais cheio significa menos margem — o mesmo peso com um {0} mais baixo é progresso que a linha sozinha não mostra.',
|
||||
|
||||
// --- bodyweight & per side ---
|
||||
'Bodyweight': 'Peso do corpo',
|
||||
'No weight to enter — just log the reps.': 'Sem peso para introduzir — regista só as repetições.',
|
||||
'Ask for a weight on every set.': 'Pedir um peso em cada série.',
|
||||
'For dips or pull-ups with a belt. Progression then follows the weight.': 'Para dips ou pull-ups com cinto. A progressão passa então a seguir o peso.',
|
||||
'Reps per side': 'Reps por lado',
|
||||
'For lunges, single-arm rows and the like.': 'Para afundos, remadas a um braço e afins.',
|
||||
'Top of the range': 'Topo do intervalo',
|
||||
'Reps climb by one whenever every set was clean. Set a ceiling to add sets instead of reps forever.': 'As repetições sobem uma sempre que todas as séries saem limpas. Define um limite para acrescentar séries em vez de repetições para sempre.',
|
||||
'Reps climb to {0}, then a set is added and the reps start over. At {1} sets it asks you to add weight instead.': 'As repetições sobem até {0}, depois acrescenta-se uma série e as repetições recomeçam. Com {1} séries passa a pedir-te peso extra.',
|
||||
'Added ({0})': 'Extra ({0})',
|
||||
'{0}/side': '{0}/lado',
|
||||
'{0} reps in every set — add a set and go back to {1}.': '{0} repetições em todas as séries — acrescenta uma série e volta a {1}.',
|
||||
'{0} sets of {1} — time to add weight or move to a harder variation.': '{0} séries de {1} — hora de acrescentar peso ou passar a uma variação mais difícil.',
|
||||
'{0} per side': '{0} por lado',
|
||||
'You still log the total: {0} is {1} per side.': 'Continuas a registar o total: {0} são {1} por lado.',
|
||||
'{0} sets · {1} work': '{0} séries · {1} trabalho',
|
||||
'Make superset with previous': 'Fazer superset com o anterior',
|
||||
'Make superset with next': 'Fazer superset com o próximo',
|
||||
'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'
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
export default {
|
||||
'Confirm': 'Подтвердить',
|
||||
'Cancel': 'Отмена',
|
||||
'Press back again to exit': 'Нажмите «Назад» ещё раз, чтобы выйти',
|
||||
'Delete': 'Удалить',
|
||||
'Save': 'Сохранить',
|
||||
'Import': 'Импорт',
|
||||
@@ -90,6 +91,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} — теперь день отдыха',
|
||||
@@ -154,13 +160,15 @@ export default {
|
||||
'Last time you hit all reps — try {0}': 'В прошлый раз все повторения сделаны — попробуй {0}',
|
||||
'Weights bumped to {0}': 'Веса подняты до {0}',
|
||||
'Remove set': 'Убрать подход',
|
||||
'Warm-up': 'Разминка',
|
||||
'Add warm-up set': 'Добавить разминочный подход',
|
||||
'Add set': 'Добавить подход',
|
||||
'Cardio logged': 'Кардио записано',
|
||||
'Discard workout?': 'Отменить тренировку?',
|
||||
'The sets you logged in this session will be lost.': 'Подходы, записанные в этой сессии, будут потеряны.',
|
||||
'Superset {0} / {1}': 'Суперсет {0} / {1}',
|
||||
'Exercise {0} / {1}': 'Упражнение {0} / {1}',
|
||||
'Superset · do these back-to-back, rest after both': 'Суперсет · выполняй подряд, отдых после обоих',
|
||||
'Superset · do these back-to-back, rest when done': 'Суперсет · выполняй подряд, отдых в конце',
|
||||
'Freestyle workout — add your first exercise.': 'Свободная тренировка — добавь первое упражнение.',
|
||||
'Finish workout early · {0} exercises': 'Завершить раньше · упражнений: {0}',
|
||||
'Rest over — next set!': 'Отдых окончен — следующий подход!',
|
||||
@@ -223,6 +231,7 @@ export default {
|
||||
'Sign in with passkey': 'Войти по ключу доступа',
|
||||
'Create new profile': 'Создать новый профиль',
|
||||
"This browser doesn't support passkeys — you can still use openGym locally on this device.": 'Этот браузер не поддерживает ключи доступа — но openGym можно использовать локально на этом устройстве.',
|
||||
"This browser doesn't support passkeys, and this instance requires an account. Try a browser or device with passkey support.": 'Этот браузер не поддерживает ключи доступа, а на этом сервере нужен аккаунт. Попробуйте браузер или устройство с поддержкой ключей доступа.',
|
||||
'Continue without account': 'Продолжить без аккаунта',
|
||||
'Passkeys use {0} — no passwords.': 'Ключи доступа используют {0} — без паролей.',
|
||||
'Each profile keeps its own plan, workouts & body weight.': 'У каждого профиля свой план, тренировки и вес тела.',
|
||||
@@ -231,6 +240,12 @@ export default {
|
||||
'Sign out?': 'Выйти?',
|
||||
'Your data is synced to your profile first, then cleared from this device.': 'Данные сначала синхронизируются с профилем, затем удаляются с устройства.',
|
||||
'Sign out': 'Выйти',
|
||||
'Sign out everywhere?': 'Выйти на всех устройствах?',
|
||||
'Signs this profile out on every device, including this one. Your passkeys keep working — sign in with them again anytime.': 'Завершает сеансы этого профиля на всех устройствах, включая это. Ключи доступа продолжают работать — по ним можно войти снова в любой момент.',
|
||||
'Sign out everywhere': 'Выйти на всех устройствах',
|
||||
'Ends this profile’s sessions on all your devices.': 'Завершает сеансы этого профиля на всех твоих устройствах.',
|
||||
'Signed out on all devices': 'Выход выполнен на всех устройствах',
|
||||
'Could not sign out everywhere — you are still signed in.': 'Не удалось выйти на всех устройствах — ты всё ещё в системе.',
|
||||
'Guest mode — data lives only in this browser. Create a passkey profile to keep it safe and separate per person.': 'Гостевой режим — данные живут только в этом браузере. Создай профиль с ключом доступа, чтобы защитить их и разделить по людям.',
|
||||
'Create passkey profile': 'Создать профиль с ключом доступа',
|
||||
'Passkeys not supported in this browser.': 'Ключи доступа не поддерживаются в этом браузере.',
|
||||
@@ -354,6 +369,15 @@ export default {
|
||||
'Admin dashboard': 'Панель администратора',
|
||||
// --- muscle map ---
|
||||
'Muscle balance': 'Баланс мышц',
|
||||
'Fatigue': 'Усталость',
|
||||
'Ready': 'Готова',
|
||||
'Recovering': 'Восстанавливается',
|
||||
'Fatigued': 'Утомлена',
|
||||
'Fatigue shows how recently each muscle was trained. High means rest.': 'Усталость показывает, насколько недавно тренировалась каждая мышца. Высокий уровень означает, что пора отдохнуть.',
|
||||
'Strength shows retained muscle strength. Train again to reset it.': 'Сила показывает, сколько мышечной силы сохранилось. Повторная тренировка сбрасывает это значение.',
|
||||
'full': 'полная',
|
||||
'floor': 'минимум',
|
||||
'Weeks since training: {0}': 'Тренировка: {0} нед. назад',
|
||||
'by sets worked': 'по подходам',
|
||||
'Week': 'Неделя',
|
||||
'not trained': 'не тренировалась',
|
||||
@@ -513,4 +537,47 @@ export default {
|
||||
'Easy — warm-up territory': 'Легко — разминочная зона',
|
||||
'RIR counts the reps you left; RPE reads the same effort off a 10-point scale — so RPE ≈ 10 − RIR. Pick the one you already think in.': 'RIR считает повторения, оставшиеся в запасе; RPE читает то же усилие по 10-балльной шкале — то есть RPE ≈ 10 − RIR. Выберите ту, в которой вы уже думаете.',
|
||||
'The highlighted row is where most working sets land. Sets you have already logged keep their own scale, and nothing else reads the value — progression and estimated 1RM are unaffected.': 'Выделенная строка — это диапазон, в который попадает большинство рабочих подходов. Уже записанные подходы сохраняют свою шкалу, и больше это значение нигде не используется: прогрессия и расчётный 1ПМ не меняются.',
|
||||
// --- effort in the stats ---
|
||||
'Effort': 'Усилие',
|
||||
'how close to failure': 'насколько близко к отказу',
|
||||
'by hard sets': 'по тяжёлым подходам',
|
||||
'Hard': 'Тяжёлые',
|
||||
'no hard sets': 'нет тяжёлых подходов',
|
||||
'No hard sets in this period': 'Нет тяжёлых подходов за этот период',
|
||||
'Every muscle group got at least one hard set in this period.': 'За этот период каждая группа мышц получила хотя бы один тяжёлый подход.',
|
||||
'No rated sets in this period.': 'Нет оценённых подходов за этот период.',
|
||||
'average effort': 'среднее усилие',
|
||||
'at {0} {1} or harder': 'при {0} {1} или тяжелее',
|
||||
'{0} of {1} finished sets rated': 'оценено {0} из {1} выполненных подходов',
|
||||
'Effort per set is switched off — turn it on in Settings to keep rating.': 'Усилие в подходе выключено — включи его в настройках, чтобы продолжать оценивать.',
|
||||
'Week by week': 'Неделя за неделей',
|
||||
'Where the sets land': 'Куда попадают подходы',
|
||||
'Most working sets belong close to failure without living there — half at the floor and half at the top average out to a healthy-looking middle.': 'Большинство рабочих подходов должны идти близко к отказу, но не жить на нём — половина внизу и половина вверху дают среднее, которое лишь выглядит здоровым.',
|
||||
'Average effort per workout': 'Среднее усилие за тренировку',
|
||||
'A fuller dot means less left in the tank — the same weight at a lower {0} is progress the line alone does not show.': 'Более плотная точка означает меньше запаса — тот же вес при меньшем {0} это прогресс, которого одна линия не показывает.',
|
||||
|
||||
// --- bodyweight & per side ---
|
||||
'Bodyweight': 'Собственный вес',
|
||||
'No weight to enter — just log the reps.': 'Вес вводить не нужно — записывай только повторения.',
|
||||
'Ask for a weight on every set.': 'Спрашивать вес в каждом подходе.',
|
||||
'For dips or pull-ups with a belt. Progression then follows the weight.': 'Для отжиманий на брусьях или подтягиваний с поясом. Тогда прогрессия идёт по весу.',
|
||||
'Reps per side': 'Повторения на сторону',
|
||||
'For lunges, single-arm rows and the like.': 'Для выпадов, тяг одной рукой и тому подобного.',
|
||||
'Top of the range': 'Верх диапазона',
|
||||
'Reps climb by one whenever every set was clean. Set a ceiling to add sets instead of reps forever.': 'Повторения растут на одно, когда все подходы чистые. Задай потолок, чтобы вместо бесконечного роста повторений добавлялся подход.',
|
||||
'Reps climb to {0}, then a set is added and the reps start over. At {1} sets it asks you to add weight instead.': 'Повторения растут до {0}, затем добавляется подход и повторения начинаются заново. Дойдя до {1} подходов, приложение предложит вместо этого добавить вес.',
|
||||
'Added ({0})': 'Доп. ({0})',
|
||||
'{0}/side': '{0}/стор.',
|
||||
'{0} reps in every set — add a set and go back to {1}.': 'Во всех подходах {0} повт. — добавь подход и вернись к {1}.',
|
||||
'{0} sets of {1} — time to add weight or move to a harder variation.': '{0} × {1} — пора добавить вес или перейти к более сложному варианту.',
|
||||
'{0} per side': '{0} на сторону',
|
||||
'You still log the total: {0} is {1} per side.': 'Ты по-прежнему записываешь общее число: {0} — это {1} на сторону.',
|
||||
'{0} sets · {1} work': '{0} подходов · {1} рабочих',
|
||||
'Make superset with previous': 'Суперсет с предыдущим',
|
||||
'Make superset with next': 'Суперсет со следующим',
|
||||
'primary': 'основная',
|
||||
'secondary': 'вспомогательная',
|
||||
'No exercises with an estimated 1RM yet.': 'Пока нет упражнений с расчётным 1ПМ.',
|
||||
'Tap a muscle to see its exercises.': 'Нажмите на мышцу, чтобы увидеть её упражнения.',
|
||||
'Unpair': 'Разъединить'
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
export default {
|
||||
'Confirm': 'Onayla',
|
||||
'Cancel': 'İptal',
|
||||
'Press back again to exit': 'Çıkmak için geri tuşuna tekrar basın',
|
||||
'Delete': 'Sil',
|
||||
'Save': 'Kaydet',
|
||||
'Import': 'İçe aktar',
|
||||
@@ -90,6 +91,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ı',
|
||||
@@ -154,13 +160,15 @@ export default {
|
||||
'Last time you hit all reps — try {0}': 'Geçen sefer tüm tekrarları yaptın — {0} dene',
|
||||
'Weights bumped to {0}': 'Ağırlıklar {0} değerine çıkarıldı',
|
||||
'Remove set': 'Set kaldır',
|
||||
'Warm-up': 'Isınma',
|
||||
'Add warm-up set': 'Isınma seti ekle',
|
||||
'Add set': 'Set ekle',
|
||||
'Cardio logged': 'Kardiyo kaydedildi',
|
||||
'Discard workout?': 'Antrenman iptal edilsin mi?',
|
||||
'The sets you logged in this session will be lost.': 'Bu oturumda kaydettiğin setler kaybolacak.',
|
||||
'Superset {0} / {1}': 'Süperset {0} / {1}',
|
||||
'Exercise {0} / {1}': 'Egzersiz {0} / {1}',
|
||||
'Superset · do these back-to-back, rest after both': 'Süperset · art arda yap, ikisinden sonra dinlen',
|
||||
'Superset · do these back-to-back, rest when done': 'Süperset · art arda yap, sonunda dinlen',
|
||||
'Freestyle workout — add your first exercise.': 'Serbest antrenman — ilk egzersizini ekle.',
|
||||
'Finish workout early · {0} exercises': 'Erken bitir · {0} egzersiz',
|
||||
'Rest over — next set!': 'Dinlenme bitti — sıradaki set!',
|
||||
@@ -223,6 +231,7 @@ export default {
|
||||
'Sign in with passkey': 'Geçiş anahtarıyla giriş yap',
|
||||
'Create new profile': 'Yeni profil oluştur',
|
||||
"This browser doesn't support passkeys — you can still use openGym locally on this device.": 'Bu tarayıcı geçiş anahtarlarını desteklemiyor — yine de openGym’i bu cihazda yerel olarak kullanabilirsin.',
|
||||
"This browser doesn't support passkeys, and this instance requires an account. Try a browser or device with passkey support.": 'Bu tarayıcı geçiş anahtarlarını desteklemiyor ve bu sunucu bir hesap gerektiriyor. Geçiş anahtarı destekleyen bir tarayıcı veya cihaz dene.',
|
||||
'Continue without account': 'Hesapsız devam et',
|
||||
'Passkeys use {0} — no passwords.': 'Geçiş anahtarları {0} kullanır — şifre yok.',
|
||||
'Each profile keeps its own plan, workouts & body weight.': 'Her profilin kendi planı, antrenmanları ve vücut ağırlığı vardır.',
|
||||
@@ -231,6 +240,12 @@ export default {
|
||||
'Sign out?': 'Çıkış yapılsın mı?',
|
||||
'Your data is synced to your profile first, then cleared from this device.': 'Verilerin önce profiline eşitlenir, sonra bu cihazdan silinir.',
|
||||
'Sign out': 'Çıkış yap',
|
||||
'Sign out everywhere?': 'Her yerden çıkış yapılsın mı?',
|
||||
'Signs this profile out on every device, including this one. Your passkeys keep working — sign in with them again anytime.': 'Bu profili, bu cihaz dahil tüm cihazlarda oturumdan çıkarır. Geçiş anahtarların çalışmaya devam eder — istediğin zaman onlarla tekrar giriş yapabilirsin.',
|
||||
'Sign out everywhere': 'Her yerden çıkış yap',
|
||||
'Ends this profile’s sessions on all your devices.': 'Bu profilin tüm cihazlarındaki oturumlarını sonlandırır.',
|
||||
'Signed out on all devices': 'Tüm cihazlarda çıkış yapıldı',
|
||||
'Could not sign out everywhere — you are still signed in.': 'Her yerden çıkış yapılamadı — hâlâ giriş yapmış durumdasın.',
|
||||
'Guest mode — data lives only in this browser. Create a passkey profile to keep it safe and separate per person.': 'Misafir modu — veriler sadece bu tarayıcıda yaşar. Güvende tutmak ve kişi başına ayırmak için geçiş anahtarlı profil oluştur.',
|
||||
'Create passkey profile': 'Geçiş anahtarlı profil oluştur',
|
||||
'Passkeys not supported in this browser.': 'Bu tarayıcıda geçiş anahtarları desteklenmiyor.',
|
||||
@@ -354,6 +369,15 @@ export default {
|
||||
'Admin dashboard': 'Yönetici paneli',
|
||||
// --- muscle map ---
|
||||
'Muscle balance': 'Kas dengesi',
|
||||
'Fatigue': 'Yorgunluk',
|
||||
'Ready': 'Hazır',
|
||||
'Recovering': 'Toparlanıyor',
|
||||
'Fatigued': 'Yorgun',
|
||||
'Fatigue shows how recently each muscle was trained. High means rest.': 'Yorgunluk, her kasın ne kadar süre önce çalıştırıldığını gösterir. Yüksek değer dinlenmek gerektiği anlamına gelir.',
|
||||
'Strength shows retained muscle strength. Train again to reset it.': 'Kuvvet, kas gücünün ne kadarının korunduğunu gösterir. Yeniden çalışarak değeri sıfırlayabilirsin.',
|
||||
'full': 'tam',
|
||||
'floor': 'minimum',
|
||||
'Weeks since training: {0}': 'Son antrenman: {0} hafta önce',
|
||||
'by sets worked': 'çalışılan sete göre',
|
||||
'Week': 'Hafta',
|
||||
'not trained': 'çalışılmadı',
|
||||
@@ -513,4 +537,47 @@ export default {
|
||||
'Easy — warm-up territory': 'Kolay — ısınma bölgesi',
|
||||
'RIR counts the reps you left; RPE reads the same effort off a 10-point scale — so RPE ≈ 10 − RIR. Pick the one you already think in.': 'RIR yedekte bıraktığın tekrarları sayar; RPE aynı eforu 10’luk ölçekte okur — yani RPE ≈ 10 − RIR. Zaten hangisiyle düşünüyorsan onu seç.',
|
||||
'The highlighted row is where most working sets land. Sets you have already logged keep their own scale, and nothing else reads the value — progression and estimated 1RM are unaffected.': 'Vurgulanan satır, çalışma setlerinin çoğunun denk geldiği yerdir. Daha önce kaydettiğin setler kendi ölçeğini korur ve bu değeri başka hiçbir şey okumaz — ilerleme ve tahmini 1RM etkilenmez.',
|
||||
// --- effort in the stats ---
|
||||
'Effort': 'Zorluk',
|
||||
'how close to failure': 'tükenmeye ne kadar yakın',
|
||||
'by hard sets': 'zor setlere göre',
|
||||
'Hard': 'Zor',
|
||||
'no hard sets': 'zor set yok',
|
||||
'No hard sets in this period': 'Bu dönemde zor set yok',
|
||||
'Every muscle group got at least one hard set in this period.': 'Bu dönemde her kas grubu en az bir zor set aldı.',
|
||||
'No rated sets in this period.': 'Bu dönemde puanlanmış set yok.',
|
||||
'average effort': 'ortalama zorluk',
|
||||
'at {0} {1} or harder': '{0} {1} veya daha zor',
|
||||
'{0} of {1} finished sets rated': '{1} tamamlanan setin {0} tanesi puanlandı',
|
||||
'Effort per set is switched off — turn it on in Settings to keep rating.': 'Set başına zorluk kapalı — puanlamaya devam etmek için Ayarlar’dan aç.',
|
||||
'Week by week': 'Hafta hafta',
|
||||
'Where the sets land': 'Setler nereye düşüyor',
|
||||
'Most working sets belong close to failure without living there — half at the floor and half at the top average out to a healthy-looking middle.': 'Çalışma setlerinin çoğu tükenmeye yakın olmalı ama orada yaşamamalı — yarısı en altta yarısı en üstte, ortalaması sağlıklı görünür.',
|
||||
'Average effort per workout': 'Antrenman başına ortalama zorluk',
|
||||
'A fuller dot means less left in the tank — the same weight at a lower {0} is progress the line alone does not show.': 'Daha dolu bir nokta depoda daha az kaldı demek — aynı ağırlığı daha düşük {0} ile kaldırmak, çizginin tek başına göstermediği bir ilerlemedir.',
|
||||
|
||||
// --- bodyweight & per side ---
|
||||
'Bodyweight': 'Vücut ağırlığı',
|
||||
'No weight to enter — just log the reps.': 'Girilecek ağırlık yok — sadece tekrarları kaydet.',
|
||||
'Ask for a weight on every set.': 'Her sette ağırlık sorulsun.',
|
||||
'For dips or pull-ups with a belt. Progression then follows the weight.': 'Kemerle yapılan dips veya barfiks için. İlerleme o zaman ağırlığı izler.',
|
||||
'Reps per side': 'Taraf başına tekrar',
|
||||
'For lunges, single-arm rows and the like.': 'Lunge, tek kol çekiş ve benzeri hareketler için.',
|
||||
'Top of the range': 'Aralığın üst sınırı',
|
||||
'Reps climb by one whenever every set was clean. Set a ceiling to add sets instead of reps forever.': 'Her set temiz çıktığında tekrarlar birer artar. Sonsuza kadar tekrar eklemek yerine set eklemek için bir üst sınır belirle.',
|
||||
'Reps climb to {0}, then a set is added and the reps start over. At {1} sets it asks you to add weight instead.': 'Tekrarlar {0} değerine çıkar, sonra bir set eklenir ve tekrarlar baştan başlar. {1} sette ise bunun yerine ağırlık eklemen istenir.',
|
||||
'Added ({0})': 'Ek ({0})',
|
||||
'{0}/side': '{0}/taraf',
|
||||
'{0} reps in every set — add a set and go back to {1}.': 'Her sette {0} tekrar — bir set ekle ve {1} tekrara dön.',
|
||||
'{0} sets of {1} — time to add weight or move to a harder variation.': '{1} tekrarlık {0} set — ağırlık ekleme ya da daha zor bir varyasyona geçme zamanı.',
|
||||
'{0} per side': 'Taraf başına {0}',
|
||||
'You still log the total: {0} is {1} per side.': 'Toplamı kaydetmeye devam ediyorsun: {0}, taraf başına {1} demek.',
|
||||
'{0} sets · {1} work': '{0} set · {1} çalışma',
|
||||
'Make superset with previous': 'Öncekiyle superset yap',
|
||||
'Make superset with next': 'Sonrakiyle superset yap',
|
||||
'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'
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
export default {
|
||||
'Confirm': '确认',
|
||||
'Cancel': '取消',
|
||||
'Press back again to exit': '再按一次返回退出',
|
||||
'Delete': '删除',
|
||||
'Save': '保存',
|
||||
'Import': '导入',
|
||||
@@ -90,6 +91,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} 已设为休息',
|
||||
@@ -154,13 +160,15 @@ export default {
|
||||
'Last time you hit all reps — try {0}': '上次完成了所有次数——试试 {0}',
|
||||
'Weights bumped to {0}': '重量已提升到 {0}',
|
||||
'Remove set': '减一组',
|
||||
'Warm-up': '热身',
|
||||
'Add warm-up set': '添加热身组',
|
||||
'Add set': '加一组',
|
||||
'Cardio logged': '有氧已记录',
|
||||
'Discard workout?': '放弃训练?',
|
||||
'The sets you logged in this session will be lost.': '本次记录的组数将丢失。',
|
||||
'Superset {0} / {1}': '超级组 {0} / {1}',
|
||||
'Exercise {0} / {1}': '动作 {0} / {1}',
|
||||
'Superset · do these back-to-back, rest after both': '超级组 · 连续完成,两个都做完再休息',
|
||||
'Superset · do these back-to-back, rest when done': '超级组 · 连续完成,全部做完再休息',
|
||||
'Freestyle workout — add your first exercise.': '自由训练——添加你的第一个动作。',
|
||||
'Finish workout early · {0} exercises': '提前结束 · {0} 个动作',
|
||||
'Rest over — next set!': '休息结束——下一组!',
|
||||
@@ -223,6 +231,7 @@ export default {
|
||||
'Sign in with passkey': '用通行密钥登录',
|
||||
'Create new profile': '创建新档案',
|
||||
"This browser doesn't support passkeys — you can still use openGym locally on this device.": '此浏览器不支持通行密钥——你仍可在本设备上本地使用 openGym。',
|
||||
"This browser doesn't support passkeys, and this instance requires an account. Try a browser or device with passkey support.": '此浏览器不支持通行密钥,且此服务器需要账户。请换用支持通行密钥的浏览器或设备。',
|
||||
'Continue without account': '不用账号继续',
|
||||
'Passkeys use {0} — no passwords.': '通行密钥使用{0}——没有密码。',
|
||||
'Each profile keeps its own plan, workouts & body weight.': '每个档案有自己的计划、训练和体重。',
|
||||
@@ -231,6 +240,12 @@ export default {
|
||||
'Sign out?': '退出登录?',
|
||||
'Your data is synced to your profile first, then cleared from this device.': '数据会先同步到档案,然后从本设备清除。',
|
||||
'Sign out': '退出登录',
|
||||
'Sign out everywhere?': '在所有设备上退出登录?',
|
||||
'Signs this profile out on every device, including this one. Your passkeys keep working — sign in with them again anytime.': '让此档案在所有设备上退出登录,包括这台。通行密钥不受影响——随时可以用它们重新登录。',
|
||||
'Sign out everywhere': '在所有设备上退出登录',
|
||||
'Ends this profile’s sessions on all your devices.': '结束此档案在你所有设备上的会话。',
|
||||
'Signed out on all devices': '已在所有设备上退出登录',
|
||||
'Could not sign out everywhere — you are still signed in.': '无法在所有设备上退出登录——你仍处于登录状态。',
|
||||
'Guest mode — data lives only in this browser. Create a passkey profile to keep it safe and separate per person.': '访客模式——数据只保存在此浏览器。创建通行密钥档案以保护数据并按人区分。',
|
||||
'Create passkey profile': '创建通行密钥档案',
|
||||
'Passkeys not supported in this browser.': '此浏览器不支持通行密钥。',
|
||||
@@ -354,6 +369,15 @@ export default {
|
||||
'Admin dashboard': '管理后台',
|
||||
// --- muscle map ---
|
||||
'Muscle balance': '肌肉平衡',
|
||||
'Fatigue': '疲劳',
|
||||
'Ready': '准备好',
|
||||
'Recovering': '恢复中',
|
||||
'Fatigued': '已疲劳',
|
||||
'Fatigue shows how recently each muscle was trained. High means rest.': '疲劳度显示每个肌群最近一次训练距今多久。数值越高,越需要休息。',
|
||||
'Strength shows retained muscle strength. Train again to reset it.': '力量显示肌肉力量保留了多少。再次训练即可重置。',
|
||||
'full': '完全',
|
||||
'floor': '下限',
|
||||
'Weeks since training: {0}': '上次训练:{0}周前',
|
||||
'by sets worked': '按训练组数',
|
||||
'Week': '本周',
|
||||
'not trained': '未训练',
|
||||
@@ -513,4 +537,47 @@ export default {
|
||||
'Easy — warm-up territory': '轻松——热身区间',
|
||||
'RIR counts the reps you left; RPE reads the same effort off a 10-point scale — so RPE ≈ 10 − RIR. Pick the one you already think in.': 'RIR 数的是你还留了几次;RPE 把同样的吃力程度换成 10 分制来读——所以 RPE ≈ 10 − RIR。选你习惯的那一种。',
|
||||
'The highlighted row is where most working sets land. Sets you have already logged keep their own scale, and nothing else reads the value — progression and estimated 1RM are unaffected.': '高亮那一行是大多数正式组落在的位置。已经记录的组保留原来的标度,而且这个值不会被别处读取——进阶计划和预估 1RM 都不受影响。',
|
||||
// --- effort in the stats ---
|
||||
'Effort': '强度',
|
||||
'how close to failure': '离力竭有多近',
|
||||
'by hard sets': '按硬组',
|
||||
'Hard': '硬组',
|
||||
'no hard sets': '没有硬组',
|
||||
'No hard sets in this period': '此期间没有硬组',
|
||||
'Every muscle group got at least one hard set in this period.': '此期间每个肌群都至少练了一个硬组。',
|
||||
'No rated sets in this period.': '此期间没有已评分的组。',
|
||||
'average effort': '平均强度',
|
||||
'at {0} {1} or harder': '{0} {1} 或更硬',
|
||||
'{0} of {1} finished sets rated': '{1} 个已完成组中有 {0} 个已评分',
|
||||
'Effort per set is switched off — turn it on in Settings to keep rating.': '每组强度已关闭——在设置中打开即可继续评分。',
|
||||
'Week by week': '逐周变化',
|
||||
'Where the sets land': '组都落在哪里',
|
||||
'Most working sets belong close to failure without living there — half at the floor and half at the top average out to a healthy-looking middle.': '大多数正式组应该接近力竭,但不要一直待在那里——一半在最底、一半在最顶,平均下来只是看着健康。',
|
||||
'Average effort per workout': '每次训练的平均强度',
|
||||
'A fuller dot means less left in the tank — the same weight at a lower {0} is progress the line alone does not show.': '点越实,油箱里剩得越少——同样的重量配上更低的 {0},是曲线本身看不出的进步。',
|
||||
|
||||
// --- bodyweight & per side ---
|
||||
'Bodyweight': '徒手动作',
|
||||
'No weight to enter — just log the reps.': '无需输入重量——只记录次数。',
|
||||
'Ask for a weight on every set.': '每组都询问重量。',
|
||||
'For dips or pull-ups with a belt. Progression then follows the weight.': '用于系负重腰带做双杠臂屈伸或引体向上。此时进阶方式跟随重量。',
|
||||
'Reps per side': '每侧次数',
|
||||
'For lunges, single-arm rows and the like.': '用于弓步蹲、单臂划船之类的动作。',
|
||||
'Top of the range': '次数上限',
|
||||
'Reps climb by one whenever every set was clean. Set a ceiling to add sets instead of reps forever.': '每组都做干净,次数就加一。设置上限后,达到上限会加一组,而不是一直加次数。',
|
||||
'Reps climb to {0}, then a set is added and the reps start over. At {1} sets it asks you to add weight instead.': '次数升到 {0} 后加一组,次数重新开始。到 {1} 组时会改为提示你加重量。',
|
||||
'Added ({0})': '负重({0})',
|
||||
'{0}/side': '{0}/侧',
|
||||
'{0} reps in every set — add a set and go back to {1}.': '每组都做到 {0} 次——加一组,次数回到 {1}。',
|
||||
'{0} sets of {1} — time to add weight or move to a harder variation.': '{0} 组 × {1} 次——该加重量或换更难的变式了。',
|
||||
'{0} per side': '每侧 {0} 次',
|
||||
'You still log the total: {0} is {1} per side.': '你记录的仍然是总数:{0} 表示每侧 {1} 次。',
|
||||
'{0} sets · {1} work': '{0} 组 · {1} 工作',
|
||||
'Make superset with previous': '与上一个组成超级组',
|
||||
'Make superset with next': '与下一个组成超级组',
|
||||
'primary': '主要',
|
||||
'secondary': '次要',
|
||||
'No exercises with an estimated 1RM yet.': '暂无估算1RM的动作。',
|
||||
'Tap a muscle to see its exercises.': '点击肌肉查看其动作。',
|
||||
'Unpair': '取消组合'
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { useStore } from './store/useStore.js'
|
||||
import { useUI } from './store/useUI.js'
|
||||
import { EXDB, EXIDX, BODYPARTS, isCardio, allExercises, equipmentOf } from './lib/exercises.js'
|
||||
import { EXDB, EXIDX, BODYPARTS, isCardio, isBodyweightEq, allExercises, equipmentOf, smOf } from './lib/exercises.js'
|
||||
import { fmtDate, fmtNum, fmtVol, fmtDur, durPart, todayISO, uid, exCount, DAYN, MONTHS_LONG, ACCENTS } from './lib/format.js'
|
||||
import { lastEntryFor, bestWeightFor, buildSets, effectiveRoutineId, workoutVolume, setsDone, setsDoneActive, lastBW, supersetUnits, unitOf, setLabel, defaultConfig, cleanupSg, modeOf, effortOf } from './lib/history.js'
|
||||
import { lastEntryFor, bestWeightFor, buildSets, effectiveRoutineId, workoutVolume, setsDone, setsDoneActive, lastBW, supersetUnits, unitOf, setLabel, defaultConfig, cleanupSg, modeOf, effortOf, isBw, isPerSide, sideReps, workSetsDone } from './lib/history.js'
|
||||
import { beep, vibrate } from './lib/sound.js'
|
||||
import { t, instrFor, getLang, INSTR_LANGS } from './lib/i18n.js'
|
||||
import { nav } from './lib/nav.js'
|
||||
@@ -11,15 +11,17 @@ import { starterRoutines } from './lib/starter.js'
|
||||
import Media, { Thumb } from './components/Media.jsx'
|
||||
import Stepper from './components/Stepper.jsx'
|
||||
import Icon from './components/Icon.jsx'
|
||||
import { Button, Slider, Switch, Segmented, SelectRow } from './components/ui.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 } from './lib/progression.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)
|
||||
@@ -291,7 +293,7 @@ function ExerciseDetail({ ex, close }) {
|
||||
<span className="tag acc">{t(ex.bp)}</span>
|
||||
{ex.tg && <span className="tag"><Icon name="target" />{t(ex.tg)}</span>}
|
||||
<span className="tag"><Icon name="dumbbell" />{t(ex.eq)}</span>
|
||||
{(ex.sm || []).slice(0, 3).map((s, i) => <span key={i} className="tag">{t(s)}</span>)}
|
||||
{smOf(ex).slice(0, 3).map((s, i) => <span key={i} className="tag">{t(s)}</span>)}
|
||||
</div>
|
||||
{ex.desc && <div className="exnote">{ex.desc}</div>}
|
||||
{best > 0 && <div className="small row" style={{ marginBottom: 6, gap: 5 }}><Icon name="trophy" style={{ fontSize: 14, color: 'var(--yellow)' }} />{t('Best:')} <b className="accent">{fmtNum(best)} {st.unit}</b>{last ? ` · ${t('last')} ${fmtDate(last.d)}: ${last.sets.map(s => setLabel(ex.id, s, last.target)).join(', ')}` : ''}</div>}
|
||||
@@ -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'))
|
||||
@@ -482,13 +489,16 @@ function ProgressionFields({ ex, mode, c, setC, routine, unit }) {
|
||||
</>
|
||||
}
|
||||
|
||||
function ExConfig({ ex, existing, onSave, onDelete, close, routine }) {
|
||||
function ExConfig({ ex, existing, onSave, onDelete, close, routine, initial }) {
|
||||
const st = useStore(s => s.S)
|
||||
const cardio = isCardio(ex.id)
|
||||
const [c, setC] = useState(existing || defaultConfig(ex.id))
|
||||
const [c, setC] = useState(existing || initial || defaultConfig(ex.id))
|
||||
// Cardio keeps its own duration+speed form; the reps/time choice (issue #16) is offered for
|
||||
// everything else, which is where the gap was — planks, hangs, wall sits, loaded carries.
|
||||
const mode = cardio ? 'cardio' : modeOf({ ...c, id: ex.id })
|
||||
// Both default from the dataset and are then whatever the config says — see isBw.
|
||||
const bw = !cardio && isBw({ ...c, id: ex.id })
|
||||
const perSide = isPerSide(c)
|
||||
// Keep whatever the other mode already had (sets, weight) and fill only what is missing.
|
||||
const setMode = m => setC(x => ({ ...defaultConfig(ex.id, m), ...x, mode: m }))
|
||||
const save = () => {
|
||||
@@ -499,12 +509,24 @@ function ExConfig({ ex, existing, onSave, onDelete, close, routine }) {
|
||||
const prog = {}
|
||||
if (c.prog) prog.prog = c.prog
|
||||
if (c.inc > 0) prog.inc = c.inc
|
||||
// Written only when it differs from what the dataset already says, so a barbell config
|
||||
// stays exactly the shape it was before these flags existed.
|
||||
// `bodyweight` is true of a hold as much as of a set of reps; `side` is not — it counts
|
||||
// reps, and a timed hold has none. Switching an exercise to Time therefore drops it
|
||||
// rather than carrying a flag nothing downstream can read.
|
||||
const flags = {}
|
||||
if (bw !== isBodyweightEq(ex.id)) flags.bodyweight = bw
|
||||
if (cardio) onSave({ sets, min: Math.max(1, Math.round(c.min) || 20), speed: Math.max(0, c.speed || 8) })
|
||||
else if (mode === 'time') onSave({ sets, mode: 'time', sec: Math.max(1, Math.round(c.sec) || 45), weight: Math.max(0, c.weight || 0), ...prog })
|
||||
else if (mode === 'time') onSave({ sets, mode: 'time', sec: Math.max(1, Math.round(c.sec) || 45), weight: Math.max(0, c.weight || 0), ...flags, ...prog })
|
||||
else {
|
||||
const reps = Math.max(1, Math.round(c.reps) || 10)
|
||||
const out = { sets, mode: 'reps', reps, weight: Math.max(0, c.weight || 0), ...prog }
|
||||
// A unilateral target is stored even: the split has to divide, and a typed 15 would
|
||||
// otherwise plan seven reps on one side and eight on the other, every session.
|
||||
const typed = Math.max(1, Math.round(c.reps) || 10)
|
||||
const reps = perSide ? Math.ceil(typed / 2) * 2 : typed
|
||||
const out = { sets, mode: 'reps', reps, weight: Math.max(0, c.weight || 0), ...flags, ...(perSide ? { side: true } : {}), ...prog }
|
||||
if (policyFor({ ...c, id: ex.id }, routine, 'reps') === 'double') out.repsMin = Math.min(reps, Math.max(1, Math.round(c.repsMin) || Math.max(1, reps - 2)))
|
||||
// A ceiling below the working reps would tell you to add a set on day one.
|
||||
if (bw && !(out.weight > 0) && c.repsMax > 0) out.repsMax = Math.max(reps, Math.round(c.repsMax))
|
||||
onSave(out)
|
||||
}
|
||||
}
|
||||
@@ -531,20 +553,57 @@ function ExConfig({ ex, existing, onSave, onDelete, close, routine }) {
|
||||
<Stepper label={t('Weight ({0})', st.unit)} value={c.weight} step={2.5} onChange={v => setC(x => ({ ...x, weight: v }))} />
|
||||
</> : <>
|
||||
<Stepper label={t('Sets')} value={c.sets} step={1} decimal={false} onChange={v => setC(x => ({ ...x, sets: v }))} />
|
||||
<Stepper label={t('Reps')} value={c.reps} step={1} decimal={false} onChange={v => setC(x => ({ ...x, reps: v }))} />
|
||||
<Stepper label={t('Weight ({0})', st.unit)} value={c.weight} step={2.5} onChange={v => setC(x => ({ ...x, weight: v }))} />
|
||||
<Stepper label={t('Reps')} value={c.reps} step={perSide ? 2 : 1} decimal={false} onChange={v => setC(x => ({ ...x, reps: v }))} />
|
||||
{/* On bodyweight work the weight stepper is the click #32 is about, so it is not here
|
||||
until there is a belt to describe — see the added-weight row below. */}
|
||||
{!bw && <Stepper label={t('Weight ({0})', st.unit)} value={c.weight} step={2.5} onChange={v => setC(x => ({ ...x, weight: v }))} />}
|
||||
</>}
|
||||
</div>
|
||||
{mode === 'time' && <div className="small dim" style={{ marginBottom: 18 }}>
|
||||
{mode === 'time' && !bw && <div className="small dim" style={{ marginBottom: 18 }}>
|
||||
{t('A timer runs while you hold the set. Leave the weight at 0 for bodyweight holds.')}
|
||||
</div>}
|
||||
{/* ---------- bodyweight + per side (issues #31/#32/#33) ---------- */}
|
||||
{!cardio && <div className="sect-b" style={{ marginBottom: 8 }}>
|
||||
<Row icon="figureStrength" iconTint="var(--acc)" title={t('Bodyweight')}
|
||||
subtitle={bw ? t('No weight to enter — just log the reps.') : t('Ask for a weight on every set.')}>
|
||||
<Switch checked={bw} onChange={v => setC(x => ({ ...x, bodyweight: v, weight: v ? 0 : x.weight }))} />
|
||||
</Row>
|
||||
{mode === 'reps' && <Row icon="shuffle" iconTint="var(--blue)" title={t('Reps per side')}
|
||||
subtitle={perSide ? t('You still log the total: {0} is {1} per side.', c.reps || 0, fmtNum(sideReps(c.reps))) : t('For lunges, single-arm rows and the like.')}>
|
||||
{/* Turning it on rounds the target up to an even number, since half of an odd
|
||||
total is a rep one side does not get. */}
|
||||
<Switch checked={perSide} onChange={v => setC(x => ({ ...x, side: v || undefined, reps: v ? Math.ceil((x.reps || 0) / 2) * 2 : x.reps }))} />
|
||||
</Row>}
|
||||
</div>}
|
||||
{/* A stepper is too wide to sit in a list row next to a label — it squeezes the text to
|
||||
one word per line — so added weight gets the same full-width treatment as sets and
|
||||
reps, with its explanation underneath. */}
|
||||
{bw && <>
|
||||
<div className="row cfgrow" style={{ marginBottom: 8 }}>
|
||||
<Stepper label={t('Added ({0})', st.unit)} value={c.weight || 0} step={2.5}
|
||||
onChange={v => setC(x => ({ ...x, weight: v }))} />
|
||||
</div>
|
||||
<div className="small dim" style={{ marginBottom: 18 }}>
|
||||
{t('For dips or pull-ups with a belt. Progression then follows the weight.')}
|
||||
</div>
|
||||
</>}
|
||||
{/* The rep ceiling only means something when there is no load to add instead. */}
|
||||
{mode === 'reps' && bw && !(c.weight > 0) && <div className="row cfgrow" style={{ marginBottom: 18 }}>
|
||||
<Stepper label={t('Top of the range')} value={c.repsMax || 0} step={1} decimal={false}
|
||||
onChange={v => setC(x => ({ ...x, repsMax: v }))} />
|
||||
</div>}
|
||||
{mode === 'reps' && bw && !(c.weight > 0) && <div className="small dim" style={{ marginTop: -10, marginBottom: 18 }}>
|
||||
{c.repsMax > 0
|
||||
? t('Reps climb to {0}, then a set is added and the reps start over. At {1} sets it asks you to add weight instead.', c.repsMax, MAX_BW_SETS)
|
||||
: t('Reps climb by one whenever every set was clean. Set a ceiling to add sets instead of reps forever.')}
|
||||
</div>}
|
||||
<ProgressionFields ex={ex} mode={mode} c={c} setC={setC} routine={routine} unit={st.unit} />
|
||||
<Button variant="primary" onClick={save}>{existing ? t('Save') : t('Add to routine')}</Button>
|
||||
{ex.custom && <><div style={{ height: 8 }} /><Button icon="pencil" onClick={() => { close(); customExSheet(ex) }}>{t('Edit or delete this exercise')}</Button></>}
|
||||
{onDelete && <><div style={{ height: 8 }} /><Button variant="danger" onClick={() => { close(); onDelete() }}>{t('Remove from routine')}</Button></>}
|
||||
</>
|
||||
}
|
||||
export const exConfigSheet = (ex, existing, onSave, onDelete, routine) => ui().openSheet(close => <ExConfig ex={ex} existing={existing} onSave={onSave} onDelete={onDelete} routine={routine} close={close} />)
|
||||
export const exConfigSheet = (ex, existing, onSave, onDelete, routine, initial) => ui().openSheet(close => <ExConfig ex={ex} existing={existing} initial={initial} onSave={onSave} onDelete={onDelete} routine={routine} close={close} />)
|
||||
|
||||
/* ============================ glyph picker ============================ */
|
||||
// Grouped by what the glyph means for a training day, so picking one is a scan
|
||||
@@ -797,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])
|
||||
@@ -858,7 +917,7 @@ function FinishSummary({ w, prs, e1prs = [], close }) {
|
||||
<div className="tiles" style={{ textAlign: 'left' }}>
|
||||
<div className="tile"><div className="l">{t('Duration')}</div><div className="v" style={{ fontSize: '1.1rem' }}>{fmtDur(w.end - w.start)}</div></div>
|
||||
<div className="tile"><div className="l">{t('Volume')}</div><div className="v" style={{ fontSize: '1.1rem' }}>{fmtVol(w.vol, st.unit)}</div></div>
|
||||
<div className="tile"><div className="l">{t('Sets')}</div><div className="v" style={{ fontSize: '1.1rem' }}>{setsDone(w)}</div></div>
|
||||
<div className="tile"><div className="l">{t('Sets')}</div><div className="v" style={{ fontSize: '1.1rem' }}>{t('{0} sets · {1} work', setsDone(w), workSetsDone(w))}</div></div>
|
||||
<div className="tile"><div className="l">{t('PRs')}</div><div className="v" style={{ fontSize: 20 }}>{prs.length || '—'}</div></div>
|
||||
</div>
|
||||
{(prs.length > 0 || e1prs.length > 0) && <div style={{ textAlign: 'left', marginBottom: 12 }}>
|
||||
@@ -887,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)
|
||||
|
||||
@@ -3,6 +3,7 @@ import { api } from '../lib/api.js'
|
||||
import { localTZ } from '../lib/format.js'
|
||||
import { registerCustom } from '../lib/exercises.js'
|
||||
import { DEMO, DEMO_SEEDED } from '../lib/demo.js'
|
||||
import { guestAllowed } from '../lib/guest.js'
|
||||
import { MOBILE, nativeLoad, nativeSave, syncReminder } from '../lib/mobile.js'
|
||||
|
||||
const KEY = 'gym_state_v1'
|
||||
@@ -70,6 +71,15 @@ export const useStore = create((set, get) => {
|
||||
}
|
||||
})
|
||||
|
||||
// Everything a sign-out leaves behind on this device, whichever way it was triggered.
|
||||
const clearLocalSession = () => {
|
||||
get().setUser(null)
|
||||
localStorage.removeItem('gym_guest')
|
||||
localStorage.removeItem('gym_dirty')
|
||||
localStorage.removeItem(KEY)
|
||||
persist(clone(DEF), false)
|
||||
}
|
||||
|
||||
return {
|
||||
S: (() => { const s = loadState(); registerCustom(s.customEx); return s })(),
|
||||
user: (() => { try { return JSON.parse(localStorage.getItem('gym_user')) || null } catch { return null } })(),
|
||||
@@ -86,6 +96,16 @@ export const useStore = create((set, get) => {
|
||||
isGuest: () => localStorage.getItem('gym_guest') === '1',
|
||||
setGuest(v) { if (v) localStorage.setItem('gym_guest', '1'); else localStorage.removeItem('gym_guest'); set({}) },
|
||||
|
||||
// Public config from /api/config (invite_only, allow_guest). null until the first successful
|
||||
// fetch — the login screen and boot both read it, so it is fetched once and cached here
|
||||
// rather than by each screen that happens to need it.
|
||||
config: null,
|
||||
async loadConfig() {
|
||||
if (get().config) return get().config
|
||||
try { const c = await api('/api/config'); set({ config: c }); return c }
|
||||
catch { return null }
|
||||
},
|
||||
|
||||
setUser(u) {
|
||||
if (u) { localStorage.setItem('gym_user', JSON.stringify(u)); localStorage.removeItem('gym_guest') }
|
||||
else localStorage.removeItem('gym_user')
|
||||
@@ -114,11 +134,18 @@ export const useStore = create((set, get) => {
|
||||
|
||||
async signOut() {
|
||||
try { await get().pushState(); await api('/api/logout', { method: 'POST', body: '{}' }) } catch (e) { /* */ }
|
||||
get().setUser(null)
|
||||
localStorage.removeItem('gym_guest')
|
||||
localStorage.removeItem('gym_dirty')
|
||||
localStorage.removeItem(KEY)
|
||||
persist(clone(DEF), false)
|
||||
clearLocalSession()
|
||||
},
|
||||
|
||||
// "Sign out everywhere": the server bumps this profile's session version, which kills every
|
||||
// session it has on any device — this browser included, so the app has to end up exactly
|
||||
// where a normal signOut leaves it. Unlike signOut the request is NOT swallowed: if it fails
|
||||
// the sessions elsewhere are all still valid, and wiping this device's copy of the data
|
||||
// would sign the user out of the one place the bump didn't reach. Caller reports the error.
|
||||
async signOutAll() {
|
||||
await get().pushState() // never throws — stores gym_dirty and moves on when offline
|
||||
await api('/api/logout/all', { method: 'POST', body: '{}' })
|
||||
clearLocalSession()
|
||||
},
|
||||
|
||||
// Demo build only: drop the seeded example profile back in (Settings → "Reset demo data").
|
||||
@@ -156,6 +183,12 @@ export const useStore = create((set, get) => {
|
||||
set({ ready: true })
|
||||
return
|
||||
}
|
||||
// Guests never authenticate, so an instance that turned guest mode off has no request to
|
||||
// refuse — the only way the switch reaches someone already inside is here, on their next
|
||||
// boot. Ending the session needs a positive `allow_guest: false`; see lib/guest.js for why
|
||||
// an unreachable server must not be allowed to lock anyone out (#42).
|
||||
const cfg = await get().loadConfig()
|
||||
if (!guestAllowed(cfg)) get().setGuest(false)
|
||||
try {
|
||||
const me = await api('/api/me')
|
||||
get().setUser(me.user)
|
||||
|
||||
@@ -10,6 +10,42 @@ import { useStore } from './useStore.js'
|
||||
const pushRestTimer = sec => { if (useStore.getState().user) api('/api/push/rest-timer', { method: 'POST', body: JSON.stringify({ seconds: sec }) }).catch(() => {}) }
|
||||
const cancelPushRestTimer = () => { if (useStore.getState().user) api('/api/push/rest-timer/cancel', { method: 'POST', body: '{}' }).catch(() => {}) }
|
||||
|
||||
const notificationsSupported = () => typeof window !== 'undefined' && 'Notification' in window
|
||||
let requestRestNotificationPermissionP = null
|
||||
|
||||
const requestRestNotificationPermission = async () => {
|
||||
if (!notificationsSupported()) return false
|
||||
if (Notification.permission === 'granted') return true
|
||||
if (Notification.permission === 'denied') return false
|
||||
if (!requestRestNotificationPermissionP) {
|
||||
requestRestNotificationPermissionP = Notification.requestPermission()
|
||||
.then(perm => perm === 'granted')
|
||||
.catch(() => false)
|
||||
.finally(() => {
|
||||
requestRestNotificationPermissionP = null
|
||||
})
|
||||
}
|
||||
return requestRestNotificationPermissionP
|
||||
}
|
||||
|
||||
const maybeRestNotification = async () => {
|
||||
if (!notificationsSupported()) return
|
||||
if (!document.hidden && document.visibilityState !== 'hidden') return
|
||||
if (Notification.permission !== 'granted' && !(await requestRestNotificationPermission())) return
|
||||
try {
|
||||
// Android Chrome forbids the Notification constructor (Illegal constructor) - the
|
||||
// service-worker registration path is the one that actually pops there.
|
||||
const reg = await navigator.serviceWorker?.getRegistration?.()
|
||||
if (reg?.showNotification) {
|
||||
reg.showNotification(t('Rest over — next set!'), { body: t('Rest over — next set!') })
|
||||
return
|
||||
}
|
||||
new Notification(t('Rest over — next set!'), { body: t('Rest over — next set!') })
|
||||
} catch {
|
||||
// Intentionally ignore: notification APIs vary by browser and policy in edge cases.
|
||||
}
|
||||
}
|
||||
|
||||
let toastTm = null
|
||||
let timerInt = null
|
||||
let timerTick = null
|
||||
@@ -42,6 +78,7 @@ export const useUI = create((set, get) => ({
|
||||
get().stopRest()
|
||||
const endsAt = Date.now() + sec * 1000
|
||||
set({ timer: { left: sec, total: sec, endsAt } })
|
||||
requestRestNotificationPermission()
|
||||
pushRestTimer(sec)
|
||||
timerTick = () => {
|
||||
const tm = get().timer
|
||||
@@ -51,7 +88,7 @@ export const useUI = create((set, get) => ({
|
||||
const snd = useStore.getState().S.sound
|
||||
if (left <= 0) {
|
||||
beep(snd, 880, 0.15); beep(snd, 880, 0.15, 0.25); beep(snd, 1320, 0.4, 0.5)
|
||||
vibrate([200, 100, 200]); get().toast(t('Rest over — next set!')); get().stopRest(); return
|
||||
vibrate([200, 100, 200]); maybeRestNotification(); get().toast(t('Rest over — next set!')); get().stopRest(); return
|
||||
}
|
||||
if (left <= 3) beep(snd, 660, 0.1)
|
||||
set({ timer: { ...tm, left } })
|
||||
|
||||
@@ -1,21 +1,25 @@
|
||||
import { useStore } from '../store/useStore.js'
|
||||
import { useUI } from '../store/useUI.js'
|
||||
import { webauthnOK, passkeyLogin, passkeyRegister, api, BIO } from '../lib/api.js'
|
||||
import { webauthnOK, passkeyLogin, passkeyRegister, BIO } from '../lib/api.js'
|
||||
import { hasData } from '../store/useStore.js'
|
||||
import { t } from '../lib/i18n.js'
|
||||
import { DEMO, REPO } from '../lib/demo.js'
|
||||
import { guestAllowed } from '../lib/guest.js'
|
||||
import { useState, useRef, useEffect } from 'react'
|
||||
import Icon from '../components/Icon.jsx'
|
||||
import { Button } from '../components/ui.jsx'
|
||||
|
||||
function RegisterSheet({ close }) {
|
||||
const { setUser, pushState, pullState } = useStore()
|
||||
const { setUser, pushState, pullState, loadConfig } = useStore()
|
||||
const config = useStore(s => s.config)
|
||||
const [name, setName] = useState('')
|
||||
const [code, setCode] = useState('')
|
||||
const [inviteOnly, setInviteOnly] = useState(false)
|
||||
const inviteOnly = !!config?.invite_only
|
||||
const ref = useRef(null)
|
||||
useEffect(() => { setTimeout(() => ref.current?.focus(), 250) }, [])
|
||||
useEffect(() => { api('/api/config').then(c => setInviteOnly(!!c.invite_only)).catch(() => {}) }, [])
|
||||
// Boot already fetched this; retry here only if that attempt failed, so the invite field still
|
||||
// appears on an instance whose config arrived late rather than never.
|
||||
useEffect(() => { loadConfig() }, [loadConfig])
|
||||
const go = async () => {
|
||||
const n = name.trim()
|
||||
if (!n) { useUI.getState().toast(t('Enter a name')); return }
|
||||
@@ -44,6 +48,8 @@ function RegisterSheet({ close }) {
|
||||
|
||||
export default function Login() {
|
||||
const { setUser, pullState, setGuest } = useStore()
|
||||
const config = useStore(s => s.config)
|
||||
const canGuest = guestAllowed(config)
|
||||
const signIn = async () => {
|
||||
try { const u = await passkeyLogin(); setUser(u); await pullState(); useUI.getState().toast(t('Welcome back, {0}', u.name)) }
|
||||
catch (e) { if (e.name !== 'NotAllowedError' && e.name !== 'AbortError') useUI.getState().toast(e.message || t('Sign-in failed')) }
|
||||
@@ -77,9 +83,13 @@ export default function Login() {
|
||||
<Button variant="primary" icon="person" onClick={signIn}>{t('Sign in with passkey')}</Button>
|
||||
<div style={{ height: 10 }} />
|
||||
<Button icon="sparkles" onClick={() => useUI.getState().openSheet(close => <RegisterSheet close={close} />)}>{t('Create new profile')}</Button>
|
||||
<div style={{ height: 10 }} />
|
||||
</> : <div className="card small muted" style={{ textAlign: 'left' }}>{t("This browser doesn't support passkeys — you can still use openGym locally on this device.")}</div>}
|
||||
<Button variant="ghost" className="dim" onClick={() => setGuest(true)}>{t('Continue without account')}</Button>
|
||||
{canGuest && <div style={{ height: 10 }} />}
|
||||
</> : <div className="card small muted" style={{ textAlign: 'left' }}>{canGuest
|
||||
? t("This browser doesn't support passkeys — you can still use openGym locally on this device.")
|
||||
// Without passkeys and without the guest entrance there is no way in from this browser,
|
||||
// so say that plainly instead of offering a local profile that cannot be created.
|
||||
: t("This browser doesn't support passkeys, and this instance requires an account. Try a browser or device with passkey support.")}</div>}
|
||||
{canGuest && <Button variant="ghost" className="dim" onClick={() => setGuest(true)}>{t('Continue without account')}</Button>}
|
||||
<div className="dim small" style={{ marginTop: 26, lineHeight: 1.5 }}>{t('Passkeys use {0} — no passwords.', BIO)}<br />{t('Each profile keeps its own plan, workouts & body weight.')}</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -4,7 +4,7 @@ import { useStore, DEF, hasData } from '../store/useStore.js'
|
||||
import { useUI } from '../store/useUI.js'
|
||||
import { ACCENTS, todayISO, localTZ } from '../lib/format.js'
|
||||
import { effortOf } from '../lib/history.js'
|
||||
import { webauthnOK, passkeyLogin, passkeyRegister, IS_ANDROID } from '../lib/api.js'
|
||||
import { api, webauthnOK, passkeyLogin, passkeyRegister, IS_ANDROID } from '../lib/api.js'
|
||||
import { pushSupported, enablePush, disablePush, sendTestPush } from '../lib/push.js'
|
||||
import { wakeLockSupported } from '../lib/wakelock.js'
|
||||
import { t, LANGS, INSTR_LANGS } from '../lib/i18n.js'
|
||||
@@ -18,7 +18,7 @@ export default function Settings() {
|
||||
const nav = useNavigate()
|
||||
const S = useStore(s => s.S)
|
||||
const user = useStore(s => s.user)
|
||||
const { update, replaceState, setUser, pullState, pushState, signOut, resetDemo } = useStore()
|
||||
const { update, replaceState, setUser, pullState, pushState, signOut, signOutAll, resetDemo } = useStore()
|
||||
const toast = useUI(s => s.toast)
|
||||
const fileRef = useRef(null)
|
||||
const importRef = useRef(null)
|
||||
@@ -53,6 +53,18 @@ export default function Settings() {
|
||||
catch (e) { if (e.name !== 'NotAllowedError' && e.name !== 'AbortError') toast(e.message || t('Sign-in failed')) }
|
||||
}
|
||||
const registerHere = () => useUI.getState().openSheet(close => <RegisterInline close={close} setUser={setUser} pushState={pushState} pullState={pullState} toast={toast} />)
|
||||
// Ends the profile's sessions on every device — this one included, so on success it lands in
|
||||
// the same place as the plain sign-out above (home, local data cleared). On failure nothing
|
||||
// local is touched: still signed in here, and say so rather than leaving a half-signed-out app.
|
||||
const signOutEverywhere = () => confirmSheet({
|
||||
title: t('Sign out everywhere?'),
|
||||
message: t('Signs this profile out on every device, including this one. Your passkeys keep working — sign in with them again anytime.'),
|
||||
confirmText: t('Sign out everywhere'), danger: true,
|
||||
onConfirm: async () => {
|
||||
try { await signOutAll(); nav('/home'); toast(t('Signed out on all devices')) }
|
||||
catch (e) { toast(t('Could not sign out everywhere — you are still signed in.')) }
|
||||
},
|
||||
})
|
||||
|
||||
return <div className="narrow">
|
||||
<div className="hdr">
|
||||
@@ -76,6 +88,7 @@ export default function Settings() {
|
||||
<Row icon="personCircle" iconTint="var(--grey)" title={user.name} subtitle={t('Signed in with passkey — data syncs to this profile.')} />
|
||||
{user.admin && <Row icon="wrench" iconTint="var(--indigo)" title={t('Admin dashboard')} accessory="chevron" onClick={() => nav('/admin')} />}
|
||||
<Row icon="signOut" iconTint="var(--red)" title={t('Sign out')} danger onClick={() => confirmSheet({ title: t('Sign out?'), message: t('Your data is synced to your profile first, then cleared from this device.'), confirmText: t('Sign out'), danger: true, onConfirm: () => { signOut(); nav('/home') } })} />
|
||||
<Row icon="shield" iconTint="var(--red)" title={t('Sign out everywhere')} subtitle={t('Ends this profile’s sessions on all your devices.')} danger onClick={signOutEverywhere} />
|
||||
</> : webauthnOK() ? <>
|
||||
<Row icon="sparkles" iconTint="var(--acc)" title={t('Create passkey profile')} subtitle={t('Keeps your data safe and separate per person.')} accessory="chevron" onClick={registerHere} />
|
||||
<Row icon="person" iconTint="var(--blue)" title={t('Sign in with passkey')} accessory="chevron" onClick={signInHere} />
|
||||
@@ -183,7 +196,8 @@ export default function Settings() {
|
||||
|
||||
<div className="dim small" style={{ textAlign: 'center', marginTop: 4, lineHeight: 1.6 }}>
|
||||
openGym · {t('free & open source (AGPL v3)')}<br />
|
||||
<a href="https://github.com/DuarteSantos8/openGym" target="_blank" rel="noopener">source code</a> · exercise data: hasaneyldrm/exercises-dataset (CC)
|
||||
<a href="https://gitea.com/DuarteSantos/openGym" target="_blank" rel="noopener">source code</a> · exercise data: hasaneyldrm/exercises-dataset (MIT)<br />
|
||||
exercise images and animations © <a href="https://gymvisual.com/" target="_blank" rel="noopener">Gym visual</a>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
@@ -314,13 +328,20 @@ function PushCard({ S, update, toast }) {
|
||||
</>
|
||||
}
|
||||
|
||||
// The same registration as the sign-in screen's, reached from Settings instead. It asks for
|
||||
// the invite code on the same terms: an invite-only instance rejects a registration without
|
||||
// one, so a form that cannot collect it is a form that cannot succeed.
|
||||
function RegisterInline({ close, setUser, pushState, pullState, toast }) {
|
||||
const nameRef = useRef(null)
|
||||
const [code, setCode] = useState('')
|
||||
const [inviteOnly, setInviteOnly] = useState(false)
|
||||
useEffect(() => { api('/api/config').then(c => setInviteOnly(!!c.invite_only)).catch(() => {}) }, [])
|
||||
const go = async () => {
|
||||
const n = (nameRef.current.value || '').trim()
|
||||
if (!n) { toast(t('Enter a name')); return }
|
||||
if (inviteOnly && !code.trim()) { toast(t('An invite code is required')); return }
|
||||
try {
|
||||
const u = await passkeyRegister(n); setUser(u); close()
|
||||
const u = await passkeyRegister(n, code.trim()); setUser(u); close()
|
||||
if (hasData(useStore.getState().S)) { await pushState(); toast(t('Profile created — data moved into it')) }
|
||||
else { await pullState(); toast(t('Welcome, {0}', u.name)) }
|
||||
} catch (e) { if (e.name !== 'NotAllowedError' && e.name !== 'AbortError') toast(e.message || t('Registration failed')) }
|
||||
@@ -329,6 +350,12 @@ function RegisterInline({ close, setUser, pushState, pullState, toast }) {
|
||||
<h3>{t('Create your profile')}</h3>
|
||||
<div className="muted small" style={{ marginBottom: 14 }}>{t('Pick a name, then confirm with your device.')}</div>
|
||||
<TextField ref={nameRef} placeholder={t('Your name')} maxLength={40} />
|
||||
{inviteOnly && <>
|
||||
<div style={{ height: 10 }} />
|
||||
<input className="input" placeholder={t('Invite code')} maxLength={40} value={code}
|
||||
onChange={e => setCode(e.target.value.toUpperCase())} style={{ letterSpacing: '.14em', fontWeight: 600, textAlign: 'center' }} />
|
||||
<div className="dim small" style={{ marginTop: 6 }}>{t('This app is invite-only — enter the code you were given.')}</div>
|
||||
</>}
|
||||
<div style={{ height: 12 }} /><Button variant="primary" onClick={go}>{t('Create passkey')}</Button>
|
||||
</>
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
import { useState } from 'react'
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useStore } from '../store/useStore.js'
|
||||
import { EXIDX } from '../lib/exercises.js'
|
||||
import { lastBW, streakWeeks, setLabel, modeOf } 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'
|
||||
@@ -10,50 +10,265 @@ import LineChart from '../components/LineChart.jsx'
|
||||
import Heatmap from '../components/Heatmap.jsx'
|
||||
import Icon from '../components/Icon.jsx'
|
||||
import BodyMap, { BodyMapLegend } from '../components/BodyMap.jsx'
|
||||
import { loadOfWorkouts, rankOf, MUSCLE_NAME } from '../lib/muscles.js'
|
||||
import { loadOfWorkouts, rankOf, MUSCLE_NAME, musclesOf } from '../lib/muscles.js'
|
||||
import { fatigueOf, strengthOf, STRENGTH_FLOOR, 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 {
|
||||
hasEffort, displayScale, scaleName, toScale, avgRir, effortSummary, effortWeeks,
|
||||
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).
|
||||
function latestMuscleTraining(workouts) {
|
||||
const latest = {}
|
||||
for (const workout of workouts || []) {
|
||||
const timestamp = Number(workout?.start || new Date(workout?.d).getTime())
|
||||
if (!Number.isFinite(timestamp)) continue
|
||||
for (const entry of workout.entries || []) {
|
||||
if (!(entry.sets || []).some(set => set?.done === true && !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
|
||||
}
|
||||
}
|
||||
}
|
||||
return latest
|
||||
}
|
||||
|
||||
export const FATIGUE_LEVELS = [
|
||||
{ at: 0, level: 0 },
|
||||
{ at: 0.15, level: 1 },
|
||||
{ at: 0.25, level: 2 },
|
||||
{ at: 0.4, level: 3 },
|
||||
{ at: 0.55, level: 4, exclusive: true },
|
||||
]
|
||||
|
||||
export const STRENGTH_LEVELS = [
|
||||
{ at: STRENGTH_FLOOR, level: 0 },
|
||||
{ at: 0.625, level: 1 },
|
||||
{ at: 0.75, level: 2 },
|
||||
{ at: 0.875, level: 3 },
|
||||
{ at: 1, level: 4 },
|
||||
]
|
||||
|
||||
function useNow() {
|
||||
const [, setTick] = useState(0)
|
||||
useEffect(() => {
|
||||
const iv = setInterval(() => setTick(tick => tick + 1), 60000)
|
||||
return () => clearInterval(iv)
|
||||
}, [])
|
||||
return Date.now()
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the whole weeks since a completed muscle-training timestamp.
|
||||
*
|
||||
* @param {number} now Current render-time timestamp in milliseconds.
|
||||
* @param {number} lastTrained Timestamp of the latest completed training event.
|
||||
* @returns {number} Non-negative whole weeks, including zero for ages under seven days.
|
||||
*/
|
||||
export function weeksSinceTraining(now, lastTrained) {
|
||||
return Math.max(0, Math.floor((now - lastTrained) / 86400000 / 7))
|
||||
}
|
||||
|
||||
function FatigueLegend() {
|
||||
return <div className="hm-legend hm-fatigue" aria-label={t('Fatigue')}>
|
||||
<span>{t('Fatigued')}</span><div className="hm-c l4" />
|
||||
<span>{t('Recovering')}</span><div className="hm-c l2" />
|
||||
<span>{t('Ready')}</span><div className="hm-c l0" />
|
||||
</div>
|
||||
}
|
||||
|
||||
function StrengthLegend() {
|
||||
return <div className="hm-legend hm-strength" aria-label={t('Strength')}>
|
||||
<span>1 <span className="dim">{t('full')}</span></span><div className="hm-c l4" /><div className="hm-c l3" /><div className="hm-c l2" />
|
||||
<div className="hm-c l1" /><div className="hm-c l0" /><span>{fmtNum(STRENGTH_FLOOR)} <span className="dim">{t('floor')}</span></span>
|
||||
</div>
|
||||
}
|
||||
|
||||
function fatigueLabel(value) {
|
||||
const state = fatigueStateOf(value)
|
||||
return t(state === 'ready' ? 'Ready' : state === 'recovering' ? 'Recovering' : 'Fatigued')
|
||||
}
|
||||
|
||||
function MuscleBalance({ S }) {
|
||||
const [view, setView] = useState('balance')
|
||||
const [win, setWin] = useState(7)
|
||||
const [hard, setHard] = useState(false)
|
||||
const [sel, setSel] = useState(null)
|
||||
const now = Date.now()
|
||||
const now = useNow()
|
||||
const workouts = S.workouts
|
||||
// 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 strengthHint = slug => {
|
||||
if (lastTrained[slug] == null) return t('not trained')
|
||||
const weeks = weeksSinceTraining(now, lastTrained[slug])
|
||||
return t('Weeks since training: {0}', weeks)
|
||||
}
|
||||
const toggleSel = m => setSel(s => (s === m ? null : m))
|
||||
const inWin = S.workouts.filter(w =>
|
||||
win === 0 ? true
|
||||
: win === 7 ? weekKey(w.d) === weekKey(todayISO())
|
||||
: (w.start || new Date(w.d).getTime()) > now - win * 86400000)
|
||||
const load = loadOfWorkouts(inWin)
|
||||
// Counting only the sets taken near failure turns the map from "where did the volume go"
|
||||
// into "where did the stimulus go" — a muscle can lead on sets and still never be trained
|
||||
// hard. Offered only when the window holds ratings at all, since with none the hard map
|
||||
// would just be empty and read as "you trained nothing".
|
||||
const rated = inWin.some(w => w.entries.some(e => e.sets.some(s => s.done && isHardSet(s))))
|
||||
const on = hard && rated
|
||||
const load = loadOfWorkouts(inWin, on ? isHardSet : null)
|
||||
const volWin = S.workouts.filter(w => (w.start || new Date(w.d).getTime()) > now - 90 * 86400000)
|
||||
const vol90 = loadOfWorkouts(volWin, null)
|
||||
const { worked, missed } = rankOf(load)
|
||||
const { 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
|
||||
|
||||
return <div className="card">
|
||||
<h2>{t('Muscle balance')} <span className="dim" style={{ textTransform: 'none', letterSpacing: 0 }}>· {t('by sets worked')}</span></h2>
|
||||
<Segmented className="seg-range" value={win} onChange={v => { setWin(v); setSel(null) }}
|
||||
options={[{ value: 7, label: t('Week') }, { value: 30, label: '30d' }, { value: 90, label: '90d' }, { value: 0, label: t('All') }]} />
|
||||
{inWin.length ? <>
|
||||
<BodyMap className="tappable" load={load} body={S.body} selected={sel}
|
||||
onMuscle={m => setSel(s => (s === m ? null : m))} />
|
||||
<BodyMapLegend />
|
||||
<Segmented className="seg-range" value={view} onChange={setView}
|
||||
options={[{ value: 'balance', label: t('Muscle balance') }, { value: 'fatigue', label: t('Fatigue') }, { value: 'strength', label: t('Strength') }]} />
|
||||
{view === 'balance' ? <>
|
||||
<div className="row between" style={{ marginBottom: 8 }}>
|
||||
<h2 style={{ margin: 0 }}>{t('Muscle balance')} <span className="dim" style={{ textTransform: 'none', letterSpacing: 0 }}>· {on ? t('by hard sets') : t('by sets worked')}</span></h2>
|
||||
{rated && <Button size="sm" icon="flame" style={on ? { color: 'var(--yellow)' } : undefined}
|
||||
onClick={() => { setHard(h => !h); setSel(null) }}>{on ? t('Hard') : t('All')}</Button>}
|
||||
</div>
|
||||
<Segmented className="seg-range" value={win} onChange={v => { setWin(v); setSel(null) }}
|
||||
options={[{ value: 7, label: t('Week') }, { value: 30, label: '30d' }, { value: 90, label: '90d' }, { value: 0, label: t('All') }]} />
|
||||
{inWin.length ? <>
|
||||
<BodyMap className="tappable" load={load} body={S.body} selected={sel}
|
||||
onMuscle={m => setSel(s => (s === m ? null : m))} />
|
||||
<BodyMapLegend />
|
||||
{sel && <div className="mrow" style={{ borderTop: 'var(--hair) solid var(--sep)', marginTop: 4, paddingTop: 10 }}>
|
||||
<span className="nm"><b>{t(MUSCLE_NAME[sel])}</b></span>
|
||||
<span className="v">{sets(sel) ? t('{0} sets', sets(sel)) : on ? t('no hard sets') : t('not trained')}</span>
|
||||
</div>}
|
||||
{!sel && top.map(m => <div key={m} className="mrow">
|
||||
<span className="nm">{t(MUSCLE_NAME[m])}</span>
|
||||
<span className="bar"><i style={{ width: Math.round(load[m] / max * 100) + '%', background: on ? 'var(--yellow)' : undefined }} /></span>
|
||||
<span className="v">{t('{0} sets', sets(m))}</span>
|
||||
</div>)}
|
||||
{missed.length > 0 && <>
|
||||
<h4 className="sec" style={{ marginTop: 12 }}>{on ? t('No hard sets in this period') : t('Not trained in this period')}</h4>
|
||||
<div className="mchips">{missed.map(m => <span key={m} className="mchip miss">{t(MUSCLE_NAME[m])}</span>)}</div>
|
||||
</>}
|
||||
{!missed.length && worked.length > 0 &&
|
||||
<div className="muted small" style={{ marginTop: 10 }}>{on
|
||||
? t('Every muscle group got at least one hard set in this period.')
|
||||
: t('Every muscle group got some work in this period.')}</div>}
|
||||
</> : <div className="muted small">{t('No workouts in this period yet.')}</div>}
|
||||
</> : view === 'fatigue' ? <>
|
||||
<h2>{t('Fatigue')}</h2>
|
||||
<BodyMap className="tappable hm-fatigue" load={fatigue} thresholds={FATIGUE_LEVELS} body={S.body} selected={sel} onMuscle={toggleSel} />
|
||||
<FatigueLegend />
|
||||
<div className="muted small" style={{ marginTop: 10 }}>{t('Fatigue shows how recently each muscle was trained. High means rest.')}</div>
|
||||
{sel && <div className="mrow" style={{ borderTop: 'var(--hair) solid var(--sep)', marginTop: 4, paddingTop: 10 }}>
|
||||
<span className="nm"><b>{t(MUSCLE_NAME[sel])}</b></span>
|
||||
<span className="v">{sets(sel) ? t('{0} sets', sets(sel)) : t('not trained')}</span>
|
||||
<span className="v">{fatigueLabel(fatigue[sel])}</span>
|
||||
</div>}
|
||||
{!sel && top.map(m => <div key={m} className="mrow">
|
||||
<span className="nm">{t(MUSCLE_NAME[m])}</span>
|
||||
<span className="bar"><i style={{ width: Math.round(load[m] / max * 100) + '%' }} /></span>
|
||||
<span className="v">{t('{0} sets', sets(m))}</span>
|
||||
</div>)}
|
||||
{missed.length > 0 && <>
|
||||
<h4 className="sec" style={{ marginTop: 12 }}>{t('Not trained in this period')}</h4>
|
||||
<div className="mchips">{missed.map(m => <span key={m} className="mchip miss">{t(MUSCLE_NAME[m])}</span>)}</div>
|
||||
</> : <>
|
||||
<h2>{t('Strength')}</h2>
|
||||
<BodyMap className="tappable hm-strength" load={strength} thresholds={STRENGTH_LEVELS} body={S.body} selected={sel} onMuscle={toggleSel} />
|
||||
<StrengthLegend />
|
||||
<div className="muted small" style={{ marginTop: 10 }}>{t('Strength shows retained muscle strength. Train again to reset it.')}</div>
|
||||
{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>}
|
||||
</>}
|
||||
{!missed.length && worked.length > 0 &&
|
||||
<div className="muted small" style={{ marginTop: 10 }}>{t('Every muscle group got some work in this period.')}</div>}
|
||||
</> : <div className="muted small">{t('No workouts in this period 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>
|
||||
<span className="v">{t('{0} sets', vol90[slug] || 0)}</span>
|
||||
</div>)}
|
||||
</>}
|
||||
</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
|
||||
// default, so a partly rated history is the normal case, and an average without its
|
||||
// denominator would quietly speak for sets that were never rated.
|
||||
function EffortCard({ S }) {
|
||||
const [win, setWin] = useState(90)
|
||||
const kind = displayScale(S)
|
||||
const hd = scaleName(kind)
|
||||
const sum = effortSummary(S, win)
|
||||
const weeks = effortWeeks(S, win)
|
||||
const hist = effortHistogram(S, win)
|
||||
const maxBin = Math.max(1, ...hist.map(b => b.n))
|
||||
// The week's set count rides along in the tooltip, because the pair is the reading:
|
||||
// volume up with effort up is fatigue piling up, volume up with effort flat is adaptation.
|
||||
const pts = weeks.map(w => ({ t: w.t, y: toScale(kind, w.rir), note: t('{0} sets', w.sets) }))
|
||||
// Bins run hardest-first in both scales: RIR 0 and RPE 10 are the same set.
|
||||
const binLabel = b => kind === 'rpe' ? (b.tail ? '≤ 6' : String(10 - b.rir)) : (b.tail ? b.rir + '+' : String(b.rir))
|
||||
|
||||
return <div className="card">
|
||||
<h2>{t('Effort')} <span className="dim" style={{ textTransform: 'none', letterSpacing: 0 }}>· {t('how close to failure')}</span></h2>
|
||||
<Segmented className="seg-range" value={win} onChange={setWin}
|
||||
options={[{ value: 30, label: '30d' }, { value: 90, label: '90d' }, { value: 365, label: '1Y' }, { value: 0, label: t('All') }]} />
|
||||
{sum.rated === 0 ? <div className="muted small">{t('No rated sets in this period.')}</div> : <>
|
||||
<div className="row between" style={{ alignItems: 'flex-end', gap: 12 }}>
|
||||
<div>
|
||||
<div className="stat-v">{sum.avg == null ? '—' : fmtNum(toScale(kind, sum.avg)) + ' ' + hd}</div>
|
||||
<div className="small dim">{t('average effort')}</div>
|
||||
</div>
|
||||
<div style={{ textAlign: 'right' }}>
|
||||
<div className="stat-v" style={{ color: 'var(--yellow)' }}>{sum.hardPct == null ? '—' : Math.round(sum.hardPct * 100) + '%'}</div>
|
||||
<div className="small dim">{t('at {0} {1} or harder', hd, fmtNum(toScale(kind, HARD_RIR)))}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="small dim" style={{ marginTop: 8 }}>{t('{0} of {1} finished sets rated', sum.rated, sum.done)}</div>
|
||||
{effortOf(S) === 'none' && <div className="small" style={{ color: 'var(--yellow)', marginTop: 4 }}>
|
||||
{t('Effort per set is switched off — turn it on in Settings to keep rating.')}
|
||||
</div>}
|
||||
{pts.length > 1 && <>
|
||||
<h4 className="sec" style={{ marginTop: 12 }}>{t('Week by week')}</h4>
|
||||
<div className="chart"><LineChart points={pts} h={140} unit={hd} color="var(--yellow)" invert={kind === 'rir'} /></div>
|
||||
</>}
|
||||
<h4 className="sec" style={{ marginTop: 12 }}>{t('Where the sets land')}</h4>
|
||||
{hist.map(b => <div key={b.rir} className="mrow">
|
||||
<span className="nm">{hd} {binLabel(b)}</span>
|
||||
<span className="bar"><i style={{ width: Math.round(b.n / maxBin * 100) + '%', background: b.rir <= HARD_RIR ? 'var(--yellow)' : 'var(--label-3)' }} /></span>
|
||||
<span className="v">{b.n ? b.n + ' · ' + Math.round(b.pct * 100) + '%' : '—'}</span>
|
||||
</div>)}
|
||||
<div className="small dim" style={{ marginTop: 8 }}>
|
||||
{t('Most working sets belong close to failure without living there — half at the floor and half at the top average out to a healthy-looking middle.')}
|
||||
</div>
|
||||
</>}
|
||||
</div>
|
||||
}
|
||||
|
||||
@@ -65,22 +280,41 @@ export default function Stats() {
|
||||
const [exId, setExId] = useState(null)
|
||||
const [exMetric, setExMetric] = useState('top')
|
||||
const now = Date.now()
|
||||
const kind = displayScale(S)
|
||||
const hd = scaleName(kind)
|
||||
|
||||
const bwPts = S.bodyweight.filter(b => range === 0 || (b.t || new Date(b.d).getTime()) > now - range * 86400000)
|
||||
.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 exHist = [...new Set(S.workouts.flatMap(w => w.entries.map(e => e.id)))].filter(id => EXIDX[id]).sort((a, b) => EXIDX[a].n < EXIDX[b].n ? -1 : 1)
|
||||
const nameOf = id => EXIDX[id]?.n || workouts.flatMap(w => w.entries).find(e => e.id === id)?.n || id
|
||||
const currentOf = 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 = 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(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 || 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'
|
||||
@@ -90,36 +324,63 @@ 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
|
||||
// with more left in the tank is progress a weight-only chart draws as a flat line.
|
||||
const exRir = exPts.map(p => avgRir(p.sets))
|
||||
const showEff = exRir.filter(v => v != null).length >= 3
|
||||
const effPts = exPts.map((p, i) => (exRir[i] == null ? null : { t: p.t, y: toScale(kind, exRir[i]), d: p.d })).filter(Boolean)
|
||||
const onE1 = showE1 && exMetric === 'e1rm'
|
||||
const onEff = showEff && exMetric === 'effort'
|
||||
const topPts = exPts.map((p, i) => ({
|
||||
t: p.t, y: p.y, d: p.d,
|
||||
// 0 RIR (nothing left) is a full dot, 4+ a faint one; unrated sessions keep the plain line.
|
||||
m: exRir[i] == null ? null : 1 - Math.min(4, Math.max(0, exRir[i])) / 4,
|
||||
note: exRir[i] == null ? undefined : hd + ' ' + fmtNum(toScale(kind, exRir[i]))
|
||||
}))
|
||||
const exOpts = [{ value: 'top', label: t('Top set') }]
|
||||
if (showE1) exOpts.push({ value: 'e1rm', label: t('Est. 1RM') })
|
||||
if (showEff) exOpts.push({ value: 'effort', label: t('Effort') })
|
||||
|
||||
return <>
|
||||
<div className="hdr"><div><h1>{t('Stats')}</h1><div className="sub">{t('Progress & history')}</div></div>
|
||||
<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} />}
|
||||
{workouts.length > 0 && <MuscleBalance S={S} />}
|
||||
{hasEffort(S) && <EffortCard S={S} />}
|
||||
|
||||
<div className="cols">
|
||||
<div className="card">
|
||||
@@ -140,30 +401,36 @@ export default function Stats() {
|
||||
{exHist.length ? <>
|
||||
<div className="sect-b" style={{ marginBottom: 10 }}>
|
||||
<SelectRow title={t('Exercise')} sheetTitle={t('Exercise progress')} value={curEx} onChange={setExId}
|
||||
options={exHist.map(id => ({ value: id, label: EXIDX[id].n }))} />
|
||||
options={exHist.map(id => ({ value: id, label: 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">
|
||||
{onEff
|
||||
? <LineChart points={effPts} h={150} unit={hd} color="var(--yellow)" invert={kind === 'rir'} />
|
||||
: <LineChart points={onE1 ? e1Pts.map(p => ({ t: p.t, y: p.y, d: p.d })) : topPts} h={150} unit={exUnit} color="var(--blue)" />}
|
||||
</div>
|
||||
{showE1 && <Segmented className="seg-range" value={exMetric} onChange={setExMetric}
|
||||
options={[{ value: 'top', label: t('Top set') }, { value: 'e1rm', label: t('Est. 1RM') }]} />}
|
||||
<div className="chart"><LineChart points={(onE1 ? e1Pts : exPts).map(p => ({ t: p.t, y: p.y, d: p.d }))} h={150} unit={exUnit} color="var(--blue)" /></div>
|
||||
<div style={{ marginTop: 8 }}>{exList.map((p, i) => <div key={i} className="row between small" style={{ padding: '6px 0', borderBottom: 'var(--hair) solid var(--sep)' }}>
|
||||
<span className="muted">{fmtDate(p.d, true)}</span><span>{p.sets.map(s => setLabel(curEx, s, p.target)).join(' ')}</span></div>)}</div>
|
||||
<div className="small dim" style={{ marginTop: 8 }}>
|
||||
{onE1 ? t('Estimated 1RM per workout') : curCardio ? t('Top speed per workout') : curTimed ? t('Longest hold per workout') : t('Best set weight per workout')} · {t('Best:')}
|
||||
{' '}<b className="accent">{fmtNum(onE1 ? e1Best.est : exBest)} {onE1 ? S.unit : exUnit}</b>
|
||||
{onEff ? t('Average effort per workout') : onE1 ? t('Estimated 1RM per workout') : curCardio ? t('Top speed per workout') : curTimed ? t('Longest hold per workout') : t('Best set weight per workout')}
|
||||
{onEff ? '' : <> · {t('Best:')}{' '}<b className="accent">{fmtNum(onE1 ? e1Best.est : exBest)} {onE1 ? S.unit : exUnit}</b></>}
|
||||
</div>
|
||||
{showE1 && <div className="small dim" style={{ marginTop: 4 }}>
|
||||
{onE1 && <div className="small dim" style={{ marginTop: 4 }}>
|
||||
{t('Best estimate from {0} on {1} — an estimate, not a tested max.', fmtNum(e1Best.w) + ' ' + S.unit + ' × ' + e1Best.r, fmtDate(e1Best.d, true))}
|
||||
</div>}
|
||||
{!onEff && !onE1 && showEff && <div className="small dim" style={{ marginTop: 4 }}>
|
||||
{t('A fuller dot means less left in the tank — the same weight at a lower {0} is progress the line alone does not show.', hd)}
|
||||
</div>}
|
||||
</> : <div className="muted small">{t('Finish your first workout to see progress curves here.')}</div>}
|
||||
</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>
|
||||
</>}
|
||||
</>
|
||||
}
|
||||
@@ -0,0 +1,274 @@
|
||||
import React, { act } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import { Window } from 'happy-dom'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
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 from './Stats.jsx'
|
||||
|
||||
const DAY = 86400000
|
||||
const HOUR = 3600000
|
||||
const BASE_NOW = Date.UTC(2026, 0, 22, 12)
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
maps: [],
|
||||
mapMounts: 0,
|
||||
S: {
|
||||
unit: 'kg', body: 'male', effort: 'rir', targetW: null,
|
||||
bodyweight: [], routines: [], workouts: [],
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('../store/useStore.js', () => ({
|
||||
useStore: selector => selector({ S: mocks.S }),
|
||||
}))
|
||||
vi.mock('react-router-dom', () => ({ useNavigate: () => () => {} }))
|
||||
vi.mock('../sheets.jsx', () => ({
|
||||
bwSheet: () => {}, goalSheet: () => {}, calendarSheet: () => {}, workoutDetailSheet: () => {},
|
||||
WorkoutRow: () => React.createElement('div'), bwDeltaColor: () => 'inherit',
|
||||
}))
|
||||
vi.mock('../components/LineChart.jsx', () => ({ default: () => React.createElement('div') }))
|
||||
vi.mock('../components/Heatmap.jsx', () => ({ default: () => React.createElement('div') }))
|
||||
vi.mock('../components/Icon.jsx', () => ({ default: props => React.createElement('span', props) }))
|
||||
vi.mock('../components/BodyMap.jsx', () => ({
|
||||
default: props => {
|
||||
mocks.maps.push(props)
|
||||
React.useEffect(() => {
|
||||
mocks.mapMounts += 1
|
||||
return () => {}
|
||||
}, [])
|
||||
return React.createElement(
|
||||
'div',
|
||||
{ 'data-body-map': true, 'data-selected-muscle': props.selected || '' },
|
||||
React.createElement('button', {
|
||||
'data-muscle': 'chest',
|
||||
onClick: () => props.onMuscle?.('chest'),
|
||||
}, 'Chest'),
|
||||
)
|
||||
},
|
||||
BodyMapLegend: () => React.createElement('div', { 'data-balance-legend': true }),
|
||||
}))
|
||||
|
||||
let dom
|
||||
let root
|
||||
let container
|
||||
|
||||
function iso(timestamp) {
|
||||
return new Date(timestamp).toISOString().slice(0, 10)
|
||||
}
|
||||
|
||||
function set(done, extra = {}) {
|
||||
return { done, w: 80, r: 8, unit: 'kg', ...extra }
|
||||
}
|
||||
|
||||
function workout(id, start, entries) {
|
||||
return { id, d: iso(start), start, unit: 'kg', entries }
|
||||
}
|
||||
|
||||
function entry(id, sets) {
|
||||
return { id, sets }
|
||||
}
|
||||
|
||||
function lifecycleWorkouts(now = BASE_NOW) {
|
||||
// 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)
|
||||
const strengthEdge = now - (14 * DAY - 30000)
|
||||
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', 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) {
|
||||
const ids = [
|
||||
'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: 12 }, () => set(true)))),
|
||||
)
|
||||
}
|
||||
|
||||
function allSubfullWorkout(now = BASE_NOW) {
|
||||
return workout('all-subfull', now - 15 * DAY, [entry('1254', [set(true)])])
|
||||
}
|
||||
|
||||
function resetFixture(workouts = lifecycleWorkouts()) {
|
||||
mocks.S.unit = 'kg'
|
||||
mocks.S.bodyweight = []
|
||||
mocks.S.workouts = workouts
|
||||
mocks.maps.length = 0
|
||||
mocks.mapMounts = 0
|
||||
}
|
||||
|
||||
function installDom() {
|
||||
dom = new Window({ url: 'http://localhost/' })
|
||||
globalThis.window = dom
|
||||
globalThis.document = dom.document
|
||||
Object.defineProperty(globalThis, 'navigator', { configurable: true, value: dom.navigator })
|
||||
for (const key of ['HTMLElement', 'HTMLIFrameElement', 'Node', 'Element', 'Event', 'MouseEvent']) {
|
||||
globalThis[key] = dom[key]
|
||||
}
|
||||
globalThis.IS_REACT_ACT_ENVIRONMENT = true
|
||||
container = document.createElement('div')
|
||||
document.body.append(container)
|
||||
root = createRoot(container)
|
||||
}
|
||||
|
||||
async function mountStats() {
|
||||
installDom()
|
||||
await act(async () => { root.render(React.createElement(Stats)) })
|
||||
}
|
||||
|
||||
async function unmountStats() {
|
||||
if (!root) return
|
||||
await act(async () => { root.unmount() })
|
||||
root = null
|
||||
container = null
|
||||
dom.close()
|
||||
dom = null
|
||||
}
|
||||
|
||||
function muscleCard() {
|
||||
return [...container.querySelectorAll('.card')].find(card =>
|
||||
[...card.querySelectorAll('.seg button')].some(button =>
|
||||
['Muscle balance', 'Fatigue', 'Strength'].includes(button.textContent.trim())))
|
||||
}
|
||||
|
||||
function buttonWithText(scope, text) {
|
||||
return [...scope.querySelectorAll('button')].find(button => button.textContent.trim() === text)
|
||||
}
|
||||
|
||||
function viewButton(text) {
|
||||
return buttonWithText(muscleCard(), text)
|
||||
}
|
||||
|
||||
function balanceRangeButton(text) {
|
||||
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.MouseEvent('click', { bubbles: true })) })
|
||||
}
|
||||
|
||||
async function tick(milliseconds) {
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(milliseconds) })
|
||||
}
|
||||
|
||||
const lastMap = () => mocks.maps.at(-1)
|
||||
const expectPressed = button => expect(button?.getAttribute('aria-pressed')).toBe('true')
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
vi.setSystemTime(BASE_NOW)
|
||||
resetFixture()
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
await unmountStats()
|
||||
vi.useRealTimers()
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
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(muscleCard(), 'All'))
|
||||
await click(muscleCard().querySelector('[data-muscle="chest"]'))
|
||||
expect(buttonWithText(muscleCard(), 'Hard')).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.')
|
||||
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(lastMap().selected).toBe('chest')
|
||||
expect(lastMap().load.chest).toBe(7)
|
||||
})
|
||||
|
||||
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 mountsBeforeTick = mocks.mapMounts
|
||||
const beforeTick = lastMap().load.chest
|
||||
expect(fatigueStateOf(beforeTick)).toBe(FATIGUE_STATES.FATIGUED)
|
||||
expect(container.textContent).toContain('Fatigued')
|
||||
|
||||
await tick(60000)
|
||||
|
||||
const afterTick = lastMap().load.chest
|
||||
expect(mocks.mapMounts).toBe(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)
|
||||
await click(viewButton('Muscle balance'))
|
||||
expect(lastMap().load.chest).toBe(6)
|
||||
})
|
||||
|
||||
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('Fatigue'))
|
||||
|
||||
// 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('renders fixed absolute bands through the actual Fatigue and Strength views', async () => {
|
||||
resetFixture([allFatiguedWorkout()])
|
||||
await mountStats()
|
||||
await click(viewButton('Fatigue'))
|
||||
const fatigueMap = lastMap()
|
||||
expect(Object.keys(fatigueMap.load)).toEqual(MUSCLES)
|
||||
expect(Object.values(fatigueMap.load).every(value => value > 0.5)).toBe(true)
|
||||
expect(Object.values(levelsOf(fatigueMap.load, fatigueMap.thresholds)).every(level => level === 4)).toBe(true)
|
||||
|
||||
await unmountStats()
|
||||
resetFixture([allSubfullWorkout()])
|
||||
await mountStats()
|
||||
await click(viewButton('Strength'))
|
||||
const strengthMap = lastMap()
|
||||
expect(Object.values(strengthMap.load).every(value => value < 1)).toBe(true)
|
||||
expect(Math.min(...Object.values(strengthMap.load))).toBe(STRENGTH_FLOOR)
|
||||
expect(strengthMap.thresholds.at(-1)).toEqual({ at: 1, level: 4 })
|
||||
})
|
||||
})
|
||||
@@ -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, setsDoneActive, supersetUnits, unitOf, setLabel, modeOf, EFFORT, effortOf, stepEffort, capEffort } from '../lib/history.js'
|
||||
import { effectiveRoutine, lastEntryFor, bestWeightFor, buildSets, freestyleConfig, defaultConfig, setsDoneActive, supersetUnits, unitOf, setLabel, modeOf, isBw, isPerSide, sideReps, repStep, EFFORT, effortOf, stepEffort, capEffort, cascadeWeight, insertWarmupRow, removeRowAt, pairAdjacent, unpairSuperset, 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() {
|
||||
@@ -54,7 +56,7 @@ function Elapsed({ start }) {
|
||||
}
|
||||
|
||||
/* ---------- one exercise block (reps: weight×reps · time: a held duration · cardio: duration+speed) ---------- */
|
||||
function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemoveSet, onStartTimed }) {
|
||||
function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemoveSet, onAddWarmup, onRemoveSetAt, onStartTimed, onPairPrev, onPairNext }) {
|
||||
const S = useStore(s => s.S)
|
||||
const working = useUI(s => s.work)
|
||||
const entry = S.active.entries[entryIdx]
|
||||
@@ -69,12 +71,22 @@ function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemov
|
||||
// What the progression policy decided for this session, and why (issue #17). Computed when
|
||||
// the session was built so the reason matches the numbers already in the rows.
|
||||
const plan = entry.plan
|
||||
// A bodyweight set has no weight to type, so the column is not there (issue #32) — one
|
||||
// stepper instead of two, which is the whole point of the flag. Adding a belt weight in the
|
||||
// config brings it back, now labelled as the addition it is.
|
||||
const cfg = { ...(entry.target || {}), id: entry.id }
|
||||
const bw = !cardio && isBw(cfg)
|
||||
const added = bw && entry.sets.some(s => s.w > 0)
|
||||
const loadCol = { f: 'w', step: 2.5, dec: true, hd: bw ? t('Added ({0})', S.unit) : t('Weight ({0})', S.unit) }
|
||||
// The reps column is the total in every mode, unilateral included — the stepper walks in
|
||||
// twos there so the number you land on is one you can actually split evenly.
|
||||
const repCol = { f: 'r', step: repStep(cfg), dec: false, hd: t('Reps') }
|
||||
const col1 = cardio ? { f: 'min', step: 1, dec: false, hd: t('Duration (min)') }
|
||||
: timed ? { f: 'sec', step: 5, dec: false, hd: t('Seconds') }
|
||||
: { f: 'w', step: 2.5, dec: true, hd: t('Weight ({0})', S.unit) }
|
||||
: (bw && !added) ? repCol : loadCol
|
||||
const col2 = cardio ? { f: 'speed', step: 0.5, dec: true, hd: t('Speed (km/h)') }
|
||||
: timed ? { f: 'w', step: 2.5, dec: true, hd: t('Weight ({0})', S.unit) }
|
||||
: { f: 'r', step: 1, dec: false, hd: t('Reps') }
|
||||
: timed ? ((bw && !added) ? null : loadCol)
|
||||
: (bw && !added) ? null : repCol
|
||||
// Effort (RIR or RPE, whichever the profile logs) only makes sense for weighted rep sets,
|
||||
// not cardio/timed holds, and is opt-in since it adds a third stepper to every row. `opt`
|
||||
// because an unlogged effort is not the same as 0 — RIR 0 says the set went to failure.
|
||||
@@ -104,8 +116,15 @@ function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemov
|
||||
<div style={{ fontSize: compact ? 17 : 20, fontWeight: 600, letterSpacing: '-.02em', textTransform: 'capitalize', lineHeight: 1.2 }}>{ex.n}</div>
|
||||
<button className="iconbtn" aria-label={t('Details')} onClick={() => exerciseDetailSheet(ex)}><Icon name="info" /></button>
|
||||
</div>
|
||||
{!compact && (onPairPrev || onPairNext) && <div className="row" style={{ gap: 6, flexWrap: 'wrap', marginBottom: 8 }}>
|
||||
{onPairPrev && <Button size="xs" variant="tinted" icon="link" title={t('Make superset with previous')} onClick={onPairPrev}>{t('Make superset with previous')}</Button>}
|
||||
{onPairNext && <Button size="xs" variant="tinted" icon="link" title={t('Make superset with next')} onClick={onPairNext}>{t('Make superset with next')}</Button>}
|
||||
</div>}
|
||||
<div className="row" style={{ gap: 6, flexWrap: 'wrap', marginBottom: 8 }}>
|
||||
{cardio && <span className="tag acc"><Icon name="figureRun" />{t('Cardio')}</span>}
|
||||
{/* You log the total; this is the split, so the set in front of you is unambiguous
|
||||
without the rep count having to mean two different things (issue #31). */}
|
||||
{!cardio && !timed && isPerSide(cfg) && <span className="tag acc nocap"><Icon name="shuffle" />{t('{0} per side', fmtNum(sideReps(entry.sets.find(s => !s.done)?.r ?? entry.sets[0]?.r)))}</span>}
|
||||
{(ex.tg || ex.bp) && <span className="tag">{t(ex.tg || ex.bp)}</span>}
|
||||
{ex.eq && <span className="tag">{t(ex.eq)}</span>}
|
||||
{best > 0 && <span className="tag nocap">{t('Best:')} {fmtNum(best)} {S.unit}</span>}
|
||||
@@ -117,20 +136,34 @@ function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemov
|
||||
</div>}
|
||||
<div className="card" style={{ marginTop: 10, marginBottom: 0 }}>
|
||||
{/* the header carries the same eff3 sizing as the rows, or the labels drift off their columns */}
|
||||
<div className={'sethead' + (col3 ? ' eff3' : '')}><span className="n-sp" /><span className="w-sp">{col1.hd}</span><span className="r-sp">{col2.hd}</span>{col3 && <span className="eff-sp">{col3.hd}</span>}{timed && <span className="ck-sp" />}<span className="ck-sp" /></div>
|
||||
{entry.sets.map((s, i) => <div key={i} className={'setrow' + (s.done ? ' done' : '') + (col3 ? ' eff3' : '')}>
|
||||
<div className="n">{i + 1}</div>
|
||||
{cell(s, i, col1, 'w')}
|
||||
{cell(s, i, col2, 'r')}
|
||||
{col3 && cell(s, i, col3, 'eff')}
|
||||
{/* A timed set is started, not typed: the timer counts the hold down and checks the
|
||||
set off itself. The checkbox stays for anyone who timed it on their own watch. */}
|
||||
{timed && <button className="setgo" aria-label={t('Start set')} disabled={s.done || !!working}
|
||||
onClick={() => onStartTimed(i)}><Icon name="play" /></button>}
|
||||
<Check checked={s.done} onChange={() => onToggle(i)} />
|
||||
</div>)}
|
||||
<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 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 => isWarmupRow(x) === warm).length
|
||||
return <div key={i}>
|
||||
{isFirstWarmup && <div className="setph">{t('Warm-up')}</div>}
|
||||
{!warm && warmBefore && <div className="setsep" />}
|
||||
<div className={'setrow' + (s.done ? ' done' : '') + (col3 ? ' eff3' : '')}>
|
||||
<div className="n">{phaseNum}</div>
|
||||
{cell(s, i, col1, 'w')}
|
||||
{col2 && cell(s, i, col2, 'r')}
|
||||
{col3 && cell(s, i, col3, 'eff')}
|
||||
{/* A timed set is started, not typed: the timer counts the hold down and checks the
|
||||
set off itself. The checkbox stays for anyone who timed it on their own watch. */}
|
||||
{timed && <button className="setgo" aria-label={t('Start set')} disabled={s.done || !!working}
|
||||
onClick={() => onStartTimed(i)}><Icon name="play" /></button>}
|
||||
{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>
|
||||
</div>
|
||||
})}
|
||||
<div style={{ height: 8 }} />
|
||||
<div className="row">
|
||||
<div className="row" style={{ flexWrap: 'wrap' }}>
|
||||
<Button size="sm" icon="flame" onClick={onAddWarmup}>{t('Add warm-up set')}</Button>
|
||||
<Button size="sm" icon="minus" disabled={entry.sets.length <= 1} onClick={onRemoveSet}>{t('Remove set')}</Button>
|
||||
<Button size="sm" icon="plus" onClick={onAddSet}>{t('Add set')}</Button>
|
||||
</div>
|
||||
@@ -139,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)
|
||||
@@ -159,6 +221,11 @@ function ActiveWorkout() {
|
||||
// what was actually logged — in the session, in history and in a backup.
|
||||
const setField = (idx, i, field, v) => mutEntry(idx, e => {
|
||||
if (v == null) delete e.sets[i][field]; else e.sets[i][field] = v
|
||||
// Changing a weight cascades to the following sets of the same phase, so a
|
||||
// heavier bar carries through the set instead of retyping every row.
|
||||
if (field === 'w') {
|
||||
e.sets = cascadeWeight(e.sets, i, v)
|
||||
}
|
||||
})
|
||||
const modeAt = idx => modeOf({ ...(A.entries[idx].target || {}), id: A.entries[idx].id })
|
||||
const addSet = idx => mutEntry(idx, e => {
|
||||
@@ -169,6 +236,51 @@ function ActiveWorkout() {
|
||||
else e.sets.push({ w: l ? l.w : 0, r: l ? l.r : e.target.reps, done: false })
|
||||
})
|
||||
const removeSet = idx => mutEntry(idx, e => { if (e.sets.length > 1) e.sets.pop() })
|
||||
const addWarmup = idx => mutEntry(idx, e => {
|
||||
const m = modeOf({ ...(e.target || {}), id: e.id })
|
||||
e.sets = insertWarmupRow(e.sets, m, e.target || {})
|
||||
})
|
||||
const removeSetAt = (idx, i) => mutEntry(idx, e => { e.sets = removeRowAt(e.sets, i) })
|
||||
const pairAt = (first, second) => update(s => {
|
||||
s.active.entries = pairAdjacent(s.active.entries, first, second)
|
||||
})
|
||||
const unpairAt = idx => update(s => {
|
||||
s.active.entries = unpairSuperset(s.active.entries, idx)
|
||||
})
|
||||
const onPairPrev = !isSuperset && cur > 0 ? () => pairAt(cur - 1, cur) : null
|
||||
const onPairNext = !isSuperset && cur < A.entries.length - 1 ? () => pairAt(cur, cur + 1) : null
|
||||
|
||||
// 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
|
||||
@@ -186,19 +298,19 @@ 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 reps training has a "working weight" worth confirming — a bodyweight plank
|
||||
// has nothing to put in that slider.
|
||||
if (e.sets.every(x => x.done)) { exJustDone = true; if (m === 'reps' && !e.asked) { e.asked = true; askTop = true } }
|
||||
// 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
|
||||
// (issue #32: the fewest taps that still record what happened).
|
||||
const loaded = m === 'reps' && !(isBw({ ...(e.target || {}), id: e.id }) && !e.sets.some(x => x.w > 0))
|
||||
if (e.sets.every(x => x.done)) { exJustDone = true; if (loaded && !e.asked) { e.asked = true; askTop = true } }
|
||||
}
|
||||
})
|
||||
// reps: topWeight first (it chains into the finish/continue prompt on the last unit).
|
||||
@@ -207,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 —
|
||||
@@ -248,15 +397,18 @@ function ActiveWorkout() {
|
||||
<div className="muted small" style={{ marginBottom: 6 }}>{isSuperset ? t('Superset {0} / {1}', unitIdx + 1, units.length) : t('Exercise {0} / {1}', unitIdx + 1, units.length)}</div>
|
||||
{isSuperset ? (
|
||||
<div className="ss-card">
|
||||
<div className="ss-hd"><Icon name="link" />{t('Superset · do these back-to-back, rest after both')}</div>
|
||||
{unit.map((idx, k) => <div key={idx} className="ss-ex">
|
||||
<div className="ss-hd" style={{ justifyContent: 'space-between' }}>
|
||||
<span className="row" style={{ gap: 5 }}><Icon name="link" />{t('Superset · do these back-to-back, rest when done')}</span>
|
||||
<Button size="xs" variant="ghost" icon="link" title={t('Unpair')} onClick={() => unpairAt(cur)}>{t('Unpair')}</Button>
|
||||
</div>
|
||||
{unit.map((idx, k) => <div key={idx} 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)} onStartTimed={i => startTimed(idx, i)} />
|
||||
onToggle={i => toggle(idx, i)} onField={(i, f, v) => setField(idx, i, f, v)} onAddSet={() => addSet(idx)} onRemoveSet={() => removeSet(idx)} onAddWarmup={() => addWarmup(idx)} onRemoveSetAt={i => removeSetAt(idx, i)} onStartTimed={i => startTimed(idx, i)} />
|
||||
</div>)}
|
||||
</div>
|
||||
) : (
|
||||
<ExerciseBlock entryIdx={cur} onToggle={i => toggle(cur, i)} onField={(i, f, v) => setField(cur, i, f, v)} onAddSet={() => addSet(cur)} onRemoveSet={() => removeSet(cur)} onStartTimed={i => startTimed(cur, i)} />
|
||||
<ExerciseBlock entryIdx={cur} onToggle={i => toggle(cur, i)} onField={(i, f, v) => setField(cur, i, f, v)} onAddSet={() => addSet(cur)} onRemoveSet={() => removeSet(cur)} onAddWarmup={() => addWarmup(cur)} onRemoveSetAt={i => removeSetAt(cur, i)} onStartTimed={i => startTimed(cur, i)} onPairPrev={onPairPrev} onPairNext={onPairNext} />
|
||||
)}
|
||||
</> : <div className="empty"><div className="ico"><Icon name="shuffle" /></div>{t('Freestyle workout — add your first exercise.')}</div>}
|
||||
|
||||
@@ -266,12 +418,26 @@ function ActiveWorkout() {
|
||||
<Button trailingIcon="chevronRight" disabled={unitIdx < 0 || unitIdx >= units.length - 1} onClick={() => update(s => { s.active.cur = units[unitIdx + 1][0] })}>{t('Next')}</Button>
|
||||
</div>
|
||||
<div style={{ height: 10 }} />
|
||||
<Button onClick={() => exercisePicker(ex => exConfigSheet(ex, null, cfg => update(s => {
|
||||
const full = { ...cfg, id: ex.id }
|
||||
const plan = nextPrescription(s, full, s.routines.find(r => r.id === s.active.routineId))
|
||||
s.active.entries.push({ id: ex.id, target: { ...cfg }, plan, sets: applyPrescription(buildSets(s, full), plan) })
|
||||
s.active.cur = s.active.entries.length - 1
|
||||
}), null, S.routines.find(r => r.id === A.routineId)))} icon="plus">{t('Add exercise')}</Button>
|
||||
<Button onClick={() => exercisePicker(ex => {
|
||||
const routine = S.routines.find(r => r.id === A.routineId)
|
||||
const freestyle = !A.routineId
|
||||
// Freestyle has no routine prescription to apply: show the last target in the config
|
||||
// sheet and carry its completed rows forward. A planned session keeps its existing path.
|
||||
const seed = freestyle ? freestyleConfig(S, { id: ex.id, ...defaultConfig(ex.id) }) : null
|
||||
exConfigSheet(ex, null, cfg => update(s => {
|
||||
const full = { ...cfg, id: ex.id }
|
||||
const plan = freestyle ? null : nextPrescription(s, full, s.routines.find(r => r.id === s.active.routineId))
|
||||
const sets = buildSets(s, full, freestyle ? { preferLast: true } : undefined)
|
||||
s.active.entries.push({ id: ex.id, target: { ...cfg }, plan, sets: freestyle ? sets : applyPrescription(sets, plan) })
|
||||
s.active.cur = s.active.entries.length - 1
|
||||
}), null, routine, seed)
|
||||
})} icon="plus">{t('Add exercise')}</Button>
|
||||
{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
|
||||
|
||||