Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3ce1a7c055 | ||
|
|
aa42040f55 | ||
|
|
0410ea34be | ||
|
|
f1c4c66729 | ||
|
|
0e74ad303c | ||
|
|
0c9e473b68 | ||
|
|
358d39590a | ||
|
|
ce4a30002a | ||
|
|
3026d92cc4 | ||
|
|
ec258e1367 | ||
|
|
9006cccb50 | ||
|
|
3d04dbb1e7 | ||
|
|
0ab0f47259 | ||
|
|
cb24bf12d7 | ||
|
|
3a79a8dd5a | ||
|
|
491132a2b7 | ||
|
|
d0361b3fe0 | ||
|
|
9add360452 | ||
|
|
19899d0fbd | ||
|
|
5edfc1e78c | ||
|
|
9216aa2f02 | ||
|
|
dcfc7f15a7 | ||
|
|
e47a5418dc | ||
|
|
a97ae06c68 | ||
|
|
03a5bd22ff | ||
|
|
0eb36abfdb | ||
|
|
b7631dc9a0 | ||
|
|
82f0b84766 | ||
|
|
8165e41d8d | ||
|
|
5314b342ff | ||
|
|
1290db11b5 | ||
|
|
57ab683bf6 | ||
|
|
3c985babea | ||
|
|
bc3ac09c77 | ||
|
|
af4de8b8ff | ||
|
|
9bec4bb785 | ||
|
|
fa879a8b40 | ||
|
|
651b03cbd1 | ||
|
|
b0b9e9350f | ||
|
|
ac66d90a3e | ||
|
|
3d30edddad | ||
|
|
287550df6c | ||
|
|
0a69ee8450 | ||
|
|
95474f955b | ||
|
|
8104539932 | ||
|
|
b28115a8f9 | ||
|
|
5ff6b7d0a8 | ||
|
|
bbf46e2aa2 | ||
|
|
69cefca19e | ||
|
|
e1c14f7ac0 | ||
|
|
6ea7526bff | ||
|
|
37d6cf895a | ||
|
|
62b69ea88d | ||
|
|
46eaefd2c7 | ||
|
|
0863aa73fb | ||
|
|
bcbde6245c | ||
|
|
a04a5cab52 | ||
|
|
4a614eb8ca | ||
|
|
e737954e37 | ||
|
|
7d2460c2c2 | ||
|
|
5762096a5f | ||
|
|
76973edad1 | ||
|
|
f37448aece | ||
|
|
7f0afae228 | ||
|
|
6eabeda89b | ||
|
|
5a1f1d673f | ||
|
|
f5b215f109 | ||
|
|
880a9c184e | ||
|
|
669756a6dd | ||
|
|
1bd69c75ff | ||
|
|
0d3ddabc96 | ||
|
|
142b444c8f | ||
|
|
39577f6f2e | ||
|
|
9c4bc16967 | ||
|
|
881fe4b2dc | ||
|
|
f0c554e86d | ||
|
|
ec3dc8ba69 | ||
|
|
e326f1b1cb | ||
|
|
781e2441ba | ||
|
|
ec84f6db06 | ||
|
|
7261403d2d | ||
|
|
50194442b6 | ||
|
|
02ea938b2c | ||
|
|
79206950c4 | ||
|
|
f52decf633 | ||
|
|
4df4406139 | ||
|
|
740b2e7df5 | ||
|
|
e6261e7b7b | ||
|
|
7e1c0ae023 | ||
|
|
3e531e72e1 | ||
|
|
032fe1a348 | ||
|
|
448c66752f | ||
|
|
dc3fafc6ef | ||
|
|
3d3e44c973 | ||
|
|
41061c1754 | ||
|
|
cf7b3496a5 | ||
|
|
ad69235f6e | ||
|
|
c667539f10 | ||
|
|
600f7ff0e6 | ||
|
|
052ef7e0ba | ||
|
|
9b72fb7f1e | ||
|
|
03f8abb46b | ||
|
|
4081ddac06 | ||
|
|
9f913055d7 | ||
|
|
00ba71d4df | ||
|
|
e4995bbe5e | ||
|
|
7b5ea14d4e | ||
|
|
23632a07ee | ||
|
|
64ea41a5df | ||
|
|
d46b9215a3 | ||
|
|
c8f4d5bd18 | ||
|
|
f8024d344d | ||
|
|
cc036406dc | ||
|
|
02b02de1b2 | ||
|
|
ba7ad8423f | ||
|
|
24b61c2411 | ||
|
|
dc765083fe | ||
|
|
2b3ffad314 | ||
|
|
d1c2247e82 | ||
|
|
d2035e0562 | ||
|
|
f38036fab6 | ||
|
|
b2ee031cf1 | ||
|
|
925190109f | ||
|
|
8b99a644ed | ||
|
|
e709f152c8 | ||
|
|
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 | ||
|
|
4c829b6d1f | ||
|
|
c5e131f81c | ||
|
|
248da53dca | ||
|
|
42d3659615 | ||
|
|
ca917f0320 | ||
|
|
54fb14be13 | ||
|
|
6905117352 | ||
|
|
0c6c22c04b | ||
|
|
4e27461b7e | ||
|
|
fa978a1bb4 | ||
|
|
c08381e558 | ||
|
|
c5172d0633 | ||
|
|
c3929b0a70 | ||
|
|
eb582e3c7b | ||
|
|
6714b16e6a | ||
|
|
6aaf2a3eea | ||
|
|
4143ab8676 | ||
|
|
92914dea43 | ||
|
|
fadeb17b6c |
No files matched your search
@@ -33,9 +33,95 @@ 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
|
||||
|
||||
# ── Activity log (optional) ────────────────────────────────────────────────
|
||||
# The admin dashboard shows an activity log: who signed in, who tried and
|
||||
# failed, and every admin action (disabling an account, creating or revoking an
|
||||
# invite code). It lives in ./data/audit.log, one JSON object per line, so you
|
||||
# can also just read it with `tail` or `jq`.
|
||||
#
|
||||
# It is ON by default. It records strictly less than this instance already
|
||||
# holds — every profile is in db.json and every workout is in state-<uid>.json,
|
||||
# both readable by any admin — and a log that ships switched off tells you
|
||||
# nothing on the day you need it. Turn it off completely with:
|
||||
#
|
||||
# AUDIT_LOG=0
|
||||
#
|
||||
# Retention is a cap, not an archive. Whichever limit is reached first wins;
|
||||
# set either to 0 to disable that limit:
|
||||
#
|
||||
# AUDIT_MAX=5000 # events kept
|
||||
# AUDIT_DAYS=90 # days kept
|
||||
#
|
||||
# IP addresses are the one thing that is OFF unless you ask, because they are
|
||||
# the only field here that says where somebody physically is. They are also the
|
||||
# only way to tell one failed sign-in from twenty. Three settings:
|
||||
#
|
||||
# AUDIT_IP=off # default — no addresses at all
|
||||
# AUDIT_IP=net # network only: 203.0.113.0/24, 2001:db8:1::/48
|
||||
# AUDIT_IP=full # the whole address
|
||||
#
|
||||
# The address is read from CF-Connecting-IP, then the first entry of
|
||||
# X-Forwarded-For, then X-Real-IP, and finally the connecting socket itself if
|
||||
# none of those is present.
|
||||
#
|
||||
# A forwarded-for header is only worth anything if whatever sits in front
|
||||
# OVERWRITES it instead of passing a client-supplied one through — otherwise a
|
||||
# caller simply states the address it would like logged. The web container now
|
||||
# overwrites X-Forwarded-For and X-Real-IP with the real peer, and DROPS
|
||||
# CF-Connecting-IP, so the bundled stack records an address nobody can choose.
|
||||
# (Before, X-Forwarded-For was appended to rather than replaced, and
|
||||
# CF-Connecting-IP was passed straight through — both were forgeable.)
|
||||
#
|
||||
# Cloudflare is first in that list on purpose: a Cloudflare tunnel does not put
|
||||
# the visitor in X-Forwarded-For at all, so that header would otherwise record
|
||||
# the tunnel itself and look perfectly plausible. If — and only if — Cloudflare
|
||||
# is genuinely in front of you, let its header through again:
|
||||
#
|
||||
# CF_CONNECTING_IP=$http_cf_connecting_ip
|
||||
#
|
||||
# That is safe there because Cloudflare sets the header itself, replacing
|
||||
# anything the client sent. Anywhere else, leave it unset.
|
||||
|
||||
# ── 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 }}
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
# Publishes the browser-only demo to GitHub Pages: https://duartesantos8.github.io/openGym/
|
||||
#
|
||||
# DORMANT since 2026-08-19, when the GitHub account was suspended. The demo is now built with the
|
||||
# same command below and served from the project's own site at https://opengym.duarte-santos.ch/demo/
|
||||
# (Vite's base is './', so it drops into a subdirectory unchanged). Kept for the day the account
|
||||
# comes back, exactly like the other workflows in this folder.
|
||||
#
|
||||
# Pages serves static files only, so this build has no backend — VITE_DEMO=1 makes the app
|
||||
# boot straight into guest mode with a seeded example history (see frontend/src/lib/demo.js).
|
||||
# The exercise images/GIFs (~140 MB) are never committed here; the demo build points at the
|
||||
@@ -30,8 +35,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 +49,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 +62,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,6 @@ frontend/dist/
|
||||
node_modules/
|
||||
*.log
|
||||
.DS_Store
|
||||
node_modules
|
||||
.claude/
|
||||
.agents/
|
||||
@@ -0,0 +1,411 @@
|
||||
# openGym — GitLab CI/CD
|
||||
#
|
||||
# This is the pipeline that actually gates and ships the project. It replaces the
|
||||
# GitHub Actions workflows (.github/, dormant since the account suspension) and the
|
||||
# gitea.com ones (.gitea/, kept only so the mirror stays buildable).
|
||||
#
|
||||
# What it does, in order:
|
||||
# test — frontend + MCP suites, on every branch, MR and tag
|
||||
# build — the two container images → registry.gitlab.com/duartesantos8/opengym/{api,web}
|
||||
# package — the signed Android APK → job artifact + generic package registry
|
||||
# deploy — the browser-only demo → GitLab Pages
|
||||
# release — a GitLab Release with the changelog section and links to APK + images
|
||||
#
|
||||
# One deliberate difference from the GitHub copy: GitHub could distinguish a bare tag
|
||||
# push from a *published* release, and only shipped images from the latter (issue #87 —
|
||||
# a tag that is later consolidated away must not leave orphan image tags behind).
|
||||
# GitLab has no such split: the tag pipeline is what creates the Release. So here the
|
||||
# rule is enforced by hand — **only push a tag when you actually mean to release it.**
|
||||
# Everything version-tagged (latest images, signed APK, Release) hangs off `v*` tags,
|
||||
# which are protected, so nobody else can trigger a release either.
|
||||
|
||||
stages:
|
||||
- test
|
||||
- build
|
||||
- package
|
||||
- deploy
|
||||
- release
|
||||
- maintenance
|
||||
|
||||
variables:
|
||||
# node:22-alpine in web/Dockerfile and api/Dockerfile — CI must match production.
|
||||
NODE_IMAGE: "node:22-alpine"
|
||||
# The demo build has no backend and no local media: the exercise images/GIFs (~140 MB)
|
||||
# are never committed, so it points at the upstream dataset on jsDelivr, pinned to a
|
||||
# commit so the CDN can cache it forever.
|
||||
DATASET: "https://cdn.jsdelivr.net/gh/hasaneyldrm/exercises-dataset@7455efae41b330c265e7cd4b78dfa848e7ce5ebd"
|
||||
GIT_DEPTH: "50"
|
||||
|
||||
# Branch pipeline *or* MR pipeline, never both for the same commit.
|
||||
workflow:
|
||||
rules:
|
||||
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
|
||||
- if: $CI_COMMIT_BRANCH && $CI_OPEN_MERGE_REQUESTS
|
||||
when: never
|
||||
- if: $CI_COMMIT_TAG
|
||||
- if: $CI_COMMIT_BRANCH
|
||||
|
||||
# ---------------------------------------------------------------------------- test
|
||||
|
||||
.node:
|
||||
image: $NODE_IMAGE
|
||||
interruptible: true
|
||||
|
||||
test:frontend:
|
||||
extends: .node
|
||||
stage: test
|
||||
cache:
|
||||
key:
|
||||
files:
|
||||
- frontend/package-lock.json
|
||||
paths:
|
||||
- frontend/.npm
|
||||
script:
|
||||
- cd frontend
|
||||
- npm ci --cache .npm --prefer-offline
|
||||
- npm test
|
||||
# A broken import or bad JSX fails the build long before any test covers it.
|
||||
- npm run build
|
||||
- node scripts/check-locales.mjs
|
||||
# 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.
|
||||
- node scripts/check-source-strings.mjs
|
||||
# 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.
|
||||
- npm run test:fatigue-probe
|
||||
rules:
|
||||
# A scheduled pipeline exists only to run `renovate` (bottom of this file) — it must not
|
||||
# re-run the suite or republish the edge images once a month for nothing.
|
||||
- if: $CI_PIPELINE_SOURCE == "schedule"
|
||||
when: never
|
||||
- when: on_success
|
||||
|
||||
test:mcp:
|
||||
extends: .node
|
||||
stage: test
|
||||
cache:
|
||||
key:
|
||||
files:
|
||||
- mcp/package-lock.json
|
||||
paths:
|
||||
- mcp/.npm
|
||||
script:
|
||||
- cd mcp
|
||||
- npm ci --cache .npm --prefer-offline
|
||||
- npm test
|
||||
# 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.
|
||||
- npm run check:node-loadable
|
||||
rules:
|
||||
# A scheduled pipeline exists only to run `renovate` (bottom of this file) — it must not
|
||||
# re-run the suite or republish the edge images once a month for nothing.
|
||||
- if: $CI_PIPELINE_SOURCE == "schedule"
|
||||
when: never
|
||||
- when: on_success
|
||||
|
||||
# --------------------------------------------------------------------------- images
|
||||
|
||||
# Images land at registry.gitlab.com/duartesantos8/opengym/{api,web} and are what
|
||||
# `docker compose pull` fetches.
|
||||
#
|
||||
# On a v* tag: linux/amd64 + linux/arm64, tagged X.Y.Z, X.Y and latest.
|
||||
# On any other branch: amd64 only, tagged `edge` and `main-<sha>`. arm64 is emulated
|
||||
# through QEMU on the shared runners and costs several times the minutes — a self-hoster
|
||||
# on a Pi pulls `latest`, which always comes from a release and is always multi-arch.
|
||||
#
|
||||
# Third way in: start a pipeline by hand (Build -> Pipelines -> New pipeline, or the API)
|
||||
# with the variable PUBLISH_LATEST set to anything. That builds exactly like a tag would — multi-arch,
|
||||
# `latest` and the version out of frontend/package.json — without cutting a release. It is
|
||||
# there for the rebuild-without-a-code-change case: a base image picking up a CVE fix, where
|
||||
# the published `latest` needs to move but the app did not change.
|
||||
build:images:
|
||||
stage: build
|
||||
image: docker:28-cli
|
||||
services:
|
||||
- docker:28-dind
|
||||
variables:
|
||||
DOCKER_HOST: tcp://docker:2376
|
||||
DOCKER_TLS_CERTDIR: "/certs"
|
||||
DOCKER_TLS_VERIFY: "1"
|
||||
DOCKER_CERT_PATH: "/certs/client"
|
||||
needs: ["test:frontend", "test:mcp"]
|
||||
parallel:
|
||||
matrix:
|
||||
- IMAGE: api
|
||||
CONTEXT: "./api"
|
||||
DOCKERFILE: "./api/Dockerfile"
|
||||
- IMAGE: web
|
||||
CONTEXT: "."
|
||||
DOCKERFILE: "./web/Dockerfile"
|
||||
before_script:
|
||||
- echo "$CI_REGISTRY_PASSWORD" | docker login -u "$CI_REGISTRY_USER" --password-stdin "$CI_REGISTRY"
|
||||
# buildx's docker-container driver refuses to read the daemon's TLS material straight
|
||||
# out of DOCKER_HOST/DOCKER_CERT_PATH ("could not create a builder instance with TLS
|
||||
# data loaded from environment"). Freezing the same environment into a named context
|
||||
# and building the builder on top of that is the supported way round it.
|
||||
- docker context create tls-environment
|
||||
script:
|
||||
- |
|
||||
set -eu
|
||||
BUILD_DATE="$(date -u +'%Y-%m-%dT%H:%M:%SZ')"
|
||||
REPO="$CI_REGISTRY_IMAGE/$IMAGE"
|
||||
if [ -n "${CI_COMMIT_TAG:-}" ] || [ -n "${PUBLISH_LATEST:-}" ]; then
|
||||
if [ -n "${CI_COMMIT_TAG:-}" ]; then
|
||||
SEMVER="${CI_COMMIT_TAG#v}"
|
||||
else
|
||||
# No tag to read the version off, so take it from the source of truth the APK job
|
||||
# already uses. `apk add nodejs` would be a 40 MB download for one field.
|
||||
SEMVER="$(sed -n 's/.*"version": *"\([^"]*\)".*/\1/p' frontend/package.json | head -1)"
|
||||
[ -n "$SEMVER" ] || { echo "could not read version from frontend/package.json" >&2; exit 1; }
|
||||
echo "PUBLISH_LATEST: building $SEMVER off $CI_COMMIT_REF_NAME, no release involved"
|
||||
fi
|
||||
VERSION="v$SEMVER"
|
||||
PLATFORMS="linux/amd64,linux/arm64"
|
||||
TAGS="-t $REPO:$SEMVER -t $REPO:${SEMVER%.*} -t $REPO:latest"
|
||||
# Only the arm64 leg needs emulation, and only for the api image (web's build
|
||||
# stage is pinned to $BUILDPLATFORM on purpose — see web/Dockerfile).
|
||||
docker run --privileged --rm tonistiigi/binfmt --install arm64
|
||||
else
|
||||
VERSION="main-$CI_COMMIT_SHORT_SHA"
|
||||
PLATFORMS="linux/amd64"
|
||||
TAGS="-t $REPO:edge -t $REPO:$VERSION"
|
||||
fi
|
||||
docker buildx create --use --name opengym --driver docker-container tls-environment
|
||||
# shellcheck disable=SC2086
|
||||
docker buildx build \
|
||||
--platform "$PLATFORMS" \
|
||||
--file "$DOCKERFILE" \
|
||||
--build-arg "VERSION=$VERSION" \
|
||||
--build-arg "VCS_REF=$CI_COMMIT_SHA" \
|
||||
--build-arg "BUILD_DATE=$BUILD_DATE" \
|
||||
--cache-from "type=registry,ref=$CI_REGISTRY_IMAGE/buildcache:$IMAGE" \
|
||||
--cache-to "type=registry,ref=$CI_REGISTRY_IMAGE/buildcache:$IMAGE,mode=max" \
|
||||
--provenance=false \
|
||||
$TAGS \
|
||||
--push \
|
||||
"$CONTEXT"
|
||||
rules:
|
||||
# A scheduled pipeline exists only to run `renovate` (bottom of this file) — it must not
|
||||
# re-run the suite or republish the edge images once a month for nothing.
|
||||
- if: $CI_PIPELINE_SOURCE == "schedule"
|
||||
when: never
|
||||
- if: $CI_COMMIT_TAG =~ /^v\d+\.\d+\.\d+$/
|
||||
- if: ($CI_PIPELINE_SOURCE == "web" || $CI_PIPELINE_SOURCE == "api") && $PUBLISH_LATEST
|
||||
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
|
||||
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
|
||||
when: manual
|
||||
allow_failure: true
|
||||
|
||||
# ------------------------------------------------------------------------------ apk
|
||||
|
||||
# The official signed APK. Signing keys live in protected CI variables, so they only
|
||||
# exist on protected refs (main and v* tags) — a fork's MR builds an unsigned APK and
|
||||
# cannot get at the key. Sideload-only by design: openGym is on no app store.
|
||||
#
|
||||
# Needs three CI/CD variables (Settings → CI/CD → Variables), all *protected*:
|
||||
# ANDROID_KEYSTORE_B64 file base64 of opengym-release.keystore
|
||||
# ANDROID_KEYSTORE_PASSWORD masked the keystore password
|
||||
# ANDROID_KEY_ALIAS plain opengym
|
||||
# KEEP THAT KEYSTORE: updates must be signed with the same key or Android refuses to
|
||||
# install them over an existing copy.
|
||||
build:apk:
|
||||
stage: package
|
||||
image: cimg/android:2026.08-node
|
||||
needs: ["test:frontend"]
|
||||
variables:
|
||||
GRADLE_USER_HOME: "$CI_PROJECT_DIR/.gradle"
|
||||
GRADLE_OPTS: "-Dorg.gradle.daemon=false"
|
||||
cache:
|
||||
key: "gradle-$CI_COMMIT_REF_SLUG"
|
||||
paths:
|
||||
- .gradle/wrapper
|
||||
- .gradle/caches
|
||||
script:
|
||||
- |
|
||||
set -eu
|
||||
cd frontend
|
||||
npm ci
|
||||
# VITE_MOBILE build + `cap sync` into android/. The mobile flavor talks to no
|
||||
# backend at all: no sign-in, no sync, media straight from the CDN.
|
||||
npm run build:mobile
|
||||
VER="$(node -p "require('./package.json').version")"
|
||||
cd android
|
||||
./gradlew --no-daemon assembleRelease
|
||||
UNSIGNED=app/build/outputs/apk/release/app-release-unsigned.apk
|
||||
BT="$(ls -d "$ANDROID_HOME"/build-tools/* | sort -V | tail -1)"
|
||||
if [ -n "${ANDROID_KEYSTORE_B64:-}" ]; then
|
||||
base64 -d "$ANDROID_KEYSTORE_B64" > "$CI_PROJECT_DIR/.ks.jks"
|
||||
"$BT/zipalign" -f -p 4 "$UNSIGNED" aligned.apk
|
||||
"$BT/apksigner" sign \
|
||||
--ks "$CI_PROJECT_DIR/.ks.jks" \
|
||||
--ks-pass "env:ANDROID_KEYSTORE_PASSWORD" \
|
||||
--ks-key-alias "$ANDROID_KEY_ALIAS" \
|
||||
--key-pass "env:ANDROID_KEYSTORE_PASSWORD" \
|
||||
--out "$CI_PROJECT_DIR/openGym-$VER.apk" aligned.apk
|
||||
rm -f "$CI_PROJECT_DIR/.ks.jks"
|
||||
"$BT/apksigner" verify --print-certs "$CI_PROJECT_DIR/openGym-$VER.apk"
|
||||
elif [ -n "${CI_COMMIT_TAG:-}" ]; then
|
||||
# A release must never quietly ship an APK nobody can install. If the key is missing
|
||||
# on a tag, something is wrong with the protected variables — say so and stop.
|
||||
echo "FATAL: $CI_COMMIT_TAG is a release tag but ANDROID_KEYSTORE_B64 is not set." >&2
|
||||
echo "Set it (protected, file type) under Settings -> CI/CD -> Variables." >&2
|
||||
exit 1
|
||||
else
|
||||
echo "No signing key on this ref — producing an UNSIGNED apk (cannot be installed)."
|
||||
"$BT/zipalign" -f -p 4 "$UNSIGNED" "$CI_PROJECT_DIR/openGym-$VER-unsigned.apk"
|
||||
fi
|
||||
echo "APK_VERSION=$VER" >> "$CI_PROJECT_DIR/apk.env"
|
||||
# On a release tag the APK also goes into the generic package registry, which is
|
||||
# what the Release links to (job artifacts expire; packages do not).
|
||||
- |
|
||||
set -eu
|
||||
cd "$CI_PROJECT_DIR"
|
||||
. ./apk.env
|
||||
if [ -n "${CI_COMMIT_TAG:-}" ] && [ -f "openGym-$APK_VERSION.apk" ]; then
|
||||
# Sideloading means nobody's app store checked this file for you, so publish the
|
||||
# digest next to it rather than leaving people to trust the download.
|
||||
sha256sum "openGym-$APK_VERSION.apk" > "openGym-$APK_VERSION.apk.sha256"
|
||||
cat "openGym-$APK_VERSION.apk.sha256"
|
||||
for f in "openGym-$APK_VERSION.apk" "openGym-$APK_VERSION.apk.sha256"; do
|
||||
curl --fail --silent --show-error \
|
||||
--header "JOB-TOKEN: $CI_JOB_TOKEN" \
|
||||
--upload-file "$f" \
|
||||
"$CI_API_V4_URL/projects/$CI_PROJECT_ID/packages/generic/opengym-android/$APK_VERSION/$f"
|
||||
echo "uploaded $f to the generic package registry"
|
||||
done
|
||||
fi
|
||||
artifacts:
|
||||
name: "openGym-apk-$CI_COMMIT_REF_SLUG"
|
||||
paths:
|
||||
- "openGym-*.apk"
|
||||
- "openGym-*.apk.sha256"
|
||||
reports:
|
||||
dotenv: apk.env
|
||||
expire_in: 30 days
|
||||
rules:
|
||||
# A scheduled pipeline exists only to run `renovate` (bottom of this file) — it must not
|
||||
# re-run the suite or republish the edge images once a month for nothing.
|
||||
- if: $CI_PIPELINE_SOURCE == "schedule"
|
||||
when: never
|
||||
- if: $CI_COMMIT_TAG =~ /^v\d+\.\d+\.\d+$/
|
||||
# An APK build is ~8 minutes of shared-runner time; on main and MRs it is one click
|
||||
# away rather than automatic. Flip `when: manual` off to have every push build one.
|
||||
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
|
||||
when: manual
|
||||
allow_failure: true
|
||||
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
|
||||
when: manual
|
||||
allow_failure: true
|
||||
|
||||
# ---------------------------------------------------------------------------- pages
|
||||
|
||||
# The browser-only demo: https://opengym-bc111a.gitlab.io/
|
||||
# (that opaque host is GitLab's "unique domain" for Pages, on by default; the tidier
|
||||
# https://duartesantos8.gitlab.io/opengym/ 308s to it. Settings → Pages turns it off.)
|
||||
# Pages serves static files only, so this build has no backend — VITE_DEMO=1 makes the
|
||||
# app boot straight into guest mode with a seeded example history (frontend/src/lib/demo.js).
|
||||
# Vite's base is './', so the bundle drops into a subdirectory unchanged.
|
||||
pages:
|
||||
extends: .node
|
||||
stage: deploy
|
||||
needs: ["test:frontend"]
|
||||
variables:
|
||||
VITE_DEMO: "1"
|
||||
script:
|
||||
- cd frontend
|
||||
- npm ci
|
||||
- VITE_IMG_BASE="$DATASET/images/" VITE_GIF_BASE="$DATASET/videos/" npm run build
|
||||
- cd ..
|
||||
- rm -rf public && mv frontend/dist public
|
||||
artifacts:
|
||||
paths:
|
||||
- public
|
||||
rules:
|
||||
# A scheduled pipeline exists only to run `renovate` (bottom of this file) — it must not
|
||||
# re-run the suite or republish the edge images once a month for nothing.
|
||||
- if: $CI_PIPELINE_SOURCE == "schedule"
|
||||
when: never
|
||||
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
|
||||
changes:
|
||||
paths:
|
||||
- "frontend/**/*"
|
||||
- ".gitlab-ci.yml"
|
||||
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
|
||||
when: manual
|
||||
allow_failure: true
|
||||
|
||||
# -------------------------------------------------------------------------- release
|
||||
|
||||
release:
|
||||
stage: release
|
||||
image: registry.gitlab.com/gitlab-org/release-cli:latest
|
||||
needs:
|
||||
- job: build:images
|
||||
- job: build:apk
|
||||
artifacts: true
|
||||
rules:
|
||||
- if: $CI_COMMIT_TAG =~ /^v\d+\.\d+\.\d+$/
|
||||
script:
|
||||
# The release notes are the matching section of CHANGELOG.md, verbatim — headings
|
||||
# there are "## v1.2.9 — 2026-08-23", so take everything up to the next "## ".
|
||||
- |
|
||||
set -eu
|
||||
awk -v tag="$CI_COMMIT_TAG" '
|
||||
$0 ~ "^## " tag "([^0-9.]|$)" { inside = 1; next }
|
||||
inside && /^## / { exit }
|
||||
inside { print }
|
||||
' CHANGELOG.md > release-notes.md
|
||||
if [ ! -s release-notes.md ]; then
|
||||
echo "openGym $CI_COMMIT_TAG" > release-notes.md
|
||||
fi
|
||||
head -40 release-notes.md
|
||||
release:
|
||||
tag_name: $CI_COMMIT_TAG
|
||||
name: "openGym $CI_COMMIT_TAG"
|
||||
description: release-notes.md
|
||||
assets:
|
||||
links:
|
||||
- name: "openGym-$APK_VERSION.apk (Android, sideload)"
|
||||
url: "$CI_API_V4_URL/projects/$CI_PROJECT_ID/packages/generic/opengym-android/$APK_VERSION/openGym-$APK_VERSION.apk"
|
||||
link_type: package
|
||||
- name: "openGym-$APK_VERSION.apk.sha256 (checksum)"
|
||||
url: "$CI_API_V4_URL/projects/$CI_PROJECT_ID/packages/generic/opengym-android/$APK_VERSION/openGym-$APK_VERSION.apk.sha256"
|
||||
link_type: other
|
||||
- name: "Container images (api + web)"
|
||||
url: "$CI_PROJECT_URL/container_registry"
|
||||
link_type: image
|
||||
|
||||
# ---------------------------------------------------------------------- dependencies
|
||||
|
||||
# Dependency updates. GitLab has no Dependabot, so Renovate runs as a job — but only on a
|
||||
# *scheduled* pipeline (Build → Pipeline schedules), so it never fires on a push and never
|
||||
# competes with a real pipeline for runner minutes. Its policy lives in `renovate.json`
|
||||
# next to this file, and it is the same policy the GitHub Dependabot config had: monthly,
|
||||
# grouped per ecosystem, majors on their own, and the native mobile projects left alone.
|
||||
#
|
||||
# Needs one CI/CD variable: RENOVATE_TOKEN — a GitLab token with `api` scope, which is what
|
||||
# lets it read the project and open merge requests.
|
||||
renovate:
|
||||
stage: maintenance
|
||||
image:
|
||||
name: renovate/renovate:41
|
||||
entrypoint: [""]
|
||||
variables:
|
||||
RENOVATE_PLATFORM: gitlab
|
||||
RENOVATE_ENDPOINT: "$CI_API_V4_URL"
|
||||
RENOVATE_AUTODISCOVER: "false"
|
||||
RENOVATE_REPOSITORIES: "$CI_PROJECT_PATH"
|
||||
RENOVATE_ONBOARDING: "false"
|
||||
RENOVATE_REQUIRE_CONFIG: "required"
|
||||
LOG_LEVEL: info
|
||||
script:
|
||||
- renovate
|
||||
rules:
|
||||
- if: $CI_PIPELINE_SOURCE == "schedule" && $RENOVATE_TOKEN
|
||||
# Also runnable by hand from the pipeline page when you want to see what it would do.
|
||||
- if: $CI_PIPELINE_SOURCE == "web" && $RENOVATE_TOKEN
|
||||
when: manual
|
||||
allow_failure: true
|
||||
@@ -0,0 +1,42 @@
|
||||
<!-- GitLab has no issue *forms*, only these Markdown templates: the prompts below are the
|
||||
same ones the GitHub/gitea forms asked for, and they are here because leaving them out
|
||||
costs a round-trip on nearly every report. Delete the italics as you fill them in. -->
|
||||
|
||||
/label ~bug
|
||||
|
||||
### What did you do?
|
||||
|
||||
*Steps to reproduce, as precisely as you can.*
|
||||
|
||||
1.
|
||||
2.
|
||||
3.
|
||||
|
||||
### What did you expect to happen?
|
||||
|
||||
### What happened instead?
|
||||
|
||||
*Error messages, console output or screenshots if you have them.*
|
||||
|
||||
### How are you running openGym?
|
||||
|
||||
*Pick one: self-hosted (docker compose) · frontend dev server (`npm run dev`) · Android APK ·
|
||||
other / not sure*
|
||||
|
||||
### Version & environment
|
||||
|
||||
- openGym version or commit:
|
||||
- Browser & OS: *e.g. Safari 17 on iOS 18, Chrome 126 on Android*
|
||||
|
||||
### Is this about login / passkeys?
|
||||
|
||||
Most login issues are an `RP_ID`/`ORIGIN` mismatch — check your `.env` against the domain you
|
||||
reach openGym on before reporting. See the [self-hosting guide](../../docs/SELF_HOSTING.md).
|
||||
|
||||
- [ ] Yes, and I have already checked `RP_ID`/`ORIGIN`
|
||||
- `RP_ID` =
|
||||
- `ORIGIN` =
|
||||
- What sits in front of the app (reverse proxy, tunnel, none):
|
||||
|
||||
<!-- Security bug? Do not use this template. Open a *confidential* issue instead — tick
|
||||
"This issue is confidential" before submitting. See SECURITY.md. -->
|
||||
@@ -0,0 +1,16 @@
|
||||
/label ~enhancement
|
||||
|
||||
### What problem does this solve?
|
||||
|
||||
*What are you trying to do that openGym doesn't support today?*
|
||||
|
||||
### Proposed approach
|
||||
|
||||
*How would you like it to work? Rough ideas are fine.*
|
||||
|
||||
### Dependencies
|
||||
|
||||
openGym is intentionally dependency-light — new packages, front or back, are a hard sell.
|
||||
See [CONTRIBUTING.md](../../CONTRIBUTING.md).
|
||||
|
||||
- [ ] This doesn't require adding a new dependency
|
||||
@@ -0,0 +1,19 @@
|
||||
<!-- GitLab has no Discussions, so questions live in the issue tracker — labelled, so nobody
|
||||
mistakes a question for agreed-on work. If you'd rather just ask, there is a Discord:
|
||||
https://discord.gg/e62jY6fwVb — an issue is the better place for anything the next
|
||||
person should be able to find by searching. -->
|
||||
|
||||
/label ~question
|
||||
|
||||
### What are you trying to do?
|
||||
|
||||
### What have you tried?
|
||||
|
||||
### Setup
|
||||
|
||||
- openGym version or commit:
|
||||
- How you run it (docker compose / dev server / APK):
|
||||
- If it is about login or passkeys — `RP_ID`, `ORIGIN`, and what sits in front of the app:
|
||||
|
||||
*Login trouble is an `RP_ID`/`ORIGIN` mismatch far more often than not:*
|
||||
[docs/SELF_HOSTING.md](../../docs/SELF_HOSTING.md).
|
||||
@@ -0,0 +1,16 @@
|
||||
### What this changes
|
||||
|
||||
### Why
|
||||
|
||||
*Link the issue if there is one: `Closes #123`.*
|
||||
|
||||
### Checklist
|
||||
|
||||
- [ ] `npm test` passes in `frontend/` (and in `mcp/` if you touched it)
|
||||
- [ ] `npm run build` succeeds
|
||||
- [ ] User-facing strings are in every locale pack — `node scripts/check-locales.mjs`
|
||||
- [ ] No new runtime dependency, or the MR explains why one is unavoidable
|
||||
- [ ] CHANGELOG.md is left alone — release notes are written at release time
|
||||
|
||||
<!-- The pipeline runs the same checks on every MR. An APK build and a container build are
|
||||
available as manual jobs on the pipeline if your change needs one. -->
|
||||
@@ -1,5 +1,720 @@
|
||||
# Changelog
|
||||
|
||||
## v1.2.12 — 2026-08-30
|
||||
|
||||
Six small fixes from the community, each read and tried on staging before it went in. All of
|
||||
them are in the active workout or the exercise settings; nothing changes on the server, so a
|
||||
self-hosted instance only needs the new web bundle.
|
||||
|
||||
### Active workout
|
||||
|
||||
- ➕ **Adding an exercise mid-session puts it right after the one you are on**, not at the end
|
||||
of the list, and the flow carries on from there: "next" takes you to the next *unfinished*
|
||||
exercise and the finish prompt only appears once nothing is left open. Before, a set added
|
||||
late could leave you looking at a completion prompt with work still pending.
|
||||
(Space-Hermes, !42)
|
||||
- ⏱️ **Removing an exercise no longer leaves a timer behind.** A rest countdown that belonged to
|
||||
the removed exercise stops with it — but a rest you are in the middle of for a *different*
|
||||
exercise keeps running and simply follows that exercise. (Space-Hermes, !51, narrowed here)
|
||||
- ⏹️ **Discarding a workout stops a running timed set.** The countdown used to keep going, and
|
||||
beep, on a session that no longer existed. Cancelling the confirmation leaves it running.
|
||||
(Space-Hermes, !59)
|
||||
- 🗺️ **A custom exercise you delete still counts in recovery.** The muscle map and the recovery
|
||||
view read the snapshot saved with each finished workout, so deleting the exercise afterwards
|
||||
no longer blanks the muscles it trained. (Space-Hermes, !58)
|
||||
|
||||
### Exercise settings
|
||||
|
||||
- 🔢 **Progression steps below one can be typed.** Entering `0.5` used to snap back to the
|
||||
default halfway through, because the field rejected the intermediate `0`. Leaving the field
|
||||
empty or at `0` with a progression rule on now marks it red and holds the save, so a step that
|
||||
cannot progress anything can no longer be stored by accident. (mflova, !60)
|
||||
- 📐 **Long values in routine rows no longer squash the title.** The value column is capped
|
||||
instead of reserving space, so a "3 × 12 @ 102.5 kg" row keeps its exercise name readable on a
|
||||
narrow phone. (MokshManral, !37)
|
||||
|
||||
With thanks to Space-Hermes, mflova and MokshManral.
|
||||
|
||||
## v1.2.11 — 2026-08-25
|
||||
|
||||
A correction release. v1.2.10 landed planned warm-ups and notes, and reviewing that release
|
||||
afterwards turned up six defects it had either introduced or made matter — three of them in the
|
||||
warm-up work itself. None of them broke a test, which is the point: they were gaps beside the
|
||||
tests rather than failures in them.
|
||||
|
||||
### Warm-ups
|
||||
|
||||
- ⚖️ **Warm-ups were counted in your session volume.** Every other part of the app leaves them
|
||||
out — records, progression, the muscle map — and the routine screen says so in as many words
|
||||
("left out of volume, records and progression"). Volume was the one place it was not true.
|
||||
Three planned warm-ups on a 3×5 at 100 kg reported 2562.5 instead of 1500, and that number is
|
||||
written into the finished workout, so it would have stayed wrong for good.
|
||||
- 📉 **On a deload, the last warm-up came out heavier than the work sets.** The ramp was built
|
||||
before progression had its say and nothing recalculated it, so a plan dropping from 100 kg to
|
||||
50 kg gave you warm-ups of 50 and 75 under work sets of 50. The ramp is now derived after the
|
||||
prescription, so it always aims at the weight you are actually about to lift. A warm-up you
|
||||
have already logged keeps its weight — it happened.
|
||||
- 🧱 **One too-heavy warm-up spread to the rest.** Editing a warm-up above the working weight
|
||||
made every warm-up added after it inherit that number. Your own edit stays as you typed it;
|
||||
what stops is the inheritance.
|
||||
|
||||
### Notes
|
||||
|
||||
- 📝 **The session note now exists.** v1.2.10 described three kinds of note and shipped two: the
|
||||
code that saves a whole-session note was there, and tested, but nothing in the app ever wrote
|
||||
one. There is a note field next to the finish button now — wrapping up is when you know how
|
||||
the session went.
|
||||
- 💾 **The session note stopped being thrown away.** In a past workout it only saved when the
|
||||
field lost focus, and Escape, the Android back gesture and swipe-to-dismiss all close a sheet
|
||||
without that ever happening. Type a note, press Escape, gone. It now saves on the way out too.
|
||||
|
||||
### Sharing, stats and settings
|
||||
|
||||
- 🔗 **Shared plans carry drop-sets and rest-pause.** A routine built as "3×5 with a double
|
||||
drop" arrived at the other end as a plain 3×5, silently. Both the intensifier and the planned
|
||||
warm-up count are now clamped in both directions, so a hand-edited plan file cannot put a
|
||||
nonsense number in front of you either.
|
||||
- 🔢 **The version is visible again**, at the bottom of Settings — which is where the support
|
||||
template has been telling people to look for it. On the phone there is no address bar, so
|
||||
there was no way to tell which build you had or whether an update installed. (issue #7)
|
||||
- ⏹️ **The rest timer can be turned off.** v1.2.10 made this worse before it made it better: it
|
||||
started resting after every set instead of finishing an exercise quietly, and there was still
|
||||
no way out. "Off" now sits with the other durations.
|
||||
- 📊 **The exercise picker in Stats no longer runs long names into the label** (mflova, !24), and
|
||||
**a chart tooltip no longer lingers from the previous exercise** (mflova, !25). The estimated-1RM
|
||||
series is memoised as well, so the tooltip stops vanishing under your finger while you read it.
|
||||
|
||||
### Website
|
||||
|
||||
- 🌐 **opengym.duarte-santos.ch has been rebuilt** — a bento layout with real device frames, a
|
||||
mobile menu that opens instead of hiding, scroll reveals that respect `prefers-reduced-motion`,
|
||||
and a section collecting where the project actually lives. It had been live for a while without
|
||||
ever being committed, so the repository and the site had drifted apart.
|
||||
|
||||
## v1.2.10 — 2026-08-25
|
||||
|
||||
The first release since the move to GitLab that is mostly **other people's work**. Nine
|
||||
contributors, thirteen merge requests: Brazilian Portuguese in full — interface, all 1,324
|
||||
exercise names and all 7,710 instruction steps — equipment profiles for people who train in more
|
||||
than one gym, drop-sets and rest-pause, a way to pair the mobile app with your own server, and a
|
||||
round of security hardening on the API and the reverse proxy.
|
||||
|
||||
Alongside that, the bugs you reported in #bugs-and-ideas and on the issue tracker, several of
|
||||
which turned out to be worse than they looked from the outside.
|
||||
|
||||
### Training
|
||||
|
||||
- 🔥 **"Add warm-up set" gave you a warm-up at your full working weight.** It looked for the row
|
||||
to ramp from at the position *before* the first work set — which for the first warm-up is
|
||||
index −1, so it fell through to the last row instead: your heaviest set. Every warm-up you
|
||||
added had to be corrected by hand. Warm-ups now ramp toward the work weight, each one closing
|
||||
half the remaining gap (50% → 75% → 87.5%), rounded down to what you can actually load.
|
||||
- 🏋️ **Warm-ups can be planned in the routine.** Set how many an exercise gets and the session
|
||||
starts with them already in place, ramped, instead of you adding them every time. They stay
|
||||
out of volume, records and progression, and they travel with a shared plan.
|
||||
- ⏱️ **The rest timer skipped the last set of every exercise.** It was written as "final sets
|
||||
finish quietly", but another exercise follows that set and you rest before it too — so a
|
||||
two-set exercise timed one rest instead of two. It now rests after every completed set except
|
||||
the last one of the session. (issue #3, and zkssyth arrived at the same rule independently)
|
||||
- 📝 **Notes you can write during a workout**, in three kinds, because they have three different
|
||||
lifetimes: what happened today, on the exercise; what is always true about the movement (seat
|
||||
height, pin position); and how the session went as a whole. The per-session note carries a
|
||||
**pin** — the app cannot know whether "shoulder twinged" is a diary line or "go narrower" is a
|
||||
message to your next self, but you do, at the moment you write it. Pinned notes come back the
|
||||
next time that exercise comes up.
|
||||
- 💥 **Drop-sets and rest-pause / myo-reps**, planned per exercise and extending the set row
|
||||
itself rather than adding new sets.
|
||||
|
||||
### Equipment, and training in more than one gym
|
||||
|
||||
- 🎒 **Equipment profiles.** Build a "Home" and a "Gym" list of what you actually own, and the
|
||||
library, the exercise picker and your routines filter to it — with a warning on any routine
|
||||
exercise that needs something the active profile does not have. Body-weight exercises are
|
||||
always available.
|
||||
|
||||
### Brazilian Portuguese
|
||||
|
||||
- 🇧🇷 **pt-BR is complete**: the interface, every built-in exercise name, and every instruction
|
||||
step. It is defined as a layer over pt-PT rather than a copy, so a string added to Portuguese
|
||||
can never silently go missing here — with tests that fingerprint every inherited entry and
|
||||
refuse European vocabulary (*ficheiro*, *telemóvel*, *ecrã*, «guillemets»).
|
||||
- 🔔 Server-sent notifications — rest-timer alerts, test pushes, workout-day reminders — follow
|
||||
the profile's language instead of always arriving in English.
|
||||
|
||||
### Fixes
|
||||
|
||||
- ✅ **Home kept asking you to do the workout you had just done.** The week strip knew the day was
|
||||
finished; the row underneath did not, and went on showing the routine behind a green Start tag.
|
||||
(issue #4)
|
||||
- 📈 **"Exercise progress" was empty for bodyweight exercises.** Pull-ups and push-ups carry no
|
||||
weight, and every point without one was dropped, so a full history read as "No data yet". When
|
||||
nothing in an exercise's history was ever loaded, the reps are the progress — so that is what
|
||||
is plotted now. Add a weighted set later and it switches back to weight. (issue #5)
|
||||
- 🫥 **The tab bar was see-through.** At 72% opacity the page read straight through it and the
|
||||
labels competed with whatever was scrolling behind them — nobody needs to read the content
|
||||
under a navigation bar. It is 94% now in both themes, and blurs less, which is also faster on
|
||||
Android, where a blur behind a fixed element is recomposited on every scroll frame. Where
|
||||
`backdrop-filter` is unavailable at all — old Android WebViews, "reduce transparency" — the
|
||||
blurred surfaces now go fully opaque instead of leaving just the alpha, which was the worst of
|
||||
both. (reported by mflova, seconded by seals187)
|
||||
- 📥 **No Smith-machine exercise could ever match on import.** The `machine → lever` rule ran
|
||||
before `smith machine → smith`, so the generic one ate the word first. Hevy's vocabulary is
|
||||
now mapped as well, and exercises it cannot match take their body part from the name instead of
|
||||
defaulting to "upper legs" — which had been attributing a third of an imported history to the
|
||||
legs. (diagnosed by rubik_97, fixed by koyosan)
|
||||
- 🗓️ **Charts show the calendar year** when the data spans more than one, so a point from
|
||||
November 2025 is not confused with February 2026. (mflova)
|
||||
- 🔤 **Exercise search matches whole words in any order**, ignores accents, and searches the
|
||||
translated names too — "bench barbell" finds the barbell bench press, "elevacao" finds
|
||||
"elevação". The haystack is now built once per exercise instead of on every keystroke.
|
||||
- 🔑 **Passkeys work in Chrome on iOS**, which was excluded by a user-agent test rather than by
|
||||
asking the browser what it supports.
|
||||
- 📱 The reps field in a superset is no longer squeezed on narrow phones, and secondary muscles
|
||||
are visible while building a plan, not only in the Exercises tab.
|
||||
|
||||
### Self-hosting
|
||||
|
||||
- 🔐 **Security hardening on the API and the proxy**: SSRF and an unbounded handler in push
|
||||
delivery, CSRF from a sibling subdomain, session-cookie shadowing, and non-forgeable proxy
|
||||
headers. Details in SECURITY.md.
|
||||
- 🧭 **When a passkey fails, the error now says what is misconfigured.** "Unexpected RP ID hash"
|
||||
told you nothing about your own `.env`; it now names the `RP_ID` and `ORIGIN` the server is
|
||||
actually running with. `docs/SELF_HOSTING.md` gained a section that works through the usual
|
||||
causes in order — including that `docker compose restart` does not re-read `.env`, and that on
|
||||
a LAN without certificates there is nothing you can configure to make passkeys work.
|
||||
- 📲 **"Connect to my server"** pairs the standalone mobile app to a self-hosted instance with a
|
||||
one-time code, no passkey ceremony needed inside the app's WebView.
|
||||
- 💾 **Optional local auto-backup** on the mobile app after finishing a workout or editing a
|
||||
routine, and a **System** theme option that follows the OS.
|
||||
|
||||
With thanks to mzspicoli, Josevi, andi242, Space_Hermes, Horus Gonzalez, wagenheimer, koyosan,
|
||||
mflova and Aaron Sachs — and to everyone who reported one of the bugs above.
|
||||
|
||||
## v1.2.9 — 2026-08-23
|
||||
|
||||
If you run openGym for other people, you have had no way to answer "who signed in, and when?" —
|
||||
the server kept no record of anything. It does now: an **activity log** in the admin dashboard,
|
||||
covering sign-ins, sign-outs, the attempts that failed, and every admin action. The other half of
|
||||
this release is that **the live demo is back**, self-hosted this time, after two months offline.
|
||||
And the project has a working home again: openGym now lives on **GitLab**, where CI builds the
|
||||
container images and the signed Android APK for every release — the thing that has been missing
|
||||
since the GitHub account went.
|
||||
|
||||
### Activity log
|
||||
|
||||
- 🧾 **The admin dashboard has an activity log.** Successful and failed sign-ins, profile
|
||||
creations and refused signups, sign-outs (including "sign out everywhere"), and every admin
|
||||
action: disabling or re-enabling an account, creating or revoking an invite code, and clearing
|
||||
the log itself. Filter it by sign-ins, admin actions or failures, and page back through it.
|
||||
- 📄 **It is a plain file.** `./data/audit.log`, one JSON object per line — `tail -f` and `jq`
|
||||
read it directly, which also means it is its own export format. Deliberately *not* part of
|
||||
`db.json`: that file is rewritten in full on every save, and the sign-in handshake is
|
||||
unauthenticated, so a log living in there would have turned one junk request into a full
|
||||
rewrite. Retention is a cap rather than an archive — the last `AUDIT_MAX` events (5,000) or
|
||||
`AUDIT_DAYS` days (90), whichever runs out first.
|
||||
- 🔒 **It records less than you might expect, on purpose.** No IP addresses unless you turn them
|
||||
on (`AUDIT_IP=net` keeps only the network, `full` keeps the address); never the browser's
|
||||
user-agent; and never the passkey id behind a failed sign-in, because that id is a stable handle
|
||||
for one device and storing it would let an admin follow an unknown device from one attempt to
|
||||
the next. A rejected invite code is not stored either — a near-miss guess sitting in a log file
|
||||
helps nobody.
|
||||
- 🧹 **Clearing it is itself logged**, and the event ids keep counting, so an erased stretch always
|
||||
leaves a visible gap.
|
||||
- ⚙️ **On by default when you update, and one variable turns it off.** It records strictly less
|
||||
than your instance already holds — every profile is in `db.json`, every workout is in
|
||||
`state-<uid>.json`, and any admin can already read both — and a log that ships switched off
|
||||
tells you nothing on the day you need it. `AUDIT_LOG=0` disables it completely; no file is
|
||||
written. Nothing leaves your server either way: this is a local file, not telemetry.
|
||||
- Guests still never appear anywhere — guest mode does not talk to the server at all.
|
||||
|
||||
### The live demo is back
|
||||
|
||||
- ▶️ **<https://opengym.duarte-santos.ch/demo/>** — the in-browser demo, running on the project's
|
||||
own site instead of GitHub Pages, which went down in August with the suspended account. Same
|
||||
build as before: no backend, no account, seeded example history, and a reset button in its
|
||||
settings. The embedded demo on the landing page works again too.
|
||||
|
||||
### openGym moved to GitLab
|
||||
|
||||
- 🏠 **<https://gitlab.com/DuarteSantos8/opengym>** is the home of the project. Same history,
|
||||
same tags, same AGPL. gitea.com was the stopgap after the GitHub suspension and stays as a
|
||||
mirror; it never had a CI runner, which is why releases there had no images.
|
||||
- 🐳 **Prebuilt images are back.** `docker compose pull` now fetches
|
||||
`registry.gitlab.com/duartesantos8/opengym/api` and `/web`, built for **amd64 and arm64** on
|
||||
every release. Pulling is anonymous — the project is public, no login, no token.
|
||||
- 🤖 **The APK is built by CI now, not by hand.** Every `vX.Y.Z` tag produces a `zipalign`ed,
|
||||
signed APK, attached to the GitLab release and mirrored onto the download page. The signing
|
||||
key sits in protected CI variables, so it exists only on `main` and on version tags — a
|
||||
merge request from a fork builds an unsigned APK and never touches the key.
|
||||
- ✅ **Every merge request is tested again.** The frontend suite (346 tests), the locale checks,
|
||||
the fatigue probe and the MCP suite all run on GitLab CI. The GitHub Actions workflows stay
|
||||
in `.github/` for the day that account comes back.
|
||||
- 🌐 The in-browser demo also builds to GitLab Pages
|
||||
(<https://opengym-bc111a.gitlab.io/>, which <https://duartesantos8.gitlab.io/opengym/>
|
||||
redirects to); <https://opengym.duarte-santos.ch/demo/> remains the copy the landing page
|
||||
embeds.
|
||||
- 📄 Security reports have a private channel again: a **confidential issue** on GitLab. See
|
||||
`SECURITY.md`.
|
||||
- 🔁 **Dependency updates continue.** GitLab has no Dependabot, so Renovate runs from a monthly
|
||||
scheduled pipeline with the same deliberately quiet policy the Dependabot config had:
|
||||
grouped per ecosystem, majors on their own, odd-numbered Node images skipped, and the
|
||||
generated `android/`/`ios/` projects left to follow their `@capacitor/*` packages. Security
|
||||
advisories ignore the schedule and land on their own.
|
||||
|
||||
### Housekeeping
|
||||
|
||||
- The self-hosting docs, `SECURITY.md` and `.env.example` cover the activity log, and the
|
||||
`api/server.js` line references in `SECURITY.md` are accurate again.
|
||||
- Every repository link in the README, the docs, the app and the website points at GitLab, and
|
||||
the website's live star/release numbers come from GitLab's API.
|
||||
|
||||
## 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).
|
||||
|
||||
### Features
|
||||
|
||||
- 🇧🇷 **Brazilian Portuguese UI** — Portuguese now has separate Portugal and
|
||||
Brazil options, with Brazilian terminology, date formatting and localized
|
||||
instructions for all 1,324 exercises. Built-in exercise titles show the
|
||||
Brazilian Portuguese name followed by the canonical English name, so both
|
||||
vocabularies remain recognizable and searchable.
|
||||
|
||||
### Fixes
|
||||
|
||||
- 🔔 **Server-generated notifications follow Brazilian Portuguese** — rest-timer
|
||||
alerts, test notifications and workout-day reminders now use the profile's
|
||||
`pt-BR` language instead of always arriving in English.
|
||||
|
||||
- ⬅️ **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
|
||||
old app recorded come across with the rest of your history. Plus: the phone stops locking itself
|
||||
mid-workout, the rest timer can hand time back as well as take it, and Settings is grouped by
|
||||
what each thing actually affects.
|
||||
|
||||
### The screen stays on while you train
|
||||
|
||||
- ☀️ **Keep screen awake — Settings → *During a workout*, on by default.** Locking, unlocking
|
||||
and finding your place again between every set was the single most annoying thing about
|
||||
logging on a phone. The screen now stays lit for as long as a workout is running and lets go
|
||||
the moment you finish it, so nothing is held while you are not training.
|
||||
- **It survives a tab switch.** Browsers release the lock whenever the page stops being visible,
|
||||
which is exactly what happens when you glance at a message. The lock is taken again each time
|
||||
the app comes back, rather than dying the first time you look away.
|
||||
- **It follows the workout, not the screen you are on.** Checking Stats mid-session keeps the
|
||||
screen awake.
|
||||
- **Where it isn't available, it says so.** iOS grants no wake lock in Low Power Mode, and older
|
||||
browsers have no Wake Lock API at all — the first is silent, the second shows the row disabled
|
||||
rather than offering a switch that does nothing. Needs HTTPS, like every other modern browser
|
||||
capability.
|
||||
|
||||
### Rest timer: take 15 seconds off, too
|
||||
|
||||
- ⏳ **A −15s button next to +15s.** The timer could only ever be extended or skipped outright;
|
||||
now it goes both ways. Taking off more than is left finishes the rest rather than counting
|
||||
into the negative — the same thing Skip does.
|
||||
- **Rearranged so three controls fit.** The clock and the progress bar take the top row and the
|
||||
controls sit underneath: −15 and +15 together in number-line order, Skip pushed to the far
|
||||
edge so the button that ends the rest is not next to the one you tap to buy more time. On a
|
||||
wide screen it stays on one line. Tap targets are bigger than they were.
|
||||
- **The bar is nearly opaque.** The set rows underneath were reading through it and making the
|
||||
clock hard to pick out.
|
||||
|
||||
### Settings, grouped by what it affects
|
||||
|
||||
- **General** (language, units) · **During a workout** (rest timer, keep screen awake, sounds,
|
||||
effort per set) · **Notifications** · **Appearance** (theme, body diagram, accent) · **Data**.
|
||||
- The old grouping mixed axes: "Units & timer" put a display preference next to two workout
|
||||
behaviours, language sat under Appearance, and *Load starter plan* was buried between the
|
||||
backup actions and the destructive reset. Data now reads in the order you would use it — fill
|
||||
the plan, bring history over from another app, restore a backup, export one, wipe everything.
|
||||
- Nothing was removed and no setting changed its meaning.
|
||||
|
||||
### Effort per set: RIR or RPE (#21)
|
||||
|
||||
- 🎯 **A third column on a working set, off by default.** Settings → *Effort per set* switches
|
||||
it between **Off**, **RIR** and **RPE**. It only appears on weighted rep sets: a plank or a
|
||||
treadmill row has nowhere to put it.
|
||||
- **Two names for the same judgement.** RIR counts the reps you left in the tank; RPE reads the
|
||||
same effort off a 10-point scale, so RPE ≈ 10 − RIR. The setting has an (i) that lays the two
|
||||
scales side by side in a conversion table rather than explaining them in a paragraph.
|
||||
- **Each set keeps the scale it was logged with.** Switching the setting changes what new sets
|
||||
ask for and nothing else — history is never silently rewritten, and a set logged as RIR 2
|
||||
still reads back as RIR 2 years later.
|
||||
- **An unrated set stays unrated.** Blank and 0 are different things: RIR 0 says the set went to
|
||||
failure. So `−` on an untouched cell leaves it empty, `+` starts at the bottom of the scale
|
||||
and walks up in even steps, and stepping back off the bottom clears the cell again — a mistap
|
||||
is always undoable.
|
||||
- **Nothing else reads the value.** Progression rules and estimated 1RM are unaffected; the
|
||||
rating is yours to look at, not an input to the maths.
|
||||
- Upgrading keeps the column you had: a profile still carrying the old `showRir` flag — from
|
||||
this device, a sync, or a backup restored later — comes across as RIR.
|
||||
|
||||
### Import brings your ratings with it
|
||||
|
||||
- 📥 **The RPE Hevy and Strong export is no longer dropped.** An `RPE` column is read into the
|
||||
set, as is an `RIR` column if a file has one, and the import summary says how many sets
|
||||
arrived with a rating — plus where to switch the column on if it's off.
|
||||
- A blank cell stays unrated rather than becoming 0. A written-out `0` counts as a rating on the
|
||||
RIR scale (a set to failure) but not on RPE, which starts at 1 — apps write 0 there to mean
|
||||
"nothing here", and reading it as an effort would stamp one on every unrated set in the file.
|
||||
- Ratings above the scale are capped instead of thrown away, and junk in the column is ignored
|
||||
without losing the set.
|
||||
- Backups already carried both fields and the setting, since a backup is the whole state — there
|
||||
are now tests pinning that, so it can't quietly stop being true.
|
||||
|
||||
## v1.2.2 — 2026-07-25
|
||||
|
||||
Training that moves on its own: an exercise can now be logged by time instead of reps, the
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
# CLAUDE.md
|
||||
|
||||
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
||||
|
||||
## What this is
|
||||
|
||||
openGym is a self-hosted gym & body-weight tracker PWA. Two containers (`api` + `web`) plus a
|
||||
`./data` folder the user owns — no third-party account, no telemetry. Passkey (WebAuthn) login,
|
||||
installable as a home-screen app, optional Capacitor shells for standalone Android/iOS builds.
|
||||
License: AGPL-3.0-or-later.
|
||||
|
||||
## Project layout
|
||||
|
||||
```
|
||||
frontend/ React 19 + Vite app (src/views, src/components, src/store, src/lib). Builds to static files.
|
||||
android/ + ios/ are the Capacitor shells for the standalone mobile app (docs/MOBILE.md).
|
||||
api/ backend — server.js (Node, no framework), deps: @simplewebauthn/server, web-push.
|
||||
web/ multi-stage Dockerfile (builds frontend → nginx) + nginx.conf.template (serves app, proxies /api).
|
||||
mcp/ optional MCP server — read-only stdio bridge exposing a user's workouts/1RM/muscle
|
||||
balance to LLM clients (Claude Desktop, Cursor…). Not part of the Docker build; only
|
||||
runs when an LLM client spawns it.
|
||||
media/ exercise img/gif, gitignored, fetched at runtime by the `media` compose service.
|
||||
website/ static marketing site (plain HTML/CSS/JS), deployed separately by .gitlab-ci.yml.
|
||||
docs/ SELF_HOSTING.md, MOBILE.md.
|
||||
```
|
||||
|
||||
## Commands
|
||||
|
||||
```bash
|
||||
# Local stack (api + web + media, prebuilt or built from source)
|
||||
cp .env.example .env
|
||||
docker compose up -d --build
|
||||
|
||||
# Frontend dev server (hot reload), proxies /api to :3000
|
||||
cd frontend && npm install && npm run dev
|
||||
|
||||
# Frontend tests (training logic: progression, 1RM, session read-back)
|
||||
cd frontend && npm test # vitest run
|
||||
cd frontend && npm run test:watch
|
||||
npx vitest run src/lib/progression.test.js # single file
|
||||
npx vitest run -t "some test name" # single test by name
|
||||
|
||||
# MCP server tests
|
||||
cd mcp && npm test
|
||||
|
||||
# Production build
|
||||
cd frontend && npm run build
|
||||
cd frontend && npm run build:mobile # + cap sync, points media at the CDN dataset
|
||||
```
|
||||
|
||||
There is no linter/formatter configured (no ESLint/Prettier config in the repo) and no
|
||||
TypeScript — match the existing style by hand.
|
||||
|
||||
The CI gate is `.gitlab-ci.yml` on GitLab, the canonical remote (see README): it runs the
|
||||
`frontend/` tests on Node 22 — the same version as `web/Dockerfile` / `api/Dockerfile`
|
||||
(`node:22-alpine`) — and additionally builds and publishes the Docker images, packages the
|
||||
signed Android APK, and deploys the demo/docs site. The Gitea and GitHub workflow copies
|
||||
(`.gitea/workflows/`, `.github/workflows/`) are dormant mirrors; neither host runs them.
|
||||
|
||||
## Architecture
|
||||
|
||||
### Frontend (`frontend/src`)
|
||||
|
||||
- **`store/useStore.js`** — single Zustand store holding the entire client-side app state (`S`),
|
||||
persisted to `localStorage` (`gym_state_v1`) and debounce-pushed to the server when signed in
|
||||
(`pushState`, see `lib/api.js`). On the Capacitor mobile build it's also mirrored to a file via
|
||||
`lib/mobile.js` (`nativeSave`), since WebView storage can be evicted. `store/useUI.js` holds
|
||||
ephemeral UI state (modals, active sheet, etc.) separately from persisted data.
|
||||
- **`lib/`** — pure, framework-free helpers, each paired with a same-directory `*.test.js`. This
|
||||
is where the domain logic lives, most importantly:
|
||||
- `progression.js` — the progression-rule engine (linear, Greyskull LP, double progression,
|
||||
time-based). Rules implement a shared policy interface; adding a new one plugs in here.
|
||||
- `onerm.js` — estimated 1RM from logged sets.
|
||||
- `finish-workout.js` — reduces a completed session back into state (weights advance, PRs, etc).
|
||||
- `recovery.js` / `recovery-view.js` — fatigue/muscle-recovery model.
|
||||
- `workout-model.js`, `supersetFlow.js` — in-session workout state machine, incl. supersets.
|
||||
- `exercises.js` / `exercises-data.js` — the exercise library (1,324 built-ins + user-defined).
|
||||
- `api.js` — the only place that talks to the backend (`fetch` wrapper, session cookie flows).
|
||||
- CONTRIBUTING.md is explicit: **anything that decides what you lift next, or reads a logged
|
||||
session back, is a pure helper here with a unit test beside it** — not verifiable by
|
||||
clicking, and the progression engine has already had two bugs that only a test caught.
|
||||
- **`views/`** — one file per screen (Home, Workout, Plan, Library, Stats, History, Settings,
|
||||
Admin, Login, RoutineEdit), routed by `react-router-dom` from `App.jsx`.
|
||||
- **`components/`** — shared UI (charts, modals, timers); `instr/` holds per-language exercise
|
||||
instruction text; `locales/` is the i18n string catalogue (`lib/i18n.js` / `i18n-core.js`).
|
||||
- Mobile: `@capacitor/*` wraps the same web build into native shells under `frontend/android` and
|
||||
`frontend/ios` (see `docs/MOBILE.md`); `mobile.js` in `lib/` gates native-only behavior (file
|
||||
persistence, local notifications, wake lock) behind a `MOBILE` flag.
|
||||
|
||||
### API (`api/server.js`)
|
||||
|
||||
Single file, no framework, plain `node:http`. Requests are dispatched through a `routes` object
|
||||
keyed by `'METHOD /path'` (e.g. `routes['GET /api/health']`) matched against `req.method + ' ' +
|
||||
url.pathname` — add a new endpoint by adding a key here. State is two flat JSON files under
|
||||
`DATA_DIR` (`db.json`: users/credentials/subscriptions/invites; `state-<uid>.json`: per-user
|
||||
workout data), written with a write-temp-then-rename atomic pattern (`atomicWrite`). Auth is
|
||||
WebAuthn passkeys (`@simplewebauthn/server`) plus a signed session cookie (HMAC'd with a
|
||||
`DATA_DIR/secret` generated on first boot) — no JWT/session-store dependency. Optional pieces
|
||||
gated by env vars: `ADMIN_UIDS` (admin dashboard), `INVITE_ONLY` (signup needs a code),
|
||||
`ALLOW_GUEST` (client-only guest mode never hits the server at all), plus a rotating
|
||||
`data/audit.log` (JSONL) for sign-in/admin events. Web Push (`web-push`, VAPID keys
|
||||
auto-generated into `data/vapid.json`) drives rest-timer-over and day-reminder notifications.
|
||||
|
||||
### MCP server (`mcp/src`)
|
||||
|
||||
Read-only stdio MCP bridge (`@modelcontextprotocol/sdk`) that lets an LLM client read a single
|
||||
user's routines/workouts/body-weight/1RM/muscle-balance directly from the same `DATA_DIR` the API
|
||||
writes to — no network call, no extra container. `state.js` loads/derives the data, `tools.js`
|
||||
defines the exposed MCP tools (zod-validated schemas), `labels.js` maps internal keys to
|
||||
human-readable labels, `index.js` wires it together. See `mcp/README.md` for the client-config
|
||||
side (Claude Desktop / Cursor).
|
||||
|
||||
### Passkeys and self-hosting constraints
|
||||
|
||||
WebAuthn passkeys are bound to an exact hostname (`RP_ID`) and require HTTPS (localhost excepted)
|
||||
— this shapes a lot of the API and Settings code (`RP_ID`/`ORIGIN` env vars, guest-mode fallback
|
||||
when neither is available). Read `docs/SELF_HOSTING.md` before touching auth, session, or
|
||||
notification code; it documents the exact env-var contract (`RP_ID`, `ORIGIN`, `PORT`,
|
||||
`WEB_PORT`, `NGINX_PORT`, `BACKEND`, `SESSION_DAYS`, `ADMIN_UIDS`, `INVITE_ONLY`, `ALLOW_GUEST`,
|
||||
`AUDIT_*`, `VAPID_SUBJECT`) that real deployments depend on.
|
||||
|
||||
### Docker / deploy
|
||||
|
||||
`docker-compose.yml` has three services: `media` (one-shot exercise-asset downloader, gitignored
|
||||
output), `api`, `web` (multi-stage build of `frontend/` served by nginx, which also proxies
|
||||
`/api` → `api` and serves the shared media volume — single origin, required for passkeys).
|
||||
`web/nginx.conf.template` is rendered from env vars at container start (`NGINX_PORT`, `BACKEND`,
|
||||
`PORT`), so host/port remapping works against prebuilt images without a rebuild.
|
||||
|
||||
## Guidelines from CONTRIBUTING.md worth knowing before changing code
|
||||
|
||||
- **Dependency-light is a hard constraint, not a preference.** Frontend: React + Router + Zustand
|
||||
and nothing else. `api/`: two dependencies total. New dependencies are a hard sell either side.
|
||||
- Don't commit `media/` or `data/` (gitignored).
|
||||
- Training-logic changes (progression, 1RM, session read-back) need a unit test in `src/lib`
|
||||
beside the code, not just manual clicking-through.
|
||||
@@ -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,12 +31,13 @@ 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.
|
||||
- **Test the flow** you touched — click through the affected screens (and the workout flow) in a
|
||||
browser before opening a PR.
|
||||
browser before opening a merge request.
|
||||
- **Training logic gets a unit test.** Anything deciding what you lift next, or reading a logged
|
||||
session back, belongs in a pure helper in `src/lib` with tests beside it (`npm test`). These
|
||||
rules are easy to get subtly wrong and nearly impossible to verify by clicking — the
|
||||
@@ -47,6 +51,22 @@ 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 quick question, or you'd rather just chat | [The Discord](https://discord.gg/e62jY6fwVb) |
|
||||
| A question, or self-hosting that won't behave | [An issue labelled `question`](https://gitlab.com/DuarteSantos8/opengym/-/issues) |
|
||||
| An idea you're not sure about yet | [An issue labelled `idea`](https://gitlab.com/DuarteSantos8/opengym/-/issues) |
|
||||
| A reproducible bug | [Issues](https://gitlab.com/DuarteSantos8/opengym/-/issues) |
|
||||
| A change you've already built | A merge request |
|
||||
|
||||
GitLab 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.
|
||||
That is the one thing the Discord can't do, so if an answer there turns out to be worth keeping,
|
||||
it belongs in an issue afterwards.
|
||||
|
||||
## Reporting bugs
|
||||
|
||||
Open an issue with: what you did, what you expected, what happened, and your browser/OS. If it's
|
||||
|
||||
@@ -46,11 +46,80 @@ 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.
|
||||
openGym obtains both through
|
||||
[**hasaneyldrm/exercises-dataset**](https://github.com/hasaneyldrm/exercises-dataset), which
|
||||
licenses them differently. Neither is covered by openGym's AGPL license.
|
||||
|
||||
That dataset is itself a redistribution: the content originates from
|
||||
[**ExerciseDB v1**](https://exercisedb.dev/) by **AscendAPI**. This is verifiable from openGym's
|
||||
own data — the stored media filenames embed ExerciseDB's `exerciseId` (openGym's `0001` is
|
||||
`0001-2gPfomN.jpg`; `2gPfomN` is ExerciseDB's id for "3/4 sit-up"), every metadata field matches,
|
||||
and the instruction sentences are identical apart from stripped `Step:N ` prefixes. See
|
||||
[issue #5](https://github.com/hasaneyldrm/exercises-dataset/issues/5) on that dataset.
|
||||
|
||||
### Metadata & instruction text
|
||||
|
||||
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`)
|
||||
originate from ExerciseDB v1 and reach openGym through the dataset above, which distributes them
|
||||
under the MIT license reproduced below. The translations into languages other than English are
|
||||
openGym's own derivative work and are covered by openGym's AGPL.
|
||||
|
||||
```
|
||||
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 — third-party, not MIT and not AGPL
|
||||
|
||||
The exercise thumbnails (180×180) and animations are **not** covered by the MIT license above and
|
||||
**not** by openGym's AGPL. Their ownership is currently **unresolved**, and openGym states this
|
||||
plainly rather than guessing:
|
||||
|
||||
- The upstream dataset attributes them to **© [Gym visual](https://gymvisual.com/)**, redistributed
|
||||
there with that rights holder's written permission — a permission granted to *that dataset* and
|
||||
**not transferable**.
|
||||
- **ExerciseDB/AscendAPI** describes itself as "the original creator and owner" of this content and
|
||||
publishes its own [terms](https://exercisedb.io/faq), which permit self-hosting, bundling and
|
||||
commercial display, while prohibiting redistribution of the raw dataset or media as a standalone
|
||||
or competing content package.
|
||||
|
||||
These two claims contradict each other. A clarification has been requested from AscendAPI; this
|
||||
notice will be updated once the provenance is settled.
|
||||
|
||||
**Until then, treat the media as third-party content licensed to neither openGym nor to you.**
|
||||
|
||||
**openGym does not redistribute it.** It is not in this repository, not in its history, and not in
|
||||
the published container 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 — **clear it with
|
||||
the rights holder first**, and keep any attribution that accompanies it intact.
|
||||
|
||||
Brazilian Portuguese exercise instructions under
|
||||
`scripts/instruction-sources/pt-BR.json` and exercise names under
|
||||
`scripts/exercise-name-sources/pt-BR.json` are original translations of that
|
||||
English source produced with OpenAI Codex and Anthropic Claude Code
|
||||
language-model assistance. They are not copied from a separate Portuguese
|
||||
dataset. Their review status and translation policy are documented alongside
|
||||
the source files.
|
||||
@@ -0,0 +1,188 @@
|
||||
# PROJECT_CONTEXT.md
|
||||
|
||||
Notes for whoever picks this up next. Not a spec — a map of what changed and why, kept next to
|
||||
the code it describes. See `CLAUDE.md` for the general architecture; this file only covers the
|
||||
drop-set / rest-pause work.
|
||||
|
||||
## What this adds
|
||||
|
||||
Two new set "shapes" on top of the existing straight/warm-up model:
|
||||
|
||||
- **Drop-set**: a main set followed by one or more weight drops, logged with no real rest.
|
||||
- **Rest-pause / myo-reps**: an activation set (a normal set near failure) followed by short
|
||||
bursts of extra reps, each preceded by a brief rest.
|
||||
|
||||
Both are **planned on the exercise**, in the same config sheet used by the routine editor and by
|
||||
"add exercise" mid-workout (`ExConfig` in `sheets.jsx`) — not decided live during the workout.
|
||||
Planning it stamps every set of that exercise and pre-fills the actual drop/burst rows with
|
||||
real, already-editable numbers the moment the session starts. A straight (unplanned) set can
|
||||
still grow a drop/burst live via "+ Drop"/"+ Burst" — that path never went away, it just isn't
|
||||
the primary one anymore.
|
||||
|
||||
## The set row (`frontend/src/lib/workout-model.js`)
|
||||
|
||||
There was never a `type` enum on a set row before this — only `phase` (`'work'` / `'warmup'`,
|
||||
with a legacy `warmup: true` boolean as fallback). This adds a **second, orthogonal**
|
||||
discriminator, `type`:
|
||||
|
||||
```js
|
||||
phase: 'work' | 'warmup' // existing axis — prep or the real session?
|
||||
type: 'straight' | 'dropset' | 'restpause' // new axis — what shape is this row? (default 'straight')
|
||||
```
|
||||
|
||||
A drop-set or rest-pause row is still exactly one entry in `entry.sets` — the extra work rides
|
||||
*inside* that row, the same trick `phase` already uses for warm-ups:
|
||||
|
||||
```js
|
||||
// dropset — main set + extra drops ON TOP of it (extraVolumeOf adds the drops back in for totals)
|
||||
{ type: 'dropset', w: 100, r: 5, done: true, drops: [{ w: 80, r: 5 }, { w: 64, r: 5 }] }
|
||||
|
||||
// restpause — the row's own r IS the total across every burst; clusters are a BREAKDOWN of that
|
||||
// same total, not extra on top of it (12 → [6, 3, 2, 1], and 6+3+2+1 == 12, always)
|
||||
{ type: 'restpause', w: 60, r: 12, done: true, clusters: [{ r: 6, restSec: 15 }, { r: 3, restSec: 15 }, { r: 2, restSec: 15 }, { r: 1, restSec: 15 }] }
|
||||
```
|
||||
|
||||
Those two extras genuinely mean different things, which trips people up (it tripped this
|
||||
implementation up first): a drop-set's `drops` are *additional* work beyond the main set — the
|
||||
main set stays a real, separate effort. A rest-pause row's `clusters` are the *decomposition* of
|
||||
its own `r` — there is no separate "first burst is the real one" distinction, `r` already speaks
|
||||
for the whole thing. Getting this backwards is exactly the bug this file's earlier revision had:
|
||||
`r` held only the split's biggest chunk, so the row displayed a random-looking fraction of what
|
||||
was configured instead of the number that was actually typed in.
|
||||
|
||||
Pure helpers in `workout-model.js`, mirroring the existing `phaseForSet`/`isWarmupRow` style:
|
||||
|
||||
- `setType(set)`, `isDropSet(set)`, `isRestPauseSet(set)` — read the discriminator.
|
||||
- `dropsOf(set)` / `clustersOf(set)` — the extras array, or `[]` for anything else.
|
||||
- `extraVolumeOf(set)` — weight×reps across a drop-set's `drops`, on top of the row's own w×r.
|
||||
**Zero for rest-pause** — see above, its `clusters` never add to this or they'd double-count.
|
||||
- `addDrop(set, drop)` / `addCluster(set, cluster)` — pure append, stamps `type`.
|
||||
- `removeDropAt(set, i)` / `removeClusterAt(set, i)` — pure remove by index; clearing the last
|
||||
one reverts the row to `'straight'`.
|
||||
- `setDropAt(set, i, patch)` / `setClusterAt(set, i, patch)` — pure in-place edit (the weight/reps
|
||||
steppers on an already-added drop/burst).
|
||||
- `nextDropWeight(prevWeight, pct)` — pct% lighter than `prevWeight`, rounded to the nearest .5.
|
||||
- `nextBurstReps(prevReps)` — roughly half of `prevReps`, floored at 1.
|
||||
- `splitBurstReps(total)` — splits a rest-pause **total** rep count into a descending,
|
||||
roughly-halving sequence of bursts that sums back to it (`12 → [6, 3, 2, 1]`). This is what a
|
||||
planned rest-pause exercise configures directly: you say how many total reps you want out of
|
||||
the whole rest-pause portion, not how many separate rests.
|
||||
|
||||
In `Workout.jsx`, `addBurstRow`/`removeCluster`/`setClusterField` all adjust the row's own `r` by
|
||||
the same delta as whatever they just did to `clusters`, so the invariant (`r` == sum of every
|
||||
`clustersOf` entry) survives live edits too, not just the initial plan — including the case of
|
||||
tapping "+ Burst" cold on a plain straight set, where the set's original reps become the seed a
|
||||
running total grows from rather than a separately-standing "main" effort. `addDrop`/`removeDrop`
|
||||
on a drop-set row do **not** do this — a drop-set's main set stays independent on purpose.
|
||||
|
||||
## Planning (`ExConfig` in `sheets.jsx`) → `cfg.intensifier`
|
||||
|
||||
The exercise config sheet (routine editor and mid-workout "add exercise" both use it) has an
|
||||
"Intensifier" picker: None / Drop-set / Rest-pause. Selecting one adds `intensifier` to the saved
|
||||
config:
|
||||
|
||||
```js
|
||||
// drop-set: every configured set becomes a drop-set — N drops, each pct% lighter than the one before
|
||||
{ intensifier: { type: 'dropset', count: 2, pct: 20 } }
|
||||
|
||||
// rest-pause: NOT applied per set. It replaces the exercise's whole set list with exactly two
|
||||
// rows regardless of the configured "Sets" (which the UI hides once this is selected, since it
|
||||
// no longer means anything) — a warm-up at the exercise's own "Reps" field, then one rest-pause
|
||||
// work set. Doing the full activation+bursts protocol several times over isn't how rest-pause is
|
||||
// actually trained, so this is a structural replacement, not a per-row stamp like drop-set.
|
||||
{ intensifier: { type: 'restpause', totalReps: 12, restSec: 15 } }
|
||||
```
|
||||
|
||||
`applyIntensifierPlan(sets, cfg)` (`history.js`) applies that. It must run **after**
|
||||
`applyPrescription`: a drop-set's chain of drops is a percentage of each row's own `w`, so it has
|
||||
to use the final prescribed weight, not the pre-progression one `buildSets` started from — same
|
||||
reasoning for where the two rest-pause rows get their weight from. Both call sites chain it last:
|
||||
|
||||
```js
|
||||
applyIntensifierPlan(applyPrescription(buildSets(st, cfg), plan), cfg) // beginWorkout, sheets.jsx
|
||||
applyIntensifierPlan(freestyle ? sets : applyPrescription(sets, plan), full) // add-exercise, Workout.jsx
|
||||
```
|
||||
|
||||
`buildSets` itself knows nothing about intensifiers — it only builds the plain rows (for
|
||||
rest-pause, `applyIntensifierPlan` discards all of them but the weight).
|
||||
|
||||
**Known open questions, deliberately left alone for now:**
|
||||
- The progression engine (`readSession`/`nextPrescription`) judges a rest-pause exercise's one
|
||||
non-warm-up row against `target.reps` — the exercise's plain "Reps" field (what the *warm-up*
|
||||
row uses), compared against the work row's `r`, which is now the rest-pause *total* and so is
|
||||
usually well above that goal. In practice this means a rest-pause exercise will almost always
|
||||
read as "hit the goal" and progress — not obviously wrong, but not a deliberately designed
|
||||
comparison either.
|
||||
- `onerm.js`'s `estimate1RM` refuses anything past `REP_CAP` (12 reps) as "work capacity, not
|
||||
strength" — a rest-pause row's `r` being the total means any rest-pause exercise with a total
|
||||
over 12 (most of them) never contributes a 1RM estimate or PR. Also not fixed — it falls out
|
||||
naturally from an existing, deliberate rule, not a new one, but worth knowing it applies here.
|
||||
|
||||
## Guided workout UI (`Workout.jsx`)
|
||||
|
||||
Every non-warm-up reps-mode row renders its drops/clusters as **editable sub-rows** right under
|
||||
it (`.subrow`, reusing the same stepper look as the main row, just smaller) — not read-only chips
|
||||
behind a sheet. A planned exercise arrives with these already filled in; nothing needs pressing
|
||||
for them to show up. `"+ Drop"`/`"+ Burst"` (hidden on whichever type doesn't apply to that row)
|
||||
just appends one more entry with the same suggested-next-value math
|
||||
(`nextDropWeight`/`nextBurstReps`), for a drop/burst beyond what was planned, or for turning an
|
||||
unplanned straight set into one on the spot.
|
||||
|
||||
There is deliberately **no countdown timer** for rest-pause bursts anymore (an earlier version of
|
||||
this had one, using the work-timer bar) — with the burst rows already pre-filled and editable,
|
||||
forcing a real-time countdown added friction without adding value; the short rest between bursts
|
||||
is self-timed.
|
||||
|
||||
**Testing gotcha, not a code bug:** `S.active` (the in-progress workout) and each routine's saved
|
||||
`intensifier` config both live in `localStorage` and are untouched by redeploying the container.
|
||||
Iterating on this feature while an old workout is still active, or without re-saving an
|
||||
already-configured exercise, replays stale pre-`totalReps` data. Discard the active workout and
|
||||
re-save the exercise's config after a schema change like this one.
|
||||
|
||||
## Settings (`useStore.js` DEF, `Settings.jsx`)
|
||||
|
||||
`S.restPauseSec` (default 15) is the fallback rest used when "+ Burst" is tapped on a set with no
|
||||
planned rest-pause of its own. It's a real user-editable default now — **Settings → During a
|
||||
workout → Rest-pause rest** — the same pattern as the existing `S.restSec` (long) rest timer.
|
||||
A planned exercise's own `intensifier.restSec` always overrides this.
|
||||
|
||||
## Why most of the app didn't need to change
|
||||
|
||||
1RM estimation (`onerm.js`) and the progression engine (`progression.js`) read a set row's own
|
||||
`w`/`r`/`sec` directly, never anything nested — so a drop-set's main set, or a rest-pause row's
|
||||
own total, is automatically the only thing they see; `drops`/`clusters` never had to be taught to
|
||||
either of them. What *did* need a one-line hook, because they sum across a session rather than
|
||||
reading one row:
|
||||
|
||||
- `workoutVolume` (`history.js`) — adds `extraVolumeOf(s)` on top of `w×r` per row. Drop-set
|
||||
drops count; rest-pause clusters don't (see above — they're already inside the row's own `r`).
|
||||
- `setTonnage` (`recovery.js`) — same split: `extraTonnage(...)` prices a drop-set's drops with
|
||||
the same intensity-weighted formula (`load × reps × min(1, load/1RM)^1.5`) as the main set, and
|
||||
is a no-op for rest-pause for the same double-counting reason.
|
||||
- `applyPrescription` (`progression.js`) — when a policy grows the set count (bodyweight double
|
||||
progression, issue #33), the newly appended row keeps the seed's `type` (that's the exercise's
|
||||
plan) but never its already-logged `drops`/`clusters` (that's specific work the new row never
|
||||
actually did).
|
||||
|
||||
`muscles.js`'s `loadOf` ("effective sets" for the muscle-balance map) is untouched on purpose: a
|
||||
drop-set/rest-pause row still counts as one set there, same as today — that model was never
|
||||
weight-based to begin with.
|
||||
|
||||
## Persistence
|
||||
|
||||
No backend or schema change was needed. `api/server.js` writes `state-<uid>.json` verbatim with
|
||||
no set-shape validation beyond "is an object". The MCP server (`mcp/src`) re-imports the same
|
||||
`workoutVolume`/`onerm.js`/`muscles.js` helpers from `frontend/src/lib` rather than duplicating
|
||||
them, so its reported volume/1RM figures pick up the fix automatically too.
|
||||
|
||||
## i18n
|
||||
|
||||
All new strings are translated in `locales/es.js` (the other ten locales fall back to English via
|
||||
`t()`, which is safe but not localized — nobody's asked for those yet).
|
||||
|
||||
## Out of scope for this pass
|
||||
|
||||
- Import from other apps (FitNotes/Strong/Hevy) — no equivalent concept there yet.
|
||||
- Planning which *specific* sets of an exercise get the intensifier — it's all-or-nothing per
|
||||
exercise (every set), which is what was asked for; a "last set only" option would need a
|
||||
per-row opt-out on top of this.
|
||||
@@ -19,9 +19,12 @@ 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://gitlab.com/DuarteSantos8/opengym/-/pipelines)
|
||||

|
||||
[](https://gitlab.com/DuarteSantos8/opengym/-/starrers)
|
||||
[](https://gitlab.com/DuarteSantos8/opengym/-/issues)
|
||||
[](https://discord.gg/e62jY6fwVb)
|
||||
[](https://buymeacoffee.com/duartesantos)
|
||||
|
||||
</div>
|
||||
|
||||
@@ -39,11 +42,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 GitLab](https://gitlab.com/DuarteSantos8/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>Want to poke at it first? The <a href="https://opengym.duarte-santos.ch/demo/">in-browser
|
||||
demo</a> is the real app with example data — no account, nothing to install.</sub>
|
||||
|
||||
</div>
|
||||
|
||||
@@ -60,23 +63,31 @@ as a home-screen app, passkey sign-in, offline support, sync across your phone a
|
||||
- 🏋️ **Weekly plan** — a routine per weekday, over a library of **1,324 exercises** (searchable, with animated demos)
|
||||
- 🗓️ **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
|
||||
- 🔗 **Supersets** — build them, and log them back-to-back with a rest only after the pair
|
||||
- ☀️ **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** — 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
|
||||
- 🛠️ **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
|
||||
- 🔑 **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, invite-only signup, and an **activity log** of sign-ins, failed attempts and admin actions. 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
|
||||
- 🌍 **13 languages** — full UI translation (EN, DE, ES, FR, IT, PT (Portugal), PT (Brazil), PL, TR, RU, ZH, KO, HI); exercise instructions localized in 11 of them and built-in exercise names shown bilingually in PT-BR, all 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)
|
||||
@@ -84,7 +95,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://gitlab.com/DuarteSantos8/opengym
|
||||
cd openGym
|
||||
cp .env.example .env
|
||||
docker compose pull # grab prebuilt images (amd64 + arm64) — skip to build from source instead
|
||||
@@ -92,8 +103,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 reaches openGym through
|
||||
> [hasaneyldrm/exercises-dataset](https://github.com/hasaneyldrm/exercises-dataset), which
|
||||
> redistributes [ExerciseDB v1](https://exercisedb.dev/) — its metadata and instruction text are
|
||||
> MIT, but the images and animations are third-party content under *neither* that MIT license nor
|
||||
> openGym's AGPL, and their ownership is currently disputed between Gym visual and ExerciseDB.
|
||||
> openGym ships none of it: your instance downloads it from upstream. Reusing it yourself,
|
||||
> commercially or not, means clearing it with the rights holder — see [NOTICE.md](NOTICE.md).
|
||||
Prefer building the images yourself instead of pulling from
|
||||
GitLab's registry? 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
|
||||
@@ -106,8 +126,10 @@ no backend — everything stays on the phone, with native workout-day reminders
|
||||
backups. Self-hosting gets you multi-device sync and profiles for friends & family; the
|
||||
mobile app is the install-and-done flavor.
|
||||
|
||||
- **Android:** [**download the APK**](https://opengym.duarte-santos.ch) and sideload it —
|
||||
openGym is deliberately not on the Play Store. Or build it yourself: **[docs/MOBILE.md](docs/MOBILE.md)**.
|
||||
- **Android:** [**download the APK**](https://opengym.duarte-santos.ch) — or straight from
|
||||
[GitLab's package registry](https://gitlab.com/DuarteSantos8/opengym/-/packages), where every
|
||||
build sits next to its `.sha256` — and sideload it; openGym is deliberately not on the Play
|
||||
Store. Or build it yourself: **[docs/MOBILE.md](docs/MOBILE.md)**.
|
||||
- **iPhone:** Apple doesn't allow installing apps outside the App Store, so there is no iOS
|
||||
download. Self-host and add it to your home screen from Safari (it's a full PWA), or build
|
||||
the native app onto your own device from Xcode — see **[docs/MOBILE.md](docs/MOBILE.md)**.
|
||||
@@ -128,13 +150,14 @@ 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
|
||||
|
||||
Lives in `./data` on your host: `db.json` (profiles + public passkeys), `state-<user>.json`
|
||||
(each user's plan, workouts, body weight, settings), and `secret` (the session-cookie key).
|
||||
(each user's plan, workouts, body weight, settings), `audit.log` (the admin activity log — sign-ins
|
||||
and admin actions, no IP addresses unless you ask for them) and `secret` (the session-cookie key).
|
||||
**Back up `./data` and you've backed up everything.** Passkey private keys never touch the
|
||||
server — they stay in your phone's secure hardware / your password manager.
|
||||
|
||||
@@ -147,11 +170,23 @@ 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)* |
|
||||
| `AUDIT_LOG` | Record sign-ins and admin actions — set `0` to record nothing | *(on)* |
|
||||
| `AUDIT_MAX` | Events kept in the activity log; `0` for no limit | `5000` |
|
||||
| `AUDIT_DAYS` | Days kept in the activity log; `0` to keep until `AUDIT_MAX` | `90` |
|
||||
| `AUDIT_IP` | Record the caller's address: `off`, `net` (network only) or `full` | `off` |
|
||||
| `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
|
||||
|
||||
@@ -162,15 +197,17 @@ Rough, community-driven — ideas and PRs welcome:
|
||||
- [x] Estimated 1RM per exercise
|
||||
- [ ] Percentage / training-max programming (5/3/1-style) on top of the progression engine
|
||||
- [ ] More starter plans (upper/lower, full-body, 5×5)
|
||||
- [x] Importers from FitNotes / Strong / Hevy, and body weight from Apple Health
|
||||
- [x] Importers from FitNotes / Strong / Hevy (including the RPE they record), and body weight from Apple Health
|
||||
- [x] Effort per set — RIR or RPE, whichever scale you think in
|
||||
- [ ] Body measurements (waist, arms…) alongside weight
|
||||
- [ ] Per-exercise notes & plate calculator
|
||||
- [ ] Exercise instructions in German & Portuguese (UI is translated; upstream dataset doesn't ship these yet)
|
||||
- [ ] Exercise instructions in German & Portuguese (Portugal); the separately curated Brazilian Portuguese pack is complete
|
||||
|
||||
## 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`.
|
||||
|
||||
@@ -179,15 +216,64 @@ 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
|
||||
|
||||
- **[Discord](https://discord.gg/e62jY6fwVb)** — release announcements, self-hosting help and
|
||||
the back-and-forth that would be a slow issue thread. Quickest way to get an answer.
|
||||
- **[Issues](https://gitlab.com/DuarteSantos8/opengym/-/issues)** — bugs, questions, self-hosting
|
||||
help and ideas. There are no Discussions here, 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. Use
|
||||
an issue over the Discord for anything the next person should be able to find by searching.
|
||||
- **Login trouble?** Most of it is an `RP_ID`/`ORIGIN` mismatch — check
|
||||
[docs/SELF_HOSTING.md](docs/SELF_HOSTING.md) before opening an issue.
|
||||
- **Merge requests** — [open one on GitLab](https://gitlab.com/DuarteSantos8/opengym/-/merge_requests); see
|
||||
[CONTRIBUTING.md](CONTRIBUTING.md).
|
||||
|
||||
> **On the GitHub repo:** `github.com/DuarteSantos8/openGym` is offline because the account was
|
||||
> suspended. **GitLab is the home of the project** — same history, same tags, same releases, and
|
||||
> the CI that builds the images and the APK runs there. (gitea.com/DuarteSantos/openGym was the
|
||||
> first stopgap and is now only a mirror.) Old GitHub issue and PR numbers in
|
||||
> [CHANGELOG.md](CHANGELOG.md) are kept as plain references; they don't map onto GitLab'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, there's a coffee button
|
||||
below (and a badge at the top) — a star, a bug report or a merge request is worth just as much.
|
||||
|
||||
<!-- GitLab has no Sponsor button the way GitHub's FUNDING.yml gave one, so the link has to
|
||||
stand on its own here. .github/FUNDING.yml stays put for the day that account returns. -->
|
||||
|
||||
<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 originate from [ExerciseDB v1](https://exercisedb.dev/) and reach openGym through
|
||||
[hasaneyldrm/exercises-dataset](https://github.com/hasaneyldrm/exercises-dataset) under the
|
||||
**MIT** license. The exercise images and animations are third-party content covered by neither
|
||||
that license nor the AGPL, and their ownership is **currently unresolved** — the upstream dataset
|
||||
attributes them to [Gym visual](https://gymvisual.com/) under a non-transferable permission, while
|
||||
[ExerciseDB/AscendAPI](https://exercisedb.io/faq) claims to be their creator and owner. A
|
||||
clarification has been requested. openGym does not redistribute them (your instance fetches them
|
||||
at first run) and does not relicense them. To reuse that media yourself, clear it with the rights
|
||||
holder first.
|
||||
|
||||
Full third-party notices, including the body-diagram geometry: **[NOTICE.md](NOTICE.md)**.
|
||||
@@ -0,0 +1,209 @@
|
||||
# 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 in GitLab's registry.
|
||||
|
||||
Updating a self-hosted instance:
|
||||
|
||||
```bash
|
||||
git pull && docker compose pull && docker compose up -d
|
||||
```
|
||||
|
||||
## Reporting a vulnerability
|
||||
|
||||
The project lives on GitLab. It has no security-advisory workflow on the free tier, but it does
|
||||
have **confidential issues**, and that is the private channel: open an issue at
|
||||
<https://gitlab.com/DuarteSantos8/opengym/-/issues/new> and tick **"This issue is confidential"**
|
||||
*before* you submit. A confidential issue is readable only by project members — you'll see it,
|
||||
I'll see it, nobody else will, and it stays that way if it is later closed.
|
||||
|
||||
If you'd rather not put the details in GitLab at all, open a confidential issue saying only
|
||||
*"I need an address for a security report"* — no details, no repro, no version — and you'll get
|
||||
one back 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 *non-confidential* issue if it can be used against other
|
||||
people's instances — and not in the Discord either, which is a public room. 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** `registry.gitlab.com/duartesantos8/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.** `web/nginx.conf.template` sets `X-Frame-Options: DENY`,
|
||||
`Content-Security-Policy: frame-ancestors 'none'`, `X-Content-Type-Options: nosniff` and
|
||||
`Referrer-Policy: same-origin`. It deliberately does **not** set HSTS or a full CSP: TLS is the
|
||||
reverse proxy's job, and a script/style policy tight enough to be worth having needs testing
|
||||
against the built app rather than being asserted here. A concrete attack that a header 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 GitLab 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:561-620`, `api/server.js:622-675`).
|
||||
- **Sessions are a signed cookie.** It carries `<uid>:<expiry>:<version>` plus an
|
||||
HMAC-SHA256 tag over it, compared in constant time (`api/server.js:230-243`). The key is 32
|
||||
random bytes generated on first run and written to `./data/secret` with mode `0600`
|
||||
(`api/server.js:40-43`). The cookie is `HttpOnly` and `SameSite=Lax`, and gets `Secure` **only
|
||||
when `ORIGIN` starts with `https:`** (`api/server.js:36`, `api/server.js:316-322`). On an https
|
||||
instance it is named `__Host-gymsid`: the prefix makes the *browser* enforce that the cookie is
|
||||
host-only, which is what stops a sibling subdomain from planting a second session cookie on the
|
||||
shared parent domain and having it shadow the real one. Over plain `http://localhost` the
|
||||
prefix is not allowed, so the old name `gymsid` stays; both are accepted on the way in, so
|
||||
upgrading signs nobody out. If one name ever arrives twice with different values, both are
|
||||
refused rather than guessing which is the real session (`api/server.js:261`).
|
||||
- **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:249`, `api/server.js:302-303`), 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:727-748`); 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:299`, `api/server.js:667`).
|
||||
- **Push endpoints cannot be aimed at your network.** A subscription's `endpoint` is a URL the
|
||||
server connects out to and it comes from whoever is signed in, so `/api/push/*` would otherwise
|
||||
be a request-forgery lever from inside the Docker network. It must be `https:`, and the
|
||||
connection is refused at socket level if the host resolves to a loopback, private, link-local
|
||||
(including cloud metadata) or CGNAT address — enforced in the agent's DNS lookup, not in a
|
||||
prior pass, so there is no rebinding window (`api/server.js:86-119`). Sends have a 10 s timeout
|
||||
(a stalling endpoint used to hang the request handler indefinitely), run at most 6 at a time,
|
||||
and each account is capped at 20 subscriptions, so one small request cannot become an unbounded
|
||||
burst of outbound connections (`api/server.js:84`).
|
||||
- **There is an activity log.** Sign-ins, sign-outs, failed and refused attempts, and every admin
|
||||
action are appended to `./data/audit.log`, one JSON object per line, and shown in the admin
|
||||
dashboard. It is on by default (`AUDIT_LOG=0` disables it) and capped at `AUDIT_MAX` events /
|
||||
`AUDIT_DAYS` days. Clearing it from the dashboard is itself recorded and the event ids keep
|
||||
counting, so an erased stretch always leaves a visible gap.
|
||||
|
||||
### 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, `audit.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.** With the
|
||||
activity log on, `./data/audit.log` adds everyone's sign-in times to that — worth remembering
|
||||
before an archive of `./data` goes somewhere you don't run.
|
||||
- **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:825-947`). 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:677-681`) — a copy taken beforehand keeps working. Sessions last **90 days** by
|
||||
default, settable with `SESSION_DAYS` (`api/server.js:33`); 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` plus an origin check, not tokens.** There are no CSRF
|
||||
tokens. `SameSite=Lax` alone was not enough: it keeps the cookie off a cross-*site* request but
|
||||
a sibling subdomain (`gym.example.com` vs anything else under `example.com` — one domain, one
|
||||
reverse proxy, several apps, i.e. the usual self-hosting layout) is the *same* site and does
|
||||
get the cookie. So every state-changing request that a browser sent must also be
|
||||
`Sec-Fetch-Site: same-origin`, or carry an `Origin` equal to `ORIGIN` where that header is
|
||||
missing (`api/server.js:344`). Requests authenticated with a Bearer token skip the check —
|
||||
a browser never attaches one by itself, so there is no ambient authority to borrow — as do the
|
||||
register/login/pair handshakes, which carry their own credential in the body and act on no
|
||||
existing session (`api/server.js:338`).
|
||||
- **User verification is preferred, not required.** Both handshakes pass
|
||||
`requireUserVerification: false` (`api/server.js:575`, `api/server.js:644`), 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:600-609`); 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. It also makes them near-invisible in the activity log: a disabled
|
||||
account is refused at the session check, so nothing it does produces an entry except the failed
|
||||
sign-ins it keeps attempting.
|
||||
- **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:544`), 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:891`) — 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:34`).
|
||||
- **The activity log is not an audit archive, and it records less than you might assume.** No IP
|
||||
address unless you set `AUDIT_IP` (`net` truncates to a /24 or /48; the default is `off`). When it is on, the
|
||||
address comes from `CF-Connecting-IP`, `X-Forwarded-For`, `X-Real-IP` or, failing all three,
|
||||
the connecting socket — so it is only as trustworthy as whatever sits in front, which has to
|
||||
*overwrite* those headers rather than pass a client-supplied one through. The bundled web
|
||||
container now does: it replaces `X-Forwarded-For`/`X-Real-IP` with the real peer and drops
|
||||
`CF-Connecting-IP` unless you set `CF_CONNECTING_IP=$http_cf_connecting_ip`, which is correct
|
||||
only with Cloudflare genuinely in front. Before that it appended to `X-Forwarded-For` and
|
||||
passed `CF-Connecting-IP` straight through, and the API reads the first entry — so any caller
|
||||
could choose the address recorded against it. Never the browser's user-agent,
|
||||
and never the passkey id behind a failed sign-in — that id is a stable
|
||||
handle for one device, and storing it would let an admin follow an unknown device from attempt
|
||||
to attempt. So a failed sign-in from a passkey this instance doesn't know is recorded as a time
|
||||
and nothing else. Retention is a cap, not an archive: old events are dropped, not exported. Any
|
||||
admin can clear the whole log from the dashboard. And four of the paths that write to it —
|
||||
the invite check on `POST /api/register/options`, and the expired-challenge and unknown-passkey
|
||||
branches of the register/login handshakes — are reachable **without a session**, so with no rate
|
||||
limit in front (see below) anyone can fill the log with noise. It is an append of ~110 bytes per
|
||||
event to a capped file, never a rewrite of `db.json`, so the cost is a log full of noise rather
|
||||
than a full disk or a slow server.
|
||||
- **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://gitlab.com/DuarteSantos8" \
|
||||
org.opencontainers.image.title="opengym-api" \
|
||||
org.opencontainers.image.description="Backend for Self-hosted gym & body-weight tracker — plan routines, log workouts (supersets & cardio too), track your weight and progress, passkey login. Your data, your server." \
|
||||
org.opencontainers.image.source="https://gitlab.com/DuarteSantos8/opengym" \
|
||||
org.opencontainers.image.url="https://gitlab.com/DuarteSantos8/opengym/container_registry" \
|
||||
org.opencontainers.image.documentation="https://gitlab.com/DuarteSantos8/opengym#readme" \
|
||||
org.opencontainers.image.licenses="AGPL-3.0-or-later" \
|
||||
org.opencontainers.image.version=$VERSION \
|
||||
org.opencontainers.image.revision=$VCS_REF \
|
||||
org.opencontainers.image.created=$BUILD_DATE
|
||||
|
||||
WORKDIR /app
|
||||
COPY package.json package-lock.json* ./
|
||||
RUN npm install --omit=dev && npm cache clean --force
|
||||
COPY server.js ./
|
||||
COPY server.js push-messages.js verify-error.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,12 +1,13 @@
|
||||
{
|
||||
"name": "gym-api",
|
||||
"version": "1.2.2",
|
||||
"version": "1.2.13",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "server.js",
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"scripts": {
|
||||
"start": "node server.js"
|
||||
"start": "node server.js",
|
||||
"test": "node --test"
|
||||
},
|
||||
"dependencies": {
|
||||
"@simplewebauthn/server": "^13.1.1",
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
const COPY = {
|
||||
en: {
|
||||
restTitle: 'Rest over 💪',
|
||||
restBody: 'Time for your next set.',
|
||||
testBody: 'Test notification ✅ — this is what alerts look like.',
|
||||
dayFallbackTitle: 'Workout planned today',
|
||||
dayRoutineSuffix: 'today',
|
||||
dayBody: "It's on your plan — let's go 💪",
|
||||
},
|
||||
'pt-BR': {
|
||||
restTitle: 'Descanso terminado 💪',
|
||||
restBody: 'Hora da próxima série.',
|
||||
testBody: 'Notificação de teste ✅ — é assim que os alertas aparecem.',
|
||||
dayFallbackTitle: 'Treino planejado para hoje',
|
||||
dayRoutineSuffix: 'hoje',
|
||||
dayBody: 'Está no seu plano — vamos treinar 💪',
|
||||
},
|
||||
};
|
||||
|
||||
const copyFor = lang => COPY[lang] || COPY.en;
|
||||
|
||||
export function restTimerPush(lang) {
|
||||
const copy = copyFor(lang);
|
||||
return { title: copy.restTitle, body: copy.restBody, tag: 'rest-timer' };
|
||||
}
|
||||
|
||||
export function testPush(lang) {
|
||||
return { title: 'openGym', body: copyFor(lang).testBody, tag: 'test' };
|
||||
}
|
||||
|
||||
export function dayReminderPush(lang, routine) {
|
||||
const copy = copyFor(lang);
|
||||
return {
|
||||
title: routine
|
||||
? `${routine.emoji || '🏋️'} ${routine.name} ${copy.dayRoutineSuffix}`
|
||||
: copy.dayFallbackTitle,
|
||||
body: copy.dayBody,
|
||||
tag: 'day-reminder',
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { dayReminderPush, restTimerPush, testPush } from './push-messages.js';
|
||||
|
||||
test('localizes every server-generated notification in pt-BR', () => {
|
||||
assert.deepEqual(restTimerPush('pt-BR'), {
|
||||
title: 'Descanso terminado 💪',
|
||||
body: 'Hora da próxima série.',
|
||||
tag: 'rest-timer',
|
||||
});
|
||||
assert.deepEqual(testPush('pt-BR'), {
|
||||
title: 'openGym',
|
||||
body: 'Notificação de teste ✅ — é assim que os alertas aparecem.',
|
||||
tag: 'test',
|
||||
});
|
||||
assert.deepEqual(dayReminderPush('pt-BR', { name: 'Treino A', emoji: '💪' }), {
|
||||
title: '💪 Treino A hoje',
|
||||
body: 'Está no seu plano — vamos treinar 💪',
|
||||
tag: 'day-reminder',
|
||||
});
|
||||
});
|
||||
|
||||
test('keeps the existing English copy as the fallback', () => {
|
||||
assert.deepEqual(restTimerPush('fr'), restTimerPush('en'));
|
||||
assert.equal(dayReminderPush('unknown', null).title, 'Workout planned today');
|
||||
assert.equal(testPush(undefined).body, 'Test notification ✅ — this is what alerts look like.');
|
||||
});
|
||||
@@ -4,11 +4,15 @@ import http from 'node:http';
|
||||
import crypto from 'node:crypto';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import https from 'node:https';
|
||||
import dns from 'node:dns';
|
||||
import {
|
||||
generateRegistrationOptions, verifyRegistrationResponse,
|
||||
generateAuthenticationOptions, verifyAuthenticationResponse
|
||||
} from '@simplewebauthn/server';
|
||||
import webpush from 'web-push';
|
||||
import { dayReminderPush, restTimerPush, testPush } from './push-messages.js';
|
||||
import { verifyError } from './verify-error.js';
|
||||
|
||||
const PORT = +(process.env.PORT || 3000);
|
||||
const DATA = process.env.DATA_DIR || '/data';
|
||||
@@ -19,7 +23,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;' : '';
|
||||
@@ -56,37 +69,112 @@ catch { vapid = webpush.generateVAPIDKeys(); fs.writeFileSync(vapidFile, JSON.st
|
||||
const VAPID_SUBJECT = process.env.VAPID_SUBJECT || (SECURE ? ORIGIN : 'mailto:admin@localhost');
|
||||
webpush.setVapidDetails(VAPID_SUBJECT, vapid.publicKey, vapid.privateKey);
|
||||
|
||||
/* A push subscription's `endpoint` is a URL this server connects out to, chosen by whoever is
|
||||
signed in — so without a check /api/push/* is a request-forgery lever, and the api container
|
||||
sits on the same Docker network as the rest of the self-hoster's stack. Three limits below:
|
||||
|
||||
1. PUSH_AGENT rejects any connection to a private/loopback/link-local address at the moment
|
||||
the socket is opened. Validating the URL alone would leave a DNS-rebinding window — the
|
||||
name is resolved a second time inside web-push — so the check has to live in the lookup
|
||||
the request itself uses, not in a prior pass.
|
||||
2. PUSH_TIMEOUT_MS: an endpoint that accepts TCP and then stalls used to hang the request
|
||||
handler that awaited it, indefinitely. web-push sets no timeout of its own.
|
||||
3. PUSH_CONCURRENCY: one small request must not turn into an unbounded burst of outbound
|
||||
connections (with MAX_SUBS_PER_USER below, that is the other half of the same problem). */
|
||||
const PUSH_TIMEOUT_MS = 10000;
|
||||
const PUSH_CONCURRENCY = 6;
|
||||
const MAX_SUBS_PER_USER = 20;
|
||||
|
||||
function isPrivateAddr(ip) {
|
||||
const v = String(ip).toLowerCase();
|
||||
const m4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(v);
|
||||
if (m4) {
|
||||
const a = +m4[1], b = +m4[2];
|
||||
if (a === 0 || a === 10 || a === 127) return true; // this-network, private, loopback
|
||||
if (a === 169 && b === 254) return true; // link-local (cloud metadata)
|
||||
if (a === 172 && b >= 16 && b <= 31) return true; // private
|
||||
if (a === 192 && b === 168) return true; // private
|
||||
if (a === 192 && b === 0) return true; // 192.0.0.0/24, 192.0.2.0/24
|
||||
if (a === 100 && b >= 64 && b <= 127) return true; // CGNAT
|
||||
if (a >= 224) return true; // multicast + reserved
|
||||
return false;
|
||||
}
|
||||
const m6 = /^::ffff:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/.exec(v);
|
||||
if (m6) return isPrivateAddr(m6[1]); // IPv4-mapped IPv6
|
||||
if (v === '::' || v === '::1') return true; // unspecified, loopback
|
||||
if (/^fe[89ab]/.test(v)) return true; // link-local
|
||||
if (/^f[cd]/.test(v)) return true; // unique local
|
||||
return false;
|
||||
}
|
||||
|
||||
// Same shape as dns.lookup, so https.Agent can use it directly.
|
||||
function guardedLookup(hostname, options, cb) {
|
||||
dns.lookup(hostname, options, (err, address, family) => {
|
||||
if (err) return cb(err);
|
||||
const list = Array.isArray(address) ? address : [{ address, family }];
|
||||
if (list.some(a => isPrivateAddr(a.address))) {
|
||||
return cb(Object.assign(new Error('refusing to connect to a private address: ' + hostname), { code: 'EPUSHBLOCKED' }));
|
||||
}
|
||||
cb(null, address, family);
|
||||
});
|
||||
}
|
||||
const PUSH_AGENT = new https.Agent({ lookup: guardedLookup, keepAlive: false });
|
||||
|
||||
// Cheap pre-check so a bad endpoint is refused at subscribe time with a useful message, rather
|
||||
// than silently never delivering. PUSH_AGENT is what actually enforces the address rule.
|
||||
function pushEndpointError(raw) {
|
||||
let u;
|
||||
try { u = new URL(String(raw || '')); } catch { return 'endpoint is not a valid URL'; }
|
||||
if (u.protocol !== 'https:') return 'endpoint must be an https:// URL';
|
||||
if (u.username || u.password) return 'endpoint must not carry credentials';
|
||||
// A literal address can be judged right here, which turns the common case into a clear error
|
||||
// at subscribe time instead of a delivery that quietly never happens. Hostnames are left to
|
||||
// PUSH_AGENT, which is the check that actually has to hold.
|
||||
const host = u.hostname.replace(/^\[|\]$/g, '');
|
||||
if (/^[0-9.]+$/.test(host) || host.includes(':')) {
|
||||
if (isPrivateAddr(host)) return 'endpoint must not point at a private address';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
async function sendPush(userId, payload) {
|
||||
const subs = db.subs.filter(s => s.userId === userId);
|
||||
if (!subs.length) return;
|
||||
const body = JSON.stringify(payload);
|
||||
let dirty = false;
|
||||
await Promise.all(subs.map(async sub => {
|
||||
// urgency 'high' is the one lever we have over delivery speed — iOS/Android throttle
|
||||
// low-urgency background push more aggressively under battery-saving modes. TTL is left
|
||||
// at the library default (long) so a briefly-offline device still gets it once reconnected,
|
||||
// rather than risking it being dropped for the sake of shaving off latency that TTL doesn't
|
||||
// actually control anyway.
|
||||
try { await webpush.sendNotification({ endpoint: sub.endpoint, keys: sub.keys }, body, { urgency: 'high' }); }
|
||||
catch (e) {
|
||||
console.error('push send failed', userId, e.statusCode, e.body || e.message);
|
||||
if (e.statusCode === 404 || e.statusCode === 410) {
|
||||
db.subs = db.subs.filter(s => s.endpoint !== sub.endpoint); dirty = true;
|
||||
let next = 0;
|
||||
const worker = async () => {
|
||||
while (next < subs.length) {
|
||||
const sub = subs[next++];
|
||||
// urgency 'high' is the one lever we have over delivery speed — iOS/Android throttle
|
||||
// low-urgency background push more aggressively under battery-saving modes. TTL is left
|
||||
// at the library default (long) so a briefly-offline device still gets it once reconnected,
|
||||
// rather than risking it being dropped for the sake of shaving off latency that TTL doesn't
|
||||
// actually control anyway.
|
||||
try {
|
||||
await webpush.sendNotification({ endpoint: sub.endpoint, keys: sub.keys }, body,
|
||||
{ urgency: 'high', timeout: PUSH_TIMEOUT_MS, agent: PUSH_AGENT });
|
||||
} catch (e) {
|
||||
console.error('push send failed', userId, e.statusCode, e.body || e.message);
|
||||
if (e.statusCode === 404 || e.statusCode === 410) {
|
||||
db.subs = db.subs.filter(s => s.endpoint !== sub.endpoint); dirty = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}));
|
||||
};
|
||||
await Promise.all(Array.from({ length: Math.min(PUSH_CONCURRENCY, subs.length) }, worker));
|
||||
if (dirty) saveDb();
|
||||
}
|
||||
|
||||
// Rest-timer alerts: client schedules on start/extend, cancels on skip or on-screen completion —
|
||||
// this only fires when the tab was backgrounded/suspended and never got to cancel it itself.
|
||||
const restTimers = new Map(); // userId -> Timeout
|
||||
function scheduleRestTimer(userId, sec) {
|
||||
function scheduleRestTimer(userId, sec, lang) {
|
||||
const t = restTimers.get(userId);
|
||||
if (t) clearTimeout(t);
|
||||
restTimers.set(userId, setTimeout(() => {
|
||||
restTimers.delete(userId);
|
||||
sendPush(userId, { title: 'Rest over 💪', body: 'Time for your next set.', tag: 'rest-timer' });
|
||||
sendPush(userId, restTimerPush(lang));
|
||||
}, sec * 1000));
|
||||
}
|
||||
function cancelRestTimer(userId) {
|
||||
@@ -130,11 +218,7 @@ setInterval(() => {
|
||||
console.log('reminder firing', user.id, rid);
|
||||
user.lastReminder = now.date;
|
||||
saveDb();
|
||||
sendPush(user.id, {
|
||||
title: routine ? `${routine.emoji || '🏋️'} ${routine.name} today` : 'Workout planned today',
|
||||
body: "It's on your plan — let's go 💪",
|
||||
tag: 'day-reminder'
|
||||
});
|
||||
sendPush(user.id, dayReminderPush(S.lang, routine));
|
||||
}
|
||||
// Checked every 10s (not 60s) — ticks aren't aligned to the top of the minute, so a 60s
|
||||
// interval could sit on your target minute for up to 59s before noticing. 10s caps that at ~9s.
|
||||
@@ -155,35 +239,127 @@ 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));
|
||||
}
|
||||
// With the __Host- prefix the *browser* guarantees the cookie is host-only (no Domain attribute
|
||||
// is even allowed) — which is what stops a sibling subdomain, e.g. anything-else.example.com
|
||||
// against gym.example.com, from planting a second session cookie for the shared parent domain
|
||||
// and having it shadow the real one. The prefix also requires Secure, so it only works on an
|
||||
// https ORIGIN; over plain http://localhost the old name stays, and localhost has no sibling
|
||||
// subdomains to worry about. Both names are accepted on the way in, so upgrading an instance
|
||||
// does not sign anybody out — they move onto the prefixed cookie at their next sign-in.
|
||||
const COOKIE = SECURE ? '__Host-gymsid' : 'gymsid';
|
||||
const LEGACY_COOKIE = 'gymsid';
|
||||
// Every value for a given name, in the order the browser sent them. Not an object: reducing
|
||||
// duplicates to one entry silently picks a winner, and picking the *last* one handed a shadowing
|
||||
// cookie the session outright.
|
||||
function cookieValues(req, name) {
|
||||
const out = [];
|
||||
for (const c of (req.headers.cookie || '').split(';')) {
|
||||
const i = c.indexOf('=');
|
||||
if (i < 0) continue;
|
||||
if (c.slice(0, i).trim() === name) out.push(c.slice(i + 1).trim());
|
||||
}
|
||||
return out;
|
||||
}
|
||||
function cookieToken(req) {
|
||||
for (const name of (COOKIE === LEGACY_COOKIE ? [COOKIE] : [COOKIE, LEGACY_COOKIE])) {
|
||||
const vals = cookieValues(req, name);
|
||||
if (!vals.length) continue;
|
||||
// Two different values under one name is not something a browser does on its own — it means
|
||||
// somebody else got to set one. There is no safe way to guess which is the real session, so
|
||||
// refuse both: a signed-out user signs back in, a shadowing attempt gets nothing.
|
||||
if (vals.some(v => v !== vals[0])) return null;
|
||||
return vals[0];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
function readSession(req) {
|
||||
const cookies = Object.fromEntries((req.headers.cookie || '').split(';').map(c => {
|
||||
const i = c.indexOf('='); return i < 0 ? ['', ''] : [c.slice(0, i).trim(), c.slice(i + 1).trim()];
|
||||
}));
|
||||
const tok = cookies.gymsid;
|
||||
// The paired mobile app has no cookie jar shared with the API's origin, so it carries the same
|
||||
// signed token in an Authorization header instead — same payload, same verification below.
|
||||
const auth = req.headers.authorization || '';
|
||||
const tok = cookieToken(req) || (auth.startsWith('Bearer ') ? auth.slice(7).trim() : null);
|
||||
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.
|
||||
function requireAdmin(req, res) {
|
||||
const user = readSession(req);
|
||||
if (!user) { json(res, 401, { error: 'not signed in' }); return null; }
|
||||
if (!isAdmin(user)) { json(res, 403, { error: 'forbidden' }); return null; }
|
||||
// Only the 403 is recorded: a 401 is any unauthenticated bot poking /api/admin/*, and
|
||||
// logging those would bury the events an operator actually wants to see.
|
||||
if (!isAdmin(user)) { audit(req, 'admin.denied', { ok: false, 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`;
|
||||
const expireCookie = name => `${name}=; Path=/; Max-Age=0; HttpOnly;${SECURE} SameSite=Lax`;
|
||||
function sessionCookie(user) {
|
||||
const fresh = `${COOKIE}=${makeSession(user)}; Path=/; Max-Age=${SESSION_DAYS * 86400}; HttpOnly;${SECURE} SameSite=Lax`;
|
||||
// Signing in also retires any pre-upgrade cookie, so nobody is left carrying an unprefixed one
|
||||
// (or a shadowing copy of it) alongside the new session.
|
||||
return COOKIE === LEGACY_COOKIE ? [fresh] : [fresh, expireCookie(LEGACY_COOKIE)];
|
||||
}
|
||||
const clearCookie = COOKIE === LEGACY_COOKIE
|
||||
? [expireCookie(LEGACY_COOKIE)]
|
||||
: [expireCookie(COOKIE), expireCookie(LEGACY_COOKIE)];
|
||||
|
||||
/* ---------- CSRF ---------- */
|
||||
// SameSite=Lax keeps the session cookie off a genuinely cross-*site* request. It does not keep it
|
||||
// off a *sibling subdomain*: gym.example.com and anything-else.example.com are the same site, and
|
||||
// that is the ordinary self-hosting layout — one domain, one reverse proxy, several apps. Nothing
|
||||
// else in a request was being checked either; readBody() JSON.parse's the body whatever the
|
||||
// Content-Type claims, so a hostile page could reach the state-changing routes with a form-style
|
||||
// POST that needs no CORS preflight at all.
|
||||
//
|
||||
// So a state-changing request that came from a browser has to come from ORIGIN. The exemptions
|
||||
// below are not holes: each of those routes carries its own credential in the body (a WebAuthn
|
||||
// challenge id, a one-shot pairing code), none of them acts on the caller's existing session, and
|
||||
// they have to keep working from the mobile WebView, whose origin is never ORIGIN.
|
||||
const CSRF_EXEMPT = new Set([
|
||||
'POST /api/register/options', 'POST /api/register/verify',
|
||||
'POST /api/login/options', 'POST /api/login/verify',
|
||||
'POST /api/pair/redeem'
|
||||
]);
|
||||
const originsMatch = (a, b) => a.replace(/\/+$/, '') === b.replace(/\/+$/, '');
|
||||
function csrfOk(req, key) {
|
||||
if (req.method === 'GET' || req.method === 'HEAD' || req.method === 'OPTIONS') return true;
|
||||
if (CSRF_EXEMPT.has(key)) return true;
|
||||
// The paired mobile app authenticates with a Bearer token. A browser never attaches one on its
|
||||
// own, so there is no ambient authority for a hostile page to borrow and no origin to check.
|
||||
if ((req.headers.authorization || '').startsWith('Bearer ')) return true;
|
||||
// Sec-Fetch-Site is set by the browser itself and no page can forge it, and it states exactly
|
||||
// the property wanted here — more precisely than comparing origins can. 'same-origin' is the
|
||||
// app talking to its own backend; a hostile page reports 'cross-site'; a sibling subdomain,
|
||||
// the case SameSite=Lax misses entirely, reports 'same-site'. It is also what keeps the Vite
|
||||
// dev server working, where the page is on another port and its Origin is legitimately not
|
||||
// ORIGIN. Absent on older Safari and on proxies that strip it, hence the fallback below.
|
||||
const site = req.headers['sec-fetch-site'];
|
||||
if (site) return site === 'same-origin' || site === 'none';
|
||||
const origin = req.headers.origin;
|
||||
// No Origin header at all means no browser sent this — curl, a script, a monitoring check.
|
||||
// Browsers put an Origin on every state-changing request and a page cannot suppress it, so the
|
||||
// forgery this exists to stop always carries one.
|
||||
if (!origin) return true;
|
||||
return originsMatch(origin, ORIGIN);
|
||||
}
|
||||
const clearCookie = `gymsid=; Path=/; Max-Age=0; HttpOnly;${SECURE} SameSite=Lax`;
|
||||
|
||||
/* ---------- challenge store (in-memory, 5 min TTL) ---------- */
|
||||
const challenges = new Map(); // cid -> {challenge, name?, uid?, exp}
|
||||
@@ -200,6 +376,21 @@ function takeChallenge(cid) {
|
||||
}
|
||||
setInterval(() => { for (const [k, v] of challenges) if (v.exp < Date.now()) challenges.delete(k); }, 60000).unref();
|
||||
|
||||
// ---------- device pairing (mobile app "connect to my server", no WebAuthn ceremony) ----------
|
||||
// A passkey ceremony can't run inside the app's WebView (its origin never matches RP_ID), so the
|
||||
// app authenticates by redeeming a short code minted from an already signed-in browser tab —
|
||||
// same 5-min-TTL/one-shot shape as the WebAuthn challenge store above.
|
||||
const pairings = new Map(); // code -> {uid, exp}
|
||||
const PAIR_CODE_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; // no 0/O/1/I — read off a screen
|
||||
function makePairCode() {
|
||||
let code;
|
||||
do {
|
||||
code = Array.from(crypto.randomBytes(8)).map(b => PAIR_CODE_ALPHABET[b % PAIR_CODE_ALPHABET.length]).join('');
|
||||
} while (pairings.has(code));
|
||||
return code;
|
||||
}
|
||||
setInterval(() => { for (const [k, v] of pairings) if (v.exp < Date.now()) pairings.delete(k); }, 60000).unref();
|
||||
|
||||
/* ---------- helpers ---------- */
|
||||
function json(res, code, obj, extraHeaders) {
|
||||
const body = JSON.stringify(obj);
|
||||
@@ -236,12 +427,106 @@ function livePresence(uid) {
|
||||
}
|
||||
setInterval(() => { for (const [k, v] of presence) if (Date.now() - v.updatedAt > PRESENCE_TTL) presence.delete(k); }, 30000).unref();
|
||||
|
||||
/* ---------- audit log ---------- */
|
||||
// Who signed in, who tried and failed, and what an admin changed. One JSON object per line in
|
||||
// ./data/audit.log, appended and never rewritten in place. It deliberately does not live in
|
||||
// db.json: that file is rewritten whole on every save, and the login/register handshakes are
|
||||
// unauthenticated and unthrottled by design (see SECURITY.md), so an audit trail in there would
|
||||
// turn one bogus request into a full db.json rewrite. A line torn by a crash costs one event and
|
||||
// is dropped on read.
|
||||
//
|
||||
// On by default. It records strictly less than the instance already holds — every account is in
|
||||
// db.json and every workout is in state-<uid>.json, both readable by any admin — and a security
|
||||
// feature that ships switched off protects nobody. IP addresses are the exception: off unless you
|
||||
// ask for them, because they are the one field here that says where somebody physically is.
|
||||
const AUDIT_ON = !/^(0|false|no|off)$/i.test(process.env.AUDIT_LOG || '');
|
||||
const AUDIT_MAX = Math.max(0, +(process.env.AUDIT_MAX || 5000) || 0); // 0 = no count cap
|
||||
const AUDIT_DAYS = Math.max(0, +(process.env.AUDIT_DAYS || 90) || 0); // 0 = no age cap
|
||||
const AUDIT_IP = /^full$/i.test(process.env.AUDIT_IP || '') ? 'full'
|
||||
: /^(1|true|yes|on|net)$/i.test(process.env.AUDIT_IP || '') ? 'net' : 'off';
|
||||
const auditFile = path.join(DATA, 'audit.log');
|
||||
let auditSeq = 0; // never reset, not even by a clear — a wiped log leaves a visible id gap
|
||||
let auditCount = 0;
|
||||
|
||||
// Which header holds the caller depends on what is in front of the API. CF-Connecting-IP comes
|
||||
// first because a Cloudflare tunnel does NOT forward the client in X-Forwarded-For — that header
|
||||
// then only carries the tunnel's own container, which looks like a valid answer and isn't. After
|
||||
// that, the first entry of X-Forwarded-For is the client and everything behind it is our own hops.
|
||||
// All three are only as trustworthy as the proxy in front: it has to overwrite them rather than
|
||||
// pass a client-supplied one through. In 'net' mode only the network survives — enough to tell
|
||||
// one source from another, not enough to point at a person.
|
||||
function clientIp(req) {
|
||||
if (AUDIT_IP === 'off') return null;
|
||||
const raw = String(req.headers['cf-connecting-ip'] || '').trim()
|
||||
|| String(req.headers['x-forwarded-for'] || '').split(',')[0].trim()
|
||||
|| String(req.headers['x-real-ip'] || '').trim()
|
||||
// Nothing in front at all: the socket peer is the client, and it cannot be forged. Behind
|
||||
// the bundled web container a header always wins before this is reached.
|
||||
|| String(req.socket?.remoteAddress || '').replace(/^::ffff:/, '').trim();
|
||||
const ip = raw.replace(/^\[|\]$/g, '').slice(0, 45);
|
||||
if (!/^[0-9a-fA-F:.]{3,45}$/.test(ip)) return null; // never store a header verbatim
|
||||
if (AUDIT_IP === 'full') return ip;
|
||||
if (/^\d{1,3}(\.\d{1,3}){3}$/.test(ip)) return ip.replace(/\.\d{1,3}$/, '.0/24');
|
||||
const g = ip.split(':').filter(Boolean).slice(0, 3).join(':');
|
||||
return g ? g + '::/48' : null;
|
||||
}
|
||||
|
||||
function auditLines() {
|
||||
let text;
|
||||
try { text = fs.readFileSync(auditFile, 'utf8'); } catch { return []; }
|
||||
const rows = [];
|
||||
for (const line of text.split('\n')) {
|
||||
if (!line) continue;
|
||||
try { const r = JSON.parse(line); if (r && r.id && r.ev) rows.push(r); } catch { /* torn line */ }
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
// Retention is a cap, not an archive: age first, then the newest AUDIT_MAX of what's left.
|
||||
function auditKeep(rows) {
|
||||
let out = rows;
|
||||
if (AUDIT_DAYS) { const cut = Date.now() - AUDIT_DAYS * 86400000; out = out.filter(r => r.ts >= cut); }
|
||||
if (AUDIT_MAX && out.length > AUDIT_MAX) out = out.slice(out.length - AUDIT_MAX);
|
||||
return out;
|
||||
}
|
||||
function compactAudit() {
|
||||
const rows = auditLines();
|
||||
for (const r of rows) if (+r.id > auditSeq) auditSeq = +r.id;
|
||||
const keep = auditKeep(rows);
|
||||
auditCount = keep.length;
|
||||
if (keep.length === rows.length) return;
|
||||
try { atomicWrite(auditFile, keep.map(r => JSON.stringify(r)).join('\n') + (keep.length ? '\n' : '')); }
|
||||
catch (e) { console.error('audit compact failed', e.message); }
|
||||
}
|
||||
|
||||
// Never throws: a log that can't be written must not break signing in.
|
||||
function audit(req, ev, f = {}) {
|
||||
if (!AUDIT_ON) return;
|
||||
const rec = { id: ++auditSeq, ts: Date.now(), ev, ok: f.ok !== false };
|
||||
if (f.user) { rec.uid = f.user.id; rec.name = String(f.user.name || '').slice(0, 40); }
|
||||
else {
|
||||
if (f.uid) rec.uid = f.uid;
|
||||
if (f.name) rec.name = String(f.name).slice(0, 40);
|
||||
}
|
||||
if (f.target) { rec.tgt = f.target.id; rec.tname = String(f.target.name || '').slice(0, 40); }
|
||||
if (f.msg) rec.msg = String(f.msg).slice(0, 120);
|
||||
const ip = clientIp(req);
|
||||
if (ip) rec.ip = ip;
|
||||
try { fs.appendFileSync(auditFile, JSON.stringify(rec) + '\n'); }
|
||||
catch (e) { return console.error('audit write failed', e.message); }
|
||||
// Amortized: a 5000-event cap rewrites the file once per ~1250 events.
|
||||
if (AUDIT_MAX && ++auditCount > AUDIT_MAX * 1.25) compactAudit();
|
||||
}
|
||||
if (AUDIT_ON) {
|
||||
compactAudit(); // prune on boot, seed auditSeq/auditCount
|
||||
setInterval(compactAudit, 3600000).unref(); // honour AUDIT_DAYS on an idle instance too
|
||||
}
|
||||
|
||||
/* ---------- routes ---------- */
|
||||
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);
|
||||
@@ -254,8 +539,11 @@ const routes = {
|
||||
const name = String(body.name || '').trim().slice(0, 40);
|
||||
if (!name) return json(res, 400, { error: 'name required' });
|
||||
const code = String(body.code || '').trim().toUpperCase();
|
||||
if (INVITE_ONLY && !db.invites.some(i => i.code === code && !i.usedBy && !i.revoked))
|
||||
if (INVITE_ONLY && !db.invites.some(i => i.code === code && !i.usedBy && !i.revoked)) {
|
||||
// The rejected code itself is never recorded — a near-miss guess in the log is a liability.
|
||||
audit(req, 'auth.register.denied', { ok: false, name, msg: 'invite-rejected' });
|
||||
return json(res, 403, { error: 'a valid invite code is required' });
|
||||
}
|
||||
const uid = crypto.randomBytes(12).toString('base64url');
|
||||
const options = await generateRegistrationOptions({
|
||||
rpName: RP_NAME, rpID: RP_ID,
|
||||
@@ -271,7 +559,10 @@ const routes = {
|
||||
'POST /api/register/verify': async (req, res) => {
|
||||
const body = await readBody(req);
|
||||
const c = takeChallenge(body.cid);
|
||||
if (!c || !c.uid) return json(res, 400, { error: 'challenge expired — try again' });
|
||||
if (!c || !c.uid) {
|
||||
audit(req, 'auth.register.fail', { ok: false, msg: 'challenge-expired' });
|
||||
return json(res, 400, { error: 'challenge expired — try again' });
|
||||
}
|
||||
let verification;
|
||||
try {
|
||||
verification = await verifyRegistrationResponse({
|
||||
@@ -281,15 +572,28 @@ const routes = {
|
||||
expectedRPID: RP_ID,
|
||||
requireUserVerification: false
|
||||
});
|
||||
} catch (e) { return json(res, 400, { error: 'verification failed: ' + e.message }); }
|
||||
if (!verification.verified) return json(res, 400, { error: 'not verified' });
|
||||
} catch (e) {
|
||||
// e.message can echo attacker-supplied response fields, so only the reason code is kept.
|
||||
audit(req, 'auth.register.fail', { ok: false, name: c.name, msg: 'verify-error' });
|
||||
return json(res, 400, { error: verifyError(e, { rpId: RP_ID, origin: ORIGIN }) });
|
||||
}
|
||||
if (!verification.verified) {
|
||||
audit(req, 'auth.register.fail', { ok: false, name: c.name, msg: 'not-verified' });
|
||||
return json(res, 400, { error: 'not verified' });
|
||||
}
|
||||
const { credential } = verification.registrationInfo;
|
||||
if (db.creds.find(x => x.id === credential.id)) return json(res, 409, { error: 'credential already registered' });
|
||||
if (db.creds.find(x => x.id === credential.id)) {
|
||||
audit(req, 'auth.register.fail', { ok: false, name: c.name, msg: 'credential-exists' });
|
||||
return json(res, 409, { error: 'credential already registered' });
|
||||
}
|
||||
// Re-check the invite at the last moment (it may have been used/revoked since options), then burn it.
|
||||
let invite = null;
|
||||
if (INVITE_ONLY) {
|
||||
invite = db.invites.find(i => i.code === c.code && !i.usedBy && !i.revoked);
|
||||
if (!invite) return json(res, 403, { error: 'invite code is no longer valid — ask for a new one' });
|
||||
if (!invite) {
|
||||
audit(req, 'auth.register.fail', { ok: false, name: c.name, msg: 'invite-invalid' });
|
||||
return json(res, 403, { error: 'invite code is no longer valid — ask for a new one' });
|
||||
}
|
||||
}
|
||||
const user = { id: c.uid, name: c.name, created: new Date().toISOString() };
|
||||
if (invite) { user.invitedBy = invite.code; invite.usedBy = user.id; invite.usedAt = user.created; }
|
||||
@@ -301,7 +605,8 @@ 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) });
|
||||
audit(req, 'auth.register.ok', { user, msg: invite ? invite.code : null });
|
||||
json(res, 200, { user: { id: user.id, name: user.name, admin: isAdmin(user) } }, { 'Set-Cookie': sessionCookie(user) });
|
||||
},
|
||||
|
||||
'POST /api/login/options': async (req, res) => {
|
||||
@@ -315,9 +620,18 @@ const routes = {
|
||||
'POST /api/login/verify': async (req, res) => {
|
||||
const body = await readBody(req);
|
||||
const c = takeChallenge(body.cid);
|
||||
if (!c) return json(res, 400, { error: 'challenge expired — try again' });
|
||||
if (!c) {
|
||||
audit(req, 'auth.login.fail', { ok: false, msg: 'challenge-expired' });
|
||||
return json(res, 400, { error: 'challenge expired — try again' });
|
||||
}
|
||||
const cred = db.creds.find(x => x.id === body.credential?.id);
|
||||
if (!cred) return json(res, 404, { error: 'unknown passkey — create a profile first' });
|
||||
if (!cred) {
|
||||
// No credential id goes in the log: it is a stable handle for one passkey, and recording it
|
||||
// would let an admin correlate an unknown device across attempts. Nothing here identifies
|
||||
// the caller beyond the timestamp (and the network, if AUDIT_IP is on).
|
||||
audit(req, 'auth.login.fail', { ok: false, msg: 'unknown-credential' });
|
||||
return json(res, 404, { error: 'unknown passkey — create a profile first' });
|
||||
}
|
||||
let verification;
|
||||
try {
|
||||
verification = await verifyAuthenticationResponse({
|
||||
@@ -333,17 +647,80 @@ const routes = {
|
||||
transports: cred.transports
|
||||
}
|
||||
});
|
||||
} catch (e) { return json(res, 400, { error: 'verification failed: ' + e.message }); }
|
||||
if (!verification.verified) return json(res, 400, { error: 'not verified' });
|
||||
} catch (e) {
|
||||
audit(req, 'auth.login.fail', { ok: false, user: db.users.find(u => u.id === cred.userId), uid: cred.userId, msg: 'verify-error' });
|
||||
return json(res, 400, { error: verifyError(e, { rpId: RP_ID, origin: ORIGIN }) });
|
||||
}
|
||||
if (!verification.verified) {
|
||||
audit(req, 'auth.login.fail', { ok: false, user: db.users.find(u => u.id === cred.userId), uid: cred.userId, msg: 'not-verified' });
|
||||
return json(res, 400, { error: 'not verified' });
|
||||
}
|
||||
cred.counter = verification.authenticationInfo.newCounter;
|
||||
saveDb();
|
||||
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) });
|
||||
if (!user) {
|
||||
audit(req, 'auth.login.fail', { ok: false, uid: cred.userId, msg: 'user-missing' });
|
||||
return json(res, 500, { error: 'user missing' });
|
||||
}
|
||||
if (user.disabled) {
|
||||
audit(req, 'auth.login.fail', { ok: false, user, msg: 'account-disabled' });
|
||||
return json(res, 403, { error: 'this account has been disabled' });
|
||||
}
|
||||
audit(req, 'auth.login.ok', { user });
|
||||
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 }),
|
||||
// Reads the session purely so the sign-out can be recorded; the cookie is cleared either way.
|
||||
// A logout with no valid cookie is a no-op and isn't worth an entry.
|
||||
'POST /api/logout': async (req, res) => {
|
||||
const user = readSession(req);
|
||||
if (user) audit(req, 'auth.logout', { user });
|
||||
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();
|
||||
audit(req, 'auth.logout.all', { user });
|
||||
json(res, 200, { ok: true }, { 'Set-Cookie': clearCookie });
|
||||
},
|
||||
|
||||
// Mobile app pairing: called from an already signed-in browser tab (Settings → "Pair the
|
||||
// mobile app") to mint a short code the phone can redeem below.
|
||||
'POST /api/pair/create': async (req, res) => {
|
||||
const user = readSession(req);
|
||||
if (!user) return json(res, 401, { error: 'not signed in' });
|
||||
const code = makePairCode();
|
||||
pairings.set(code, { uid: user.id, exp: Date.now() + 5 * 60000 });
|
||||
audit(req, 'auth.pair.create', { user });
|
||||
json(res, 200, { code });
|
||||
},
|
||||
|
||||
// Called from the mobile app itself with the code shown in the browser. No session required —
|
||||
// the code IS the credential, one-shot and 5-minute-lived like a WebAuthn challenge.
|
||||
'POST /api/pair/redeem': async (req, res) => {
|
||||
const body = await readBody(req);
|
||||
const code = String(body.code || '').trim().toUpperCase();
|
||||
const p = pairings.get(code);
|
||||
if (p) pairings.delete(code);
|
||||
if (!p || p.exp < Date.now()) {
|
||||
audit(req, 'auth.pair.fail', { ok: false, msg: 'code-invalid' });
|
||||
return json(res, 400, { error: 'invalid or expired code' });
|
||||
}
|
||||
const user = db.users.find(u => u.id === p.uid);
|
||||
if (!user || user.disabled) {
|
||||
audit(req, 'auth.pair.fail', { ok: false, uid: p.uid, msg: 'user-unavailable' });
|
||||
return json(res, 400, { error: 'invalid or expired code' });
|
||||
}
|
||||
audit(req, 'auth.pair.ok', { user });
|
||||
json(res, 200, { token: makeSession(user), user: { id: user.id, name: user.name, admin: isAdmin(user) } });
|
||||
},
|
||||
|
||||
'GET /api/data': async (req, res) => {
|
||||
const user = readSession(req);
|
||||
@@ -372,8 +749,21 @@ const routes = {
|
||||
const body = await readBody(req);
|
||||
const sub = body.subscription;
|
||||
if (!sub?.endpoint || !sub?.keys?.p256dh || !sub?.keys?.auth) return json(res, 400, { error: 'invalid subscription' });
|
||||
const bad = pushEndpointError(sub.endpoint);
|
||||
if (bad) return json(res, 400, { error: bad });
|
||||
// Only the two keys the push protocol needs are kept: `sub` is caller-supplied and would
|
||||
// otherwise put arbitrary fields into db.json, which every admin route reads back out.
|
||||
const keys = { p256dh: String(sub.keys.p256dh), auth: String(sub.keys.auth) };
|
||||
db.subs = db.subs.filter(s => s.endpoint !== sub.endpoint);
|
||||
db.subs.push({ userId: user.id, endpoint: sub.endpoint, keys: sub.keys, created: new Date().toISOString() });
|
||||
// A browser holds one subscription per device, so this cap is far above real use. Without
|
||||
// it a single account could pile up endpoints without limit — every one of them a target
|
||||
// sendPush() would then contact, and a whole rewrite of db.json per addition.
|
||||
const mine = db.subs.filter(s => s.userId === user.id);
|
||||
if (mine.length >= MAX_SUBS_PER_USER) {
|
||||
const drop = new Set(mine.slice(0, mine.length - MAX_SUBS_PER_USER + 1).map(s => s.endpoint));
|
||||
db.subs = db.subs.filter(s => !drop.has(s.endpoint));
|
||||
}
|
||||
db.subs.push({ userId: user.id, endpoint: sub.endpoint, keys, created: new Date().toISOString() });
|
||||
saveDb();
|
||||
json(res, 200, { ok: true });
|
||||
},
|
||||
@@ -390,7 +780,7 @@ const routes = {
|
||||
'POST /api/push/test': async (req, res) => {
|
||||
const user = readSession(req);
|
||||
if (!user) return json(res, 401, { error: 'not signed in' });
|
||||
await sendPush(user.id, { title: 'openGym', body: 'Test notification ✅ — this is what alerts look like.', tag: 'test' });
|
||||
await sendPush(user.id, testPush(readState(user.id)?.lang));
|
||||
json(res, 200, { ok: true });
|
||||
},
|
||||
|
||||
@@ -400,7 +790,7 @@ const routes = {
|
||||
const body = await readBody(req);
|
||||
const sec = Math.max(1, Math.min(3600, Math.round(+body.seconds || 0)));
|
||||
if (!sec) return json(res, 400, { error: 'seconds required' });
|
||||
scheduleRestTimer(user.id, sec);
|
||||
scheduleRestTimer(user.id, sec, readState(user.id)?.lang);
|
||||
json(res, 200, { ok: true });
|
||||
},
|
||||
|
||||
@@ -467,7 +857,7 @@ const routes = {
|
||||
},
|
||||
|
||||
'POST /api/admin/user/disable': async (req, res) => {
|
||||
if (!requireAdmin(req, res)) return;
|
||||
const admin = requireAdmin(req, res); if (!admin) return;
|
||||
const body = await readBody(req);
|
||||
const u = db.users.find(x => x.id === body.id);
|
||||
if (!u) return json(res, 404, { error: 'no such user' });
|
||||
@@ -475,6 +865,7 @@ const routes = {
|
||||
u.disabled = !!body.disabled;
|
||||
if (u.disabled) presence.delete(u.id); // drop them off "training now" at once
|
||||
saveDb();
|
||||
audit(req, u.disabled ? 'admin.user.disable' : 'admin.user.enable', { user: admin, target: u });
|
||||
json(res, 200, { ok: true, id: u.id, disabled: u.disabled });
|
||||
},
|
||||
|
||||
@@ -491,30 +882,93 @@ 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();
|
||||
audit(req, 'admin.invite.create', { user: admin, msg: code });
|
||||
json(res, 200, { invite });
|
||||
},
|
||||
|
||||
'POST /api/admin/invites/revoke': async (req, res) => {
|
||||
if (!requireAdmin(req, res)) return;
|
||||
const admin = requireAdmin(req, res); if (!admin) return;
|
||||
const body = await readBody(req);
|
||||
const inv = db.invites.find(i => i.code === String(body.code || '').toUpperCase());
|
||||
if (!inv) return json(res, 404, { error: 'no such code' });
|
||||
if (inv.usedBy) return json(res, 400, { error: 'already used — cannot revoke' });
|
||||
db.invites = db.invites.filter(i => i.code !== inv.code);
|
||||
saveDb();
|
||||
audit(req, 'admin.invite.revoke', { user: admin, msg: inv.code });
|
||||
json(res, 200, { ok: true });
|
||||
},
|
||||
|
||||
/* ---------- activity log ---------- */
|
||||
// Newest first, paged by id. Not by offset: the log grows at the front of this view, so an
|
||||
// offset cursor would repeat a row whenever an event lands between two pages; and not by
|
||||
// timestamp, because two events can share a millisecond. auditKeep() runs on read as well as
|
||||
// on the hourly compaction, so nothing past its retention is ever served.
|
||||
'GET /api/admin/audit': async (req, res) => {
|
||||
if (!requireAdmin(req, res)) return;
|
||||
const q = new URL(req.url, 'http://x').searchParams;
|
||||
const limit = Math.max(1, Math.min(200, +q.get('limit') || 100));
|
||||
const before = +q.get('before') || Infinity;
|
||||
const cat = q.get('cat') || '';
|
||||
let rows = auditKeep(auditLines()).reverse();
|
||||
if (cat === 'fail') rows = rows.filter(r => !r.ok);
|
||||
else if (cat) rows = rows.filter(r => String(r.ev).startsWith(cat + '.'));
|
||||
const page = rows.filter(r => r.id < before).slice(0, limit);
|
||||
json(res, 200, {
|
||||
events: page,
|
||||
total: rows.length,
|
||||
nextBefore: page.length === limit ? page[page.length - 1].id : null,
|
||||
enabled: AUDIT_ON, ip_mode: AUDIT_IP,
|
||||
retention: { max: AUDIT_MAX, days: AUDIT_DAYS },
|
||||
now: Date.now()
|
||||
});
|
||||
},
|
||||
|
||||
// Deleting the log is itself logged, and auditSeq is not reset — so a clear always leaves a
|
||||
// visible gap in the ids and can't be used to quietly erase a trace. There is no export route:
|
||||
// ./data/audit.log already is the export, in a format jq reads directly.
|
||||
'POST /api/admin/audit/clear': async (req, res) => {
|
||||
const admin = requireAdmin(req, res); if (!admin) return;
|
||||
try { fs.unlinkSync(auditFile); } catch { /* nothing logged yet */ }
|
||||
auditCount = 0;
|
||||
audit(req, 'admin.audit.clear', { user: admin });
|
||||
json(res, 200, { ok: true });
|
||||
}
|
||||
};
|
||||
|
||||
http.createServer(async (req, res) => {
|
||||
// Same-origin (the deployed nginx-proxied web app) never triggers CORS, so this only matters
|
||||
// for the paired mobile app calling in from its own WebView origin. It carries no cookie
|
||||
// (auth is the Authorization header instead), so Allow-Credentials is deliberately never set —
|
||||
// reflecting the origin here can't expose the cookie session to anyone.
|
||||
const origin = req.headers.origin;
|
||||
if (origin) { res.setHeader('Access-Control-Allow-Origin', origin); res.setHeader('Vary', 'Origin'); }
|
||||
if (req.method === 'OPTIONS') {
|
||||
res.writeHead(204, {
|
||||
'Access-Control-Allow-Methods': 'GET,POST,PUT,DELETE,OPTIONS',
|
||||
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
|
||||
'Access-Control-Max-Age': '86400'
|
||||
});
|
||||
return res.end();
|
||||
}
|
||||
const url = new URL(req.url, 'http://x');
|
||||
const key = req.method + ' ' + url.pathname;
|
||||
const handler = routes[key];
|
||||
if (!handler) return json(res, 404, { error: 'not found' });
|
||||
if (!csrfOk(req, key)) {
|
||||
// Logged, not audited: this is reachable without a session, and an audit entry per attempt
|
||||
// would let anyone fill the log. An operator who has genuinely mis-set ORIGIN needs to see
|
||||
// the mismatch, and the container log is where they will look.
|
||||
console.warn('refused cross-origin', key, 'origin=' + req.headers.origin, 'expected=' + ORIGIN);
|
||||
return json(res, 403, { error: 'cross-origin request refused' });
|
||||
}
|
||||
try { await handler(req, res); }
|
||||
catch (e) {
|
||||
console.error(key, e);
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
// @simplewebauthn reports an RP_ID or origin mismatch as an opaque "Unexpected ..." string, and
|
||||
// whoever reads it in the browser has no way to connect that to their .env. A misconfigured
|
||||
// RP_ID/ORIGIN is the single most common self-hosting failure (see docs/SELF_HOSTING.md), so
|
||||
// name both values back. Neither is a secret: one is the address bar, the other its hostname.
|
||||
const MISCONFIGURED = /unexpected (rp id|authentication response origin|registration response origin)/i;
|
||||
|
||||
export function verifyError(e, { rpId, origin } = {}) {
|
||||
const msg = String((e && e.message) || 'verification failed');
|
||||
if (!MISCONFIGURED.test(msg)) return 'verification failed: ' + msg;
|
||||
return `${msg} — this server is configured with RP_ID=${rpId} and ORIGIN=${origin}, and both `
|
||||
+ 'must match the address you opened. See docs/SELF_HOSTING.md.';
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { verifyError } from './verify-error.js';
|
||||
|
||||
const cfg = { rpId: 'gym.example.com', origin: 'https://gym.example.com' };
|
||||
|
||||
test('names the configured values when the RP ID does not match', () => {
|
||||
const out = verifyError(new Error('Unexpected RP ID hash'), cfg);
|
||||
assert.match(out, /RP_ID=gym\.example\.com/);
|
||||
assert.match(out, /ORIGIN=https:\/\/gym\.example\.com/);
|
||||
assert.match(out, /SELF_HOSTING\.md/);
|
||||
});
|
||||
|
||||
test('does the same for an origin mismatch, on login and on registration', () => {
|
||||
assert.match(verifyError(new Error('Unexpected authentication response origin'), cfg), /must match the address you opened/);
|
||||
assert.match(verifyError(new Error('Unexpected registration response origin'), cfg), /must match the address you opened/);
|
||||
});
|
||||
|
||||
test('leaves an unrelated verification failure alone', () => {
|
||||
assert.equal(
|
||||
verifyError(new Error('Signature verification failed'), cfg),
|
||||
'verification failed: Signature verification failed'
|
||||
);
|
||||
});
|
||||
|
||||
test('does not throw on a missing or empty error', () => {
|
||||
assert.equal(verifyError(undefined, cfg), 'verification failed: verification failed');
|
||||
assert.equal(verifyError(new Error(''), cfg), 'verification failed: verification failed');
|
||||
});
|
||||
|
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: registry.gitlab.com/duartesantos8/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: registry.gitlab.com/duartesantos8/opengym/web:latest
|
||||
build:
|
||||
context: .
|
||||
dockerfile: web/Dockerfile
|
||||
@@ -48,7 +61,17 @@ 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}
|
||||
# Empty drops the CF-Connecting-IP header, so a direct client cannot forge the address
|
||||
# the activity log records. Cloudflare users set CF_CONNECTING_IP=$$http_cf_connecting_ip.
|
||||
- CF_CONNECTING_IP=${CF_CONNECTING_IP:-}
|
||||
volumes:
|
||||
- ./media/img:/usr/share/nginx/html/img:ro
|
||||
- ./media/gif:/usr/share/nginx/html/gif:ro
|
||||
@@ -0,0 +1,76 @@
|
||||
# Importing Data
|
||||
|
||||
## Plans
|
||||
|
||||
Plans/routines can be imported from a plain text json file.
|
||||
The app supports exporting and an export always contain *every* current routine.
|
||||
|
||||
If you don't want to share every plan that you have currently created, you can either:
|
||||
- edit the exported json with a text editor
|
||||
or (if you don't feel like editing json files):
|
||||
- open the [Demo](https://opengym.duarte-santos.ch/demo/#/home)
|
||||
- import your plans
|
||||
- make changes
|
||||
- export a new json file for sharing
|
||||
|
||||
If you are using the standalone app on your mobile, you can use the demo for creating plans on your PC and import them.
|
||||
The demo stores all data in your browser, it is not public or shared in any way.
|
||||
|
||||
Writing a json file yourself will be a bit of a complex task since the IDs of the exercises have to match the IDs in the database.
|
||||
|
||||
## History
|
||||
|
||||
To import your history from other applications, you'll need an export that is in `CSV` format.
|
||||
The app tries to match the exercise names to link them to the exercises in the database.
|
||||
|
||||
> Note: The history is a log of past exercises.
|
||||
> Because plans change and history does not, it is completely disconnected from routines.
|
||||
>
|
||||
> Exercises depend on name matching, so custom exercises might be named differently, as they might be in other apps.
|
||||
|
||||
These apps have been tested to work without adjustments to the column names:
|
||||
|
||||
| App | How to export |
|
||||
|---|---|
|
||||
| **FitNotes (Android)** | Settings → Backup/Export → **Spreadsheet Export** |
|
||||
| **FitNotes 2 (iOS)** | Export workouts as CSV; also manual/auto iCloud backups |
|
||||
| **Strong** | Settings → Export Data |
|
||||
| **Gravl** | Profile → Export Data |
|
||||
| **Hevy** | Profile → Settings → Export & Import Data (Workouts or Measurements) |
|
||||
|
||||
You can also create your own `CSV` file:
|
||||
|
||||
### Minimal Example
|
||||
|
||||
```csv
|
||||
workout name,exercise,date,weight kg,reps
|
||||
Leg Day,Squat,2026-08-21,120,5
|
||||
Leg Day,Squat,2026-08-21,125,4
|
||||
Leg Day,Leg Press,2026-08-21,200,1
|
||||
```
|
||||
These field names are supported:
|
||||
|
||||
| Canonical Field | Supported CSV Headers (first match wins) |
|
||||
|---|---|
|
||||
| `exercise` | `exercise`, `exercise name`, `exercise title` |
|
||||
| `date` | `date`, `workout date` |
|
||||
| `startTime` | `start time`, `start date` |
|
||||
| `endTime` | `end time` |
|
||||
| `workoutName` | `workout name`, `title`, `workout` |
|
||||
| `category` | `category`, `body part`, `muscle group` |
|
||||
| `weightKg` | `weight kg` |
|
||||
| `weightLb` | `weight lbs`, `weight lb` |
|
||||
| `weight` | `weight` |
|
||||
| `weightUnit` | `weight unit`, `unit` |
|
||||
| `reps` | `reps`, `repetitions` |
|
||||
| `rpe` | `rpe`, `rpe rating` |
|
||||
| `rir` | `rir`, `reps in reserve` |
|
||||
| `distanceKm` | `distance km` |
|
||||
| `distance` | `distance` |
|
||||
| `distanceUnit` | `distance unit` |
|
||||
| `seconds` | `seconds`, `duration seconds`, `set duration sec` |
|
||||
| `time` | `time`, `duration` |
|
||||
| `setType` | `set type` |
|
||||
| `note` | `comment`, `comments`, `notes`, `note`, `workout notes` |
|
||||
|
||||
|
||||
@@ -10,11 +10,35 @@ openGym ships in two flavors from the same codebase:
|
||||
| Reminders | Web Push from your server | native local notifications, no server involved |
|
||||
| Exercise media | served by your server (`img/`, `gif/`) | loaded from the jsDelivr CDN |
|
||||
|
||||
The mobile flavor never talks to a backend: no sign-in screen, no sync, no telemetry.
|
||||
State is mirrored from `localStorage` into `opengym-state.json` in the app's private data
|
||||
directory on every change (iOS is allowed to evict WebView storage under pressure — the
|
||||
file mirror is the durable copy and is restored on launch). Backups go out through the
|
||||
OS share sheet instead of a browser download.
|
||||
The mobile flavor never talks to a backend by default: no sign-in screen, no sync, no
|
||||
telemetry. State is mirrored from `localStorage` into `opengym-state.json` in the app's
|
||||
private data directory on every change (iOS is allowed to evict WebView storage under
|
||||
pressure — the file mirror is the durable copy and is restored on launch). Backups go out
|
||||
through the OS share sheet instead of a browser download.
|
||||
|
||||
### Connecting the app to your own server
|
||||
|
||||
On first launch the app asks how you want to use it. Alongside the fully local mode above,
|
||||
you can instead **connect it to a self-hosted openGym server** — your data then lives there,
|
||||
synced the same way the browser PWA does, instead of only on the phone. This is a mode of the
|
||||
same app, not a different build or download.
|
||||
|
||||
Passkeys can't be used for this: the app's WebView runs at its own origin, which never
|
||||
matches the real hostname WebAuthn needs. Instead you *pair* the device from a browser
|
||||
that's already signed in: Settings → **"Pair the mobile app"** shows a one-time code (valid
|
||||
5 minutes); enter your server's address and that code in the app (same first-launch screen,
|
||||
or Settings → **"Connect to my server"** later) to finish. Notes:
|
||||
|
||||
- Requires network access every time the app is used — there's no offline file mirror once
|
||||
connected, same as the browser PWA.
|
||||
- Use an HTTPS address if at all possible: the connection carries a bearer token instead of
|
||||
a cookie, and that token would otherwise cross the network in plain text.
|
||||
- "Sign out everywhere" (Settings → Account, in the browser) revokes a paired app's access
|
||||
too — it's the same signed session token either way, just delivered over a header instead
|
||||
of a cookie. See `/api/pair/create` and `/api/pair/redeem` in `api/server.js` for the
|
||||
exchange itself.
|
||||
- Settings → "Disconnect" syncs one last time, then drops the device cleanly back to local
|
||||
mode.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
@@ -61,9 +85,25 @@ accounts, no store rules, no yearly fees between you and an open-source app.
|
||||
|
||||
### Android — sideload the APK
|
||||
|
||||
The official signed APK is at **[opengym.duarte-santos.ch](https://opengym.duarte-santos.ch)**.
|
||||
The official signed APK is in three places, all the same file:
|
||||
|
||||
- **[opengym.duarte-santos.ch](https://opengym.duarte-santos.ch)** — the download page.
|
||||
- **[GitLab's package registry](https://gitlab.com/DuarteSantos8/opengym/-/packages)** — every
|
||||
build under `opengym-android/<version>/`, with a `.sha256` beside it. Direct link, no login:
|
||||
`https://gitlab.com/api/v4/projects/85678327/packages/generic/opengym-android/<version>/openGym-<version>.apk`
|
||||
- **[The GitLab release](https://gitlab.com/DuarteSantos8/opengym/-/releases)** for that version,
|
||||
which links to the two above.
|
||||
|
||||
Android asks you to allow installs from the browser the first time — that's standard for any
|
||||
app outside the Play Store.
|
||||
app outside the Play Store. Check the `.sha256` if you got the file from anywhere else.
|
||||
|
||||
Both come out of CI: the `build:apk` job in [`.gitlab-ci.yml`](../.gitlab-ci.yml) runs
|
||||
`npm run build:mobile` and `./gradlew assembleRelease`, then `zipalign`s and signs the result
|
||||
with the release key. The key lives in *protected* CI variables (`ANDROID_KEYSTORE_B64`,
|
||||
`ANDROID_KEYSTORE_PASSWORD`, `ANDROID_KEY_ALIAS`), so it only exists on `main` and on `v*`
|
||||
tags — a merge request from a fork can build an APK, but gets an unsigned one and never sees
|
||||
the key. On a `v*` tag the signed APK is also pushed to the generic package registry, which is
|
||||
what the release links to.
|
||||
|
||||
To build and sign your own:
|
||||
|
||||
@@ -95,7 +135,10 @@ that would simply install. Your free options:
|
||||
|
||||
- Bump `versionName`/`versionCode` in `android/app/build.gradle` per release; keep them in
|
||||
step with `frontend/package.json`. `versionCode` must strictly increase or updates won't
|
||||
install over an existing APK.
|
||||
install over an existing APK. The APK is *named* from `frontend/package.json` (the CI job
|
||||
reads `version` out of it), so the two drifting apart shows up as a misnamed file.
|
||||
- Tagging `vX.Y.Z` is what ships everything: images, APK, release notes. Don't push a version
|
||||
tag you don't mean to release — `v*` tags are protected for that reason.
|
||||
- **License:** openGym is AGPL-3.0, which by itself sits badly with app-store terms of
|
||||
service. `NOTICE.md` carries an app-store exception (an additional permission under
|
||||
AGPL §7) granted by the copyright holder — relevant only if store distribution ever happens.
|
||||
|
||||
@@ -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://gitlab.com/DuarteSantos8/opengym
|
||||
cd openGym
|
||||
cp .env.example .env
|
||||
docker compose pull # prebuilt images from ghcr.io (amd64 + arm64) — or skip and build from source
|
||||
docker compose pull # prebuilt images from GitLab (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.
|
||||
@@ -42,6 +42,21 @@ passkey prompt won't appear. To use openGym from your phone you need a real HTTP
|
||||
|
||||
(You can still open it over LAN in **guest mode**, which stores data only in that browser.)
|
||||
|
||||
The standalone mobile app (`docs/MOBILE.md`) sidesteps this entirely for its "connect to my
|
||||
server" mode: instead of a passkey ceremony (impossible from inside its WebView, which never
|
||||
runs at your real hostname), it pairs by redeeming a short one-time code — minted from
|
||||
Settings → "Pair the mobile app" in an already signed-in browser tab — for a bearer token
|
||||
sent as an `Authorization` header rather than a cookie. Two consequences worth knowing if
|
||||
you're poking at the API directly:
|
||||
|
||||
- `POST /api/pair/create` (needs a session) and `POST /api/pair/redeem` (doesn't) implement
|
||||
this — see `api/server.js`. The returned token is the exact same signed value a cookie
|
||||
carries, so "sign out everywhere" invalidates it too.
|
||||
- The server reflects `Access-Control-Allow-Origin` for any request that sends an `Origin`
|
||||
header, so the app's own WebView origin can call the API cross-origin. It never sends
|
||||
`Access-Control-Allow-Credentials`, so this doesn't let a browser read your cookie session
|
||||
from another origin — only bearer-token requests benefit from it.
|
||||
|
||||
## 3. Expose it over HTTPS on your own domain
|
||||
|
||||
Put openGym behind something that terminates TLS for a hostname you control, then point it at
|
||||
@@ -90,11 +105,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 +120,65 @@ 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.
|
||||
|
||||
### The activity log
|
||||
|
||||
The dashboard also keeps an **activity log**: sign-ins, sign-outs, failed attempts, refused
|
||||
signups, and every admin action (disabling an account, creating or revoking an invite code). It
|
||||
lives in `./data/audit.log` as one JSON object per line, so `tail -f data/audit.log` and `jq`
|
||||
work on it directly, and the dashboard reads the same file.
|
||||
|
||||
It is on by default and keeps the last 5,000 events or 90 days, whichever comes first
|
||||
(`AUDIT_LOG=0` turns it off entirely; `AUDIT_MAX` and `AUDIT_DAYS` change the caps). **IP
|
||||
addresses are not recorded** unless you set `AUDIT_IP=net` (network only, e.g. `203.0.113.0/24`)
|
||||
or `AUDIT_IP=full`. Neither the browser's user-agent nor the passkey id of a failed sign-in is
|
||||
ever stored: the first is a fingerprint, and the second would let you follow an unknown device
|
||||
from one attempt to the next.
|
||||
|
||||
Two things worth expecting. **Guests never appear** — guest mode never talks to the server, so
|
||||
there is nothing to log, exactly as there is nothing for the rest of the dashboard to show. And
|
||||
**a disabled account goes quiet**: a disabled user is refused at the session check, so their only
|
||||
entries are the failed sign-ins they keep making.
|
||||
|
||||
Clearing the log from the dashboard records the clear itself, and the event ids keep counting, so
|
||||
a gap is always visible.
|
||||
|
||||
`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`:
|
||||
|
||||
@@ -115,10 +186,12 @@ Everything is in `./data`:
|
||||
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.)
|
||||
That archive contains all profiles, passkeys and workout history — and, if the activity log is
|
||||
on, `audit.log` with everyone's sign-in times. Worth knowing before you ship the archive to a
|
||||
backup service you don't run. 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.
|
||||
@@ -130,7 +203,16 @@ first run and saved to `./data/vapid.json`, and each user's browser reports its
|
||||
automatically when they turn the reminder on — it fires at their local time, and follows them if
|
||||
they travel, regardless of what timezone the server itself runs in.
|
||||
|
||||
## 7. Updating
|
||||
**Keep screen awake** (Settings → *During a workout*) has the same transport requirement: the
|
||||
Wake Lock API is only available over HTTPS or on `http://localhost`, so on a plain-LAN-IP
|
||||
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.
|
||||
|
||||
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:
|
||||
|
||||
@@ -150,15 +232,73 @@ docker compose up -d --build
|
||||
The app shell is versioned (`?v=N`) so clients pick up changes on next load. Your `./data` and the
|
||||
downloaded media are untouched.
|
||||
|
||||
## Passkeys fail even though `RP_ID` looks right
|
||||
|
||||
The most common support question, and the values are usually *nearly* correct. Work through
|
||||
these in order — the first two account for most of it.
|
||||
|
||||
**1. Ask the server what it actually loaded.** It prints both values on startup:
|
||||
|
||||
```
|
||||
docker compose logs api | grep 'gym-api on'
|
||||
# gym-api on :3000 (rpID=gym.example.com, origin=https://gym.example.com)
|
||||
```
|
||||
|
||||
If that disagrees with your `.env`, the container is still running the old environment.
|
||||
`docker compose restart` does **not** re-read `.env` — use `docker compose up -d`.
|
||||
|
||||
**2. Check the exact shape of each value.** They are not the same kind of string:
|
||||
|
||||
| | Correct | Wrong |
|
||||
|---|---|---|
|
||||
| `RP_ID` | `gym.example.com` | `https://gym.example.com`, `gym.example.com:8080`, `gym.example.com/` |
|
||||
| `ORIGIN` | `https://gym.example.com` | `gym.example.com`, `https://gym.example.com/` |
|
||||
|
||||
`RP_ID` is a bare hostname: no scheme, no port, no trailing slash. `ORIGIN` is the full origin
|
||||
*with* the scheme and *without* a trailing slash. Both must match your address bar exactly.
|
||||
|
||||
**3. Behind a tunnel or reverse proxy, use the public hostname.** With Cloudflare Tunnel,
|
||||
Traefik, nginx or Caddy in front, the browser only ever sees the public name — so that is what
|
||||
both values must be. Not the container name, not the LAN IP, not the internal port:
|
||||
|
||||
```env
|
||||
RP_ID=gym.example.com
|
||||
ORIGIN=https://gym.example.com
|
||||
```
|
||||
|
||||
The tunnel's own route may point wherever it likes (`http://localhost:8080` is fine). It is the
|
||||
browser-facing name that has to appear here.
|
||||
|
||||
**4. `www.` is a different host.** A passkey registered on `gym.example.com` will not work on
|
||||
`www.gym.example.com`. Pick one and redirect the other.
|
||||
|
||||
**5. Changing the hostname invalidates existing passkeys.** They were bound to the old one, so
|
||||
everybody registers again — which is why it pays to settle the domain before others join.
|
||||
|
||||
> On a LAN without certificates there is nothing to configure that makes passkeys work over
|
||||
> plain `http://192.168.x.x`: browsers only allow WebAuthn on HTTPS (or `localhost`). Use guest
|
||||
> mode, the standalone mobile app (`docs/MOBILE.md`), or put a certificate in front of it.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
| Symptom | Fix |
|
||||
|---|---|
|
||||
| No passkey prompt on my phone | You're on `http://` or an IP, not HTTPS. Set up a domain (section 3). |
|
||||
| "verification failed" on login | `RP_ID`/`ORIGIN` don't match the URL in the address bar. Make them exact, restart. |
|
||||
| "verification failed" on login | `RP_ID`/`ORIGIN` don't match the URL in the address bar. See the section above — start with what the server logged on startup. |
|
||||
| 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 3
|
||||
versionName "1.2.2"
|
||||
versionCode 14
|
||||
versionName "1.2.13"
|
||||
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.2",
|
||||
"version": "1.2.13",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "opengym-frontend",
|
||||
"version": "1.2.2",
|
||||
"version": "1.2.13",
|
||||
"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.2",
|
||||
"version": "1.2.13",
|
||||
"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',
|
||||
)
|
||||
@@ -0,0 +1,17 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import { createHash } from 'node:crypto'
|
||||
import pt from '../src/locales/pt.js'
|
||||
import { PT_BR_OVERRIDES } from '../src/locales/pt-BR.js'
|
||||
|
||||
const inherited = Object.entries(pt)
|
||||
.filter(([key]) => !(key in PT_BR_OVERRIDES))
|
||||
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
|
||||
const fingerprint = createHash('sha256').update(JSON.stringify(inherited)).digest('hex')
|
||||
|
||||
console.log(JSON.stringify({
|
||||
overrides: Object.keys(PT_BR_OVERRIDES).length,
|
||||
inherited: inherited.length,
|
||||
fingerprint,
|
||||
...(process.argv.includes('--list') ? { entries: inherited } : {})
|
||||
}, null, 2))
|
||||
@@ -6,6 +6,8 @@ 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'
|
||||
import TabBar from './components/TabBar.jsx'
|
||||
@@ -14,6 +16,7 @@ import Modals from './components/Modals.jsx'
|
||||
import Toast from './components/Toast.jsx'
|
||||
import RestTimer from './components/RestTimer.jsx'
|
||||
import Login from './views/Login.jsx'
|
||||
import MobileOnboarding from './views/MobileOnboarding.jsx'
|
||||
import Home from './views/Home.jsx'
|
||||
import Plan from './views/Plan.jsx'
|
||||
import RoutineEdit from './views/RoutineEdit.jsx'
|
||||
@@ -26,9 +29,14 @@ import Admin from './views/Admin.jsx'
|
||||
|
||||
bindUI(useUI) // lets the shared controls open sheets without importing the store at module scope
|
||||
|
||||
// theme === 'system' follows the OS/browser preference instead of a fixed choice.
|
||||
const resolveTheme = theme => theme === 'light' || theme === 'dark'
|
||||
? theme
|
||||
: (window.matchMedia?.('(prefers-color-scheme: dark)').matches ? 'dark' : 'light')
|
||||
|
||||
function applyPrefs(theme, accent) {
|
||||
const de = document.documentElement
|
||||
de.dataset.theme = theme === 'light' ? 'light' : 'dark'
|
||||
de.dataset.theme = resolveTheme(theme)
|
||||
de.dataset.accent = ACCENTS[accent] ? accent : 'lime'
|
||||
const meta = document.querySelector('meta[name="theme-color"]')
|
||||
if (meta) meta.content = de.dataset.theme === 'light' ? '#f2f2f7' : '#000000'
|
||||
@@ -39,13 +47,26 @@ function Shell() {
|
||||
const loc = useLocation()
|
||||
const { S, user, ready } = useStore()
|
||||
const isGuest = useStore(s => s.isGuest())
|
||||
const needsMobileOnboarding = useStore(s => s.needsMobileOnboarding)
|
||||
const langV = useLang() // re-renders the whole shell when the language (pack) changes
|
||||
useEffect(() => { setNav(navigate) }, [navigate])
|
||||
useEffect(() => { applyPrefs(S.theme, S.accent) }, [S.theme, S.accent])
|
||||
// 'system' needs to react live if the OS theme flips while the app is open, not just on
|
||||
// the next mount — a fixed 'dark'/'light' choice never re-fires this since matchMedia
|
||||
// isn't consulted for those.
|
||||
useEffect(() => {
|
||||
if (S.theme !== 'system' || !window.matchMedia) return
|
||||
const mql = window.matchMedia('(prefers-color-scheme: dark)')
|
||||
const onChange = () => applyPrefs(S.theme, S.accent)
|
||||
mql.addEventListener('change', onChange)
|
||||
return () => mql.removeEventListener('change', onChange)
|
||||
}, [S.theme, S.accent])
|
||||
useEffect(() => { setLang(S.lang || 'en') }, [S.lang])
|
||||
useEffect(() => { document.documentElement.lang = S.lang || 'en' }, [langV, S.lang])
|
||||
// every tab/route change starts at the top of the page
|
||||
useEffect(() => { window.scrollTo(0, 0) }, [loc.pathname])
|
||||
// bound to the workout, not to the route — checking Stats mid-session keeps the screen on
|
||||
useWakeLock(!!S.active && S.keepAwake !== false)
|
||||
|
||||
const authed = user || isGuest
|
||||
if (!ready && !authed) return (
|
||||
@@ -62,7 +83,7 @@ function Shell() {
|
||||
re-mounts the boundary, so the tab bar is always a way out */}
|
||||
<div id="app" className="vfade" key={loc.pathname}>
|
||||
<ErrorBoundary>
|
||||
{!authed ? <Login /> : (
|
||||
{!authed ? <Login /> : needsMobileOnboarding ? <MobileOnboarding /> : (
|
||||
<Routes>
|
||||
<Route path="/home" element={<Home />} />
|
||||
<Route path="/plan" element={<Plan />} />
|
||||
@@ -89,5 +110,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}>
|
||||
|
||||
@@ -112,6 +112,7 @@ const P = {
|
||||
signOut: <><path d="M14.2 4.6H7a1.9 1.9 0 0 0-1.9 1.9v11a1.9 1.9 0 0 0 1.9 1.9h7.2" /><path d="m16.8 8.4 3.6 3.6-3.6 3.6M20.4 12H10.2" /></>,
|
||||
shuffle: <><path d="M3.6 7.2h2.9c1.6 0 2.8.9 3.8 2.4l3 4.8c1 1.5 2.2 2.4 3.8 2.4h2.9M3.6 16.8h2.9c1.6 0 2.8-.9 3.8-2.4l.7-1.1M15.6 9.9l.7-1.1c1-1.5 2.2-2.4 3.8-2.4h1.9" /><path d="m17.9 4.3 2.8 2.1-2.8 2.1M17.9 14.7l2.8 2.1-2.8 2.1" /></>,
|
||||
info: <><circle cx="12" cy="12" r="8.2" /><path d="M12 11v5.4" /><circle cx="12" cy="7.9" r=".9" fill="currentColor" stroke="none" /></>,
|
||||
warning: <><path d="M12 3.4 21.2 19.4H2.8Z" /><path d="M12 9.6v4.4" /><circle cx="12" cy="16.6" r=".9" fill="currentColor" stroke="none" /></>,
|
||||
}
|
||||
|
||||
// A few keys are aliases so call sites can say what they mean.
|
||||
|
||||
@@ -4,13 +4,26 @@ 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)
|
||||
const [hover, setHover] = useState(null) // { x, y, iso, v }
|
||||
|
||||
// A new dataset has different coordinates and meaning, so never carry the previous
|
||||
// point selection into it. Layout timing removes the marker before the new chart paints.
|
||||
useLayoutEffect(() => {
|
||||
setHover(null)
|
||||
}, [points])
|
||||
|
||||
// The tooltip is placed after layout, from its measured size, because the chart
|
||||
// lives in an overflow-clipped box: a fixed half-width offset (what this used to
|
||||
// do) hangs the label off the edge on the first and last point, and the clip then
|
||||
@@ -42,7 +55,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 +97,11 @@ 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 hoverSource = single ? [points[0]] : points
|
||||
const hoverDates = hoverSource.map(p => p.d || isoOf(new Date(p.t)))
|
||||
const showYear = new Set(hoverDates.map(iso => new Date(iso + 'T12:00:00').getFullYear())).size > 1
|
||||
const hoverPts = hoverSource.map((p, i) => ({ x: X(p.t), y: Y(p.y), iso: hoverDates[i], v: p.y, note: p.note }))
|
||||
const marked = points.some(p => p.m != null)
|
||||
|
||||
const onMove = e => {
|
||||
const c = e.touches ? e.touches[0] : e
|
||||
@@ -111,6 +131,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,8 +141,8 @@ export default function LineChart({ points, h = 150, unit = '', color = 'var(--a
|
||||
</g>}
|
||||
</svg>
|
||||
{hover && <div className="ctip" ref={tipRef}>
|
||||
{fmtDate(hover.iso, true)} · {fmtNum(hover.v)}{unit ? ' ' + unit : ''}
|
||||
{fmtDate(hover.iso, true, showYear)} · {fmtNum(hover.v)}{unit ? ' ' + unit : ''}{hover.note ? ' · ' + hover.note : ''}
|
||||
</div>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
// @vitest-environment happy-dom
|
||||
import React, { act } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
|
||||
import LineChart from './LineChart.jsx'
|
||||
import { fmtDate, isoOf } from '../lib/format.js'
|
||||
|
||||
globalThis.IS_REACT_ACT_ENVIRONMENT = true
|
||||
|
||||
let container
|
||||
let root
|
||||
|
||||
beforeEach(() => {
|
||||
container = document.createElement('div')
|
||||
document.body.appendChild(container)
|
||||
root = createRoot(container)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
act(() => root.unmount())
|
||||
container.remove()
|
||||
})
|
||||
|
||||
const point = (year, month, day, y) => ({
|
||||
d: `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`,
|
||||
t: new Date(year, month - 1, day, 12).getTime(),
|
||||
y
|
||||
})
|
||||
|
||||
const firstPoints = [
|
||||
{ t: Date.UTC(2026, 0, 1), y: 80, d: '2026-01-01' },
|
||||
{ t: Date.UTC(2026, 0, 15), y: 82, d: '2026-01-15' },
|
||||
]
|
||||
const nextPoints = [
|
||||
{ t: Date.UTC(2026, 1, 1), y: 78, d: '2026-02-01' },
|
||||
{ t: Date.UTC(2026, 1, 15), y: 79, d: '2026-02-15' },
|
||||
]
|
||||
|
||||
function renderChart(points) {
|
||||
act(() => root.render(<LineChart points={points} axes={false} unit="kg" />))
|
||||
}
|
||||
|
||||
function hoverAt(clientX) {
|
||||
act(() => {
|
||||
container.querySelector('.chart-i').dispatchEvent(new MouseEvent('mousemove', { bubbles: true, clientX }))
|
||||
})
|
||||
return container.querySelector('.ctip').textContent
|
||||
}
|
||||
|
||||
describe('LineChart hover date', () => {
|
||||
it('keeps same-year points in the compact format', () => {
|
||||
const first = point(2026, 1, 15, 70)
|
||||
renderChart([first, point(2026, 2, 15, 71)])
|
||||
|
||||
expect(hoverAt(0)).toBe(`${fmtDate(first.d, true)} · 70 kg`)
|
||||
})
|
||||
|
||||
it('includes the calendar year at a short cross-year boundary', () => {
|
||||
const first = point(2025, 11, 30, 70)
|
||||
const last = point(2026, 2, 1, 71)
|
||||
renderChart([first, last])
|
||||
|
||||
expect(hoverAt(0)).toBe(`${fmtDate(first.d, true, true)} · 70 kg`)
|
||||
expect(hoverAt(340)).toBe(`${fmtDate(last.d, true, true)} · 71 kg`)
|
||||
})
|
||||
|
||||
it('keeps a single point compact', () => {
|
||||
const only = point(2026, 7, 4, 70)
|
||||
renderChart([only])
|
||||
|
||||
expect(hoverAt(170)).toBe(`${fmtDate(only.d, true)} · 70 kg`)
|
||||
})
|
||||
|
||||
it('uses timestamp-only points when deciding whether to show the year', () => {
|
||||
const first = point(2025, 12, 31, 70)
|
||||
const last = point(2026, 1, 1, 71)
|
||||
const timestampOnly = [{ t: first.t, y: first.y }, { t: last.t, y: last.y }]
|
||||
renderChart(timestampOnly)
|
||||
|
||||
const lastIso = isoOf(new Date(last.t))
|
||||
expect(hoverAt(340)).toBe(`${fmtDate(lastIso, true, true)} · 71 kg`)
|
||||
})
|
||||
})
|
||||
|
||||
describe('LineChart hover state', () => {
|
||||
it('clears the tooltip and hover markers when points are replaced, then allows hovering again', () => {
|
||||
renderChart(firstPoints)
|
||||
hoverAt(170)
|
||||
|
||||
expect(container.querySelector('.ctip')).toBeTruthy()
|
||||
expect(container.querySelector('.cvl')).toBeTruthy()
|
||||
expect(container.querySelector('.chl')).toBeTruthy()
|
||||
|
||||
renderChart(nextPoints)
|
||||
|
||||
expect(container.querySelector('.ctip')).toBeNull()
|
||||
expect(container.querySelector('.cvl')).toBeNull()
|
||||
expect(container.querySelector('.chl')).toBeNull()
|
||||
|
||||
hoverAt(170)
|
||||
expect(container.querySelector('.ctip')).toBeTruthy()
|
||||
expect(container.querySelector('.cvl')).toBeTruthy()
|
||||
})
|
||||
})
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useState } from 'react'
|
||||
import { imgSrc, gifSrc } from '../lib/exercises.js'
|
||||
import { useStore } from '../store/useStore.js'
|
||||
import { t } from '../lib/i18n.js'
|
||||
import { t, exerciseNameFor } from '../lib/i18n.js'
|
||||
import Icon from './Icon.jsx'
|
||||
|
||||
// Big autoplaying animation; tap toggles to the still frame. `compact` shrinks it (superset cards).
|
||||
@@ -18,7 +18,7 @@ export default function Media({ ex, id, compact, minimizable }) {
|
||||
const toggleSize = e => { e.stopPropagation(); update(s => { s.gifSize = mini ? 'full' : 'mini' }) }
|
||||
return (
|
||||
<div className={'exmedia' + (compact ? ' compact' : '') + (mini ? ' mini' : '')} id={id} onClick={() => setPlaying(p => !p)}>
|
||||
<img decoding="async" src={playing ? gifSrc(ex) : imgSrc(ex)} alt={ex.n} />
|
||||
<img decoding="async" src={playing ? gifSrc(ex) : imgSrc(ex)} alt={exerciseNameFor(ex)} />
|
||||
{minimizable && (
|
||||
<button className="giftoggle" onClick={toggleSize}>
|
||||
<Icon name={mini ? 'expand' : 'minimize'} />{mini ? t('Expand') : t('Minimize')}
|
||||
|
||||
@@ -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)
|
||||
})
|
||||
})
|
||||
@@ -34,12 +34,21 @@ export default function RestTimer() {
|
||||
<Button size="sm" variant="primary" icon="check" onClick={finishWorkEarly}>{t('Done')}</Button>
|
||||
</div>
|
||||
)
|
||||
// Three controls plus the clock don't fit one line on a phone — at 360px the bar is left
|
||||
// with about 30px and stops saying anything. So the rest variant stacks: clock and bar
|
||||
// read at a glance, controls get their own row. −15 and +15 sit together in number-line
|
||||
// order; Skip is pushed to the far edge, away from the button you tap to buy more time.
|
||||
return (
|
||||
<div id="timer">
|
||||
<div className="t">{clock(timer.left)}</div>
|
||||
<div className="bar"><i style={{ width: pct + '%' }} /></div>
|
||||
<Button size="sm" icon="plus" onClick={() => addRest(15)}>15s</Button>
|
||||
<Button size="sm" variant="primary" onClick={stopRest}>{t('Skip')}</Button>
|
||||
<div id="timer" className="rest">
|
||||
<div className="head">
|
||||
<div className="t">{clock(timer.left)}</div>
|
||||
<div className="bar"><i style={{ width: pct + '%' }} /></div>
|
||||
</div>
|
||||
<div className="acts">
|
||||
<Button size="sm" icon="minus" onClick={() => addRest(-15)}>15s</Button>
|
||||
<Button size="sm" icon="plus" onClick={() => addRest(15)}>15s</Button>
|
||||
<Button size="sm" variant="primary" className="skip" onClick={stopRest}>{t('Skip')}</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -21,15 +21,18 @@ import Icon from './Icon.jsx'
|
||||
// Numeric input accepting "," as decimal separator — iOS decimal keypads in many
|
||||
// locales only offer a comma, and type="number" reports "" for it (value snaps to
|
||||
// 0). Keeps a local string draft while focused so partial input like "33," survives.
|
||||
export function NumberField({ value, onChange, decimal = true, className = '', ...rest }) {
|
||||
// `nullable` is for fields where "nothing entered" and 0 mean different things (RIR: a
|
||||
// logged 0 is a set taken to failure). Those clear back to null instead of snapping to 0.
|
||||
export function NumberField({ value, onChange, decimal = true, nullable = false, className = '', ...rest }) {
|
||||
const [draft, setDraft] = useState(null)
|
||||
const committed = useRef(null)
|
||||
if (draft !== null && committed.current !== value) { setDraft(null); committed.current = null }
|
||||
// null and undefined are the same "empty" here — a nullable field's key is dropped once cleared.
|
||||
if (draft !== null && (committed.current ?? null) !== (value ?? null)) { setDraft(null); committed.current = null }
|
||||
const commit = raw => {
|
||||
let s = raw.replace(/,/g, '.').replace(/[^0-9.]/g, '')
|
||||
const i = s.indexOf('.')
|
||||
if (i !== -1) s = decimal ? s.slice(0, i + 1) + s.slice(i + 1).replace(/\./g, '') : s.slice(0, i)
|
||||
const n = s === '' || s === '.' ? 0 : Math.max(0, parseFloat(s))
|
||||
const n = s === '' || s === '.' ? (nullable ? null : 0) : Math.max(0, parseFloat(s))
|
||||
committed.current = n
|
||||
setDraft(s)
|
||||
onChange(n)
|
||||
@@ -112,13 +115,13 @@ export function Segmented({ options, value, onChange, className = '' }) {
|
||||
|
||||
/* ============================ stepper ============================ */
|
||||
|
||||
export function Stepper({ value, step = 1, onChange, decimal = true, className = '', label, unit }) {
|
||||
export function Stepper({ value, step = 1, onChange, decimal = true, className = '', label, unit, invalid = false }) {
|
||||
const set = v => onChange(Math.max(0, Math.round((v || 0) * 100) / 100))
|
||||
const inner = (
|
||||
<div className={'stp ' + className}>
|
||||
<button onClick={() => set((+value || 0) - step)} aria-label="Decrease"><Icon name="minus" /></button>
|
||||
<span className="val">
|
||||
<NumberField value={value} decimal={decimal} onChange={onChange} />
|
||||
<NumberField value={value} decimal={decimal} onChange={onChange} aria-invalid={invalid ? 'true' : undefined} />
|
||||
{unit && <i>{unit}</i>}
|
||||
</span>
|
||||
<button onClick={() => set((+value || 0) + step)} aria-label="Increase"><Icon name="plus" /></button>
|
||||
@@ -245,7 +248,7 @@ export function Row({ icon, iconTint, title, subtitle, value, accessory = 'none'
|
||||
// theme entirely — on dark mode it flashes a white sheet — and can't show more
|
||||
// than a bare label per option. This opens our own sheet with a checkmark on the
|
||||
// current value, which is also how iOS itself handles a long option list.
|
||||
export function SelectRow({ icon, iconTint, title, value, options, onChange, sheetTitle }) {
|
||||
export function SelectRow({ icon, iconTint, title, value, options, onChange, sheetTitle, stackedValue = false }) {
|
||||
const cur = options.find(o => o.value === value)
|
||||
const open = () => {
|
||||
const { openSheet } = require_ui()
|
||||
@@ -267,7 +270,50 @@ export function SelectRow({ icon, iconTint, title, value, options, onChange, she
|
||||
return h
|
||||
}
|
||||
return (
|
||||
<Row icon={icon} iconTint={iconTint} title={title} value={cur ? cur.label : value} accessory="chevron" onClick={open} />
|
||||
<Row icon={icon} iconTint={iconTint} title={title} value={cur ? cur.label : value} accessory="chevron" onClick={open}
|
||||
className={stackedValue ? 'lrow-stack-value' : ''} />
|
||||
)
|
||||
}
|
||||
|
||||
/** Multi-select row for additive exercise metadata. The sheet mirrors selection locally so
|
||||
* each tap updates its checkmark immediately while the caller persists the value. */
|
||||
export function MultiSelectRow({ icon, iconTint, title, values, options, onToggle, sheetTitle, noneLabel, doneLabel }) {
|
||||
const selected = options.filter(o => values.includes(o.value))
|
||||
const summary = selected.length ? selected.map(o => o.label).join(', ') : (noneLabel || '')
|
||||
const open = () => {
|
||||
const { openSheet } = require_ui()
|
||||
openSheet(close => <MultiSelectSheet values={values} options={options} onToggle={onToggle}
|
||||
title={sheetTitle || title} doneLabel={doneLabel} close={close} />)
|
||||
}
|
||||
return (
|
||||
<Row icon={icon} iconTint={iconTint} title={title} value={summary} accessory="chevron" onClick={open} />
|
||||
)
|
||||
}
|
||||
|
||||
function MultiSelectSheet({ values, options, onToggle, title, doneLabel, close }) {
|
||||
const [sel, setSel] = useState(values)
|
||||
const toggle = value => {
|
||||
setSel(current => current.includes(value) ? current.filter(x => x !== value) : [...current, value])
|
||||
onToggle(value)
|
||||
}
|
||||
return (
|
||||
<>
|
||||
<h3>{title}</h3>
|
||||
<div className="sect-b">
|
||||
{options.map(o => {
|
||||
const on = sel.includes(o.value)
|
||||
return (
|
||||
<button key={o.value} className={'lrow tap' + (on ? ' on' : '')} onClick={() => toggle(o.value)}>
|
||||
<span className="lrow-m"><span className="lrow-t">{o.label}</span>
|
||||
{o.subtitle && <span className="lrow-s">{o.subtitle}</span>}</span>
|
||||
{on && <Icon name="check" className="lrow-k" />}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
<div style={{ height: 8 }} />
|
||||
<Button variant="primary" onClick={close}>{doneLabel || 'Done'}</Button>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
// generated by scripts/build-pt-br-exercise-names.mjs — edit scripts/exercise-name-sources/pt-BR.json
|
||||
export default {"1000":"elevação de panturrilha invertida unilateral com faixa elástica","1001":"afundo estático unilateral com faixa elástica","1002":"elevação de pernas retas deitado com faixa elástica","1003":"agachamento com remada e faixa elástica","1004":"agachamento com faixa elástica","1005":"abdominal em pé com faixa elástica","1007":"abdominal rotacional em pé com faixa elástica","1008":"subida no step com faixa elástica","1009":"levantamento terra pernas semiestendidas com faixa elástica","1010":"levantamento terra pernas estendidas com faixa elástica","1011":"torção sentado com faixa elástica","1012":"desenvolvimento acima da cabeça com rotação e faixa elástica","1013":"puxada pegada supinada com faixa elástica","1014":"abdominal em v com faixa elástica","1015":"pallof press vertical com faixa elástica","1016":"rosca de punho com faixa elástica","1017":"elevação em y com faixa elástica","1018":"encolhimento de ombros com faixa elástica","1022":"remada para deltoide posterior em pé com faixa elástica","1023":"levantamento terra pernas semiestendidas com costas retas e faixa elástica","1160":"burpee","1167":"alongamento dinâmico de peitoral (masculino)","1201":"Burpee com halteres","1253":"elevação de panturrilha burro na máquina","1254":"supino com faixa elástica","1255":"pullover declinado com barra","1256":"supino declinado pegada supinada com barra","1257":"supino inclinado pegada supinada com barra","1258":"supino pegada aberta supinada com barra","1259":"alongamento de peitoral atrás da cabeça","1260":"supino declinado unilateral no cabo","1261":"supino declinado no cabo","1262":"crucifixo declinado unilateral no cabo","1263":"crucifixo unilateral na bola de exercício no cabo","1264":"crucifixo inclinado unilateral na bola de exercício no cabo","1265":"supino inclinado unilateral no cabo","1266":"supino inclinado unilateral na bola de exercício no cabo","1267":"supino unilateral na bola de exercício no cabo","1268":"supino na bola de exercício no cabo","1269":"crossover em pé ereto no cabo","1270":"crossover para peitoral superior no cabo","1271":"alongamento de peito e parte frontal do ombro","1272":"alongamento de peito com bola de exercício","1273":"flexão de braços com palma","1274":"flexão de braços profunda","1275":"flexão de braços com queda","1276":"Crucifixo declinado unilateral com halter","1277":"Crucifixo com halteres na bola de estabilidade","1278":"Crucifixo inclinado com halteres na bola de estabilidade","1279":"Crucifixo inclinado unilateral com halter","1280":"Crucifixo inclinado unilateral com halter na bola de estabilidade","1281":"Supino inclinado unilateral com halter","1282":"Supino inclinado unilateral com halter na bola de estabilidade","1283":"Supino inclinado com halteres na bola de estabilidade","1284":"Pullover deitado na bola de estabilidade com halter","1285":"Crucifixo unilateral no banco com halter","1286":"Crucifixo unilateral na bola de estabilidade com halter","1287":"Supino declinado unilateral com halter","1288":"Crucifixo unilateral na bola de estabilidade com halter","1289":"Supino inclinado unilateral com halter","1290":"Supino unilateral na bola de estabilidade com halter","1291":"Pullover unilateral na bola de estabilidade com halter","1292":"Crucifixo com uma perna na bola de estabilidade (halteres)","1293":"Supino na bola de estabilidade com halteres","1294":"Pullover com extensão de quadril na bola de estabilidade (halteres)","1295":"Pullover na bola de estabilidade com halteres","1296":"flexão de braços em pique na bola de estabilidade","1297":"contração isométrica de peitoral","1298":"supino unilateral com kettlebell no chão","1299":"supino inclinado na máquina","1300":"supino declinado na máquina","1301":"supino interno na máquina","1302":"passe de peito com bola medicinal","1303":"empurrão de peito com bola medicinal a partir de três apoios","1304":"empurrão de peito com bola medicinal (resposta múltipla)","1305":"empurrão de peito com bola medicinal (resposta única)","1306":"flexão de braços pliométrica","1307":"flexão de braços na bosu","1308":"supino pegada aberta na máquina Smith","1309":"supino declinado pegada aberta na máquina Smith","1310":"flexão de braços com queda e peso","1311":"flexão de braços com mãos afastadas","1312":"empurrão de peito com bola medicinal com saída em corrida","1313":"remada unilateral na máquina","1314":"extensão de tronco na bola de estabilidade","1316":"pullover com braços flexionados com barra","1317":"remada no banco inclinado pegada supinada com barra","1318":"remada no banco inclinado no cabo","1319":"remada com rotação da palma no cabo","1320":"remada sentada crossover com corda no cabo","1321":"remada sentada elevada com corda no cabo","1322":"remada no banco inclinado com extensão de corda no cabo","1323":"remada sentada com corda no cabo","1324":"remada superior no cabo","1325":"puxada atrás da nuca pegada abLine truncated
|
||||
@@ -165,8 +165,9 @@ button,.chip,.tile,.item,.wday,.cal-d,.swatch,.hm-c,.lrow,.seg button,.stp butto
|
||||
padding:calc(var(--sat) + 8px) var(--pad) calc(128px + var(--sab));
|
||||
max-width:560px;margin:0 auto;
|
||||
}
|
||||
/* while the rest timer floats above the tab bar, keep its height scrollable-past */
|
||||
body.resting #app{padding-bottom:calc(206px + var(--sab))}
|
||||
/* while the rest timer floats above the tab bar, keep its height scrollable-past
|
||||
(the rest variant is two rows tall — ~44px more than the single-row work timer) */
|
||||
body.resting #app{padding-bottom:calc(250px + var(--sab))}
|
||||
@keyframes viewfade{from{opacity:0;transform:translateY(4px)}to{opacity:1;transform:none}}
|
||||
#app.vfade{animation:viewfade var(--med) var(--ease)}
|
||||
|
||||
@@ -232,10 +233,38 @@ 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.
|
||||
The cap is max-width, not flex-basis: .lrow-m is flex:1, so its basis is 0 and it absorbs
|
||||
none of the shrink — a long value would otherwise take the whole row and squeeze the title
|
||||
to 21px. A basis of 45% fixes that but reserves the space even for "3", costing the title
|
||||
141px on the rows that need it most. A cap does neither. */
|
||||
.lrow-v{color:var(--label-2);font-size:17px;letter-spacing:-.012em;flex:0 1 auto;max-width:45%;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)}
|
||||
/* The Stats exercise name gets its own line so long names cannot run into the title.
|
||||
Two columns only — label/value on the left, chevron on the right — so this is for rows
|
||||
WITHOUT an icon. `.lrow-i` is not placed here; on a row that has one it would auto-place
|
||||
into the grid and push the layout around. Give it a leading column before using this
|
||||
anywhere else. */
|
||||
.lrow.lrow-stack-value{
|
||||
display:grid;grid-template-columns:minmax(0,1fr) auto;grid-template-rows:auto auto;
|
||||
}
|
||||
.lrow.lrow-stack-value .lrow-m{grid-column:1;grid-row:1}
|
||||
.lrow.lrow-stack-value .lrow-v{grid-column:1;grid-row:2;text-align:left}
|
||||
.lrow.lrow-stack-value .lrow-c{grid-column:2;grid-row:1 / span 2;align-self:center}
|
||||
/* an (i) before a row's control: painted small and dim so the control stays the loud thing,
|
||||
but with a finger-sized target like everything else — the padding is the hit area and the
|
||||
vertical negative margin keeps it from making the row taller. The horizontal ones pull the
|
||||
hit area back under the row's own 12px gap instead of adding to it. */
|
||||
.helpbtn{
|
||||
color:var(--label-3);font-size:16px;background:none;line-height:0;flex:none;
|
||||
margin:-11px -2px -11px -4px;padding:11px 4px;
|
||||
}
|
||||
.helpbtn:active{color:var(--label)}
|
||||
|
||||
/* -------------------------------------------------------------- buttons -- */
|
||||
.btn{
|
||||
@@ -258,15 +287,21 @@ h4.sec{
|
||||
.btn:disabled{opacity:.32;pointer-events:none}
|
||||
|
||||
/* ----------------------------------------------------------- tab bar ----- */
|
||||
/* Nearly opaque, and deliberately so. At the old 72% the page read straight through the bar
|
||||
and the labels had to compete with whatever was scrolling behind them — nobody needs to read
|
||||
the content under a navigation bar. 94% keeps a hint of movement behind the glass without
|
||||
letting text through. The blur is also down from 24px to 10px: this is a fixed element, so
|
||||
the WebView recomposites the blurred region on every scroll frame, and on Android that is
|
||||
the single most expensive thing on the screen. See @supports below for the no-blur case. */
|
||||
#tabbar{
|
||||
position:fixed;left:0;right:0;bottom:0;z-index:50;
|
||||
display:flex;justify-content:space-around;align-items:flex-end;
|
||||
padding:7px 6px calc(6px + var(--sab));
|
||||
background:color-mix(in srgb,var(--bg-el) 72%,transparent);
|
||||
backdrop-filter:saturate(180%) blur(24px);-webkit-backdrop-filter:saturate(180%) blur(24px);
|
||||
background:color-mix(in srgb,var(--bg-el) 94%,transparent);
|
||||
-webkit-backdrop-filter:saturate(180%) blur(10px);backdrop-filter:saturate(180%) blur(10px);
|
||||
border-top:var(--hair) solid var(--sep-op);
|
||||
}
|
||||
:root[data-theme="light"] #tabbar{background:rgba(249,249,251,.78)}
|
||||
:root[data-theme="light"] #tabbar{background:rgba(249,249,251,.94)}
|
||||
#tabbar button{
|
||||
flex:1;display:flex;flex-direction:column;align-items:center;gap:3px;
|
||||
color:var(--label-3);font-size:10px;font-weight:500;letter-spacing:.005em;padding-top:3px;
|
||||
@@ -303,6 +338,21 @@ h4.sec{
|
||||
}
|
||||
@keyframes ping{0%{transform:scale(1);opacity:.7}100%{transform:scale(1.45);opacity:0}}
|
||||
|
||||
/* NOTE on every backdrop-filter pair in this file: the -webkit- line comes first and the
|
||||
standard property last, which is the order a prefixed/standard pair wants — whichever is
|
||||
written last wins in the cascade, and that should be the standard name.
|
||||
|
||||
Where backdrop-filter is genuinely unsupported there is no glass either — only the alpha,
|
||||
and the page shows through unblurred, which is the worst of both. Older Android WebViews
|
||||
never had it, and "reduce transparency" accessibility settings drop it. Those surfaces go
|
||||
fully opaque instead. Keep this in sync with the rules above. */
|
||||
@supports not ((backdrop-filter:blur(1px)) or (-webkit-backdrop-filter:blur(1px))){
|
||||
#tabbar{background:var(--bg-el)}
|
||||
:root[data-theme="light"] #tabbar{background:#f9f9fb}
|
||||
#timer{background:var(--surface)}
|
||||
#toast{background:var(--surface-2)}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ week strip -- */
|
||||
.week{display:flex;justify-content:space-between;gap:4px}
|
||||
.wday{
|
||||
@@ -480,6 +530,7 @@ h4.sec{
|
||||
-moz-appearance:textfield;appearance:textfield;
|
||||
}
|
||||
.stp .num::-webkit-inner-spin-button{display:none}
|
||||
.stp.invalid{box-shadow:inset 0 0 0 1px var(--red)}
|
||||
|
||||
/* --- slider --- */
|
||||
.sld{position:relative;height:32px;display:flex;align-items:center;cursor:pointer;touch-action:none}
|
||||
@@ -522,7 +573,7 @@ h4.sec{
|
||||
position:absolute;bottom:9px;display:inline-flex;align-items:center;gap:4px;
|
||||
background:rgba(0,0,0,.45);color:#fff;border-radius:99px;padding:5px 11px;
|
||||
font-size:12px;font-weight:500;
|
||||
backdrop-filter:blur(12px);-webkit-backdrop-filter:blur(12px);
|
||||
-webkit-backdrop-filter:blur(12px);backdrop-filter:blur(12px);
|
||||
}
|
||||
.exmedia .gifhint{right:9px}
|
||||
.exmedia .giftoggle{left:9px}
|
||||
@@ -539,11 +590,15 @@ h4.sec{
|
||||
.sethead .n-sp{width:24px;flex:none}
|
||||
.sethead .w-sp{flex:1.4;text-align:center}
|
||||
.sethead .r-sp{flex:1;text-align:center}
|
||||
.sethead .eff-sp{text-align:center}
|
||||
.sethead .ck-sp{width:30px;flex:none}
|
||||
.setrow{display:flex;align-items:center;gap:8px;padding:7px 0;position:relative}
|
||||
.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;
|
||||
@@ -551,9 +606,34 @@ h4.sec{
|
||||
}
|
||||
.setrow .stp.w{flex:1.4;min-width:0}
|
||||
.setrow .stp.r{flex:1;min-width:0}
|
||||
.setrow .stp.eff{flex:1.1;min-width:0}
|
||||
.setrow .stp button{width:32px;height:40px}
|
||||
/* a 3rd stepper (RIR) needs narrower buttons and a tighter row gap to fit next to weight+reps
|
||||
on narrow phones, same technique as the exercise-config sheet's three-steppers-in-a-row
|
||||
(.cfgrow below) — RIR's own value is short ("1.5") so its buttons shrink the most, weight/reps
|
||||
just enough to make room since their values ("82.5", "12") need more of what's left.
|
||||
The header shares the numbers so its labels stay centred over the steppers they name. */
|
||||
.setrow.eff3,.sethead.eff3{gap:6px}
|
||||
.setrow.eff3 .stp.w,.sethead.eff3 .w-sp{flex:1.2}
|
||||
.setrow.eff3 .stp.r,.sethead.eff3 .r-sp{flex:1}
|
||||
.setrow.eff3 .stp.eff,.sethead.eff3 .eff-sp{flex:.85}
|
||||
.setrow.eff3 .stp button{width:23px}
|
||||
.setrow.eff3 .stp.eff button{width:20px}
|
||||
.setrow.eff3 .stp .num{font-size:14px}
|
||||
.setrow.done .n{background:var(--acc);color:var(--on-acc)}
|
||||
.setrow.done{opacity:.45}
|
||||
/* drop-set drops / rest-pause bursts riding on a work row, editable like the row itself
|
||||
(issue: drop-sets & rest-pause) */
|
||||
.subrow{display:flex;align-items:center;gap:6px;padding:3px 0 3px 32px}
|
||||
.subrow .subn{font-size:11px;color:var(--label-3);flex:none;width:46px}
|
||||
.subrow .stp.mini{flex:1;min-width:0}
|
||||
.subrow .stp.mini button{width:26px;height:30px}
|
||||
.subrow .stp.mini .num{font-size:13px}
|
||||
.subrow .iconbtn{width:26px;height:26px;font-size:11px;flex:none}
|
||||
.setextra{display:flex;flex-wrap:wrap;gap:6px;margin:2px 0 8px 32px}
|
||||
.setextra .chip.add{display:inline-flex;align-items:center;gap:4px;color:var(--acc)}
|
||||
.setextra .chip.add svg{width:13px;height:13px}
|
||||
.setextra .chip.add:disabled{opacity:.35}
|
||||
/* why the next target is what it is (issue #17) */
|
||||
.progline{
|
||||
display:flex;align-items:flex-start;gap:7px;margin:6px 0 2px;
|
||||
@@ -580,8 +660,10 @@ h4.sec{
|
||||
/* --- rest timer --- */
|
||||
#timer{
|
||||
position:fixed;left:12px;right:12px;bottom:calc(88px + var(--sab));z-index:60;
|
||||
background:color-mix(in srgb,var(--surface) 82%,transparent);
|
||||
backdrop-filter:saturate(180%) blur(24px);-webkit-backdrop-filter:saturate(180%) blur(24px);
|
||||
/* nearly opaque: the set rows underneath were reading through the old 82% and made the
|
||||
clock hard to pick out mid-set. The blur stays, so it still sits above the page. */
|
||||
background:color-mix(in srgb,var(--surface) 97%,transparent);
|
||||
-webkit-backdrop-filter:saturate(180%) blur(10px);backdrop-filter:saturate(180%) blur(10px);
|
||||
border-radius:var(--r-lg);padding:12px 14px;
|
||||
display:flex;align-items:center;gap:12px;
|
||||
box-shadow:0 12px 34px -8px rgba(0,0,0,.55);
|
||||
@@ -591,6 +673,14 @@ h4.sec{
|
||||
#timer .t{font-size:26px;font-weight:600;letter-spacing:-.026em;font-variant-numeric:tabular-nums;min-width:66px}
|
||||
#timer .bar{flex:1;height:4px;background:var(--surface-3);border-radius:99px;overflow:hidden}
|
||||
#timer .bar i{display:block;height:100%;background:var(--acc);transition:width 1s linear}
|
||||
/* rest variant: −15/+15/Skip and the clock won't share one line on a phone, so the clock and
|
||||
bar take the top row and the controls take their own. The work timer keeps a single row —
|
||||
it only ever has two buttons. */
|
||||
#timer.rest{flex-direction:column;align-items:stretch;gap:10px}
|
||||
#timer.rest .head{display:flex;align-items:center;gap:12px}
|
||||
#timer.rest .acts{display:flex;align-items:center;gap:8px}
|
||||
#timer.rest .acts .btn{padding-top:11px;padding-bottom:11px} /* sweaty hands, mid-set */
|
||||
#timer.rest .acts .skip{margin-left:auto;min-width:84px}
|
||||
/* work timer (issue #16): the same bar doing the opposite job — outlined and tinted so a
|
||||
glance tells "you are holding this" apart from "you are recovering". */
|
||||
#timer.working{border:var(--hair) solid var(--acc)}
|
||||
@@ -606,7 +696,7 @@ h4.sec{
|
||||
#modal-root.open{display:block}
|
||||
.mback{
|
||||
position:absolute;inset:0;background:rgba(0,0,0,.4);
|
||||
backdrop-filter:blur(2px);-webkit-backdrop-filter:blur(2px);
|
||||
-webkit-backdrop-filter:blur(2px);backdrop-filter:blur(2px);
|
||||
touch-action:none;overscroll-behavior:none;
|
||||
}
|
||||
.sheet{
|
||||
@@ -630,6 +720,32 @@ h4.sec{
|
||||
:root[data-theme="light"] .center{background:#fff}
|
||||
@keyframes pop{from{transform:translate(-50%,-50%) scale(.94);opacity:0}to{transform:translate(-50%,-50%) scale(1);opacity:1}}
|
||||
|
||||
/* --- RIR/RPE conversion table (effort help sheet) ---
|
||||
The two scales only click when you see them side by side, so the numbers get fixed-width
|
||||
tabular columns you can read straight down, and the words take whatever is left. Built out
|
||||
of the same grouped-list parts as the rest of the app (surface fill, inset hairlines) rather
|
||||
than a real <table>, so it inherits the card look and wraps properly on a narrow phone. */
|
||||
.efftbl{background:var(--surface);border-radius:var(--r-lg);overflow:hidden;margin:14px 0 12px}
|
||||
.efftbl .r{display:flex;align-items:center;gap:10px;padding:10px 14px;position:relative}
|
||||
.efftbl .r+.r::before{
|
||||
content:'';position:absolute;left:14px;right:0;top:0;height:var(--hair);background:var(--sep);
|
||||
}
|
||||
.efftbl .n{
|
||||
width:36px;flex:none;text-align:center;font-size:17px;font-weight:600;
|
||||
letter-spacing:-.02em;font-variant-numeric:tabular-nums;
|
||||
}
|
||||
.efftbl .f{flex:1;min-width:0;font-size:15px;color:var(--label-2);line-height:1.3}
|
||||
/* the header names the columns without competing with them */
|
||||
.efftbl .hd{background:var(--surface-2);padding-top:8px;padding-bottom:8px}
|
||||
.efftbl .hd .n,.efftbl .hd .f{
|
||||
font-size:11px;font-weight:600;letter-spacing:.05em;text-transform:uppercase;
|
||||
color:var(--label-3);
|
||||
}
|
||||
/* the row a working set usually lands on — the anchor the others are read against */
|
||||
.efftbl .r.on{background:var(--acc-soft)}
|
||||
.efftbl .r.on .n{color:var(--acc)}
|
||||
.efftbl .r.on .f{color:var(--label)}
|
||||
|
||||
/* --- glyph picker (replaces the emoji grid) --- */
|
||||
.glyph-grid{display:grid;grid-template-columns:repeat(5,1fr);gap:9px}
|
||||
.glyph-cell{
|
||||
@@ -713,6 +829,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
|
||||
@@ -724,6 +852,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)}
|
||||
@@ -752,7 +883,7 @@ h4.sec{
|
||||
position:fixed;left:50%;transform:translateX(-50%) translateY(6px);
|
||||
bottom:calc(96px + var(--sab));z-index:200;
|
||||
background:color-mix(in srgb,var(--surface-2) 88%,transparent);
|
||||
backdrop-filter:saturate(180%) blur(20px);-webkit-backdrop-filter:saturate(180%) blur(20px);
|
||||
-webkit-backdrop-filter:saturate(180%) blur(20px);backdrop-filter:saturate(180%) blur(20px);
|
||||
border-radius:99px;padding:11px 20px;font-size:15px;font-weight:500;
|
||||
box-shadow:0 10px 30px -6px rgba(0,0,0,.5);
|
||||
opacity:0;pointer-events:none;transition:opacity var(--med),transform var(--med) var(--ease);
|
||||
@@ -804,6 +935,13 @@ h4.sec{
|
||||
border-radius:var(--r-lg);padding:14px;
|
||||
background:var(--surface);box-shadow:inset 0 0 0 1.5px var(--acc-line);
|
||||
}
|
||||
/* A superset nests a card inside the page's own gutter, so its inset is paid twice. On a
|
||||
narrow phone that left the weight and reps steppers too tight to show a three-digit
|
||||
number — reported as "the reps textbox becomes too small when superset on mobile". The
|
||||
card only gives up its own padding; the rows inside keep their spacing. */
|
||||
@media (max-width:400px){
|
||||
.ss-card{padding:10px 8px}
|
||||
}
|
||||
.ss-hd{
|
||||
font-size:12px;font-weight:600;color:var(--acc);margin-bottom:12px;
|
||||
text-align:center;display:flex;align-items:center;justify-content:center;gap:5px;
|
||||
@@ -815,7 +953,7 @@ h4.sec{
|
||||
.today-row{
|
||||
display:flex;align-items:center;justify-content:space-between;gap:10px;
|
||||
margin-top:12px;padding:12px 14px;border-radius:var(--r);background:var(--surface-2);
|
||||
transition:background var(--fast);width:100%;text-align:left;
|
||||
transition:background var(--fast);width:100%;text-align:left;cursor:pointer;
|
||||
}
|
||||
.today-row:active{background:var(--surface-3)}
|
||||
.today-row .lbl2{font-size:11px;font-weight:500;letter-spacing:.03em;text-transform:uppercase;color:var(--label-3)}
|
||||
@@ -824,6 +962,13 @@ h4.sec{
|
||||
letter-spacing:-.012em;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;margin-top:2px;
|
||||
}
|
||||
|
||||
/* Only where a pointer really hovers — on a phone :hover sticks to the row after the tap.
|
||||
Lighter than :active, which goes all the way to --surface-3, so the two stay distinct. */
|
||||
@media (hover:hover){
|
||||
.today-row:hover{background:color-mix(in srgb,var(--surface-2),var(--surface-3) 60%)}
|
||||
:root[data-theme="light"] .today-row:hover{background:color-mix(in srgb,var(--surface-2),var(--surface-3) 85%)}
|
||||
}
|
||||
|
||||
/* --------------------------------------------------- desktop (≥1000px) --- */
|
||||
.cols{display:block}
|
||||
@media (min-width:1000px){
|
||||
@@ -844,6 +989,9 @@ h4.sec{
|
||||
.sheet{left:50%;right:auto;margin-left:-320px;width:640px;border-radius:var(--r-xl) var(--r-xl) 0 0}
|
||||
.center{width:340px}
|
||||
#timer{left:50%;right:auto;margin-left:-260px;width:520px;bottom:112px}
|
||||
/* 520px fits the clock, the bar and all three controls on one line again */
|
||||
#timer.rest{flex-direction:row;align-items:center;gap:14px}
|
||||
#timer.rest .head{flex:1;min-width:0}
|
||||
.exmedia img{height:380px}
|
||||
.hm-wrap{display:flex;flex-direction:column;align-items:center}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
// generated by scripts/build-pt-br-instructions.mjs — edit scripts/instruction-sources/pt-BR.json
|
||||
export default {"1000":["Fique em pé com os pés afastados na largura do quadril e posicione a faixa elástica ao redor da parte anterior do pé.","Segure-se em um objeto estável para se equilibrar.","Eleve lentamente o calcanhar do chão, transferindo o peso corporal para a parte anterior do pé.","Faça uma breve pausa no alto e depois abaixe lentamente o calcanhar até a posição inicial.","Repita pelo número desejado de repetições e depois troque para a outra perna."],"1001":["Fique em pé com os pés afastados na largura do quadril e coloque uma faixa elástica ao redor dos tornozelos.","Dê um passo grande à frente com o pé direito e um passo menor para trás com o pé esquerdo.","Flexione os joelhos e abaixe o corpo até que a coxa direita fique paralela ao chão, mantendo o joelho esquerdo ligeiramente acima do chão.","Empurre o chão com o calcanhar direito para retornar à posição inicial.","Repita do outro lado."],"1002":["Deite-se de costas com as pernas retas e os pés juntos.","Coloque a faixa elástica ao redor do arco dos pés e segure as extremidades da faixa com as mãos.","Contraindo o abdômen, eleve as duas pernas do chão até ficarem perpendiculares ao chão.","Faça uma pausa no topo do movimento e, em seguida, abaixe lentamente as pernas até a posição inicial.","Repita pelo número desejado de repetições."],"1003":["Prenda a faixa elástica a um ponto de ancoragem firme na altura da cintura.","Fique em pé de frente para o ponto de ancoragem, com os pés afastados na largura dos ombros.","Segure as alças da faixa elástica com as palmas voltadas uma para a outra e os braços estendidos à frente.","Flexione os joelhos e desça até a posição de agachamento, mantendo as costas retas e o peito elevado.","A partir da posição de agachamento, puxe as alças da faixa elástica em direção ao corpo, aproximando as escápulas.","Faça uma breve pausa no final do movimento; depois, libere lentamente a tensão e retorne à posição inicial.","Repita pelo número desejado de repetições."],"1004":["Fique em pé com os pés afastados na largura dos ombros e a faixa elástica posicionada logo acima dos joelhos.","Mantendo o peito elevado e o abdômen contraído, leve o quadril para trás e flexione os joelhos para descer até a posição de agachamento.","Certifique-se de que os joelhos acompanhem a direção dos dedos dos pés e que o peso esteja sobre os calcanhares.","Faça uma breve pausa embaixo; depois, empurre o chão com os calcanhares para retornar à posição inicial.","Repita pelo número desejado de repetições."],"1005":["Fixe a faixa elástica em um ponto de ancoragem firme na altura da cintura.","Fique de pé de costas para o ponto de ancoragem, com os pés afastados na largura dos ombros.","Segure a faixa com as duas mãos e traga-a até o peito, mantendo os cotovelos dobrados e próximos ao corpo.","Contraia o abdômen e flexione o tronco lentamente para frente, levando o peito em direção aos joelhos.","Faça uma pausa no topo do movimento e, em seguida, retorne lentamente à posição inicial.","Repita pelo número desejado de repetições."],"1007":["Fique de pé com os pés afastados na largura dos ombros e passe a faixa elástica pela parte superior das costas, cruzando-a na frente do peito.","Segure as extremidades da faixa com as mãos, mantendo os cotovelos dobrados e próximos ao corpo.","Contraia o abdômen e gire o tronco para um dos lados, levando o cotovelo em direção ao joelho oposto.","Faça uma pausa e, em seguida, retorne à posição inicial.","Repita do outro lado.","Continue alternando os lados pelo número desejado de repetições."],"1008":["Coloque uma faixa elástica ao redor das coxas, logo acima dos joelhos.","Fique em pé de frente para um degrau ou plataforma, com os pés afastados na largura do quadril.","Suba na plataforma com o pé direito, empurrando-a com o calcanhar.","Estenda a perna esquerda para trás, mantendo-a reta.","Abaixe o pé esquerdo de volta ao chão.","Repita subindo na plataforma com o pé esquerdo.","Continue alternando as pernas pelo número desejado de repetições."],"1009":["Fique em pé com os pés afastados na largura dos ombros e coloque a faixa elástica ao redor dos tornozelos.","Segure a faixa elástica com as duas mãos à frente das coxas, com as palmas voltadas para o corpo.","Mantendo as costas retas e o abdômen contraído, incline o tronco à frente a partir do quadril e abaixe lentamente a parte superior do corpo em direção ao chão.","Ao descer, leve o quadril para trás e deixe os joelhos flexionarem levemente.","Abaixe a faixa elástica em direção ao chão, sentindo o alongamento nos músculos posteriores das coxas.","Faça uma breve pausa embaixo; depois, contraia os glúteos e os músculos posteriores das coxas para elevar a parte superior do corpo de volta à posição inicial.","Repita pelo número desejado de repetições."],"1010":["Fique em pé com os pés afastados na
Line truncated
|
||||
@@ -3,10 +3,33 @@ export const IS_APPLE = /iPhone|iPad|iPod|Macintosh/.test(navigator.userAgent)
|
||||
export const IS_ANDROID = /Android/.test(navigator.userAgent)
|
||||
export const BIO = IS_APPLE ? 'Face ID / Touch ID' : IS_ANDROID ? 'fingerprint or face unlock' : 'your fingerprint, face or PIN'
|
||||
export const VAULT = IS_APPLE ? 'iCloud Keychain' : IS_ANDROID ? 'Google Password Manager' : 'your password manager'
|
||||
export const webauthnOK = () => !!(window.PublicKeyCredential && navigator.credentials)
|
||||
// PublicKeyCredential is the WebAuthn-specific capability signal. Do not also gate the UI on
|
||||
// navigator.credentials: some browsers expose WebAuthn while that generic Credential Management
|
||||
// API check produces a false negative (notably Chrome on iOS). The real create/get calls still run
|
||||
// only after the user chooses a passkey action and surface any genuine browser error there.
|
||||
export const webauthnOK = () => typeof window.PublicKeyCredential !== 'undefined'
|
||||
|
||||
// The paired mobile app (lib/remote.js) is the only caller of these — everywhere else stays on
|
||||
// same-origin cookies, so remoteBase/remoteToken stay empty and api() behaves exactly as before.
|
||||
let remoteBase = ''
|
||||
let remoteToken = null
|
||||
export function setRemoteAuth(base, token) { remoteBase = base || ''; remoteToken = token || null }
|
||||
|
||||
export async function api(path, opts) {
|
||||
const r = await fetch(path, Object.assign({ headers: { 'Content-Type': 'application/json' } }, opts))
|
||||
const headers = Object.assign({ 'Content-Type': 'application/json' }, opts && opts.headers)
|
||||
if (remoteToken) headers.Authorization = 'Bearer ' + remoteToken
|
||||
const r = await fetch(remoteBase + path, Object.assign({}, opts, { headers }))
|
||||
const data = await r.json().catch(() => ({}))
|
||||
if (!r.ok) { const e = new Error(data.error || ('HTTP ' + r.status)); e.status = r.status; throw e }
|
||||
return data
|
||||
}
|
||||
|
||||
// Bootstraps the connection itself: the base isn't configured yet (that's what this call decides),
|
||||
// so it talks straight to the server the user typed in, no Authorization header.
|
||||
export async function pairRedeem(serverBase, code) {
|
||||
const r = await fetch(serverBase + '/api/pair/redeem', {
|
||||
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ code })
|
||||
})
|
||||
const data = await r.json().catch(() => ({}))
|
||||
if (!r.ok) { const e = new Error(data.error || ('HTTP ' + r.status)); e.status = r.status; throw e }
|
||||
return data
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import { webauthnOK } from './api.js'
|
||||
|
||||
const originalPublicKeyCredential = window.PublicKeyCredential
|
||||
const originalCredentials = navigator.credentials
|
||||
|
||||
function setCapability(target, property, value) {
|
||||
Object.defineProperty(target, property, { configurable: true, value })
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
setCapability(window, 'PublicKeyCredential', originalPublicKeyCredential)
|
||||
setCapability(navigator, 'credentials', originalCredentials)
|
||||
})
|
||||
|
||||
describe('webauthnOK', () => {
|
||||
it('accepts WebAuthn when PublicKeyCredential is exposed', () => {
|
||||
setCapability(window, 'PublicKeyCredential', class PublicKeyCredential {})
|
||||
setCapability(navigator, 'credentials', {})
|
||||
expect(webauthnOK()).toBe(true)
|
||||
})
|
||||
|
||||
it('does not reject WebAuthn when the generic credentials check is unavailable', () => {
|
||||
setCapability(window, 'PublicKeyCredential', class PublicKeyCredential {})
|
||||
setCapability(navigator, 'credentials', undefined)
|
||||
expect(webauthnOK()).toBe(true)
|
||||
})
|
||||
|
||||
it('rejects browsers without the WebAuthn credential type', () => {
|
||||
setCapability(window, 'PublicKeyCredential', undefined)
|
||||
setCapability(navigator, 'credentials', {})
|
||||
expect(webauthnOK()).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,73 @@
|
||||
// Rendering for the admin activity log (GET /api/admin/audit).
|
||||
//
|
||||
// The server stores reason codes, not sentences — `{ ev: 'auth.login.fail', msg: 'unknown-credential' }`
|
||||
// rather than "someone tried a passkey we don't know". Turning those into English
|
||||
// belongs here and not in Admin.jsx: it is the only part of the feature that can be wrong in a way
|
||||
// a person sees, and as a plain module it is testable without mounting the dashboard.
|
||||
//
|
||||
// Like the rest of the admin screen this is English-only — the operator surface deliberately
|
||||
// stays out of the per-language string packs (see the header of views/Admin.jsx). Times still
|
||||
// follow the UI language, the way numbers and dates already do.
|
||||
import { dateLocale } from './i18n-core.js'
|
||||
|
||||
// The first segment of an event name is also the filter chip it belongs to.
|
||||
export const auditCat = ev => String(ev || '').split('.')[0]
|
||||
|
||||
const LABELS = {
|
||||
'auth.login.ok': 'Signed in',
|
||||
'auth.login.fail': 'Sign-in failed',
|
||||
'auth.register.ok': 'Created a profile',
|
||||
'auth.register.fail': 'Profile creation failed',
|
||||
'auth.register.denied': 'Signup refused',
|
||||
'auth.logout': 'Signed out',
|
||||
'auth.logout.all': 'Signed out everywhere',
|
||||
'admin.user.disable': 'Disabled an account',
|
||||
'admin.user.enable': 'Re-enabled an account',
|
||||
'admin.invite.create': 'Created an invite code',
|
||||
'admin.invite.revoke': 'Revoked an invite code',
|
||||
'admin.audit.clear': 'Cleared the activity log',
|
||||
'admin.denied': 'Blocked from the admin dashboard'
|
||||
}
|
||||
// An unknown event is shown raw rather than dropped or rendered as "undefined": a dashboard
|
||||
// that is one version behind the server should still say *something* truthful.
|
||||
export const auditLabel = ev => LABELS[ev] || String(ev || 'Unknown event')
|
||||
|
||||
const REASONS = {
|
||||
'challenge-expired': 'the sign-in took too long and expired',
|
||||
'unknown-credential': 'unknown passkey',
|
||||
'verify-error': 'the passkey could not be verified',
|
||||
'not-verified': 'the passkey was rejected',
|
||||
'user-missing': 'the passkey points at a profile that no longer exists',
|
||||
'account-disabled': 'the account is disabled',
|
||||
'credential-exists': 'that passkey already belongs to a profile',
|
||||
'invite-invalid': 'the invite code was used or revoked in the meantime',
|
||||
'invite-rejected': 'wrong or already-used invite code'
|
||||
}
|
||||
export const auditReason = msg => REASONS[msg] || (msg ? String(msg) : '')
|
||||
|
||||
// → { title, sub }. `sub` is the house "a · b · c" metadata line used by every list row.
|
||||
export function auditLine(e) {
|
||||
if (!e) return { title: '', sub: '' }
|
||||
const parts = []
|
||||
if (e.name) parts.push(e.name)
|
||||
else if (e.uid) parts.push(e.uid)
|
||||
else if (!e.ok) parts.push('unknown caller')
|
||||
if (e.tname) parts.push('→ ' + e.tname)
|
||||
// The reason codes and the invite codes share the msg field; only failures read as a reason.
|
||||
if (e.msg) parts.push(e.ok ? e.msg : auditReason(e.msg))
|
||||
if (e.ip) parts.push(e.ip)
|
||||
return { title: auditLabel(e.ev), sub: parts.join(' · ') }
|
||||
}
|
||||
|
||||
// The activity log is the one place in the app that needs a clock, and fmtDate() renders none —
|
||||
// it is used by every other view and is not worth changing for this.
|
||||
export function fmtWhen(ts, now = Date.now()) {
|
||||
if (!ts) return ''
|
||||
const d = new Date(ts)
|
||||
const time = d.toLocaleTimeString(dateLocale(), { hour: '2-digit', minute: '2-digit' })
|
||||
const n = new Date(now)
|
||||
const sameDay = d.toDateString() === n.toDateString()
|
||||
if (sameDay) return 'today ' + time
|
||||
if (now - ts < 6 * 86400000 && ts <= now) return d.toLocaleDateString(dateLocale(), { weekday: 'short' }) + ' ' + time
|
||||
return d.toLocaleDateString(dateLocale(), { day: 'numeric', month: 'short' }) + ' ' + time
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { auditCat, auditLabel, auditReason, auditLine, fmtWhen } from './audit.js'
|
||||
|
||||
// Every event name and reason code the server can emit (api/server.js, the audit block).
|
||||
// If a new one is added there without a label here, the first test fails rather than the
|
||||
// dashboard quietly printing a dotted identifier at a person.
|
||||
const EVENTS = [
|
||||
'auth.login.ok', 'auth.login.fail', 'auth.register.ok', 'auth.register.fail',
|
||||
'auth.register.denied', 'auth.logout', 'auth.logout.all',
|
||||
'admin.user.disable', 'admin.user.enable', 'admin.invite.create',
|
||||
'admin.invite.revoke', 'admin.audit.clear', 'admin.denied'
|
||||
]
|
||||
const REASONS = [
|
||||
'challenge-expired', 'unknown-credential', 'verify-error', 'not-verified',
|
||||
'user-missing', 'account-disabled', 'credential-exists', 'invite-invalid', 'invite-rejected'
|
||||
]
|
||||
|
||||
describe('auditLabel', () => {
|
||||
it('has a sentence for every event the server emits', () => {
|
||||
for (const ev of EVENTS) {
|
||||
expect(auditLabel(ev), ev).not.toBe(ev)
|
||||
expect(auditLabel(ev)).toMatch(/^[A-Z]/)
|
||||
}
|
||||
})
|
||||
|
||||
it('shows an unknown event raw instead of rendering undefined', () => {
|
||||
// A dashboard one version behind the server must still say something truthful.
|
||||
expect(auditLabel('auth.something.new')).toBe('auth.something.new')
|
||||
expect(auditLabel(undefined)).toBe('Unknown event')
|
||||
expect(auditLabel('')).toBe('Unknown event')
|
||||
})
|
||||
})
|
||||
|
||||
describe('auditCat', () => {
|
||||
it('takes the filter category from the first segment', () => {
|
||||
expect(auditCat('auth.login.ok')).toBe('auth')
|
||||
expect(auditCat('admin.invite.create')).toBe('admin')
|
||||
})
|
||||
it('survives a missing event name', () => {
|
||||
expect(auditCat(undefined)).toBe('')
|
||||
})
|
||||
it('puts every known event in exactly auth or admin', () => {
|
||||
expect([...new Set(EVENTS.map(auditCat))].sort()).toEqual(['admin', 'auth'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('auditReason', () => {
|
||||
it('has plain English for every reason code', () => {
|
||||
for (const m of REASONS) {
|
||||
expect(auditReason(m), m).not.toBe(m)
|
||||
expect(auditReason(m).length).toBeGreaterThan(3)
|
||||
}
|
||||
})
|
||||
it('falls back to the raw code and tolerates none at all', () => {
|
||||
expect(auditReason('brand-new-code')).toBe('brand-new-code')
|
||||
expect(auditReason(undefined)).toBe('')
|
||||
})
|
||||
})
|
||||
|
||||
describe('auditLine', () => {
|
||||
it('names the person who did it', () => {
|
||||
expect(auditLine({ ev: 'auth.login.ok', ok: true, uid: 'u1', name: 'Duarte' }))
|
||||
.toEqual({ title: 'Signed in', sub: 'Duarte' })
|
||||
})
|
||||
|
||||
it('shows both sides of an admin action', () => {
|
||||
const l = auditLine({ ev: 'admin.user.disable', ok: true, uid: 'a', name: 'Duarte', tgt: 'b', tname: 'Ana' })
|
||||
expect(l.title).toBe('Disabled an account')
|
||||
expect(l.sub).toBe('Duarte · → Ana')
|
||||
})
|
||||
|
||||
it('translates the reason on a failure but not the invite code on a success', () => {
|
||||
expect(auditLine({ ev: 'auth.login.fail', ok: false, msg: 'unknown-credential' }).sub)
|
||||
.toBe('unknown caller · unknown passkey')
|
||||
// admin.invite.* put the actual code in msg — that must not be run through auditReason.
|
||||
expect(auditLine({ ev: 'admin.invite.create', ok: true, name: 'Duarte', msg: 'A1B2C3D4' }).sub)
|
||||
.toBe('Duarte · A1B2C3D4')
|
||||
})
|
||||
|
||||
it('says "unknown caller" only when a failure carries no identity', () => {
|
||||
expect(auditLine({ ev: 'auth.login.fail', ok: false }).sub).toBe('unknown caller')
|
||||
// A successful event without a name is not an anonymous attacker, so it stays blank.
|
||||
expect(auditLine({ ev: 'auth.logout', ok: true }).sub).toBe('')
|
||||
})
|
||||
|
||||
it('falls back to the uid when the name was never recorded', () => {
|
||||
expect(auditLine({ ev: 'auth.login.fail', ok: false, uid: 'Xy1', msg: 'user-missing' }).sub)
|
||||
.toBe('Xy1 · the passkey points at a profile that no longer exists')
|
||||
})
|
||||
|
||||
it('appends the network when the operator opted into IPs', () => {
|
||||
expect(auditLine({ ev: 'auth.login.ok', ok: true, name: 'Duarte', ip: '203.0.113.0/24' }).sub)
|
||||
.toBe('Duarte · 203.0.113.0/24')
|
||||
})
|
||||
|
||||
it('renders nothing rather than throwing on a missing record', () => {
|
||||
expect(auditLine(undefined)).toEqual({ title: '', sub: '' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('fmtWhen', () => {
|
||||
const at = (y, m, d, h, min) => new Date(y, m - 1, d, h, min).getTime()
|
||||
const now = at(2026, 8, 23, 15, 0) // Sunday
|
||||
|
||||
it('says "today" for the same calendar day', () => {
|
||||
expect(fmtWhen(at(2026, 8, 23, 9, 5), now)).toMatch(/^today /)
|
||||
expect(fmtWhen(at(2026, 8, 23, 0, 1), now)).toMatch(/^today /)
|
||||
})
|
||||
|
||||
it('uses the weekday inside the last six days', () => {
|
||||
const s = fmtWhen(at(2026, 8, 21, 18, 30), now)
|
||||
expect(s).not.toMatch(/^today/)
|
||||
expect(s).toMatch(/^[A-Za-zÀ-ÿ.]+ \d/)
|
||||
})
|
||||
|
||||
it('falls back to a date once it is older', () => {
|
||||
expect(fmtWhen(at(2026, 8, 12, 14, 32), now)).toMatch(/\d/)
|
||||
expect(fmtWhen(at(2026, 8, 12, 14, 32), now)).not.toMatch(/^today/)
|
||||
})
|
||||
|
||||
it('always carries a time of day — that is the whole point of not reusing fmtDate', () => {
|
||||
for (const ts of [at(2026, 8, 23, 9, 5), at(2026, 8, 21, 18, 30), at(2026, 8, 12, 14, 32)]) {
|
||||
expect(fmtWhen(ts, now)).toMatch(/\d{1,2}[:.]\d{2}/)
|
||||
}
|
||||
})
|
||||
|
||||
it('does not call a future timestamp "3 days ago"', () => {
|
||||
// Clock skew between server and browser is real; a tomorrow must not read as a weekday.
|
||||
expect(fmtWhen(at(2026, 8, 30, 10, 0), now)).not.toMatch(/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)/)
|
||||
})
|
||||
|
||||
it('returns an empty string for a missing timestamp', () => {
|
||||
expect(fmtWhen(0)).toBe('')
|
||||
expect(fmtWhen(undefined)).toBe('')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,62 @@
|
||||
// Android system back (the gesture and the hardware/nav button are the same event).
|
||||
//
|
||||
// Capacitor's BridgeActivity does not handle back at all — without a JS listener the
|
||||
// activity simply finishes, so a back swipe quit the app from anywhere, whatever the
|
||||
// WebView history said. That made the sheet history entries from #63 dead weight in the
|
||||
// packaged app: they only ever worked in a browser tab, where the browser walks history
|
||||
// itself.
|
||||
//
|
||||
// Once a `backButton` listener exists, the plugin stops falling through to finish() —
|
||||
// back can then ONLY leave the app through App.exitApp(), which is why the last step is
|
||||
// an explicit press-again-to-exit rather than a silent no-op.
|
||||
import { MOBILE } from './mobile.js'
|
||||
import { useUI } from '../store/useUI.js'
|
||||
import { t } from './i18n.js'
|
||||
|
||||
// How long a first back press stays armed as "press again to exit" (the toast shows 2.2s).
|
||||
export const EXIT_WINDOW = 2000
|
||||
|
||||
// What a back press means, given what is on screen. Pure, so the table below is testable.
|
||||
export function decideBack({ top, canGoBack, exitArmed }) {
|
||||
if (top) return top.locked ? 'ignore' : 'sheet' // a locked sheet swallows back on purpose
|
||||
if (canGoBack) return 'history' // a page/tab we pushed ourselves
|
||||
return exitArmed ? 'exit' : 'arm-exit'
|
||||
}
|
||||
|
||||
export function makeBackHandler({ getSheets, closeSheet, toast, goBack, exit, now = Date.now }) {
|
||||
let armedAt = -Infinity
|
||||
return (ev = {}) => {
|
||||
const sheets = getSheets()
|
||||
const action = decideBack({
|
||||
top: sheets[sheets.length - 1],
|
||||
canGoBack: !!ev.canGoBack,
|
||||
exitArmed: now() - armedAt < EXIT_WINDOW,
|
||||
})
|
||||
if (action !== 'arm-exit') armedAt = -Infinity
|
||||
if (action === 'sheet') closeSheet(sheets[sheets.length - 1].id)
|
||||
else if (action === 'history') goBack()
|
||||
else if (action === 'arm-exit') { armedAt = now(); toast(t('Press back again to exit')) }
|
||||
else if (action === 'exit') exit()
|
||||
return action
|
||||
}
|
||||
}
|
||||
|
||||
// Registers the listener for the native shell. No-op in web builds, where the browser
|
||||
// (or the PWA shell) walks history on its own and there is no plugin to talk to.
|
||||
export async function initBackButton() {
|
||||
if (!MOBILE) return () => {}
|
||||
try {
|
||||
const { App } = await import('@capacitor/app')
|
||||
const handler = makeBackHandler({
|
||||
getSheets: () => useUI.getState().sheets,
|
||||
closeSheet: id => useUI.getState().closeSheet(id),
|
||||
toast: msg => useUI.getState().toast(msg),
|
||||
goBack: () => window.history.back(),
|
||||
exit: () => App.exitApp(),
|
||||
})
|
||||
const sub = await App.addListener('backButton', handler)
|
||||
return () => sub.remove()
|
||||
} catch (e) {
|
||||
return () => {} // no plugin (older install): leave back to the default behaviour
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { decideBack, makeBackHandler, EXIT_WINDOW } from './back.js'
|
||||
|
||||
// Back on Android has to serve three layers with one event: the sheet stack on top, the
|
||||
// page history under it, and — because a registered listener stops the plugin from ever
|
||||
// finishing the activity itself — a deliberate way out of the app at the bottom.
|
||||
describe('decideBack', () => {
|
||||
it('dismisses the top sheet before touching history', () => {
|
||||
expect(decideBack({ top: { id: 's1' }, canGoBack: true, exitArmed: false })).toBe('sheet')
|
||||
})
|
||||
|
||||
it('lets a locked sheet swallow the press', () => {
|
||||
expect(decideBack({ top: { id: 's1', locked: true }, canGoBack: true, exitArmed: true })).toBe('ignore')
|
||||
})
|
||||
|
||||
it('walks history when nothing is open', () => {
|
||||
expect(decideBack({ top: undefined, canGoBack: true, exitArmed: false })).toBe('history')
|
||||
})
|
||||
|
||||
it('arms the exit at the bottom of the stack, and exits on the second press', () => {
|
||||
expect(decideBack({ top: undefined, canGoBack: false, exitArmed: false })).toBe('arm-exit')
|
||||
expect(decideBack({ top: undefined, canGoBack: false, exitArmed: true })).toBe('exit')
|
||||
})
|
||||
})
|
||||
|
||||
function harness() {
|
||||
const calls = { closed: [], toasts: [], back: 0, exit: 0 }
|
||||
let sheets = []
|
||||
let now = 1000
|
||||
const handler = makeBackHandler({
|
||||
getSheets: () => sheets,
|
||||
closeSheet: id => { calls.closed.push(id); sheets = sheets.filter(s => s.id !== id) },
|
||||
toast: m => calls.toasts.push(m),
|
||||
goBack: () => { calls.back++ },
|
||||
exit: () => { calls.exit++ },
|
||||
now: () => now,
|
||||
})
|
||||
return { calls, handler, setSheets: s => { sheets = s }, tick: ms => { now += ms } }
|
||||
}
|
||||
|
||||
describe('makeBackHandler', () => {
|
||||
it('closes stacked sheets one press at a time', () => {
|
||||
const h = harness()
|
||||
h.setSheets([{ id: 'a' }, { id: 'b' }])
|
||||
expect(h.handler({ canGoBack: true })).toBe('sheet')
|
||||
expect(h.handler({ canGoBack: true })).toBe('sheet')
|
||||
expect(h.calls.closed).toEqual(['b', 'a'])
|
||||
expect(h.calls.back).toBe(0)
|
||||
})
|
||||
|
||||
it('does not close a locked sheet, and does not arm the exit behind it', () => {
|
||||
const h = harness()
|
||||
h.setSheets([{ id: 'a', locked: true }])
|
||||
expect(h.handler({ canGoBack: false })).toBe('ignore')
|
||||
expect(h.calls.closed).toEqual([])
|
||||
expect(h.calls.toasts).toEqual([])
|
||||
expect(h.calls.exit).toBe(0)
|
||||
})
|
||||
|
||||
it('goes back a page while the WebView still has app history', () => {
|
||||
const h = harness()
|
||||
expect(h.handler({ canGoBack: true })).toBe('history')
|
||||
expect(h.calls.back).toBe(1)
|
||||
expect(h.calls.exit).toBe(0)
|
||||
})
|
||||
|
||||
// The whole point of the fix: one press at the root must never be the end of the app.
|
||||
it('warns once, then exits on a second press inside the window', () => {
|
||||
const h = harness()
|
||||
expect(h.handler({ canGoBack: false })).toBe('arm-exit')
|
||||
expect(h.calls.toasts).toHaveLength(1)
|
||||
expect(h.calls.exit).toBe(0)
|
||||
h.tick(EXIT_WINDOW - 1)
|
||||
expect(h.handler({ canGoBack: false })).toBe('exit')
|
||||
expect(h.calls.exit).toBe(1)
|
||||
})
|
||||
|
||||
it('re-arms rather than exiting once the window has passed', () => {
|
||||
const h = harness()
|
||||
h.handler({ canGoBack: false })
|
||||
h.tick(EXIT_WINDOW + 1)
|
||||
expect(h.handler({ canGoBack: false })).toBe('arm-exit')
|
||||
expect(h.calls.exit).toBe(0)
|
||||
expect(h.calls.toasts).toHaveLength(2)
|
||||
})
|
||||
|
||||
// A sheet opened (or a page pushed) after the warning means the user is still using the
|
||||
// app — the next back belongs to that sheet, and the one after must warn again.
|
||||
it('disarms the exit as soon as another press does real work', () => {
|
||||
const h = harness()
|
||||
h.handler({ canGoBack: false })
|
||||
h.setSheets([{ id: 'a' }])
|
||||
expect(h.handler({ canGoBack: true })).toBe('sheet')
|
||||
expect(h.handler({ canGoBack: false })).toBe('arm-exit')
|
||||
expect(h.calls.exit).toBe(0)
|
||||
})
|
||||
|
||||
it('treats a missing event payload as no history', () => {
|
||||
const h = harness()
|
||||
expect(h.handler()).toBe('arm-exit')
|
||||
})
|
||||
})
|
||||
@@ -11,4 +11,4 @@
|
||||
// lands in a self-hosted bundle.
|
||||
export const DEMO = import.meta.env.VITE_DEMO === '1'
|
||||
export const DEMO_SEEDED = 'gym_demo_seeded_v1'
|
||||
export const REPO = 'https://github.com/DuarteSantos8/openGym'
|
||||
export const REPO = 'https://gitlab.com/DuarteSantos8/opengym'
|
||||
@@ -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
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,34 @@
|
||||
import { t } from './i18n.js'
|
||||
import { EXDB } from './exercises-data.js'
|
||||
|
||||
// Every equipment value present in the catalogue, most common first — this becomes the
|
||||
// checklist Settings shows when you build a profile.
|
||||
export const ALL_EQUIPMENT = (() => {
|
||||
const c = {}
|
||||
EXDB.forEach(e => { if (e.eq) c[e.eq] = (c[e.eq] || 0) + 1 })
|
||||
return Object.keys(c).sort((a, b) => c[b] - c[a] || (a < b ? -1 : 1))
|
||||
})()
|
||||
|
||||
// Body weight is never gated by a profile — no gym or home setup can take it away from you,
|
||||
// and every profile should be able to see bodyweight exercises regardless of what's checked.
|
||||
const ALWAYS_AVAILABLE = 'body weight'
|
||||
|
||||
export function activeProfile(S) {
|
||||
if (!S.equipFilterOn) return null
|
||||
const profiles = S.equipProfiles || []
|
||||
return profiles.find(p => p.id === S.activeEquipId) || null
|
||||
}
|
||||
|
||||
// Whether an exercise is usable under the active profile. With filtering off, or no profile
|
||||
// selected, everything is available — this is purely additive, never a trap that hides your
|
||||
// whole library because you haven't set anything up yet.
|
||||
export function exAvailable(S, ex) {
|
||||
const p = activeProfile(S)
|
||||
if (!p) return true
|
||||
if (!ex.eq || ex.eq === ALWAYS_AVAILABLE) return true
|
||||
return (p.equipment || []).includes(ex.eq)
|
||||
}
|
||||
|
||||
export function newProfile(name) {
|
||||
return { id: 'eq' + Date.now().toString(36) + Math.random().toString(36).slice(2, 6), name, equipment: [] }
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import batch from './exercise-muscle-batch-1.json' with { type: 'json' }
|
||||
import { MACHINE_BATCH_2 } from './exercise-muscle-batch-2.js'
|
||||
|
||||
/**
|
||||
* ExRx-informed metadata for the first compound-lift batch. The raw generated catalogue remains
|
||||
* untouched; exercises.js applies this layer to the runtime index.
|
||||
*/
|
||||
export const COMPOUND_LIFT_BATCH_1 = Object.freeze(batch)
|
||||
|
||||
// Keep the phase-2 artifact in its own module for auditing while preserving the phase-1 resolver
|
||||
// interface consumed by exercises.js and downstream muscle helpers.
|
||||
export { MACHINE_BATCH_2 }
|
||||
|
||||
/**
|
||||
* Reserved for owner-approved corrections. This layer is intentionally separate from the
|
||||
* generated batch so a correction can replace a generated body part or muscle list without
|
||||
* editing generated data. Explicit metadata on a user/custom exercise wins as well.
|
||||
*/
|
||||
export const USER_EXERCISE_MUSCLE_OVERRIDES = Object.freeze({})
|
||||
|
||||
export function exerciseMuscleMetadataFor(id) {
|
||||
return {
|
||||
...(COMPOUND_LIFT_BATCH_1[id] || {}),
|
||||
...(MACHINE_BATCH_2[id] || {}),
|
||||
...(USER_EXERCISE_MUSCLE_OVERRIDES[id] || {})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { BODYPARTS, EXDB, EXIDX, registerCustom } from './exercises.js'
|
||||
import { COMPOUND_LIFT_BATCH_1 } from './exercise-muscle-batch-1.js'
|
||||
import { MUSCLES, musclesOf } from './muscles.js'
|
||||
|
||||
const ids = Object.keys(COMPOUND_LIFT_BATCH_1)
|
||||
const catalogueIds = new Set(EXDB.map(ex => ex.id))
|
||||
|
||||
const duplicateFree = values => values.length === new Set(values).size
|
||||
|
||||
describe('compound-lift muscle metadata batch 1', () => {
|
||||
it('contains a bounded first batch of compound-lift catalogue entries', () => {
|
||||
expect(ids.length).toBeGreaterThanOrEqual(60)
|
||||
expect(ids.length).toBeLessThanOrEqual(120)
|
||||
expect(ids.every(id => catalogueIds.has(id))).toBe(true)
|
||||
})
|
||||
|
||||
it('stores canonical primary and secondary arrays for every batch entry', () => {
|
||||
for (const [id, metadata] of Object.entries(COMPOUND_LIFT_BATCH_1)) {
|
||||
expect(metadata.primaries.length, id).toBeGreaterThan(0)
|
||||
expect(duplicateFree(metadata.primaries), id).toBe(true)
|
||||
expect(duplicateFree(metadata.secondaries), id).toBe(true)
|
||||
expect(metadata.primaries.some(muscle => metadata.secondaries.includes(muscle)), id).toBe(false)
|
||||
expect(metadata.primaries.every(muscle => MUSCLES.includes(muscle)), id).toBe(true)
|
||||
expect(metadata.secondaries.every(muscle => MUSCLES.includes(muscle)), id).toBe(true)
|
||||
expect(EXIDX[id]).toMatchObject(metadata)
|
||||
}
|
||||
})
|
||||
|
||||
it('follows the documented ExRx family templates and preserves source-known muscles', () => {
|
||||
expect(COMPOUND_LIFT_BATCH_1['0043']).toEqual({
|
||||
bp: 'upper legs',
|
||||
primaries: ['quadriceps', 'gluteal', 'adductors'],
|
||||
secondaries: ['hamstring', 'calves', 'lower-back', 'abs', 'obliques']
|
||||
})
|
||||
expect(COMPOUND_LIFT_BATCH_1['0032']).toEqual({
|
||||
bp: 'full body',
|
||||
primaries: ['gluteal', 'hamstring', 'lower-back'],
|
||||
secondaries: ['quadriceps', 'adductors', 'calves', 'abs', 'obliques']
|
||||
})
|
||||
expect(COMPOUND_LIFT_BATCH_1['0025']).toEqual({
|
||||
bp: 'chest', primaries: ['chest'], secondaries: ['triceps', 'deltoids', 'biceps']
|
||||
})
|
||||
expect(COMPOUND_LIFT_BATCH_1['0091']).toEqual({
|
||||
bp: 'shoulders', primaries: ['deltoids'],
|
||||
secondaries: ['chest', 'triceps', 'trapezius', 'serratus']
|
||||
})
|
||||
expect(COMPOUND_LIFT_BATCH_1['0027']).toEqual({
|
||||
bp: 'back', primaries: ['upper-back'],
|
||||
secondaries: ['biceps', 'deltoids', 'forearm']
|
||||
})
|
||||
expect(COMPOUND_LIFT_BATCH_1['0652']).toEqual({
|
||||
bp: 'back', primaries: ['upper-back'], secondaries: ['biceps', 'deltoids', 'forearm']
|
||||
})
|
||||
expect(musclesOf(EXDB.find(exercise => exercise.id === '0587'))).toMatchObject({ chest: 0.4 })
|
||||
expect(musclesOf(EXIDX['0587'])).toMatchObject({ chest: 0.4 })
|
||||
})
|
||||
|
||||
it('keeps torso bracing secondary and does not label the twisting press full body', () => {
|
||||
expect(COMPOUND_LIFT_BATCH_1['0414']).toEqual({
|
||||
bp: 'shoulders', primaries: ['deltoids'], secondaries: ['triceps', 'trapezius', 'abs']
|
||||
})
|
||||
expect(COMPOUND_LIFT_BATCH_1['1012']).toEqual({
|
||||
bp: 'shoulders', primaries: ['deltoids'],
|
||||
secondaries: ['triceps', 'trapezius', 'abs', 'obliques']
|
||||
})
|
||||
expect(COMPOUND_LIFT_BATCH_1['1012'].primaries).not.toContain('abs')
|
||||
expect(COMPOUND_LIFT_BATCH_1['1012'].secondaries).toContain('obliques')
|
||||
})
|
||||
|
||||
it('marks the cross-region lifts as Full body while keeping classic areas available', () => {
|
||||
expect(EXIDX['0069']).toMatchObject({ bp: 'full body', primaries: ['quadriceps', 'gluteal', 'adductors'] })
|
||||
expect(EXIDX['0032'].bp).toBe('full body')
|
||||
expect(BODYPARTS).toContain('full body')
|
||||
expect(EXIDX['0025'].bp).toBe('chest')
|
||||
expect(EXIDX['0652'].bp).toBe('back')
|
||||
})
|
||||
|
||||
it('lets an explicit user exercise override the batch and restores the catalogue afterward', () => {
|
||||
registerCustom([{ id: '0025', n: 'Owner bench correction', bp: 'chest', primaries: ['triceps'], secondaries: [] }])
|
||||
expect(EXIDX['0025']).toMatchObject({ primaries: ['triceps'], secondaries: [] })
|
||||
registerCustom([])
|
||||
expect(EXIDX['0025']).toMatchObject(COMPOUND_LIFT_BATCH_1['0025'])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,8 @@
|
||||
import batch from './exercise-muscle-batch-2.json' with { type: 'json' }
|
||||
|
||||
/**
|
||||
* ExRx-informed metadata for machine, cable, sled, and Smith-machine catalogue entries.
|
||||
* `exercises.js` applies this as a runtime overlay so the raw generated catalogue remains
|
||||
* compatible with imports and historical records.
|
||||
*/
|
||||
export const MACHINE_BATCH_2 = Object.freeze(batch)
|
||||
@@ -0,0 +1,135 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { BODYPARTS, EXDB, EXIDX, registerCustom } from './exercises.js'
|
||||
import { MACHINE_BATCH_2 } from './exercise-muscle-batch-2.js'
|
||||
import { MUSCLES, musclesOf } from './muscles.js'
|
||||
|
||||
const ids = Object.keys(MACHINE_BATCH_2)
|
||||
const catalogue = new Map(EXDB.map(exercise => [exercise.id, exercise]))
|
||||
const duplicateFree = values => values.length === new Set(values).size
|
||||
|
||||
const expectMapping = (id, expected) => {
|
||||
expect(MACHINE_BATCH_2[id], id).toEqual(expected)
|
||||
expect(EXIDX[id], id).toMatchObject(expected)
|
||||
}
|
||||
|
||||
describe('machine muscle metadata batch 2', () => {
|
||||
it('contains a bounded batch of machine and cable catalogue entries', () => {
|
||||
expect(ids.length).toBeGreaterThanOrEqual(60)
|
||||
expect(ids.length).toBeLessThanOrEqual(120)
|
||||
expect(ids.length).toBe(119)
|
||||
expect(ids.every(id => catalogue.has(id))).toBe(true)
|
||||
expect(ids.every(id => /machine|cable/.test(catalogue.get(id).eq))).toBe(true)
|
||||
})
|
||||
|
||||
it('uses only existing body-part keys and canonical drawable muscle slugs', () => {
|
||||
for (const [id, metadata] of Object.entries(MACHINE_BATCH_2)) {
|
||||
expect(BODYPARTS, id).toContain(metadata.bp)
|
||||
expect(metadata.primaries.length, id).toBeGreaterThan(0)
|
||||
expect(duplicateFree(metadata.primaries), id).toBe(true)
|
||||
expect(duplicateFree(metadata.secondaries), id).toBe(true)
|
||||
expect(metadata.primaries.some(muscle => metadata.secondaries.includes(muscle)), id).toBe(false)
|
||||
expect(metadata.primaries.every(muscle => MUSCLES.includes(muscle)), id).toBe(true)
|
||||
expect(metadata.secondaries.every(muscle => MUSCLES.includes(muscle)), id).toBe(true)
|
||||
expect(EXIDX[id]).toMatchObject(metadata)
|
||||
}
|
||||
})
|
||||
|
||||
it('maps the pec-deck family from the lever seated-fly template', () => {
|
||||
expectMapping('0596', {
|
||||
bp: 'chest', primaries: ['chest'], secondaries: ['deltoids', 'biceps', 'serratus']
|
||||
})
|
||||
})
|
||||
|
||||
it('maps chest-press machines to chest with pressing assistants', () => {
|
||||
expectMapping('0577', {
|
||||
bp: 'chest', primaries: ['chest'], secondaries: ['deltoids', 'triceps', 'biceps']
|
||||
})
|
||||
})
|
||||
|
||||
it('maps cable crossovers to drawing-ready upper-back support', () => {
|
||||
expectMapping('0155', {
|
||||
bp: 'chest', primaries: ['chest'], secondaries: ['upper-back', 'trapezius']
|
||||
})
|
||||
})
|
||||
|
||||
it('maps machine/cable lat pulldowns to upper back with arm-and-shoulder synergy', () => {
|
||||
expectMapping('0579', {
|
||||
bp: 'back',
|
||||
primaries: ['upper-back'],
|
||||
secondaries: ['biceps', 'deltoids', 'forearm', 'trapezius', 'triceps']
|
||||
})
|
||||
})
|
||||
|
||||
it('maps seated rows to upper back with the phase-1 pull template', () => {
|
||||
expectMapping('1350', {
|
||||
bp: 'back',
|
||||
primaries: ['upper-back'],
|
||||
secondaries: ['biceps', 'deltoids', 'forearm', 'trapezius', 'chest', 'triceps']
|
||||
})
|
||||
})
|
||||
|
||||
it('maps assisted triceps dip variants to full synergist support', () => {
|
||||
expectMapping('0019', {
|
||||
bp: 'upper arms',
|
||||
primaries: ['triceps'],
|
||||
secondaries: ['deltoids', 'chest', 'upper-back', 'trapezius', 'biceps']
|
||||
})
|
||||
expectMapping('1451', {
|
||||
bp: 'upper arms',
|
||||
primaries: ['triceps'],
|
||||
secondaries: ['deltoids', 'chest', 'upper-back', 'trapezius', 'biceps']
|
||||
})
|
||||
})
|
||||
|
||||
it('maps lever triceps extension without ExRx synergist secondaries', () => {
|
||||
expectMapping('0607', {
|
||||
bp: 'upper arms', primaries: ['triceps'], secondaries: []
|
||||
})
|
||||
})
|
||||
|
||||
it('maps sled leg presses to the multi-primary lower-body template', () => {
|
||||
expectMapping('0739', {
|
||||
bp: 'upper legs', primaries: ['quadriceps', 'gluteal', 'adductors'], secondaries: ['hamstring', 'calves']
|
||||
})
|
||||
})
|
||||
|
||||
it('maps leg extensions as quadriceps isolation', () => {
|
||||
expectMapping('0585', {
|
||||
bp: 'upper legs', primaries: ['quadriceps'], secondaries: []
|
||||
})
|
||||
})
|
||||
|
||||
it('maps seated leg curls to hamstrings with calf assistance', () => {
|
||||
expectMapping('0599', {
|
||||
bp: 'upper legs', primaries: ['hamstring'], secondaries: ['calves', 'adductors']
|
||||
})
|
||||
})
|
||||
|
||||
it('maps machine shoulder presses to deltoids with direct press support', () => {
|
||||
expectMapping('0603', {
|
||||
bp: 'shoulders', primaries: ['deltoids'],
|
||||
secondaries: ['chest', 'triceps', 'trapezius', 'serratus', 'biceps']
|
||||
})
|
||||
})
|
||||
|
||||
it('preserves raw dataset metadata while enriching only the runtime catalogue', () => {
|
||||
const raw = catalogue.get('0577')
|
||||
expect(raw).toMatchObject({ id: '0577', n: 'lever chest press', tg: 'pectorals', mg: 'triceps' })
|
||||
expect(raw).not.toHaveProperty('primaries')
|
||||
expect(raw).not.toHaveProperty('secondaries')
|
||||
expect(musclesOf(raw)).toEqual({ chest: 1, deltoids: 0.4, triceps: 0.4 })
|
||||
expect(musclesOf(EXIDX['0577'])).toEqual({ chest: 1, deltoids: 0.4, triceps: 0.4, biceps: 0.4 })
|
||||
})
|
||||
|
||||
it('gives an explicit custom collision precedence and restores the machine overlay', () => {
|
||||
registerCustom([{
|
||||
id: '0577', n: 'Owner machine press correction', bp: 'chest',
|
||||
primaries: ['triceps'], secondaries: []
|
||||
}])
|
||||
expect(EXIDX['0577']).toMatchObject({ primaries: ['triceps'], secondaries: [] })
|
||||
expect(musclesOf(EXIDX['0577'])).toEqual({ triceps: 1 })
|
||||
registerCustom([])
|
||||
expect(EXIDX['0577']).toMatchObject(MACHINE_BATCH_2['0577'])
|
||||
expect(musclesOf(EXIDX['0577'])).toEqual({ chest: 1, deltoids: 0.4, triceps: 0.4, biceps: 0.4 })
|
||||
})
|
||||
})
|
||||
@@ -1,10 +1,51 @@
|
||||
import { EXDB } from './exercises-data.js'
|
||||
import { t } from './i18n.js'
|
||||
import { USER_EXERCISE_MUSCLE_OVERRIDES, exerciseMuscleMetadataFor } from './exercise-muscle-batch-1.js'
|
||||
import { t, getVersion, exerciseNameSearchText } from './i18n-core.js'
|
||||
|
||||
export { EXDB }
|
||||
|
||||
// The generated dataset remains the compatibility/raw export. The runtime catalogue applies
|
||||
// owner-approved muscle metadata as a narrow overlay, so imports and historical tests that rely
|
||||
// on the upstream shape keep working while EXIDX and pickers see the corrected model.
|
||||
const catalogueExercise = ex => {
|
||||
const metadata = exerciseMuscleMetadataFor(ex?.id)
|
||||
if (!Object.keys(metadata).length) return ex
|
||||
const out = { ...ex, ...metadata }
|
||||
const user = USER_EXERCISE_MUSCLE_OVERRIDES[ex?.id] || {}
|
||||
// A future dataset row may carry explicit arrays of its own; preserve those over generated
|
||||
// defaults unless the owner has deliberately supplied a correction for the same field.
|
||||
for (const key of ['primaries', 'secondaries']) {
|
||||
if (Object.prototype.hasOwnProperty.call(ex, key) && !Object.prototype.hasOwnProperty.call(user, key)) out[key] = ex[key]
|
||||
}
|
||||
if (Array.isArray(out.primaries)) out.primaries = [...out.primaries]
|
||||
if (Array.isArray(out.secondaries)) out.secondaries = [...out.secondaries]
|
||||
return out
|
||||
}
|
||||
|
||||
export const CATALOGUE = EXDB.map(catalogueExercise)
|
||||
|
||||
// The generated dataset already supplies secondary muscles for most exercises. Keep the
|
||||
// handful of conservative catalogue additions that are useful to the muscle map here so a
|
||||
// dataset refresh does not erase them. Values follow the dataset's existing alias vocabulary.
|
||||
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()
|
||||
CATALOGUE.forEach(e => { EXIDX[e.id] = e })
|
||||
export const BODYPARTS = [...new Set(CATALOGUE.map(e => e.bp))].sort()
|
||||
|
||||
// Equipment options present in a given list of exercises, most common first (issue #6).
|
||||
// Deriving them from the *already filtered* list keeps the chip row short and means
|
||||
@@ -19,27 +60,138 @@ export function equipmentOf(list) {
|
||||
// merged into the id index here so every EXIDX[id] lookup keeps working unchanged.
|
||||
let customIds = []
|
||||
export function registerCustom(list) {
|
||||
customIds.forEach(id => delete EXIDX[id])
|
||||
customIds.forEach(id => {
|
||||
delete EXIDX[id]
|
||||
const builtIn = CATALOGUE.find(ex => ex.id === id)
|
||||
if (builtIn) EXIDX[id] = builtIn
|
||||
})
|
||||
customIds = (list || []).map(e => e.id)
|
||||
;(list || []).forEach(e => { EXIDX[e.id] = e })
|
||||
}
|
||||
// Full searchable catalogue — customs first so your own exercises are easy to find.
|
||||
export const allExercises = st => [...(st.customEx || []), ...EXDB]
|
||||
export const allExercises = st => [...(st.customEx || []), ...CATALOGUE]
|
||||
|
||||
function searchableText(value) {
|
||||
if (Array.isArray(value)) return value.map(searchableText).join(' ')
|
||||
if (value == null) return ''
|
||||
try { return String(value) } catch { return '' }
|
||||
}
|
||||
|
||||
/** Case-insensitive search over built-in and legacy custom exercise metadata. */
|
||||
function isSubsequence(needle, hay) {
|
||||
let i = 0
|
||||
for (const ch of hay) {
|
||||
if (ch === needle[i]) i++
|
||||
if (i === needle.length) return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Fuzzy match score for one exercise against a query. Best hits: exact field match, then
|
||||
// field prefix, then word-boundary starts, then substrings (closer to the start scores
|
||||
// better), and finally typo-tolerant ordered subsequences. Fields are weighted - the name
|
||||
// dominates, target/equipment matter, muscles and description are supporting evidence.
|
||||
// 0 means no match, so matchesExerciseSearch stays a boolean filter while the picker can
|
||||
// rank results by score.
|
||||
export function searchScore(exercise, query) {
|
||||
const needle = searchableText(query).toLowerCase().trim()
|
||||
if (!needle) return 1
|
||||
const source = exercise && typeof exercise === 'object' ? exercise : {}
|
||||
const fields = [['n', 100], ['tg', 40], ['eq', 40], ['sm', 30], ['muscleGroups', 30], ['primaries', 30], ['secondaries', 30], ['desc', 10], ['cues', 10]]
|
||||
// Token-level matching: every query word must match somewhere (any order), so
|
||||
// "press bench" finds "Bench Press". The score sums each token's best hit.
|
||||
const tokens = needle.split(/[^a-z0-9]+/).filter(Boolean)
|
||||
if (!tokens.length) return 0
|
||||
let total = 0
|
||||
for (const token of tokens) {
|
||||
let best = 0
|
||||
for (const [field, weight] of fields) {
|
||||
const hay = searchableText(source[field]).toLowerCase()
|
||||
if (!hay) continue
|
||||
if (hay === token) best = Math.max(best, weight * 4)
|
||||
else if (hay.startsWith(token)) best = Math.max(best, weight * 3)
|
||||
const idx = hay.indexOf(token)
|
||||
if (idx > 0) best = Math.max(best, weight * 2 - Math.min(idx, 20) * 0.5)
|
||||
if (hay.split(/[^a-z0-9]+/).some(w => w.startsWith(token))) best = Math.max(best, weight * 2.5)
|
||||
if (isSubsequence(token, hay)) best = Math.max(best, weight + Math.max(0, 10 - (hay.length - token.length)))
|
||||
}
|
||||
if (!best) return 0 // every token must match
|
||||
total += best
|
||||
}
|
||||
return total
|
||||
}
|
||||
|
||||
export function matchesExerciseSearch(exercise, query) {
|
||||
return searchScore(exercise, query) > 0
|
||||
}
|
||||
|
||||
// Media normally sits next to the app (img/ and gif/, mounted into the web container).
|
||||
// A build can point them somewhere else — the demo build pulls them off a CDN instead of
|
||||
// shipping ~140 MB of images into the deployment.
|
||||
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.
|
||||
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
|
||||
// down on the first `ex.n`.
|
||||
export const exOr = id => EXIDX[id] ||
|
||||
{ id, n: t('Unknown exercise'), bp: '', tg: '', eq: '', sm: [], st: [], missing: true }
|
||||
|
||||
// Normalizes text by lowercasing and stripping diacritics/accents (e.g. "elevação" -> "elevacao")
|
||||
export const normalizeStr = s => (s || '')
|
||||
.normalize('NFD')
|
||||
.replace(/[\u0300-\u036f]/g, '')
|
||||
.toLowerCase()
|
||||
|
||||
// Multi-token, accent-insensitive and multilingual exercise search.
|
||||
// Matches when all whitespace-separated words in the query appear anywhere in the exercise's
|
||||
// name, equipment, target muscle, body part (both in English and translated to active language),
|
||||
// secondary muscles or description.
|
||||
//
|
||||
// The haystack is built once per exercise and cached: NFD-normalising ~1300 catalogue entries
|
||||
// on every keystroke costs ~8ms on a desktop and several times that on a phone. The cache key
|
||||
// is the i18n version (bumped by every setLang), so switching language rebuilds the translated
|
||||
// terms. Custom exercises are re-cached automatically — the store clones state on update, so an
|
||||
// edited exercise arrives as a new object the WeakMap has never seen.
|
||||
const corpusCache = new WeakMap()
|
||||
|
||||
function corpusOf(e) {
|
||||
const v = getVersion()
|
||||
const hit = corpusCache.get(e)
|
||||
if (hit && hit.v === v) return hit.s
|
||||
const sm = Array.isArray(e?.sm) ? e.sm : []
|
||||
const s = normalizeStr([
|
||||
exerciseNameSearchText(e),
|
||||
e?.tg || '', t(e?.tg || ''),
|
||||
e?.eq || '', t(e?.eq || ''),
|
||||
e?.bp || '', t(e?.bp || ''),
|
||||
...sm, ...sm.map(m => t(m)),
|
||||
e?.desc || ''
|
||||
].join(' '))
|
||||
corpusCache.set(e, { v, s })
|
||||
return s
|
||||
}
|
||||
|
||||
export function matchExercise(e, query) {
|
||||
if (!query) return true
|
||||
const tokens = normalizeStr(query).split(/\s+/).filter(Boolean)
|
||||
if (!tokens.length) return true
|
||||
if (!e || typeof e !== 'object') return false
|
||||
const corpus = corpusOf(e)
|
||||
return tokens.every(tok => corpus.includes(tok))
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { matchExercise, normalizeStr } from './exercises.js'
|
||||
import { _setLangState } from './i18n-core.js'
|
||||
|
||||
describe('normalizeStr', () => {
|
||||
it('handles null, undefined and empty strings', () => {
|
||||
expect(normalizeStr(null)).toBe('')
|
||||
expect(normalizeStr(undefined)).toBe('')
|
||||
expect(normalizeStr('')).toBe('')
|
||||
})
|
||||
|
||||
it('lowercases text and removes diacritics / accents', () => {
|
||||
expect(normalizeStr('Elevação Lateral')).toBe('elevacao lateral')
|
||||
expect(normalizeStr('SUPINO INCLINADO COM HALTERES')).toBe('supino inclinado com halteres')
|
||||
expect(normalizeStr('Tríceps & Panturrilhas')).toBe('triceps & panturrilhas')
|
||||
expect(normalizeStr('Quadríceps / Glúteos')).toBe('quadriceps / gluteos')
|
||||
})
|
||||
})
|
||||
|
||||
describe('matchExercise', () => {
|
||||
const benchPress = {
|
||||
id: '0025',
|
||||
n: 'barbell bench press',
|
||||
bp: 'chest',
|
||||
tg: 'pectorals',
|
||||
eq: 'barbell',
|
||||
sm: ['triceps', 'deltoids'],
|
||||
desc: 'Classic chest exercise using a barbell on a flat bench.'
|
||||
}
|
||||
|
||||
const lateralRaise = {
|
||||
id: '0283',
|
||||
n: 'dumbbell lateral raise',
|
||||
bp: 'shoulders',
|
||||
tg: 'delts',
|
||||
eq: 'dumbbell',
|
||||
sm: ['traps'],
|
||||
desc: 'Shoulder isolation movement.'
|
||||
}
|
||||
|
||||
it('returns true for empty or whitespace-only query', () => {
|
||||
expect(matchExercise(benchPress, '')).toBe(true)
|
||||
expect(matchExercise(benchPress, ' ')).toBe(true)
|
||||
expect(matchExercise(benchPress, null)).toBe(true)
|
||||
})
|
||||
|
||||
it('matches exact and partial words in exercise name regardless of case', () => {
|
||||
expect(matchExercise(benchPress, 'bench')).toBe(true)
|
||||
expect(matchExercise(benchPress, 'BENCH')).toBe(true)
|
||||
expect(matchExercise(benchPress, 'barbell')).toBe(true)
|
||||
expect(matchExercise(benchPress, 'press')).toBe(true)
|
||||
expect(matchExercise(benchPress, 'squat')).toBe(false)
|
||||
})
|
||||
|
||||
it('matches multiple tokens in ANY order (not just sequential)', () => {
|
||||
// "bench barbell" is reversed order compared to "barbell bench press"
|
||||
expect(matchExercise(benchPress, 'bench barbell')).toBe(true)
|
||||
expect(matchExercise(benchPress, 'press bench barbell')).toBe(true)
|
||||
expect(matchExercise(benchPress, 'barbell press chest')).toBe(true)
|
||||
expect(matchExercise(benchPress, 'bench squat')).toBe(false)
|
||||
})
|
||||
|
||||
it('matches target muscle, equipment, secondary muscles and description', () => {
|
||||
expect(matchExercise(benchPress, 'pectorals')).toBe(true)
|
||||
expect(matchExercise(benchPress, 'triceps barbell')).toBe(true)
|
||||
expect(matchExercise(benchPress, 'flat bench')).toBe(true)
|
||||
expect(matchExercise(lateralRaise, 'dumbbell shoulder')).toBe(true)
|
||||
})
|
||||
|
||||
it('matches accent-insensitively', () => {
|
||||
const customEx = {
|
||||
id: 'custom-1',
|
||||
n: 'Elevação de Panturrilha',
|
||||
bp: 'lower legs',
|
||||
tg: 'calves',
|
||||
eq: 'body weight',
|
||||
desc: 'Exercício para panturrilhas em pé.'
|
||||
}
|
||||
|
||||
expect(matchExercise(customEx, 'elevacao')).toBe(true)
|
||||
expect(matchExercise(customEx, 'elevação')).toBe(true)
|
||||
expect(matchExercise(customEx, 'panturrilha elevacao')).toBe(true)
|
||||
expect(matchExercise(customEx, 'ELEVACAO PE')).toBe(true)
|
||||
})
|
||||
|
||||
it('matches translated UI terms when a language is active', () => {
|
||||
_setLangState('pt', {
|
||||
chest: 'peito',
|
||||
barbell: 'barra',
|
||||
dumbbell: 'halteres',
|
||||
shoulders: 'ombros'
|
||||
}, null)
|
||||
|
||||
// "peito" is the translated bp, "barra" is the translated eq
|
||||
expect(matchExercise(benchPress, 'peito')).toBe(true)
|
||||
expect(matchExercise(benchPress, 'barra')).toBe(true)
|
||||
expect(matchExercise(benchPress, 'peito barra bench')).toBe(true)
|
||||
expect(matchExercise(lateralRaise, 'halteres ombros')).toBe(true)
|
||||
})
|
||||
|
||||
// The pt-BR exercise-name pack (!16) renames the catalogue in the UI. Searching has to reach
|
||||
// that name as well as the canonical English one, or the library goes dark for pt-BR profiles
|
||||
// the moment they type what they see on screen.
|
||||
it('matches the localized exercise name as well as the English one', () => {
|
||||
_setLangState('pt-BR', {}, null, { '0025': 'supino reto com barra' })
|
||||
|
||||
expect(matchExercise(benchPress, 'supino')).toBe(true)
|
||||
expect(matchExercise(benchPress, 'supino barra')).toBe(true)
|
||||
expect(matchExercise(benchPress, 'bench press')).toBe(true) // English still reaches it
|
||||
expect(matchExercise(lateralRaise, 'supino')).toBe(false) // untranslated entry unaffected
|
||||
})
|
||||
|
||||
it('rebuilds the cached haystack when the language changes', () => {
|
||||
_setLangState('pt-BR', {}, null, { '0025': 'supino reto com barra' })
|
||||
expect(matchExercise(benchPress, 'supino')).toBe(true)
|
||||
|
||||
_setLangState('en', null, null, null)
|
||||
expect(matchExercise(benchPress, 'supino')).toBe(false)
|
||||
expect(matchExercise(benchPress, 'bench')).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,40 @@
|
||||
// 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 }
|
||||
}
|
||||
// What you typed about this exercise today, and whether you asked to see it again next
|
||||
// time. Written only when there is something to keep, so an untouched entry is byte-for-byte
|
||||
// the shape it always was.
|
||||
const note = (entry.note || '').trim()
|
||||
if (note) {
|
||||
completed.note = note
|
||||
if (entry.notePin) completed.notePin = true
|
||||
}
|
||||
return completed
|
||||
}).filter(entry => entry.sets.some(set => set.done))
|
||||
|
||||
const sessionNote = (active?.note || '').trim()
|
||||
|
||||
return {
|
||||
id: active.id,
|
||||
d: active.d,
|
||||
start: active.start,
|
||||
end,
|
||||
routineId: active.routineId,
|
||||
name: active.name,
|
||||
bw: active.bw,
|
||||
entries,
|
||||
prs,
|
||||
...(sessionNote ? { note: sessionNote } : {}),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
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 },
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
// Notes written during a session have to survive it, or "write a note during your workout"
|
||||
// means "write a note and lose it when you tap Finish".
|
||||
describe('session notes', () => {
|
||||
const active = (entry) => ({
|
||||
id: 'w1', d: '2026-08-25', start: 1, routineId: 'r1', name: 'Push', bw: null,
|
||||
entries: [{ id: '0025', sets: [{ w: 100, r: 5, done: true }], ...entry }],
|
||||
})
|
||||
|
||||
it('keeps a per-exercise note and its pin', () => {
|
||||
const w = buildCompletedWorkout(active({ note: ' narrower grip next time ', notePin: true }))
|
||||
expect(w.entries[0].note).toBe('narrower grip next time')
|
||||
expect(w.entries[0].notePin).toBe(true)
|
||||
})
|
||||
|
||||
it('keeps an unpinned note without inventing a pin', () => {
|
||||
const w = buildCompletedWorkout(active({ note: 'shoulder twinged' }))
|
||||
expect(w.entries[0].note).toBe('shoulder twinged')
|
||||
expect('notePin' in w.entries[0]).toBe(false)
|
||||
})
|
||||
|
||||
it('writes no note fields at all when nothing was typed', () => {
|
||||
const w = buildCompletedWorkout(active({ note: ' ', notePin: true }))
|
||||
expect('note' in w.entries[0]).toBe(false)
|
||||
expect('notePin' in w.entries[0]).toBe(false)
|
||||
})
|
||||
|
||||
it('keeps a whole-session note on the workout', () => {
|
||||
const a = active({})
|
||||
expect(buildCompletedWorkout({ ...a, note: 'slept badly' }).note).toBe('slept badly')
|
||||
expect('note' in buildCompletedWorkout(a)).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -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')
|
||||
@@ -12,9 +12,11 @@ export const DAYS = ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa']
|
||||
export const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
|
||||
export const MONTHS_LONG = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
|
||||
|
||||
export function fmtDate(iso, long) {
|
||||
export function fmtDate(iso, long, withYear = false) {
|
||||
const d = new Date(iso + 'T12:00:00')
|
||||
return d.toLocaleDateString(dateLocale(), long ? { weekday: 'short', day: 'numeric', month: 'short' } : { day: 'numeric', month: 'short' })
|
||||
const options = long ? { weekday: 'short', day: 'numeric', month: 'short' } : { day: 'numeric', month: 'short' }
|
||||
if (withYear) options.year = 'numeric'
|
||||
return d.toLocaleDateString(dateLocale(), options)
|
||||
}
|
||||
export function fmtDur(ms) {
|
||||
const m = Math.floor(ms / 60000)
|
||||
@@ -44,4 +46,4 @@ export function weekKey(d) {
|
||||
export const localTZ = () => { try { return Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC' } catch { return 'UTC' } }
|
||||
|
||||
export const uid = () => Date.now().toString(36) + Math.random().toString(36).slice(2, 7)
|
||||
export const ACCENTS = { lime: '#30d158', sky: '#0a84ff', orange: '#ff9f0a', violet: '#bf5af2', pink: '#ff375f', red: '#ff453a', teal: '#40c8e0', gold: '#ffd60a' }
|
||||
export const ACCENTS = { lime: '#30d158', sky: '#0a84ff', orange: '#ff9f0a', violet: '#bf5af2', pink: '#ff375f', red: '#ff453a', teal: '#40c8e0', gold: '#ffd60a' }
|
||||
@@ -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, extraVolumeOf, nextDropWeight, splitBurstReps } from './workout-model.js'
|
||||
const objectOf = value => value && typeof value === 'object' && !Array.isArray(value) ? value : {}
|
||||
// Completed-state-independent work rows whose authoritative mode matches the requested mode.
|
||||
const workRowsForMode = (entry = {}, mode = 'reps') => {
|
||||
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,36 +32,117 @@ 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))
|
||||
return Math.floor(n / 60) + ':' + String(n % 60).padStart(2, '0')
|
||||
}
|
||||
|
||||
// How hard a set felt, if the profile logs it at all. Two scales for the same thing, kept in
|
||||
// their own fields: RIR counts the reps still in the tank, RPE reads the same effort off a
|
||||
// 10-point scale from the top (RPE 8 ≈ RIR 2). A set logged on one scale is never silently
|
||||
// rewritten as the other — switching the setting changes what new sets ask for, nothing else.
|
||||
// `min`..`max` is the range the stepper walks. RIR bottoms out at 0 (a set taken to failure);
|
||||
// RPE bottoms out at 6, since the scale is only meaningful for working sets and anything
|
||||
// lighter is a warm-up nobody rates.
|
||||
export const EFFORT = {
|
||||
rir: { f: 'rir', hd: 'RIR', step: 0.5, min: 0, max: 10 },
|
||||
rpe: { f: 'rpe', hd: 'RPE', step: 0.5, min: 6, max: 10 }
|
||||
}
|
||||
// One tap of an effort stepper. Empty is not 0 — an unlogged effort must not become "went to
|
||||
// failure" from one stray tap — so − on an empty cell leaves it empty, and + starts at the
|
||||
// bottom of the scale and walks up from there in even steps. Stepping back off the bottom
|
||||
// clears the cell again, so a mistap is undoable. null means "nothing logged"; the caller
|
||||
// stores that by dropping the key rather than writing a null.
|
||||
export function stepEffort(kind, cur, dir) {
|
||||
const e = EFFORT[kind]
|
||||
if (!e) return cur ?? null
|
||||
if (cur == null) return dir < 0 ? null : e.min
|
||||
const n = Math.round((cur + dir * e.step) * 100) / 100
|
||||
if (dir < 0 && n < e.min) return null
|
||||
// only the ceiling is enforced on the way up: a value typed below the floor (nothing stops
|
||||
// someone entering RPE 3) still steps in even increments instead of snapping to the floor.
|
||||
return dir > 0 ? Math.min(e.max, n) : Math.max(e.min, n)
|
||||
}
|
||||
// A typed effort is capped but not floored — clamping up while someone types "10" would turn
|
||||
// the first keystroke into the floor and fight the input.
|
||||
export const capEffort = (kind, v) =>
|
||||
(v == null || !EFFORT[kind] ? v : Math.min(EFFORT[kind].max, v))
|
||||
// Which scale a profile logs. `showRir` is the boolean this replaced and is only consulted
|
||||
// when the profile has no answer of its own — an explicit 'none' has to win over it, or a
|
||||
// backup or another device that still carries the old flag would switch the column back on.
|
||||
export const effortOf = S => {
|
||||
const e = S && S.effort
|
||||
return e === 'none' || EFFORT[e] ? e : (S && S.showRir ? 'rir' : 'none')
|
||||
}
|
||||
// The "(RIR 2)" / "(RPE 8)" tail on a set summary, empty when nothing was logged.
|
||||
const effortTail = s => {
|
||||
const k = s.rir != null ? 'rir' : s.rpe != null ? 'rpe' : null
|
||||
return k ? ` (${EFFORT[k].hd} ${fmtNum(s[k])})` : ''
|
||||
}
|
||||
|
||||
// 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}`
|
||||
// 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).
|
||||
@@ -56,23 +152,124 @@ 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)
|
||||
if (!en) continue
|
||||
// Work sets only. Every caller asks the same question — "what did you actually lift last
|
||||
// time" — to seed the next session's rows, to size a freestyle config, and to print "Last
|
||||
// time" on the card. A warm-up answers none of them: seeding position 0 from a 50% ramp row
|
||||
// walks the working weight DOWN a little every session, and counting the ramp rows makes a
|
||||
// 3x5 come back as a 5-set exercise. Warm-ups are already excluded from volume, records and
|
||||
// progression; this is the same rule one level up.
|
||||
const done = en.sets.filter(s => s.done && !isWarmupRow(s))
|
||||
// `target` is what the session prescribed; finished workouts carry it so labels and the
|
||||
// progression engine can read a session back the way it was logged. Older workouts have
|
||||
// none — modeOf() falls back to the body part for them, which is what they were.
|
||||
if (en && en.sets.some(s => s.done)) return { d: S.workouts[i].d, sets: en.sets.filter(s => s.done), target: en.target || null }
|
||||
if (done.length) return { d: S.workouts[i].d, sets: done, target: en.target || null }
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** How long any single note may get. Long enough for a paragraph, short enough to stay a note. */
|
||||
export const NOTE_MAX = 500
|
||||
|
||||
/**
|
||||
* The most recent session note the user pinned for this exercise, or null.
|
||||
*
|
||||
* A note written mid-session is about that session — "shoulder twinged today". Some of them are
|
||||
* about the NEXT one instead: "go a notch narrower". The pin is how the user says which, at the
|
||||
* moment of writing, when they are the only one who knows. Pinned notes surface again the next
|
||||
* time the exercise comes up; unpinned ones stay in that day's history.
|
||||
*
|
||||
* Only the newest pinned note is returned: a pin is a message to your next self, and a stack of
|
||||
* them from six sessions ago is noise, not context.
|
||||
*/
|
||||
export function pinnedNoteFor(S, exId) {
|
||||
const workouts = S?.workouts || []
|
||||
for (let i = workouts.length - 1; i >= 0; i--) {
|
||||
const en = (workouts[i].entries || []).find(e => e.id === exId)
|
||||
const note = (en?.note || '').trim()
|
||||
if (note && en.notePin) return { note, d: workouts[i].d }
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** The standing note for an exercise — the one that is true every session. */
|
||||
export const exNoteFor = (S, exId) => ((S?.exNotes || {})[exId] || '').trim() || null
|
||||
|
||||
// A freestyle exercise starts with the last target the user actually trained, rather than the
|
||||
// generic config sheet defaults used when there is no history. The set rows themselves are still
|
||||
// built by buildSets(), which copies each completed set by position; only the target shape and
|
||||
// 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
|
||||
}
|
||||
@@ -87,10 +284,34 @@ 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) {
|
||||
/**
|
||||
* Build the rows a planned exercise starts a session with: its work sets, preceded by however
|
||||
* many warm-up sets the routine asks for (`cfg.warmupSets`, 0 by default so an existing plan
|
||||
* behaves exactly as before).
|
||||
*
|
||||
* The warm-ups are stacked with insertWarmupRow, one call each, so the ramp is the same one
|
||||
* the in-session "Add warm-up set" button produces: each row halves the gap left to the work
|
||||
* weight, giving 50% / 75% / 87.5% for three. `options.step` is the exercise's loading step,
|
||||
* passed in by the caller (see insertWarmupRow for why this module cannot read it itself).
|
||||
*/
|
||||
export function buildSets(S, cfg, options = {}) {
|
||||
const rows = buildWorkSets(S, cfg, options)
|
||||
const warm = Math.max(0, Math.min(MAX_PLANNED_WARMUPS, Math.round(cfg.warmupSets) || 0))
|
||||
if (!warm) return rows
|
||||
const mode = modeOf(cfg)
|
||||
let out = rows
|
||||
for (let i = 0; i < warm; i++) out = insertWarmupRow(out, mode, cfg, options.step)
|
||||
return out
|
||||
}
|
||||
|
||||
/** Beyond this a "warm-up" is its own workout; the config stepper stops here too. */
|
||||
export const MAX_PLANNED_WARMUPS = 5
|
||||
|
||||
function buildWorkSets(S, cfg, options = {}) {
|
||||
const last = lastEntryFor(S, cfg.id)
|
||||
const n = Math.max(1, cfg.sets || 1)
|
||||
const mode = modeOf(cfg)
|
||||
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)
|
||||
@@ -116,14 +337,65 @@ 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
|
||||
}
|
||||
|
||||
/**
|
||||
* Stamp every work row with the exercise's planned intensifier and pre-fill its drops/clusters,
|
||||
* already computed and editable — the plan designs the set, not a button pressed mid-workout.
|
||||
*
|
||||
* Must run AFTER applyPrescription: a drop-set's chain of drops is a percentage of each row's
|
||||
* own `w`, so it has to be computed from the final prescribed weight, not the pre-progression
|
||||
* one buildSets started from — otherwise a bumped working weight would leave stale, cheaper
|
||||
* drops sitting underneath it.
|
||||
*/
|
||||
export function applyIntensifierPlan(sets, cfg) {
|
||||
const kind = cfg && cfg.intensifier && cfg.intensifier.type
|
||||
if (kind !== 'dropset' && kind !== 'restpause') return sets
|
||||
if (kind === 'dropset') {
|
||||
const count = Math.max(1, Math.round(cfg.intensifier.count) || 1)
|
||||
const pct = cfg.intensifier.pct
|
||||
return sets.map(s => {
|
||||
if (isWarmupRow(s)) return s
|
||||
const drops = []
|
||||
let w = s.w || 0
|
||||
for (let k = 0; k < count; k++) { w = nextDropWeight(w, pct); drops.push({ w, r: s.r }) }
|
||||
return { ...s, type: 'dropset', drops }
|
||||
})
|
||||
}
|
||||
// Rest-pause trains as exactly two sets, not one per configured `sets` count: a warm-up at
|
||||
// the exercise's own configured reps, then a single rest-pause work set. Doing the full
|
||||
// activation+bursts protocol several times over isn't how rest-pause is actually trained, so
|
||||
// planning it replaces whatever buildSets built rather than stamping each of those rows.
|
||||
// The work row's own reps are the total — not "the total minus what the bursts carry" — and
|
||||
// the bursts are the full breakdown of that same total, down to the last one. See
|
||||
// extraVolumeOf/setTonnage: a rest-pause row's `clusters` are read-only display of how `r`
|
||||
// breaks down, not extra volume on top of it, precisely so this doesn't double-count.
|
||||
const restSec = Math.max(5, cfg.intensifier.restSec || 15)
|
||||
const totalReps = Math.max(1, Math.round(cfg.intensifier.totalReps) || 1)
|
||||
const w = (sets.find(s => !isWarmupRow(s)) || sets[0] || {}).w || 0
|
||||
const warmup = { w, r: Math.max(1, Math.round(cfg.reps) || 1), done: false, phase: 'warmup' }
|
||||
const work = { w, r: totalReps, done: false, type: 'restpause', clusters: splitBurstReps(totalReps).map(r => ({ r, restSec })) }
|
||||
return [warmup, work]
|
||||
}
|
||||
export function workoutVolume(w) {
|
||||
let v = 0
|
||||
w.entries.forEach(e => e.sets.forEach(s => { if (s.done) v += (s.w || 0) * (s.r || 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. Drop-set drops and rest-pause bursts add their
|
||||
// own weight x reps on top of the row's main/activation set (see extraVolumeOf).
|
||||
// Warm-ups are excluded here as everywhere else. The config sheet promises it in so many
|
||||
// words ("left out of volume, records and progression") and every other consumer already
|
||||
// does it; this line was the one that did not, which only stopped being harmless when a
|
||||
// routine started planning warm-ups by default. The number is written into the saved
|
||||
// workout, so an inflated one would stay wrong forever.
|
||||
w.entries.forEach(e => e.sets.forEach(s => {
|
||||
if (s.done && !isWarmupRow(s)) v += (s.w || 0) * (s.r || 0) + extraVolumeOf(s)
|
||||
}))
|
||||
return v
|
||||
}
|
||||
export function setsDone(w) {
|
||||
@@ -164,3 +436,168 @@ 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 at the end of the warm-up block, ramping toward the working weight.
|
||||
*
|
||||
* Each added row halves what is left between the last warm-up and the first work set, so the
|
||||
* first one lands at half the working weight, a second at three quarters, and so on — and a
|
||||
* row you edited by hand is what the next one ramps from. `step` is the exercise's own loading
|
||||
* step (progression.js's defaultIncrement, passed in by the caller so this module keeps no
|
||||
* dependency on progression — that one already imports from here): a warm-up you cannot
|
||||
* actually load onto the bar is noise.
|
||||
*
|
||||
* The reference is the first WORK row, never `rows[at - 1]` alone: for the first warm-up
|
||||
* `at` is 0, and reading `rows[-1]` used to fall through to the *last* row — the heaviest
|
||||
* work set — so "add warm-up set" handed you a full-weight set to correct by hand.
|
||||
*/
|
||||
/**
|
||||
* Recompute the warm-up block so it ramps toward the weight the work rows ACTUALLY carry.
|
||||
*
|
||||
* buildSets prepends the warm-ups before a prescription is applied, and applyPrescription
|
||||
* deliberately rewrites work rows only — so without this the ramp still aims at last
|
||||
* session's weight. On a deload that put the last warm-up above every work set, which is
|
||||
* the exact opposite of what a warm-up is for.
|
||||
*
|
||||
* A warm-up already logged keeps its weight and becomes what the next one ramps from: it
|
||||
* happened, and rewriting performed work is data loss. Entries with nothing to ramp toward
|
||||
* — cardio, bodyweight, an unloaded hold — are returned untouched.
|
||||
*/
|
||||
export function rerampWarmups(rows, step = 2.5) {
|
||||
const firstWork = rows.findIndex(x => !isWarmupRow(x))
|
||||
if (firstWork <= 0) return rows
|
||||
const target = rows[firstWork].w || 0
|
||||
if (!(target > 0)) return rows
|
||||
const out = rows.slice()
|
||||
let from = 0
|
||||
for (let i = 0; i < firstWork; i++) {
|
||||
if (out[i].done) { from = out[i].w || 0; continue }
|
||||
const w = target > from
|
||||
? Math.max(0, Math.min(target, Math.floor((from + (target - from) / 2) / step) * step))
|
||||
: target
|
||||
out[i] = { ...out[i], w }
|
||||
from = w
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
export function insertWarmupRow(rows, mode, target, step = 2.5) {
|
||||
const firstWork = rows.findIndex(x => !isWarmupRow(x))
|
||||
const at = firstWork === -1 ? rows.length : firstWork
|
||||
const prev = at > 0 ? rows[at - 1] : null // the warm-up this one ramps from
|
||||
const work = firstWork === -1 ? null : rows[firstWork]
|
||||
const rampTo = to => {
|
||||
const from = prev ? (prev.w || 0) : 0
|
||||
// Nothing to ramp toward: bodyweight, cardio, a timed hold with no load.
|
||||
if (!(to > 0)) return 0
|
||||
// Already at or past the work weight — which happens when a warm-up was edited by hand
|
||||
// above it. Returning `from` here handed the next warm-up that same too-heavy number and
|
||||
// let it propagate down the block. A warm-up is never heavier than the set it warms up for.
|
||||
if (to <= from) return to
|
||||
// Rounded DOWN to the step: a warm-up that lands a notch light costs nothing, one that
|
||||
// lands a notch heavy is a set you have to strip plates off before you can use it.
|
||||
return Math.max(0, Math.min(to, Math.floor((from + (to - from) / 2) / step) * step))
|
||||
}
|
||||
const warm = mode === 'cardio'
|
||||
? {
|
||||
min: prev ? prev.min : (work ? work.min : (target.min || 20)),
|
||||
speed: prev ? prev.speed : (work ? work.speed : (target.speed || 8)),
|
||||
done: false, phase: 'warmup', warmup: true,
|
||||
}
|
||||
: mode === 'time'
|
||||
? {
|
||||
sec: prev ? prev.sec : (work ? work.sec : (target.sec || 45)),
|
||||
w: rampTo(work ? (work.w || 0) : (target.weight || 0)),
|
||||
done: false, phase: 'warmup', warmup: true,
|
||||
}
|
||||
: {
|
||||
w: rampTo(work ? (work.w || 0) : (target.weight || 0)),
|
||||
r: work ? work.r : (prev ? prev.r : target.reps),
|
||||
done: false, phase: 'warmup', warmup: true,
|
||||
}
|
||||
const next = rows.slice()
|
||||
next.splice(at, 0, warm)
|
||||
return next
|
||||
}
|
||||
|
||||
/** 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 } from './history.js'
|
||||
import { modeOf, isTimed, fmtSec, setLabel, defaultConfig, buildSets, freestyleConfig, exLine, workoutVolume, bestWeightFor, bestWeightForEntry, effortOf, stepEffort, capEffort, isBw, isPerSide, sideReps, repStep, cascadeWeight, insertWarmupRow, removeRowAt, workSetsDone, pairAdjacent, unpairSuperset, supersetUnits, applyIntensifierPlan, pinnedNoteFor, exNoteFor } from './history.js'
|
||||
import { EXDB } from './exercises.js'
|
||||
|
||||
// Real ids out of the shipped catalogue, so the body-part fallback is exercised for real.
|
||||
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', () => {
|
||||
@@ -63,6 +66,190 @@ describe('setLabel', () => {
|
||||
expect(setLabel(LIFT, { w: 0, r: 0 })).toBe('0×0')
|
||||
expect(setLabel(CARDIO, {})).toBe('0 min @ 0 km/h')
|
||||
})
|
||||
|
||||
it('appends RIR when present, including a valid 0', () => {
|
||||
expect(setLabel(LIFT, { w: 60, r: 10, rir: 2 })).toBe('60×10 (RIR 2)')
|
||||
expect(setLabel(LIFT, { w: 60, r: 10, rir: 1.5 })).toBe('60×10 (RIR 1.5)')
|
||||
expect(setLabel(LIFT, { w: 60, r: 10, rir: 0 })).toBe('60×10 (RIR 0)')
|
||||
})
|
||||
|
||||
it('says nothing about RIR on a set that never logged one', () => {
|
||||
expect(setLabel(LIFT, { w: 60, r: 10 })).toBe('60×10')
|
||||
// cleared in the UI: the key is dropped, but a null must read the same as absent
|
||||
expect(setLabel(LIFT, { w: 60, r: 10, rir: null })).toBe('60×10')
|
||||
})
|
||||
|
||||
it('appends RPE for a set logged on that scale', () => {
|
||||
expect(setLabel(LIFT, { w: 60, r: 10, rpe: 8 })).toBe('60×10 (RPE 8)')
|
||||
expect(setLabel(LIFT, { w: 60, r: 10, rpe: 9.5 })).toBe('60×10 (RPE 9.5)')
|
||||
expect(setLabel(LIFT, { w: 60, r: 10, rpe: null })).toBe('60×10')
|
||||
})
|
||||
|
||||
it('keeps each set on the scale it was logged with', () => {
|
||||
// switching the setting must not rewrite history: an old RIR set still reads as RIR
|
||||
expect(setLabel(LIFT, { w: 60, r: 10, rir: 2 })).toBe('60×10 (RIR 2)')
|
||||
// and a set that somehow carries both is described once, by the one it was logged with
|
||||
expect(setLabel(LIFT, { w: 60, r: 10, rir: 2, rpe: 8 })).toBe('60×10 (RIR 2)')
|
||||
})
|
||||
})
|
||||
|
||||
describe('effortOf', () => {
|
||||
it('reads the scale a profile logs', () => {
|
||||
expect(effortOf({ effort: 'rpe' })).toBe('rpe')
|
||||
expect(effortOf({ effort: 'rir' })).toBe('rir')
|
||||
expect(effortOf({ effort: 'none' })).toBe('none')
|
||||
expect(effortOf({})).toBe('none')
|
||||
})
|
||||
|
||||
it('keeps the column for a profile still carrying the old showRir flag', () => {
|
||||
expect(effortOf({ showRir: true })).toBe('rir')
|
||||
// what a stored profile actually looks like once it is overlaid on DEF
|
||||
expect(effortOf({ effort: null, showRir: true })).toBe('rir')
|
||||
expect(effortOf({ effort: null })).toBe('none')
|
||||
expect(effortOf({ showRir: false })).toBe('none')
|
||||
// once the new setting is chosen it wins, whatever the old flag said
|
||||
expect(effortOf({ showRir: true, effort: 'rpe' })).toBe('rpe')
|
||||
expect(effortOf({ showRir: true, effort: 'none' })).toBe('none')
|
||||
})
|
||||
|
||||
// The store cannot be imported here (it reaches for `navigator` at module load), so the
|
||||
// overlay it performs is reproduced literally: stored profile spread over the defaults.
|
||||
// DEF.effort is null precisely so this lands on the showRir fallback rather than on 'none'.
|
||||
const overlay = stored => ({ unit: 'kg', effort: null, ...stored })
|
||||
|
||||
it('survives the overlay every load path performs', () => {
|
||||
// upgrading with the column on: local state, a server pull and a restored backup all
|
||||
// arrive as a stored object spread over the defaults, and all must keep the column
|
||||
expect(effortOf(overlay({ showRir: true }))).toBe('rir')
|
||||
expect(effortOf(overlay({ showRir: false }))).toBe('none')
|
||||
// a profile predating the RIR feature entirely
|
||||
expect(effortOf(overlay({}))).toBe('none')
|
||||
// and one written by this version
|
||||
expect(effortOf(overlay({ effort: 'rpe' }))).toBe('rpe')
|
||||
// an old backup restored over a profile that had already chosen: the file wins, because
|
||||
// an import replaces state wholesale rather than merging
|
||||
expect(effortOf(overlay({ showRir: true, effort: undefined }))).toBe('rir')
|
||||
})
|
||||
|
||||
it('is not fooled by a junk value', () => {
|
||||
expect(effortOf({ effort: 'rpe10' })).toBe('none')
|
||||
expect(effortOf({ effort: 'RIR' })).toBe('none')
|
||||
expect(effortOf({ effort: 'f' })).toBe('none')
|
||||
expect(effortOf(null)).toBe('none')
|
||||
expect(effortOf(undefined)).toBe('none')
|
||||
// a junk value with the old flag still set falls back rather than showing nothing
|
||||
expect(effortOf({ effort: 'nope', showRir: true })).toBe('rir')
|
||||
})
|
||||
})
|
||||
|
||||
describe('stepEffort', () => {
|
||||
it('starts at the bottom of the scale and walks up', () => {
|
||||
// the first + on an empty cell lands on the lowest value, not on some "typical" middle:
|
||||
// the stepper counts up from the floor the way every other stepper in the app does
|
||||
expect(stepEffort('rir', null, 1)).toBe(0)
|
||||
expect(stepEffort('rpe', null, 1)).toBe(6)
|
||||
// and then in even steps
|
||||
expect(stepEffort('rir', 0, 1)).toBe(0.5)
|
||||
expect(stepEffort('rir', 0.5, 1)).toBe(1)
|
||||
expect(stepEffort('rpe', 6, 1)).toBe(6.5)
|
||||
})
|
||||
|
||||
it('leaves an untouched cell unlogged when stepped down', () => {
|
||||
// one stray − on a fresh row must not stamp "(RIR 0)" — went to failure — on the set
|
||||
expect(stepEffort('rir', null, -1)).toBe(null)
|
||||
expect(stepEffort('rpe', null, -1)).toBe(null)
|
||||
expect(stepEffort('rir', undefined, -1)).toBe(null)
|
||||
})
|
||||
|
||||
it('clears the cell again when stepped back off the floor', () => {
|
||||
// so a mistap is undoable rather than sticking at the floor for good
|
||||
expect(stepEffort('rir', 0, -1)).toBe(null)
|
||||
expect(stepEffort('rpe', 6, -1)).toBe(null)
|
||||
// but a step that stays inside the scale is an ordinary step
|
||||
expect(stepEffort('rir', 0.5, -1)).toBe(0)
|
||||
expect(stepEffort('rpe', 6.5, -1)).toBe(6)
|
||||
})
|
||||
|
||||
it('stops at the top of the scale', () => {
|
||||
expect(stepEffort('rir', 9.5, 1)).toBe(10)
|
||||
expect(stepEffort('rir', 10, 1)).toBe(10)
|
||||
expect(stepEffort('rpe', 10, 1)).toBe(10)
|
||||
})
|
||||
|
||||
it('keeps halves clean instead of drifting into float dust', () => {
|
||||
let v = null
|
||||
for (let i = 0; i < 6; i++) v = stepEffort('rpe', v, 1)
|
||||
expect(v).toBe(8.5)
|
||||
expect(stepEffort('rir', 0.1 + 0.2, 1)).toBe(0.8)
|
||||
})
|
||||
|
||||
it('steps evenly from a value typed below the floor rather than snapping', () => {
|
||||
// nothing stops someone typing RPE 3; the stepper must not jump them to 6 on one tap
|
||||
expect(stepEffort('rpe', 3, 1)).toBe(3.5)
|
||||
// stepping down out of the scale from there just clears it
|
||||
expect(stepEffort('rpe', 3, -1)).toBe(null)
|
||||
})
|
||||
|
||||
it('does nothing when the profile logs no effort at all', () => {
|
||||
expect(stepEffort('none', null, 1)).toBe(null)
|
||||
expect(stepEffort('none', 2, 1)).toBe(2)
|
||||
expect(stepEffort(undefined, 2, -1)).toBe(2)
|
||||
})
|
||||
})
|
||||
|
||||
describe('capEffort', () => {
|
||||
it('caps a typed value at the top of the scale', () => {
|
||||
expect(capEffort('rir', 12)).toBe(10)
|
||||
expect(capEffort('rpe', 99)).toBe(10)
|
||||
expect(capEffort('rpe', 8)).toBe(8)
|
||||
})
|
||||
|
||||
it('does not floor a typed value, so typing "10" survives its first keystroke', () => {
|
||||
// clamping up would turn the "1" of "10" into 6 and fight the input
|
||||
expect(capEffort('rpe', 1)).toBe(1)
|
||||
expect(capEffort('rir', 0)).toBe(0)
|
||||
})
|
||||
|
||||
it('passes an emptied field through untouched', () => {
|
||||
expect(capEffort('rir', null)).toBe(null)
|
||||
expect(capEffort('rpe', undefined)).toBe(undefined)
|
||||
expect(capEffort('none', 12)).toBe(12)
|
||||
})
|
||||
})
|
||||
|
||||
// End-to-end on the data, not the pixels: what a set carries after the taps a real session
|
||||
// makes, and what it reads back as afterwards.
|
||||
describe('logging effort across a session', () => {
|
||||
it('logs a working set on the chosen scale', () => {
|
||||
// four + taps from empty on an RPE profile: 6, 6.5, 7, 7.5
|
||||
let v = null
|
||||
for (let i = 0; i < 4; i++) v = stepEffort('rpe', v, 1)
|
||||
expect(setLabel(LIFT, { w: 80, r: 5, rpe: v })).toBe('80×5 (RPE 7.5)')
|
||||
})
|
||||
|
||||
it('a set taken to failure is logged, not left blank', () => {
|
||||
const v = stepEffort('rir', null, 1) // one + on an RIR profile
|
||||
expect(v).toBe(0)
|
||||
expect(setLabel(LIFT, { w: 100, r: 3, rir: v })).toBe('100×3 (RIR 0)')
|
||||
})
|
||||
|
||||
it('switching the setting mid-history rewrites nothing', () => {
|
||||
const old = { w: 60, r: 10, rir: 2 } // logged while the profile was on RIR
|
||||
const fresh = { w: 60, r: 10, rpe: 8 } // logged after switching to RPE
|
||||
expect(effortOf({ effort: 'rpe' })).toBe('rpe')
|
||||
expect(setLabel(LIFT, old)).toBe('60×10 (RIR 2)')
|
||||
expect(setLabel(LIFT, fresh)).toBe('60×10 (RPE 8)')
|
||||
// turning the column off entirely hides the control but keeps both sets readable
|
||||
expect(effortOf({ effort: 'none' })).toBe('none')
|
||||
expect(setLabel(LIFT, old)).toBe('60×10 (RIR 2)')
|
||||
})
|
||||
|
||||
it('never attaches effort to a mode that has no place for it', () => {
|
||||
// cardio and timed sets have no third stepper, and their labels ignore the field even
|
||||
// if an import or an old file put one there
|
||||
expect(setLabel(CARDIO, { min: 20, speed: 9, rpe: 8 })).toBe('20 min @ 9 km/h')
|
||||
expect(setLabel(LIFT, { sec: 45, rir: 2 }, { id: LIFT, mode: 'time' })).toBe('0:45')
|
||||
})
|
||||
})
|
||||
|
||||
describe('defaultConfig', () => {
|
||||
@@ -71,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')
|
||||
@@ -85,6 +336,116 @@ 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 }
|
||||
])
|
||||
})
|
||||
|
||||
// Planned warm-ups: the routine says how many, buildSets stacks them onto the work sets with
|
||||
// the same ramp the in-session button uses. A plan without the field must not change shape.
|
||||
it('adds no rows when the config asks for no warm-ups', () => {
|
||||
const S = { exWeights: {}, workouts: [] }
|
||||
const cfg = { id: '0025', mode: 'reps', sets: 2, reps: 5, weight: 100 }
|
||||
expect(buildSets(S, cfg)).toEqual([
|
||||
{ w: 100, r: 5, done: false },
|
||||
{ w: 100, r: 5, done: false },
|
||||
])
|
||||
})
|
||||
|
||||
it('prepends the planned warm-ups as a ramp toward the work weight', () => {
|
||||
const S = { exWeights: {}, workouts: [] }
|
||||
const cfg = { id: '0025', mode: 'reps', sets: 2, reps: 5, weight: 100, warmupSets: 3 }
|
||||
const rows = buildSets(S, cfg, { step: 2.5 })
|
||||
expect(rows.map(r => r.w)).toEqual([50, 75, 87.5, 100, 100])
|
||||
expect(rows.slice(0, 3).every(r => r.phase === 'warmup')).toBe(true)
|
||||
expect(rows.slice(3).every(r => r.phase === undefined)).toBe(true)
|
||||
})
|
||||
|
||||
it('caps the planned warm-ups and ignores nonsense values', () => {
|
||||
const S = { exWeights: {}, workouts: [] }
|
||||
const base = { id: '0025', mode: 'reps', sets: 1, reps: 5, weight: 100 }
|
||||
expect(buildSets(S, { ...base, warmupSets: 99 }, { step: 2.5 }).filter(r => r.phase === 'warmup')).toHaveLength(5)
|
||||
expect(buildSets(S, { ...base, warmupSets: -2 }, { step: 2.5 })).toHaveLength(1)
|
||||
expect(buildSets(S, { ...base, warmupSets: 'x' }, { step: 2.5 })).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('keeps planned warm-ups out of the work-set count', () => {
|
||||
const S = { exWeights: {}, workouts: [] }
|
||||
const rows = buildSets(S, { id: '0025', mode: 'reps', sets: 3, reps: 5, weight: 100, warmupSets: 2 }, { step: 2.5 })
|
||||
const logged = { entries: [{ id: '0025', sets: rows.map(r => ({ ...r, done: true })) }] }
|
||||
expect(logged.entries[0].sets).toHaveLength(5)
|
||||
expect(workSetsDone(logged)).toBe(3)
|
||||
})
|
||||
|
||||
it('inherits the target for timed and cardio exercises too', () => {
|
||||
const timed = {
|
||||
exWeights: {},
|
||||
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 }))
|
||||
@@ -123,6 +484,63 @@ 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('applyIntensifierPlan', () => {
|
||||
it('pre-fills every work row with a chain of drops, each pct% lighter than the one before', () => {
|
||||
const sets = [{ w: 100, r: 8, done: false }, { w: 100, r: 8, done: false }]
|
||||
const out = applyIntensifierPlan(sets, { intensifier: { type: 'dropset', count: 2, pct: 20 } })
|
||||
expect(out).toEqual([
|
||||
{ w: 100, r: 8, done: false, type: 'dropset', drops: [{ w: 80, r: 8 }, { w: 64, r: 8 }] },
|
||||
{ w: 100, r: 8, done: false, type: 'dropset', drops: [{ w: 80, r: 8 }, { w: 64, r: 8 }] },
|
||||
])
|
||||
})
|
||||
|
||||
it('collapses rest-pause to exactly two rows regardless of how many sets were configured: a warm-up at the exercise\'s own reps, then one work set whose own reps ARE the total', () => {
|
||||
const sets = [{ w: 60, r: 8, done: false }, { w: 60, r: 8, done: false }, { w: 60, r: 8, done: false }]
|
||||
const out = applyIntensifierPlan(sets, { reps: 8, intensifier: { type: 'restpause', totalReps: 12, restSec: 15 } })
|
||||
expect(out).toEqual([
|
||||
{ w: 60, r: 8, done: false, phase: 'warmup' },
|
||||
{ w: 60, r: 12, done: false, type: 'restpause', clusters: [{ r: 6, restSec: 15 }, { r: 3, restSec: 15 }, { r: 2, restSec: 15 }, { r: 1, restSec: 15 }] },
|
||||
])
|
||||
// the full breakdown always sums back to the row's own r — no reps missing, none double-counted
|
||||
expect(out[1].clusters.reduce((sum, c) => sum + c.r, 0)).toBe(out[1].r)
|
||||
})
|
||||
|
||||
it('the warm-up reps come from the exercise\'s own configured reps, not the rest-pause total', () => {
|
||||
const sets = [{ w: 60, r: 8, done: false }]
|
||||
const out = applyIntensifierPlan(sets, { reps: 5, intensifier: { type: 'restpause', totalReps: 20, restSec: 15 } })
|
||||
expect(out[0]).toEqual({ w: 60, r: 5, done: false, phase: 'warmup' })
|
||||
})
|
||||
|
||||
it('carries the prescribed weight from the built sets onto both new rows', () => {
|
||||
const sets = [{ w: 82.5, r: 8, done: false }]
|
||||
const out = applyIntensifierPlan(sets, { reps: 8, intensifier: { type: 'restpause', totalReps: 4, restSec: 15 } })
|
||||
expect(out[0].w).toBe(82.5)
|
||||
expect(out[1].w).toBe(82.5)
|
||||
})
|
||||
|
||||
it('never touches a warm-up row', () => {
|
||||
const sets = [{ w: 20, r: 8, done: false, phase: 'warmup' }, { w: 100, r: 8, done: false }]
|
||||
const out = applyIntensifierPlan(sets, { intensifier: { type: 'dropset', count: 1, pct: 20 } })
|
||||
expect(out[0]).toEqual({ w: 20, r: 8, done: false, phase: 'warmup' })
|
||||
expect(out[1].type).toBe('dropset')
|
||||
})
|
||||
|
||||
it('leaves sets untouched with no intensifier configured', () => {
|
||||
const sets = [{ w: 100, r: 8, done: false }]
|
||||
expect(applyIntensifierPlan(sets, {})).toBe(sets)
|
||||
expect(applyIntensifierPlan(sets, { intensifier: { type: 'nonsense' } })).toBe(sets)
|
||||
})
|
||||
})
|
||||
|
||||
describe('workoutVolume', () => {
|
||||
@@ -134,4 +552,296 @@ 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('adds drop-set drops on top of the row\'s main set', () => {
|
||||
const dropRow = { type: 'dropset', w: 100, r: 5, done: true, drops: [{ w: 80, r: 5 }, { w: 60, r: 5 }] }
|
||||
expect(workoutVolume({ entries: [{ id: LIFT, sets: [dropRow] }] })).toBe(100 * 5 + 80 * 5 + 60 * 5)
|
||||
})
|
||||
|
||||
it('counts a rest-pause row once — its own r is already the total across every burst', () => {
|
||||
const burstRow = { type: 'restpause', w: 60, r: 20, done: true, clusters: [{ r: 10, restSec: 15 }, { r: 5, restSec: 15 }, { r: 3, restSec: 15 }, { r: 1, restSec: 15 }, { r: 1, restSec: 15 }] }
|
||||
expect(workoutVolume({ entries: [{ id: LIFT, sets: [burstRow] }] })).toBe(60 * 20)
|
||||
})
|
||||
|
||||
it('ignores drops/bursts on a row that was never checked off', () => {
|
||||
const dropRow = { type: 'dropset', w: 100, r: 5, done: false, drops: [{ w: 80, r: 5 }] }
|
||||
expect(workoutVolume({ entries: [{ id: LIFT, sets: [dropRow] }] })).toBe(0)
|
||||
})
|
||||
|
||||
it('leaves an unloaded bodyweight set at zero volume rather than inventing a number', () => {
|
||||
const w = { entries: [{ id: BW, target: { bodyweight: true }, sets: [{ w: 0, r: 20, done: true }] }] }
|
||||
expect(workoutVolume(w)).toBe(0)
|
||||
})
|
||||
|
||||
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, ramping toward the work weight', () => {
|
||||
const rows = [
|
||||
{ warmup: true, w: 20, r: 8, done: true },
|
||||
{ warmup: true, w: 30, r: 8, done: false },
|
||||
{ w: 60, r: 8, done: false },
|
||||
]
|
||||
const next = insertWarmupRow(rows, 'reps', { reps: 8 }, 2.5)
|
||||
expect(next.length).toBe(4)
|
||||
expect(next[2].warmup).toBe(true)
|
||||
expect(next[2].w).toBe(45) // halfway from the last warm-up (30) to the work set (60)
|
||||
expect(next[3].w).toBe(60) // work row still after the warm-up block
|
||||
})
|
||||
|
||||
// The first warm-up is the case that was broken: `at` is 0, so the old code read rows[-1],
|
||||
// fell through to `rows[rows.length - 1]` — the heaviest work set — and handed you a
|
||||
// "warm-up" at your full working weight.
|
||||
it('gives the first warm-up half the working weight, not the working weight itself', () => {
|
||||
const next = insertWarmupRow([{ w: 100, r: 5, done: false }], 'reps', { reps: 5 }, 2.5)
|
||||
expect(next.length).toBe(2)
|
||||
expect(next[0]).toMatchObject({ w: 50, r: 5, phase: 'warmup', warmup: true, done: false })
|
||||
expect(next[1].w).toBe(100)
|
||||
})
|
||||
|
||||
it('rounds the ramp to the exercise loading step', () => {
|
||||
// 0 -> 95 halves to 47.5, which is not loadable in 5 kg steps: 45 is.
|
||||
expect(insertWarmupRow([{ w: 95, r: 5 }], 'reps', { reps: 5 }, 5)[0].w).toBe(45)
|
||||
})
|
||||
|
||||
it('keeps bodyweight warm-ups at zero and never exceeds the work set', () => {
|
||||
expect(insertWarmupRow([{ w: 0, r: 12 }], 'reps', { reps: 12 }, 2.5)[0].w).toBe(0)
|
||||
// A warm-up already at the working weight cannot ramp any further.
|
||||
const at100 = insertWarmupRow([{ warmup: true, w: 100, r: 5 }, { w: 100, r: 5 }], 'reps', { reps: 5 }, 2.5)
|
||||
expect(at100[1].w).toBe(100)
|
||||
})
|
||||
|
||||
it('ramps a timed hold the same way and leaves cardio on the work row values', () => {
|
||||
expect(insertWarmupRow([{ sec: 45, w: 40, done: false }], 'time', { sec: 45 }, 2.5)[0])
|
||||
.toMatchObject({ sec: 45, w: 20, phase: 'warmup' })
|
||||
expect(insertWarmupRow([{ min: 20, speed: 10, done: false }], 'cardio', { min: 20 }, 2.5)[0])
|
||||
.toMatchObject({ min: 20, speed: 10, phase: 'warmup' })
|
||||
})
|
||||
|
||||
it('removeRowAt never empties an entry below one row', () => {
|
||||
expect(removeRowAt([{ w: 60 }], 0).length).toBe(1)
|
||||
const rows = [{ w: 60 }, { w: 70 }]
|
||||
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)
|
||||
})
|
||||
})
|
||||
|
||||
describe('pinnedNoteFor', () => {
|
||||
const S = {
|
||||
workouts: [
|
||||
{ d: '2026-08-01', entries: [{ id: '0025', note: 'felt heavy', notePin: true }] },
|
||||
{ d: '2026-08-08', entries: [{ id: '0025', note: 'just a diary line' }] },
|
||||
{ d: '2026-08-15', entries: [{ id: '0025', note: 'go narrower', notePin: true }] },
|
||||
{ d: '2026-08-22', entries: [{ id: '0293', note: 'other exercise', notePin: true }] },
|
||||
],
|
||||
}
|
||||
|
||||
it('returns only the newest pinned note for that exercise', () => {
|
||||
expect(pinnedNoteFor(S, '0025')).toEqual({ note: 'go narrower', d: '2026-08-15' })
|
||||
})
|
||||
|
||||
it('ignores notes that were not pinned', () => {
|
||||
expect(pinnedNoteFor({ workouts: [{ d: '2026-08-08', entries: [{ id: '0025', note: 'diary' }] }] }, '0025')).toBeNull()
|
||||
})
|
||||
|
||||
it('is null for an exercise with no notes, and safe on empty state', () => {
|
||||
expect(pinnedNoteFor(S, '9999')).toBeNull()
|
||||
expect(pinnedNoteFor({}, '0025')).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('exNoteFor', () => {
|
||||
it('reads the standing note and trims it away when blank', () => {
|
||||
expect(exNoteFor({ exNotes: { '0025': ' seat 4, pin 7 ' } }, '0025')).toBe('seat 4, pin 7')
|
||||
expect(exNoteFor({ exNotes: { '0025': ' ' } }, '0025')).toBeNull()
|
||||
expect(exNoteFor({}, '0025')).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,67 @@
|
||||
// Runtime-agnostic core of the i18n module: state, constants and readers (t, dateLocale,
|
||||
// instrFor, exerciseNameFor, getLang). Plain Node-loadable — the browser-only pieces
|
||||
// (import.meta.glob lazy
|
||||
// loads, the React subscription hook) live in i18n.js and re-export from here.
|
||||
|
||||
export const LANGS = {
|
||||
en: 'English', de: 'Deutsch', es: 'Español', fr: 'Français', it: 'Italiano',
|
||||
pt: 'Português (Portugal)', 'pt-BR': 'Português (Brasil)', pl: 'Polski',
|
||||
tr: 'Türkçe', ru: 'Русский', zh: '中文',
|
||||
ko: '한국어', hi: 'हिन्दी'
|
||||
}
|
||||
export const INSTR_LANGS = ['en', 'es', 'fr', 'it', 'tr', 'ru', 'zh', 'hi', 'pl', 'ko', 'pt-BR']
|
||||
export const EXERCISE_NAME_LANGS = ['pt-BR']
|
||||
export const DATE_LOCALES = {
|
||||
en: 'en-GB', de: 'de-DE', es: 'es-ES', fr: 'fr-FR', it: 'it-IT', pt: 'pt-PT', 'pt-BR': 'pt-BR',
|
||||
pl: 'pl-PL', tr: 'tr-TR', ru: 'ru-RU', zh: 'zh-CN', ko: 'ko-KR', hi: 'hi-IN'
|
||||
}
|
||||
|
||||
let lang = 'en' // set only by _setLangState, called from i18n.js setLang
|
||||
let dict = {} // current locale pack (empty = English fallback)
|
||||
let instr = null // { exId: [steps] } for the current language, null = English
|
||||
let exerciseNames = null // { exId: translated name }, null = original catalogue name
|
||||
let version = 0 // bumped on every setLang; drives the React subscription selector
|
||||
|
||||
export const getLang = () => lang
|
||||
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 || []
|
||||
|
||||
// Built-in catalogue names are bilingual when a complete translated name pack is active.
|
||||
// User-created exercises have no entry in the pack and keep their exact chosen name.
|
||||
export const exerciseNameFor = ex => {
|
||||
const translated = exerciseNames && ex && exerciseNames[ex.id]
|
||||
if (!translated) return ex?.n || ''
|
||||
// Some names (Burpee, Pilates, brand/model terms) are the established pt-BR term too.
|
||||
// Repeating an identical loanword in parentheses adds noise rather than context.
|
||||
return translated.toLocaleLowerCase('pt-BR') === ex.n.toLocaleLowerCase('en')
|
||||
? translated
|
||||
: `${translated} (${ex.n})`
|
||||
}
|
||||
|
||||
// Search both the localized and canonical English title without changing persisted data.
|
||||
export const exerciseNameSearchText = ex => {
|
||||
const translated = exerciseNames && ex && exerciseNames[ex.id]
|
||||
return translated ? `${translated} ${ex.n}` : (ex?.n || '')
|
||||
}
|
||||
|
||||
// Called by i18n.js's setLang once the locale pack has been loaded — kept here rather than
|
||||
// exported as setLang because loading packs requires import.meta.glob, which is Vite-only.
|
||||
// `dict`, `instr` and `exerciseNames` may be null to reset to their English fallbacks.
|
||||
export function _setLangState(newLang, newDict, newInstr, newExerciseNames) {
|
||||
lang = LANGS[newLang] ? newLang : 'en'
|
||||
dict = lang === 'en' ? {} : (newDict || {})
|
||||
instr = lang === 'en' || !INSTR_LANGS.includes(lang) ? null : (newInstr || null)
|
||||
exerciseNames = lang === 'en' || !EXERCISE_NAME_LANGS.includes(lang) ? null : (newExerciseNames || null)
|
||||
version++
|
||||
return version
|
||||
}
|
||||
@@ -1,56 +1,45 @@
|
||||
// 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, EXERCISE_NAME_LANGS, DATE_LOCALES,
|
||||
getLang, dateLocale, t, instrFor, exerciseNameFor, exerciseNameSearchText, 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, EXERCISE_NAME_LANGS, DATE_LOCALES,
|
||||
getLang, dateLocale, t, instrFor, exerciseNameFor, exerciseNameSearchText
|
||||
}
|
||||
|
||||
// Vite code-splits locale, instruction and exercise-name packs via import.meta.glob. They are
|
||||
// lazy, so the production bundle ships English only until another language is selected.
|
||||
const localePacks = import.meta.glob('../locales/*.js')
|
||||
const instrPacks = import.meta.glob('../instr/*.js')
|
||||
const exerciseNamePacks = import.meta.glob('../exercise-names/*.js')
|
||||
|
||||
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, exerciseNames = null
|
||||
try { dict = l === 'en' ? {} : (await localePacks['../locales/' + l + '.js']()).default } catch (e) { dict = {} }
|
||||
try { instr = l === 'en' || !INSTR_LANGS.includes(l) ? null : (await instrPacks['../instr/' + l + '.js']()).default } catch (e) { instr = null }
|
||||
try {
|
||||
dict = l === 'en' ? {} : (await localePacks['../locales/' + l + '.js']()).default
|
||||
instr = l === 'en' || !INSTR_LANGS.includes(l) ? null : (await instrPacks['../instr/' + l + '.js']()).default
|
||||
} catch (e) { dict = {}; instr = null }
|
||||
exerciseNames = l === 'en' || !EXERCISE_NAME_LANGS.includes(l)
|
||||
? null
|
||||
: (await exerciseNamePacks['../exercise-names/' + l + '.js']()).default
|
||||
} catch (e) { exerciseNames = null }
|
||||
_setLangState(l, dict, instr, exerciseNames)
|
||||
notify()
|
||||
}
|
||||
|
||||
// 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 ---- */
|
||||
|
||||
@@ -57,22 +58,26 @@ const norm = h => h.toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim()
|
||||
const COLUMNS = [
|
||||
['exercise', ['exercise', 'exercise name', 'exercise title']],
|
||||
['date', ['date', 'workout date']],
|
||||
['startTime', ['start time']],
|
||||
['startTime', ['start time', 'start date']],
|
||||
['endTime', ['end time']],
|
||||
['workoutName', ['workout name', 'title']],
|
||||
['workoutName', ['workout name', 'title', 'workout']],
|
||||
['category', ['category', 'body part', 'muscle group']],
|
||||
['weightKg', ['weight kg']],
|
||||
['weightLb', ['weight lbs', 'weight lb']],
|
||||
['weight', ['weight']],
|
||||
['weightUnit', ['weight unit', 'unit']],
|
||||
['reps', ['reps', 'repetitions']],
|
||||
// Hevy and Strong both write an RPE per set. Nothing mainstream exports RIR, but read it
|
||||
// when it is there rather than dropping the column on the floor.
|
||||
['rpe', ['rpe', 'rpe rating']],
|
||||
['rir', ['rir', 'reps in reserve']],
|
||||
['distanceKm', ['distance km']],
|
||||
['distance', ['distance']],
|
||||
['distanceUnit', ['distance unit']],
|
||||
['seconds', ['seconds', 'duration seconds']],
|
||||
['seconds', ['seconds', 'duration seconds', 'set duration sec']],
|
||||
['time', ['time', 'duration']],
|
||||
['setType', ['set type']],
|
||||
['note', ['comment', 'comments', 'notes', 'note']],
|
||||
['note', ['comment', 'comments', 'notes', 'note', 'workout notes']],
|
||||
]
|
||||
|
||||
function mapHeader(header) {
|
||||
@@ -106,7 +111,9 @@ export function detectSource(header) {
|
||||
const SYN = [
|
||||
[/\bbb\b/g, 'barbell'], [/\bdb\b/g, 'dumbbell'], [/\bkb\b/g, 'kettlebell'],
|
||||
[/\bohp\b/g, 'overhead press'], [/\bbw\b/g, 'body weight'], [/\bbodyweight\b/g, 'body weight'],
|
||||
[/\bmachine\b/g, 'lever'], [/\bsmith machine\b/g, 'smith'], [/\bez bar\b/g, 'ez barbell'],
|
||||
// 'smith machine' first: the generic machine->lever rule would otherwise eat the word
|
||||
// and leave 'smith lever', which matches no entry in the dataset.
|
||||
[/\bsmith machine\b/g, 'smith'], [/\bmachine\b/g, 'lever'], [/\bez bar\b/g, 'ez barbell'],
|
||||
[/\bpull ups?\b/g, 'pull up'], [/\bchin ups?\b/g, 'chin up'], [/\bpush ups?\b/g, 'push up'],
|
||||
[/\bsit ups?\b/g, 'sit up'], [/\bdips?\b/g, 'dip'], [/\braises?\b/g, 'raise'],
|
||||
[/\bcurls?\b/g, 'curl'], [/\bpresses\b/g, 'press'], [/\bextensions?\b/g, 'extension'],
|
||||
@@ -169,6 +176,36 @@ 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',
|
||||
// Hevy's own vocabulary, from a real export. Hevy writes the equipment in parentheses
|
||||
// and uses "bicep"/"chest fly"/"reverse fly" where the dataset says "biceps"/"fly"/
|
||||
// "reverse fly", so these are near-misses the word-bag cannot close on its own.
|
||||
'bicep curl (dumbbell)': '0294', 'bicep curl (cable)': '0868', 'bicep curl (barbell)': '0031',
|
||||
'chest fly (dumbbell)': '0308', 'chest fly (machine)': '0596', 'butterfly (pec deck)': '0596',
|
||||
'incline chest fly (dumbbell)': '0319', 'cable fly crossovers': '1269',
|
||||
'rear delt reverse fly (dumbbell)': '0383', 'rear delt reverse fly (machine)': '0602',
|
||||
'chest supported reverse fly (dumbbell)': '0383',
|
||||
'bench press (smith machine)': '0748', 'overhead press (smith machine)': '0766',
|
||||
'hack squat (machine)': '0743', 'iso-lateral row (machine)': '0571',
|
||||
'seated cable row - bar grip': '0218', 'reverse grip lat pulldown (cable)': '0673',
|
||||
'single arm lateral raise (cable)': '0192', 'plate front raise': '0310',
|
||||
'back extension (weighted hyperextension)': '0573',
|
||||
'behind the back bicep wrist curl (barbell)': '0104',
|
||||
// A face pull is a rope rear-delt row; the dataset has no entry under that name.
|
||||
'face pull': '0203',
|
||||
// Cardio again: the only candidates in a 29-entry cardio vocabulary.
|
||||
'jumping jack': '3220', 'jumping jacks': '3220', 'battle ropes': '0128',
|
||||
'stair machine (steps)': '2311', 'stair machine': '2311',
|
||||
}
|
||||
|
||||
let ALIAS_IDX = null
|
||||
@@ -214,6 +251,23 @@ export function matchExercise(name) {
|
||||
return ties === 1 ? best : null
|
||||
}
|
||||
|
||||
// Hevy exports no category column, so every invented exercise fell through to the
|
||||
// 'upper legs' default and a third of an imported history was attributed to the legs in
|
||||
// the muscle map. When there is no category, read the body part off the name instead.
|
||||
const NAME_BP = [
|
||||
[/\b(curl|bicep|biceps|tricep|triceps|skullcrusher|pushdown)\b/, 'upper arms'],
|
||||
[/\b(wrist|forearm|forearms|grip)\b/, 'lower arms'],
|
||||
[/\b(bench|chest|pec|fly|flye|crossover|crossovers|dip)\b/, 'chest'],
|
||||
[/\b(row|pulldown|pullup|pull up|chin up|lat|lats|back|deadlift|shrug)\b/, 'back'],
|
||||
[/\b(shoulder|delt|delts|overhead|lateral raise|front raise|face pull|press up)\b/, 'shoulders'],
|
||||
[/\b(calf|calves)\b/, 'lower legs'],
|
||||
[/\b(squat|lunge|leg|glute|hamstring|quad|hip thrust|deadlift)\b/, 'upper legs'],
|
||||
[/\b(ab|abs|core|plank|crunch|sit up|oblique|russian twist)\b/, 'waist'],
|
||||
[/\b(run|running|jog|bike|cycling|rope|ropes|jump|jacks|burpee|sprint|treadmill|stair)\b/, 'cardio'],
|
||||
[/\bneck\b/, 'neck'],
|
||||
]
|
||||
const bpFromName = name => (NAME_BP.find(([re]) => re.test(name)) || [])[1] || null
|
||||
|
||||
// Categories the exporters use -> the dataset's body parts, for exercises we invent.
|
||||
const CATEGORY_BP = {
|
||||
chest: 'chest', back: 'back', lats: 'back', shoulders: 'shoulders', delts: 'shoulders',
|
||||
@@ -226,14 +280,26 @@ const CATEGORY_BP = {
|
||||
/* ----------------------------------------------------------- conversion --- */
|
||||
|
||||
const num = v => { const n = parseFloat(String(v ?? '').replace(',', '.')); return isFinite(n) ? n : 0 }
|
||||
// An effort rating out of someone else's export. A blank cell means "not rated" and has to
|
||||
// stay absent rather than becoming 0 — and 0 itself means opposite things on the two scales:
|
||||
// RIR 0 is a set taken to failure and worth keeping, while RPE has no 0 (the scale is 1–10),
|
||||
// so an app writing 0 for "nothing here" must not be read as an effort. Ratings above the
|
||||
// scale are capped rather than dropped — the set was still rated, just written oddly.
|
||||
const effortNum = (raw, zeroMeansRated) => {
|
||||
const s = String(raw ?? '').trim()
|
||||
if (!s) return null
|
||||
const n = parseFloat(s.replace(',', '.'))
|
||||
if (!isFinite(n) || n < 0 || (n === 0 && !zeroMeansRated)) return null
|
||||
return Math.min(10, Math.round(n * 100) / 100)
|
||||
}
|
||||
const LB_TO_KG = 0.45359237
|
||||
const p2 = n => String(n).padStart(2, '0')
|
||||
const MON = { jan: 1, feb: 2, mar: 3, apr: 4, may: 5, jun: 6, jul: 7, aug: 8, sep: 9, oct: 10, nov: 11, dec: 12 }
|
||||
|
||||
/** "2020-12-30 18:51:52" · "2024-03-07" · "22 Dec 2025, 08:00" · "07/03/2024" -> { d, t } */
|
||||
/** "2020-12-30 18:51:52" · "2024-03-07" · "2024/03/07" · "2024.03.07" · "22 Dec 2025, 08:00" · "07/03/2024" -> { d, t } */
|
||||
export function parseWhen(s) {
|
||||
const v = String(s || '').trim()
|
||||
let m = v.match(/^(\d{4})-(\d{1,2})-(\d{1,2})(?:[T ](\d{1,2}):(\d{2}))?/)
|
||||
let m = v.match(/^(\d{4})[-/.](\d{1,2})[-/.](\d{1,2})(?:[T ](\d{1,2}):(\d{2}))?/)
|
||||
if (m) return { d: `${m[1]}-${p2(m[2])}-${p2(m[3])}`, t: hm(m[4], m[5]) }
|
||||
m = v.match(/^(\d{1,2})\s+([A-Za-z]{3})[a-z]*\.?\s+(\d{4})(?:,?\s+(\d{1,2}):(\d{2}))?/)
|
||||
if (m && MON[m[2].toLowerCase()]) return { d: `${m[3]}-${p2(MON[m[2].toLowerCase()])}-${p2(m[1])}`, t: hm(m[4], m[5]) }
|
||||
@@ -288,7 +354,7 @@ export function parseWorkoutCSV(text, { unit = 'kg' } = {}) {
|
||||
const byDate = new Map()
|
||||
const created = new Map()
|
||||
const unmatched = new Set()
|
||||
let sets = 0, skipped = 0, matched = 0, warmups = 0
|
||||
let sets = 0, skipped = 0, matched = 0, warmups = 0, rpeSets = 0, rirSets = 0
|
||||
let sawLb = false, sawKg = false
|
||||
|
||||
const cell = (r, f) => (map[f] === undefined ? '' : String(r[map[f]] ?? '').trim())
|
||||
@@ -318,7 +384,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)
|
||||
@@ -329,7 +396,8 @@ export function parseWorkoutCSV(text, { unit = 'kg' } = {}) {
|
||||
if (!c) {
|
||||
c = {
|
||||
id: 'im' + uid(), n: name.toLowerCase(), custom: true, eq: 'custom', tg: '', desc: '',
|
||||
bp: CATEGORY_BP[cell(r, 'category').toLowerCase()] || (km || (mins && !reps) ? 'cardio' : 'upper legs'),
|
||||
bp: CATEGORY_BP[cell(r, 'category').toLowerCase()] || (km || (mins && !reps) ? 'cardio' : null)
|
||||
|| bpFromName(name.toLowerCase()) || 'upper legs',
|
||||
}
|
||||
created.set(key, c)
|
||||
unmatched.add(name)
|
||||
@@ -341,8 +409,17 @@ 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.
|
||||
if (!isCardio) {
|
||||
const rir = effortNum(cell(r, 'rir'), true)
|
||||
const rpe = rir == null ? effortNum(cell(r, 'rpe'), false) : null
|
||||
if (rir != null) { set.rir = rir; rirSets++ }
|
||||
else if (rpe != null) { set.rpe = rpe; rpeSets++ }
|
||||
}
|
||||
|
||||
let day = byDate.get(when.d)
|
||||
if (!day) {
|
||||
@@ -380,7 +457,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()
|
||||
@@ -401,7 +478,7 @@ export function parseWorkoutCSV(text, { unit = 'kg' } = {}) {
|
||||
matched: new Set([...resolved.values()].filter(Boolean)).size,
|
||||
matchedSets: matched,
|
||||
created: created.size, unmatchedNames: [...unmatched].sort(),
|
||||
sets, skipped, warmups, fileUnit, mixedUnits, converted,
|
||||
sets, skipped, warmups, fileUnit, mixedUnits, converted, rpeSets, rirSets,
|
||||
from: dates[0] || null, to: dates[dates.length - 1] || null,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
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',
|
||||
'8 Aug 2026,Bench Press,80,5,Working',
|
||||
'2026/08/08,Bench Press,85,3,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 },
|
||||
{ w: 80, r: 5, done: true },
|
||||
{ w: 85, r: 3, done: true },
|
||||
])
|
||||
expect(entry.topW).toBe(85)
|
||||
})
|
||||
})
|
||||
|
||||
// gravl writes its units in parentheses ("Weight (kg)", "Set Duration (sec)"). Header text is
|
||||
// normalised before it is matched, so the alias table has to hold the normalised form — an alias
|
||||
// written with the parentheses can never match. Sample rows are from the gravl export in !21.
|
||||
const GRAVL = [
|
||||
'Date,Start Date,Workout,Source,Workout Duration (min),Energy,Exercise,Superset,Set,Set Type,Reps,Weight (kg),Distance (km),Set Duration (sec),Incline,Steps,Effort,Workout Notes',
|
||||
'2026/01/01,1:11 PM,Push Day,,11,11,Chin Up,No,1,Normal,11,11,0,,,,Ideal,felt strong',
|
||||
'2026/01/22,2:22 PM,External Something,APP,21,22,Walking,No,0,Normal,0,0,0,22,,,,',
|
||||
].join('\n')
|
||||
|
||||
describe('gravl export', () => {
|
||||
it('reads slash dates, parenthesised weight and per-set duration', () => {
|
||||
const parsed = parseWorkoutCSV(GRAVL, { unit: 'kg' })
|
||||
|
||||
expect(parsed.skipped).toBe(0)
|
||||
expect(parsed.from).toBe('2026-01-01')
|
||||
expect(parsed.to).toBe('2026-01-22')
|
||||
|
||||
const [lift, cardio] = parsed.workouts
|
||||
expect(lift.name).toBe('Push Day')
|
||||
expect(lift.entries[0].sets).toEqual([{ w: 11, r: 11, done: true }])
|
||||
|
||||
// "Set Duration (sec)" is seconds, not minutes: read as `time` it would land as 22 minutes.
|
||||
expect(cardio.entries[0].sets).toEqual([{ min: 0.4, speed: 0, done: true }])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,148 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { parseWorkoutCSV } from './import-csv.js'
|
||||
import { setLabel, effortOf } from './history.js'
|
||||
|
||||
// Headers as the real exports write them, trimmed to the columns that matter here.
|
||||
const HEVY = 'title,start_time,end_time,exercise_title,set_index,set_type,weight_kg,reps,rpe'
|
||||
const STRONG = 'Date,Workout Name,Exercise Name,Set Order,Weight,Reps,Seconds,RPE'
|
||||
const FITNOTES = 'Date,Exercise,Category,Weight,Reps,Distance,Distance Unit,Time'
|
||||
|
||||
const rows = (head, ...lines) => parseWorkoutCSV([head, ...lines].join('\n'), { unit: 'kg' })
|
||||
// every set of the first workout, in file order
|
||||
const setsOf = p => p.workouts.flatMap(w => w.entries.flatMap(e => e.sets))
|
||||
|
||||
describe('importing effort from another app', () => {
|
||||
it('reads the RPE Hevy writes per set', () => {
|
||||
const p = rows(HEVY,
|
||||
'Push,"12 Jan 2026, 18:00","12 Jan 2026, 19:00",Bench Press (Barbell),0,normal,60,10,8',
|
||||
'Push,"12 Jan 2026, 18:00","12 Jan 2026, 19:00",Bench Press (Barbell),1,normal,60,8,9.5')
|
||||
expect(p.error).toBeUndefined()
|
||||
expect(setsOf(p).map(s => s.rpe)).toEqual([8, 9.5])
|
||||
expect(p.rpeSets).toBe(2)
|
||||
expect(p.rirSets).toBe(0)
|
||||
})
|
||||
|
||||
it('reads the RPE Strong writes per set', () => {
|
||||
const p = rows(STRONG,
|
||||
'2026-01-12 18:00:00,Push,Bench Press (Barbell),1,60,10,0,7.5')
|
||||
expect(setsOf(p)[0].rpe).toBe(7.5)
|
||||
expect(p.rpeSets).toBe(1)
|
||||
})
|
||||
|
||||
it('reads an RIR column when a file has one', () => {
|
||||
const p = rows('Date,Exercise,Weight,Reps,RIR',
|
||||
'2026-01-12,Bench Press,60,10,2',
|
||||
'2026-01-12,Bench Press,60,6,0') // 0 RIR is a real rating: taken to failure
|
||||
expect(setsOf(p).map(s => s.rir)).toEqual([2, 0])
|
||||
expect(p.rirSets).toBe(2)
|
||||
expect(setsOf(p).every(s => s.rpe === undefined)).toBe(true)
|
||||
})
|
||||
|
||||
it('treats a blank rating as not rated, not as zero', () => {
|
||||
const p = rows(HEVY,
|
||||
'Push,"12 Jan 2026, 18:00",,Bench Press (Barbell),0,normal,60,10,',
|
||||
'Push,"12 Jan 2026, 18:00",,Bench Press (Barbell),1,normal,60,10,8')
|
||||
const s = setsOf(p)
|
||||
expect('rpe' in s[0]).toBe(false) // the key is absent, so the set reads as unrated
|
||||
expect(s[1].rpe).toBe(8)
|
||||
expect(p.rpeSets).toBe(1)
|
||||
})
|
||||
|
||||
it('does not read a written-out 0 as an RPE', () => {
|
||||
// RPE runs 1–10, so a 0 in that column is an app saying "nothing here". Reading it as a
|
||||
// rating would stamp an effort on every unrated set in the file.
|
||||
const p = rows(STRONG, '2026-01-12 18:00:00,Push,Bench Press (Barbell),1,60,10,0,0')
|
||||
expect('rpe' in setsOf(p)[0]).toBe(false)
|
||||
expect(p.rpeSets).toBe(0)
|
||||
})
|
||||
|
||||
it('caps a rating that overruns the scale instead of dropping the set', () => {
|
||||
const p = rows(STRONG, '2026-01-12 18:00:00,Push,Bench Press (Barbell),1,60,10,0,12')
|
||||
expect(setsOf(p)[0].rpe).toBe(10)
|
||||
})
|
||||
|
||||
it('ignores junk in the rating column', () => {
|
||||
const p = rows(STRONG,
|
||||
'2026-01-12 18:00:00,Push,Bench Press (Barbell),1,60,10,0,hard',
|
||||
'2026-01-12 18:00:00,Push,Bench Press (Barbell),2,60,10,0,-3')
|
||||
expect(setsOf(p).every(s => !('rpe' in s))).toBe(true)
|
||||
expect(p.rpeSets).toBe(0)
|
||||
expect(p.sets).toBe(2) // the sets still import, just unrated
|
||||
})
|
||||
|
||||
it('keeps one scale per set when a file carries both columns', () => {
|
||||
const p = rows('Date,Exercise,Weight,Reps,RPE,RIR',
|
||||
'2026-01-12,Bench Press,60,10,8,2')
|
||||
const s = setsOf(p)[0]
|
||||
expect(s.rir).toBe(2)
|
||||
expect('rpe' in s).toBe(false)
|
||||
// and it reads back on the scale it was stored with
|
||||
expect(setLabel('0025', s)).toBe('60×10 (RIR 2)')
|
||||
})
|
||||
|
||||
it('puts no effort on a cardio row', () => {
|
||||
// a treadmill row has no third stepper to show it in
|
||||
const p = rows('Date,Exercise,Distance,Distance Unit,Time,RPE',
|
||||
'2026-01-12,Running,5,km,00:30:00,7')
|
||||
const s = setsOf(p)[0]
|
||||
expect(s.min).toBe(30)
|
||||
expect('rpe' in s).toBe(false)
|
||||
expect(p.rpeSets).toBe(0)
|
||||
})
|
||||
|
||||
it('leaves a file without any rating column exactly as it was', () => {
|
||||
const p = rows(FITNOTES, '2026-01-12,Bench Press,Chest,60,10,,,')
|
||||
const s = setsOf(p)[0]
|
||||
expect(s).toEqual({ w: 60, r: 10, done: true })
|
||||
expect(p.rpeSets + p.rirSets).toBe(0)
|
||||
})
|
||||
|
||||
it('carries the rating through the unit conversion', () => {
|
||||
// lb -> kg rewrites the weight; the rating must survive that pass untouched
|
||||
const p = parseWorkoutCSV([
|
||||
'Date,Exercise,Weight,Weight Unit,Reps,RPE',
|
||||
'2026-01-12,Bench Press,135,lbs,10,8',
|
||||
].join('\n'), { unit: 'kg' })
|
||||
const s = setsOf(p)[0]
|
||||
expect(s.w).toBe(61.2)
|
||||
expect(s.rpe).toBe(8)
|
||||
expect('u' in s).toBe(false) // the row's unit marker never reaches the set
|
||||
})
|
||||
})
|
||||
|
||||
// The backup is the whole state serialised, so effort travels with it by construction. This
|
||||
// pins that it stays true — a set losing its rating on a backup round trip would be silent.
|
||||
describe('effort in a backup', () => {
|
||||
// what Settings does on import: the file spread over the defaults. DEF cannot be imported
|
||||
// here (the store reaches for `navigator` at load), so its shape is reproduced literally.
|
||||
const DEF_LIKE = { unit: 'kg', workouts: [], routines: [], effort: null }
|
||||
const roundTrip = S => Object.assign({ ...DEF_LIKE }, JSON.parse(JSON.stringify(S)))
|
||||
|
||||
it('exports and re-imports both scales and the setting', () => {
|
||||
const S = {
|
||||
unit: 'kg', effort: 'rpe', routines: [],
|
||||
workouts: [{
|
||||
d: '2026-01-12', entries: [{ id: '0025', sets: [
|
||||
{ w: 60, r: 10, rpe: 8, done: true },
|
||||
{ w: 60, r: 8, rir: 1, done: true },
|
||||
{ w: 60, r: 12, done: true },
|
||||
] }],
|
||||
}],
|
||||
}
|
||||
const back = roundTrip(S)
|
||||
expect(effortOf(back)).toBe('rpe')
|
||||
const [a, b, c] = back.workouts[0].entries[0].sets
|
||||
expect(a.rpe).toBe(8)
|
||||
expect(b.rir).toBe(1)
|
||||
expect('rpe' in c || 'rir' in c).toBe(false)
|
||||
expect(setLabel('0025', a)).toBe('60×10 (RPE 8)')
|
||||
expect(setLabel('0025', b)).toBe('60×8 (RIR 1)')
|
||||
expect(setLabel('0025', c)).toBe('60×12')
|
||||
})
|
||||
|
||||
it('restores a backup written before the setting existed', () => {
|
||||
// the old flag survives the round trip and still decides the column
|
||||
expect(effortOf(roundTrip({ showRir: true, workouts: [], routines: [] }))).toBe('rir')
|
||||
expect(effortOf(roundTrip({ workouts: [], routines: [] }))).toBe('none')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,111 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { matchExercise, parseWorkoutCSV } from './import-csv.js'
|
||||
import { EXIDX } from './exercises.js'
|
||||
|
||||
// The names other apps actually export, and the catalogue entry each has to land on.
|
||||
// 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',
|
||||
// Hevy's vocabulary, from a real export. It writes the equipment in parentheses and says
|
||||
// "bicep"/"chest fly" where the catalogue says "biceps"/"fly", so the word-bag lands one
|
||||
// word off on every one of these and they arrived as custom exercises.
|
||||
'Bicep Curl (Dumbbell)': '0294',
|
||||
'Bicep Curl (Cable)': '0868',
|
||||
'Chest Fly (Machine)': '0596',
|
||||
'Butterfly (Pec Deck)': '0596',
|
||||
'Incline Chest Fly (Dumbbell)': '0319',
|
||||
'Rear Delt Reverse Fly (Dumbbell)': '0383',
|
||||
'Face Pull': '0203',
|
||||
'Battle Ropes': '0128',
|
||||
'Hack Squat (Machine)': '0743',
|
||||
'Seated Cable Row - Bar Grip': '0218',
|
||||
'Single Arm Lateral Raise (Cable)': '0192',
|
||||
}
|
||||
|
||||
describe('foreign exercise names resolve to the catalogue', () => {
|
||||
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')
|
||||
})
|
||||
|
||||
// SYN rewrote 'machine' -> 'lever' before it ever reached 'smith machine' -> 'smith',
|
||||
// so every Smith-machine name arrived as "smith lever ..." and could not match anything
|
||||
// in the catalogue. The two rules are order-dependent; this pins the order.
|
||||
it('resolves Smith-machine names rather than leaving a stray "lever"', () => {
|
||||
expect(matchExercise('Bench Press (Smith Machine)')).toBe('0748')
|
||||
expect(matchExercise('Overhead Press (Smith Machine)')).toBe('0766')
|
||||
expect(matchExercise('Smith Machine Bench Press')).toBe('0748')
|
||||
})
|
||||
|
||||
// The generic machine -> lever rule still has to work on its own.
|
||||
it('keeps the plain machine alias working', () => {
|
||||
expect(matchExercise('Seated Fly (Machine)')).toBe('0596')
|
||||
})
|
||||
|
||||
it('still refuses to guess', () => {
|
||||
expect(matchExercise('Some Movement I Invented')).toBe(null)
|
||||
expect(matchExercise('')).toBe(null)
|
||||
})
|
||||
})
|
||||
|
||||
// Hevy exports no category column, so every invented exercise took the 'upper legs' default
|
||||
// and a third of an imported history was attributed to the legs in the muscle map. With no
|
||||
// category to read, the body part comes off the name instead.
|
||||
describe('invented exercises get a body part from their name', () => {
|
||||
const HEAD = 'title,start_time,end_time,description,exercise_title,superset_id,exercise_notes,set_index,set_type,weight_kg,reps,distance_km,duration_seconds,rpe'
|
||||
const row = name => `W,"09 Oct 2025, 19:22","09 Oct 2025, 20:22",,"${name}",,,0,normal,40,10,,,`
|
||||
const bpOf = name => {
|
||||
const r = parseWorkoutCSV([HEAD, row(name)].join('\n'), { unit: 'kg' })
|
||||
return r.customEx[0] && r.customEx[0].bp
|
||||
}
|
||||
|
||||
it('reads the body part off names the catalogue does not have', () => {
|
||||
expect(bpOf('Kirk Shrug Machine Thing')).toBe('back')
|
||||
expect(bpOf('Bicep Curl Contraption')).toBe('upper arms')
|
||||
expect(bpOf('Standing Calf Thing')).toBe('lower legs')
|
||||
})
|
||||
|
||||
it('no longer files everything under the legs', () => {
|
||||
expect(bpOf('Some Chest Contraption')).not.toBe('upper legs')
|
||||
expect(bpOf('Some Chest Contraption')).toBe('chest')
|
||||
})
|
||||
|
||||
it('leaves a genuine leg movement on the legs', () => {
|
||||
expect(bpOf('Bulgarian Split Squat Machine v9')).toBe('upper legs')
|
||||
})
|
||||
|
||||
it('still prefers an explicit category column when the file has one', () => {
|
||||
const head = 'Date,Exercise,Category,Weight,Reps'
|
||||
const r = parseWorkoutCSV([head, '2025-10-09,Some Invented Lift,Shoulders,40,10'].join('\n'), { unit: 'kg' })
|
||||
expect(r.customEx[0].bp).toBe('shoulders')
|
||||
})
|
||||
})
|
||||
@@ -9,7 +9,8 @@
|
||||
//
|
||||
// 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'
|
||||
import { todayISO } from './format.js'
|
||||
|
||||
export const MOBILE = import.meta.env.VITE_MOBILE === '1'
|
||||
|
||||
@@ -30,6 +31,27 @@ export async function nativeSave(state) {
|
||||
} catch (e) { /* keep the localStorage copy */ }
|
||||
}
|
||||
|
||||
// "Connect to my server" mode (lib/remote.js): which of local-only / a paired remote account this
|
||||
// device chose, kept in its own file — never inside opengym-state.json, since that file's content
|
||||
// is exactly what pushState() PUTs to a server, and a device's own connection secret must never
|
||||
// travel as if it were training data.
|
||||
const REMOTE_FILE = 'opengym-remote.json'
|
||||
|
||||
export async function loadRemoteFile() {
|
||||
try {
|
||||
const { Filesystem, Directory, Encoding } = await import('@capacitor/filesystem')
|
||||
const r = await Filesystem.readFile({ path: REMOTE_FILE, directory: Directory.Data, encoding: Encoding.UTF8 })
|
||||
return JSON.parse(r.data)
|
||||
} catch (e) { return null } // never decided yet
|
||||
}
|
||||
|
||||
export async function saveRemoteFile(data) {
|
||||
try {
|
||||
const { Filesystem, Directory, Encoding } = await import('@capacitor/filesystem')
|
||||
await Filesystem.writeFile({ path: REMOTE_FILE, directory: Directory.Data, data: JSON.stringify(data), encoding: Encoding.UTF8 })
|
||||
} catch (e) { /* worst case: onboarding asks again next launch */ }
|
||||
}
|
||||
|
||||
// (Re)schedule the workout-day reminder: one repeating notification per weekday that has a
|
||||
// routine in the weekly plan. Cheap enough to run after any state change — the plan or the
|
||||
// reminder time may just have been edited. `interactive` gates the OS permission prompt to
|
||||
@@ -66,3 +88,20 @@ export async function shareExport(json, filename) {
|
||||
const w = await Filesystem.writeFile({ path: filename, directory: Directory.Cache, data: json, encoding: Encoding.UTF8 })
|
||||
await Share.share({ title: filename, url: w.uri })
|
||||
}
|
||||
|
||||
// "Auto-backup on changes" (Settings): a dated snapshot dropped into the Documents folder —
|
||||
// visible in Files (iOS) / a file manager (Android), unlike the private mirror nativeSave keeps
|
||||
// — so whatever the user points at that folder (a sync app, a manual copy) always has something
|
||||
// recent. One file per day; later triggers the same day just overwrite it.
|
||||
export async function writeAutoBackup(state) {
|
||||
try {
|
||||
const { Filesystem, Directory, Encoding } = await import('@capacitor/filesystem')
|
||||
await Filesystem.writeFile({
|
||||
path: `opengym-backup-${todayISO()}.json`,
|
||||
directory: Directory.Documents,
|
||||
data: JSON.stringify(state),
|
||||
encoding: Encoding.UTF8,
|
||||
recursive: true,
|
||||
})
|
||||
} catch (e) { /* best effort — the private mirror in Directory.Data still has the data */ }
|
||||
}
|
||||
@@ -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.
|
||||
@@ -64,26 +65,171 @@ const BY_BODYPART = {
|
||||
'upper legs': { quadriceps: 0.4, hamstring: 0.35, gluteal: 0.25 },
|
||||
'lower legs': { calves: 0.8, tibialis: 0.2 },
|
||||
neck: { trapezius: 1 },
|
||||
'full body': { chest: 0.2, 'upper-back': 0.2, gluteal: 0.2, quadriceps: 0.2, hamstring: 0.1, abs: 0.1 },
|
||||
cardio: {},
|
||||
}
|
||||
|
||||
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]
|
||||
|
||||
function firstPresent(object, keys) {
|
||||
if (!object || typeof object !== 'object') return null
|
||||
for (const key of keys) {
|
||||
if (Object.prototype.hasOwnProperty.call(object, key)) return object[key]
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
// Completed history entries may retain a nested snapshot after their custom exercise is
|
||||
// deleted from the profile catalogue. Prefer that snapshot when the outer entry has no muscle
|
||||
// metadata of its own, while keeping direct/legacy entry fields authoritative when present.
|
||||
function metadataOf(ex) {
|
||||
if (!ex || typeof ex !== 'object') return ex
|
||||
const DIRECT_KEYS = [
|
||||
'muscleGroups', 'muscles', 'targetMuscles', 'muscleWeights',
|
||||
'primaries', 'primaryMuscles', 'primary', 'secondaries', 'secondaryMuscles', 'secondary',
|
||||
]
|
||||
const hasDirect = DIRECT_KEYS.some(key => Object.prototype.hasOwnProperty.call(ex, key))
|
||||
|| [ex.tg, ex.mg, ...arrayOf(ex.sm)].some(value => value != null && value !== '')
|
||||
return !hasDirect && ex.muscleSnapshot && typeof ex.muscleSnapshot === 'object' && !Array.isArray(ex.muscleSnapshot)
|
||||
? ex.muscleSnapshot
|
||||
: ex
|
||||
}
|
||||
|
||||
function explicitPartsOf(ex) {
|
||||
if (!ex || typeof ex !== 'object') return null
|
||||
const primary = firstPresent(ex, ['primaries', 'primaryMuscles', 'primary'])
|
||||
const secondary = firstPresent(ex, ['secondaries', 'secondaryMuscles', 'secondary'])
|
||||
if (primary !== null || secondary !== null) return {
|
||||
primary: arrayOf(primary), secondary: arrayOf(secondary)
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function explicitGroupsOf(ex) {
|
||||
if (!ex || typeof ex !== 'object') return null
|
||||
if (Object.prototype.hasOwnProperty.call(ex, 'muscleGroups')) {
|
||||
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(entry) {
|
||||
const ex = metadataOf(entry)
|
||||
if (!ex || typeof ex !== 'object') return false
|
||||
const parts = explicitPartsOf(ex)
|
||||
if (parts && [...parts.primary, ...parts.secondary].some(value => canonicalMuscle(value))) return true
|
||||
const groups = explicitGroupsOf(ex)
|
||||
if (groups && groups.some(value => canonicalMuscle(value))) return true
|
||||
return [ex.tg, ex.mg, ...arrayOf(smOf(ex))].some(value => canonicalMuscle(value))
|
||||
}
|
||||
|
||||
function canonicalMuscle(value) {
|
||||
const name = String(value || '').toLowerCase().trim()
|
||||
if (MUSCLES.includes(name)) return name
|
||||
return ALIAS[name] || null
|
||||
}
|
||||
|
||||
function canonicalUnique(values) {
|
||||
const out = []
|
||||
for (const value of values || []) {
|
||||
const slug = canonicalMuscle(value)
|
||||
if (slug && !out.includes(slug)) out.push(slug)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** Canonical unique muscle groups, accepting new primary/secondary arrays and legacy fields. */
|
||||
export function muscleGroupsOf(entry) {
|
||||
const ex = metadataOf(entry)
|
||||
const parts = explicitPartsOf(ex)
|
||||
const explicit = explicitGroupsOf(ex)
|
||||
const useParts = parts && [...parts.primary, ...parts.secondary].some(value => canonicalMuscle(value))
|
||||
const source = useParts
|
||||
? [...parts.primary, ...parts.secondary]
|
||||
: explicit || [ex?.tg, ex?.mg, ...arrayOf(smOf(ex))]
|
||||
const out = canonicalUnique(source)
|
||||
if (!out.length && !useParts && explicit == null) {
|
||||
canonicalUnique(Object.keys(BY_BODYPART[ex?.bp] || {})).forEach(slug => out.push(slug))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
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 parts = explicitPartsOf(ex)
|
||||
const explicit = explicitGroupsOf(ex)
|
||||
const useParts = parts && [...parts.primary, ...parts.secondary].some(value => canonicalMuscle(value))
|
||||
if (useParts) {
|
||||
parts.primary.forEach(m => add(m, 1))
|
||||
parts.secondary.forEach(m => add(m, SECONDARY))
|
||||
} else if (explicit) explicit.forEach(m => add(m, 1))
|
||||
else {
|
||||
add(ex.tg, 1)
|
||||
add(ex.mg, SECONDARY)
|
||||
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 }
|
||||
const parts = explicitPartsOf(ex)
|
||||
if (parts) {
|
||||
const primaries = canonicalUnique(parts.primary)
|
||||
const secondaries = canonicalUnique(parts.secondary).filter(slug => !primaries.includes(slug))
|
||||
if (primaries.length) out.primaries = primaries
|
||||
if (secondaries.length) out.secondaries = secondaries
|
||||
}
|
||||
if (hasExplicitMuscleMetadata(ex)) out.muscleGroups = [...muscleGroupsOf(ex)]
|
||||
return out
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 +238,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,174 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { EXIDX, EXDB, smOf } from './exercises.js'
|
||||
import { MUSCLE_NAME, exerciseMuscleSnapshot, hasExplicitMuscleMetadata, loadOf, loadOfWorkouts, matchesMuscleGroups, muscleGroupsOf, musclesOf } from './muscles.js'
|
||||
|
||||
describe('multi-muscle exercise metadata', () => {
|
||||
it('normalizes legacy primary/secondary fields and removes duplicate groups', () => {
|
||||
const ex = { tg: 'pectorals', mg: 'triceps', sm: ['triceps', 'chest'] }
|
||||
expect(muscleGroupsOf(ex)).toEqual(['chest', 'triceps'])
|
||||
expect(musclesOf(ex)).toEqual({ chest: 1, triceps: 0.4 })
|
||||
})
|
||||
|
||||
it('uses explicit multi-group metadata when present and supports legacy single groups', () => {
|
||||
expect(muscleGroupsOf({ muscleGroups: ['chest', 'pectorals', 'triceps'] })).toEqual(['chest', 'triceps'])
|
||||
expect(muscleGroupsOf({ tg: 'chest' })).toEqual(['chest'])
|
||||
expect(MUSCLE_NAME.chest).toBe('Chest')
|
||||
})
|
||||
|
||||
it('falls back to the legacy body-part map when an optional multi-group field is empty', () => {
|
||||
expect(muscleGroupsOf({ bp: 'back', muscleGroups: [] })).toEqual(['upper-back', 'lower-back'])
|
||||
expect(matchesMuscleGroups({ bp: 'back', muscleGroups: [] }, ['lower-back'])).toBe(true)
|
||||
})
|
||||
|
||||
it('matches an exercise when any requested muscle group matches', () => {
|
||||
const ex = { muscleGroups: ['chest', 'triceps'] }
|
||||
expect(matchesMuscleGroups(ex, ['hamstring', 'triceps'])).toBe(true)
|
||||
expect(matchesMuscleGroups(ex, ['hamstring', 'gluteal'])).toBe(false)
|
||||
expect(matchesMuscleGroups(ex, [])).toBe(true)
|
||||
})
|
||||
|
||||
it('counts one effective set per unique group instead of double counting duplicates', () => {
|
||||
expect(loadOf([{ id: 'inline', ex: { tg: 'chest', sm: ['chest', 'triceps'] }, sets: 2 }]))
|
||||
.toEqual({ chest: 2, triceps: 0.8 })
|
||||
})
|
||||
|
||||
it('uses multi-muscle metadata carried by a history entry when its catalogue id is unavailable', () => {
|
||||
expect(loadOfWorkouts([{ entries: [{
|
||||
id: 'deleted-custom', muscleGroups: ['chest', 'chest', 'triceps'],
|
||||
sets: [{ done: true }]
|
||||
}] }])).toEqual({ chest: 1, triceps: 1 })
|
||||
})
|
||||
})
|
||||
|
||||
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: 1,
|
||||
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('explicit multi-primary metadata', () => {
|
||||
it('gives every primary full weight and secondaries supporting weight', () => {
|
||||
const ex = {
|
||||
bp: 'chest', tg: 'abs', mg: 'triceps', sm: ['lower back'],
|
||||
primaries: ['chest', 'triceps', 'chest'], secondaries: ['deltoids', 'triceps']
|
||||
}
|
||||
expect(muscleGroupsOf(ex)).toEqual(['chest', 'triceps', 'deltoids'])
|
||||
expect(musclesOf(ex)).toEqual({ chest: 1, triceps: 1, deltoids: 0.4 })
|
||||
})
|
||||
|
||||
it('keeps the body-part fallback when primaries are absent or explicitly empty', () => {
|
||||
const expected = { 'upper-back': 0.75, 'lower-back': 0.25 }
|
||||
expect(musclesOf({ bp: 'back' })).toEqual(expected)
|
||||
expect(musclesOf({ bp: 'back', primaries: [] })).toEqual(expected)
|
||||
})
|
||||
|
||||
it('keeps legacy metadata when a new array field is present but empty', () => {
|
||||
expect(exerciseMuscleSnapshot({ bp: 'chest', tg: 'abs', primaries: [] })).toMatchObject({
|
||||
muscleGroups: ['abs']
|
||||
})
|
||||
})
|
||||
|
||||
it('provides a conservative Full body fallback for legacy custom exercises', () => {
|
||||
expect(muscleGroupsOf({ bp: 'full body' })).toEqual(['chest', 'upper-back', 'gluteal', 'quadriceps', 'hamstring', 'abs'])
|
||||
expect(musclesOf({ bp: 'full body' })).toEqual({
|
||||
chest: 0.2, 'upper-back': 0.2, gluteal: 0.2, quadriceps: 0.2, hamstring: 0.1, abs: 0.1
|
||||
})
|
||||
})
|
||||
|
||||
it('preserves explicit primary and secondary arrays in history snapshots', () => {
|
||||
expect(exerciseMuscleSnapshot({
|
||||
n: 'Deadlift', bp: 'full body', primaries: ['gluteal', 'lower-back'], secondaries: ['hamstring']
|
||||
})).toMatchObject({
|
||||
n: 'Deadlift', bp: 'full body', primaries: ['gluteal', 'lower-back'], secondaries: ['hamstring'],
|
||||
muscleGroups: ['gluteal', 'lower-back', 'hamstring']
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
describe('map load with warm-up phases', () => {
|
||||
it('excludes warm-up sets from the by-sets-worked map', () => {
|
||||
const w = {
|
||||
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)
|
||||
})
|
||||
})
|
||||
|
||||
// A custom exercise that was deleted from the catalogue survives in history only as the
|
||||
// muscleSnapshot finish-workout wrote. Reading it back is what keeps those sessions in the
|
||||
// body map and in Stats instead of silently contributing nothing.
|
||||
describe('deleted custom exercises', () => {
|
||||
const snapshotEntry = {
|
||||
id: 'gone-custom-1',
|
||||
sets: [{ w: 60, r: 8, done: true }],
|
||||
muscleSnapshot: { n: 'Deleted custom', bp: 'chest', muscleGroups: ['chest'], muscleWeights: { chest: 1 } },
|
||||
}
|
||||
|
||||
it('reads muscle load back out of the snapshot', () => {
|
||||
expect(loadOfWorkouts([{ d: '2026-08-01', entries: [snapshotEntry] }])).toEqual({ chest: 1 })
|
||||
})
|
||||
|
||||
it('reports the snapshot groups as explicit metadata', () => {
|
||||
expect(hasExplicitMuscleMetadata(snapshotEntry)).toBe(true)
|
||||
expect(muscleGroupsOf(snapshotEntry)).toEqual(['chest'])
|
||||
})
|
||||
|
||||
it('still prefers the entry\'s own metadata when it has any', () => {
|
||||
const withOwn = { ...snapshotEntry, tg: 'quadriceps' }
|
||||
expect(muscleGroupsOf(withOwn)).toEqual(['quadriceps'])
|
||||
})
|
||||
})
|
||||
|
||||
// muscles.js counts completed work, so its warm-up boundary has to agree with the one the
|
||||
// session runtime uses — including the legacy spellings phaseForSet normalises.
|
||||
describe('warm-up boundary', () => {
|
||||
it('excludes every phase spelling the workout model treats as a warm-up', () => {
|
||||
const entries = spelling => [{ id: '0025', sets: [{ w: 100, r: 5, done: true, phase: spelling }] }]
|
||||
for (const spelling of ['warmup', 'warm-up', 'warm_up', 'Warmup', ' warmup ']) {
|
||||
expect(loadOfWorkouts([{ d: '2026-08-01', entries: entries(spelling) }]), spelling).toEqual({})
|
||||
}
|
||||
})
|
||||
})
|
||||