Compare commits

...
25 Commits
Author SHA1 Message Date
Duarte Santos 663e0b3987 Release v1.2.4: the effort stats, and bodyweight training that knows it is
v1.2.3 is published, so this is the next patch and everything since it belongs in
this one version: the Effort card and the readings built on it, the bodyweight and
per-side work from issues #31/#32/#33, and two fixes worth naming.

Versions bumped in frontend, api and the Android module (versionCode 5). CHANGELOG
gets the release heading and a Fixed section, README two feature bullets.
2026-08-01 17:07:17 +02:00
Duarte Santos 5a0345c905 Merge bodyweight: issues #31, #32, #33 2026-08-01 17:06:31 +02:00
Duarte Santos 1e86d6ace2 Config sheet: a stepper is not a list-row accessory
Added weight sat inside a list row next to its label, which is fine for a switch
and wrong for a stepper: the control took the width it needed and left the text
column wrapping one word per line. It now gets the same full-width treatment as
sets and reps, with the explanation underneath, and reuses the "Added (kg)" label
the set table already uses.

Also stops a long value overlapping its own title in a list row — flex:none meant
"Follow the routine (Linear progression)" ran straight through "Rule", since the
title's column was already free to shrink to nothing. The value shrinks and
ellipsises instead. Pre-existing, visible in every settings row with a long value.
2026-08-01 17:00:30 +02:00
Duarte Santos a5e360cde5 Settings can register on an invite-only instance too
The sign-in screen asks for an invite code when the server says it needs one. The
same registration reached from Settings never did: it collected a name, called
passkeyRegister without the second argument, and the server refused it. On an
invite-only instance that path could not succeed at all, with nothing on screen to
explain why.

It now reads /api/config and shows the code field on the same terms, reusing the
sign-in screen's own strings so nothing new needs translating.
2026-08-01 16:52:30 +02:00
Duarte Santos 00b4f543a3 Per side stays on reps work, where reps exist
Switching a per-side exercise to Time carried `side` onto the hold: the config
sheet hides the toggle in that mode but still saved the flag, and the workout
badge then halved a rep count a timed set does not have, reading "0 per side".

Dropped at all three points it could get through — the config sheet no longer
writes it outside reps mode, the badge no longer renders outside it, and the plan
serialiser refuses it on a hold so an older file cannot bring it back.
2026-08-01 16:48:57 +02:00
Duarte Santos 4afffcb248 Per side: log the total, show the split
Feedback on #31: a rep count that sometimes means one side and sometimes both is
the ambiguity, not the fix for it. So the logged number is the total — 16 — the
same as every other set in the app, and the split is derived for planning: "8 per
side" on the exercise, "3 × 16 · 8/side" on the plan line and the printed sheet.

Unilateral targets step in twos. 16 → 18 → 20, in the config stepper, the set-row
stepper and the bodyweight rep progression, because half of an odd total is a rep
one side never gets. Turning the flag on rounds an existing target up to even, and
a saved target is stored even for the same reason. An odd total that arrives some
other way still displays honestly, as 8.5 per side, since that is what it means.

Volume loses its per-side case: both sides are already in the number logged.
2026-08-01 16:47:44 +02:00
Duarte Santos c33ff15d9d Bodyweight work, logged the way it is done
A push-up has no weight to type and the app asked for one anyway, on a quarter of
the catalogue. Issues #31, #32 and #33 are the same gap seen from three sides: the
app assumed progress lived in the load.

Two flags on the exercise config rather than two new modes, because "bodyweight"
and "per side" are equally true of a rep set and a timed hold:

  bodyweight — seeded from the equipment the dataset already records. The weight
               column is gone, the set row is one stepper, and the working-weight
               prompt stops asking about a weight that was never there. A belt
               weight reads as an addition and hands progression back to the
               normal policies, because now there is something to add.
  side       — 8 logged is 8 per side. The total is spelled out where there is
               width for it, and volume counts both sides so a routine that moved
               to single-arm work no longer halves itself on the chart.

Bodyweight progression grows reps, and now sets: a rep ceiling sends the reps back
to the bottom and adds a set instead of climbing forever, stopping at six with the
advice it should have given all along. No ceiling keeps the old behaviour exactly.

Both flags are written to a plan only when they disagree with the catalogue, and
absent reads as false, so every existing plan, workout and backup is read
unchanged.
2026-08-01 16:37:52 +02:00
Duarte Santos 8de55ce0d9 Merge pull request #29 from DuarteSantos8/dependabot/npm_and_yarn/frontend/frontend-120fce7b1d
Bump react-router-dom from 7.18.1 to 7.18.2 in /frontend in the frontend group
2026-08-01 14:49:40 +01:00
Duarte Santos aefb13b544 Merge pull request #30 from DuarteSantos8/dependabot/github_actions/actions-6382876e44
Bump docker/login-action from 4.5.2 to 4.6.0 in the actions group
2026-08-01 14:49:21 +01:00
dependabot[bot] 7354b1ca0c Bump docker/login-action from 4.5.2 to 4.6.0 in the actions group
Bumps the actions group with 1 update: [docker/login-action](https://github.com/docker/login-action).


Updates `docker/login-action` from 4.5.2 to 4.6.0
- [Release notes](https://github.com/docker/login-action/releases)
- [Commits](https://github.com/docker/login-action/compare/v4.5.2...v4.6.0)

---
updated-dependencies:
- dependency-name: docker/login-action
  dependency-version: 4.6.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: actions
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-08-01 00:45:03 +00:00
dependabot[bot] f5562febca Bump react-router-dom in /frontend in the frontend group
Bumps the frontend group in /frontend with 1 update: [react-router-dom](https://github.com/remix-run/react-router/tree/HEAD/packages/react-router-dom).


Updates `react-router-dom` from 7.18.1 to 7.18.2
- [Release notes](https://github.com/remix-run/react-router/releases)
- [Changelog](https://github.com/remix-run/react-router/blob/react-router-dom@7.18.2/packages/react-router-dom/CHANGELOG.md)
- [Commits](https://github.com/remix-run/react-router/commits/react-router-dom@7.18.2/packages/react-router-dom)

---
updated-dependencies:
- dependency-name: react-router-dom
  dependency-version: 7.18.2
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: frontend
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-08-01 00:44:33 +00:00
Duarte Santos 1f40230727 Dependabot: majors arrive on their own, and Capacitor waits
Grouping by ecosystem cut the noise, which was the point, but it also let a
Capacitor 7 → 8 migration turn up as "the frontend group, 7 updates" — six
routine siblings and one native-platform migration, indistinguishable in the
list. CI would have gone green on it too: the test workflow builds the web app
and never touches the mobile flavour, so the check would have been reassuring
about something it had not looked at.

Minor and patch stay grouped and quiet. Majors get their own PR per ecosystem,
where being alone is the signal.

Capacitor majors are ignored outright for now: Capacitor 8 declares Node >= 22
and the build host runs 20, and frontend/android and frontend/ios are committed,
so the upgrade also means migrating Gradle/AGP and the Podfile. That is a piece
of work to schedule, not a PR to merge. The comment says to drop the ignore once
the build host moves to Node 22.
2026-07-31 20:35:12 +02:00
Duarte Santos de65e1099a Merge pull request #28 from DuarteSantos8/dependabot/github_actions/actions-d8aa18c958 2026-07-31 19:30:56 +01:00
dependabot[bot] be2fb2dd1d Bump the actions group across 1 directory with 10 updates
Bumps the actions group with 10 updates in the / directory:

| Package | From | To |
| --- | --- | --- |
| [actions/checkout](https://github.com/actions/checkout) | `4` | `7` |
| [docker/setup-qemu-action](https://github.com/docker/setup-qemu-action) | `3` | `4` |
| [docker/setup-buildx-action](https://github.com/docker/setup-buildx-action) | `3` | `4` |
| [docker/login-action](https://github.com/docker/login-action) | `3` | `4.5.2` |
| [docker/metadata-action](https://github.com/docker/metadata-action) | `5` | `6` |
| [docker/build-push-action](https://github.com/docker/build-push-action) | `6` | `7` |
| [actions/setup-node](https://github.com/actions/setup-node) | `4` | `7` |
| [actions/configure-pages](https://github.com/actions/configure-pages) | `5` | `6` |
| [actions/upload-pages-artifact](https://github.com/actions/upload-pages-artifact) | `3` | `5` |
| [actions/deploy-pages](https://github.com/actions/deploy-pages) | `4` | `5` |



Updates `actions/checkout` from 4 to 7
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v4...v7)

Updates `docker/setup-qemu-action` from 3 to 4
- [Release notes](https://github.com/docker/setup-qemu-action/releases)
- [Commits](https://github.com/docker/setup-qemu-action/compare/v3...v4)

Updates `docker/setup-buildx-action` from 3 to 4
- [Release notes](https://github.com/docker/setup-buildx-action/releases)
- [Commits](https://github.com/docker/setup-buildx-action/compare/v3...v4)

Updates `docker/login-action` from 3 to 4.5.2
- [Release notes](https://github.com/docker/login-action/releases)
- [Commits](https://github.com/docker/login-action/compare/v3...v4.5.2)

Updates `docker/metadata-action` from 5 to 6
- [Release notes](https://github.com/docker/metadata-action/releases)
- [Commits](https://github.com/docker/metadata-action/compare/v5...v6)

Updates `docker/build-push-action` from 6 to 7
- [Release notes](https://github.com/docker/build-push-action/releases)
- [Commits](https://github.com/docker/build-push-action/compare/v6...v7)

Updates `actions/setup-node` from 4 to 7
- [Release notes](https://github.com/actions/setup-node/releases)
- [Commits](https://github.com/actions/setup-node/compare/v4...v7)

Updates `actions/configure-pages` from 5 to 6
- [Release notes](https://github.com/actions/configure-pages/releases)
- [Commits](https://github.com/actions/configure-pages/compare/v5...v6)

Updates `actions/upload-pages-artifact` from 3 to 5
- [Release notes](https://github.com/actions/upload-pages-artifact/releases)
- [Commits](https://github.com/actions/upload-pages-artifact/compare/v3...v5)

Updates `actions/deploy-pages` from 4 to 5
- [Release notes](https://github.com/actions/deploy-pages/releases)
- [Commits](https://github.com/actions/deploy-pages/compare/v4...v5)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-version: '7'
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: actions
- dependency-name: actions/configure-pages
  dependency-version: '6'
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: actions
- dependency-name: actions/deploy-pages
  dependency-version: '5'
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: actions
- dependency-name: actions/setup-node
  dependency-version: '7'
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: actions
- dependency-name: actions/upload-pages-artifact
  dependency-version: '5'
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: actions
- dependency-name: docker/build-push-action
  dependency-version: '7'
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: actions
- dependency-name: docker/login-action
  dependency-version: 4.5.2
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: actions
- dependency-name: docker/metadata-action
  dependency-version: '6'
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: actions
- dependency-name: docker/setup-buildx-action
  dependency-version: '4'
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: actions
- dependency-name: docker/setup-qemu-action
  dependency-version: '4'
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: actions
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-07-31 17:34:50 +00:00
Duarte Santos 611987545a Dependabot: don't chase Node majors that were never LTS
The first run offered node:22-alpine → 25-alpine in both Dockerfiles. Odd
majors are Current, not LTS, and stop getting fixes about six months in — for
an image other people self-host that trades stability for nothing. Even majors
are still proposed, so 22 → 24 will show up as a PR, which is the move actually
worth reviewing.
2026-07-31 19:32:57 +02:00
Duarte Santos accc3c1038 Sessions you can actually end, and invite codes worth guessing at
SECURITY.md documented three weaknesses two hours ago. Documented is better than
hidden; fixed is better than documented.

Sessions were a signed cookie the server trusted for a year, and /api/logout
only cleared it in the browser you clicked it in — a copy left on a shared
machine stayed good until it expired, and the only way to end it was deleting
./data/secret and signing out the entire instance. The cookie payload now
carries the user's session version, and POST /api/logout/all bumps it, which
kills every cookie that account ever had. Settings grows a "Sign out
everywhere" row for it.

Cookies already in the wild have no version field. They read as version 0 and
match a user who has never bumped, so nobody is signed out by this deploy and
db.json needs no migration — sv appears lazily on the first bump. Verified
against a server running the new code with a db.json shaped like the live one.

Session default drops from 365 days to 90, overridable with SESSION_DAYS. The
expiry is baked into each cookie when issued, so lowering it never cuts an
existing session short.

Invite codes go from 32 to 64 bits. The app has no rate limiting by design and
/api/register/options answers whether a code is valid, so the code itself has to
be the part not worth guessing. Existing codes still work — validation is an
exact string compare. Unused old ones are worth revoking and reissuing.

What did not change: no rate limiting, still the reverse proxy's job, still the
first caveat in SECURITY.md. requireUserVerification stays false — raising it
could refuse passkeys that already exist, which is a lockout, not a fix.
2026-07-31 19:32:57 +02:00
Duarte Santos 1574811af0 Wake-lock test: stop assigning to a global Node now owns
The first CI run found this, which is the point of having one. Node 21+ defines
globalThis.navigator itself as a getter with no setter, so `globalThis.navigator
= {...}` throws under ESM strict mode. This box runs Node 20, where the global
does not exist and the assignment is fine — the test has never failed locally
and never would.

Only the first test failed: its afterEach deletes the built-in accessor, so
every later test assigned cleanly against the hole it left. defineProperty works
on both runtimes.

Production images are node:22-alpine (web/Dockerfile, api/Dockerfile), so the
version CI runs is the right one and the test was what needed fixing.
2026-07-31 19:21:03 +02:00
Duarte Santos b45dbca2a6 Demo: rate the sets, so the demo shows the effort stats
The live demo is the shop window, and it was the one place the new Effort card
could not appear — demoSeed fabricated twelve weeks of training with no ratings
at all, so every chart that reads effort rendered empty or absent.

The seed now rates about 82% of finished sets, deterministically as before:
effort tracks position in the session and the block's progression, one deload
week sits well away from failure, the first three weeks are written in RPE as if
imported from another app, and one exercise stays unrated throughout so the
partial-coverage case is visible rather than theoretical. Only reps-mode sets
are rated — a reps-in-reserve number on a cardio set would be nonsense.
2026-07-31 19:12:18 +02:00
Duarte Santos 3a120df205 A security policy, and dependency updates that stay quiet
openGym ships passkeys, a signed session cookie and an admin dashboard, and
people run it on the open internet. Until now someone finding a hole had no
option but a public issue.

SECURITY.md documents the model as it actually is, verified against server.js
rather than described from memory: what the session cookie is and how long it
lasts, that it cannot be revoked individually, that ./data is unencrypted and
its holder can mint a session for any account, that there is no rate limiting,
and what changing RP_ID costs. A self-hoster deciding whether to run this for
other people deserves that list up front.

Dependabot is monthly and grouped one PR per ecosystem — a default setup on a
solo project produces noise that stops being read, which is the opposite of the
point. Android/iOS are left out on purpose: Capacitor pins those to the npm
packages, so bumping them separately breaks the mobile build.

Also: api/ has had two dependencies since notifications landed. CONTRIBUTING
still claimed one.
2026-07-31 19:12:18 +02:00
Duarte Santos 051a37abbf CI: actually run the tests, and hold the locales to one key set
There are 159 unit tests and nothing ran them. Both existing workflows fire on
push to main only, so the two outside pull requests merged so far were reviewed
by eye alone. This runs the suite, the build and a locale check on every pull
request.

The locale check exists because of a bug that shipped last week: a feature added
17 strings to de.js only, and the other ten languages fell back to English
mid-sentence with nothing failing anywhere. The checker compares every locale
against the union of all keys, so a string added to one file flags the other ten
instead of passing unnoticed.
2026-07-31 19:12:18 +02:00
Duarte Santos 8440cf3546 Changelog: the effort stats, under Unreleased
v1.2.3 is published, so this is the start of the next version rather than an
amendment to that one — it stays under Unreleased until there is a release to
fold it into.
2026-07-31 19:00:42 +02:00
Duarte Santos b0d176aba3 Merge branch 'effort-stats': the effort ratings, read back as statistics
Sets have carried an RIR/RPE rating since v1.2.3, but nothing ever read it
back — the number lived in the set label and nowhere else. This is the other
half: a trend per week, the spread across the scale, the share of sets taken
near failure, a hard-sets mode on the muscle map, and the rating riding along
on each exercise's own curve.
2026-07-31 18:49:41 +02:00
Duarte Santos 42ac8c8513 Send questions to Discussions, and put a Sponsor button on the repo
Discussions has been enabled since the start and empty since the start, so
every question arrives as an issue — the tracker is carrying design debates and
"how do I" alongside actual bugs, and the answers end up buried in closed
issues where the next person searching won't find them.

The "New issue" screen now offers Q&A, Ideas and Show-and-tell before the
templates, which is where that traffic gets intercepted; README and CONTRIBUTING
say the same thing in a table.

FUNDING.yml does nothing until the account is enrolled in GitHub Sponsors —
GitHub simply doesn't render the button. Stated plainly next to it: openGym is
AGPL, there is no paid tier and nothing is held back for sponsors. A project
that starts selling access to its maintainer stops being the thing people
starred.
2026-07-31 18:43:15 +02:00
Duarte Santos f232b5ba7e Effort stats: the other ten languages, and drop what nothing calls
The card shipped translated into German only, so every other UI language fell
back to the English source strings mid-sentence — the locale files have been
key-for-key identical until now, and they are again (607 each).

exerciseEffort() had no caller: Stats builds its per-exercise curve from the
points it already has, which are filtered by training mode, so the library
version would have drawn a different set of sessions. Removed with its tests
rather than left as a second answer to the same question.
2026-07-31 16:55:21 +02:00
Duarte Santos caaf61d91e Stats: read the effort back — trend, distribution, hard sets, per exercise
Rating a set only paid off inside the set label until now: Stats never looked at
rir/rpe at all. It reads them now, in four places.

lib/effort.js aggregates everything in RIR and converts back to whichever scale the
profile reads. A history that mixes the two — own logs in RIR, an imported file in
RPE — has to average as one series or every chart draws half the data, and RIR is the
internal unit because its zero is real where RPE's floor of 6 is a convention.

- an Effort card: average and share of sets taken near failure, the week-by-week curve
  with the week's volume in the tooltip, and where the sets land on the scale
- the muscle map gains a hard-sets mode: a muscle can lead on volume and still never
  be trained near failure
- Exercise progress carries effort on the top-set dots and as a curve of its own — the
  same weight with more left in the tank is progress a weight-only line draws flat
- LineChart learns an inverted axis (RIR counts down as it gets harder) and per-point marks

Every number carries how much of the training it speaks for: rating is optional and off
by default, so an unrated set is left out rather than read as failure, and an average
waits for five rated sets before it claims to be one.
2026-07-31 16:17:08 +02:00
47 changed files with 2017 additions and 124 deletions

No files matched your search

+10
View File
@@ -34,6 +34,16 @@ RP_NAME=openGym
#
# INVITE_ONLY=1
# ── 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
# ── 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
+4
View File
@@ -0,0 +1,4 @@
# 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
+11 -2
View File
@@ -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.
+102
View File
@@ -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']
+6 -6
View File
@@ -23,22 +23,22 @@ 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
- uses: docker/setup-qemu-action@v4
- uses: docker/setup-buildx-action@v4
- uses: docker/login-action@v3
- 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,7 +47,7 @@ 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 }}
+5 -5
View File
@@ -30,8 +30,8 @@ jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
- uses: actions/checkout@v7
- uses: actions/setup-node@v7
with:
node-version: 22
cache: npm
@@ -44,8 +44,8 @@ jobs:
VITE_DEMO: '1'
VITE_IMG_BASE: ${{ env.DATASET }}/images/
VITE_GIF_BASE: ${{ env.DATASET }}/videos/
- uses: actions/configure-pages@v5
- uses: actions/upload-pages-artifact@v3
- uses: actions/configure-pages@v6
- uses: actions/upload-pages-artifact@v5
with:
path: frontend/dist
@@ -57,4 +57,4 @@ jobs:
url: ${{ steps.deploy.outputs.page_url }}
steps:
- id: deploy
uses: actions/deploy-pages@v4
uses: actions/deploy-pages@v5
+43
View File
@@ -0,0 +1,43 @@
# 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/**'
- '.github/workflows/test.yml'
push:
branches: [main]
paths:
- 'frontend/**'
- '.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
+70
View File
@@ -1,5 +1,75 @@
# Changelog
## 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
+14 -1
View File
@@ -28,7 +28,8 @@ cd frontend && npm test
## Guidelines
- **Keep it dependency-light.** The frontend uses React + Router + Zustand and nothing else;
new deps (front or back) are a hard sell. `api/` has exactly one dependency — keep it that way.
new deps (front or back) are a hard sell. `api/` has two (`@simplewebauthn/server` for passkeys,
`web-push` for notifications) — keep it near that.
- **Match the style.** Small components, clear names, comments only where the "why" isn't obvious.
State lives in the Zustand store (`src/store`); pure helpers in `src/lib`.
- **Don't commit** the exercise media (`media/`) or `data/` — they're gitignored.
@@ -47,6 +48,18 @@ cd frontend && npm test
`src/lib/progression.js` — the policy interface is already there
- Accessibility passes on the workout and chart screens
## Where to ask what
| You have | Goes to |
| --- | --- |
| A question, or self-hosting that won't behave | [Discussions → Q&A](https://github.com/DuarteSantos8/openGym/discussions/categories/q-a) |
| An idea you're not sure about yet | [Discussions → Ideas](https://github.com/DuarteSantos8/openGym/discussions/categories/ideas) |
| A reproducible bug | [Issues](https://github.com/DuarteSantos8/openGym/issues) |
| A change you've already built | A pull request |
An answered question in Q&A is worth more than the same answer buried in a closed issue — the
next person searching "passkey login fails behind my reverse proxy" actually finds it.
## Reporting bugs
Open an issue with: what you did, what you expected, what happened, and your browser/OS. If it's
+18
View File
@@ -66,6 +66,8 @@ as a home-screen app, passkey sign-in, offline support, sync across your phone a
- 📈 **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
- 🏃 **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
@@ -182,11 +184,27 @@ 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.
## Community
- **[Q&A](https://github.com/DuarteSantos8/openGym/discussions/categories/q-a)** — self-hosting
help, passkey/login trouble, "how do I…". Most login problems turn out to be an `RP_ID`/`ORIGIN`
mismatch.
- **[Ideas](https://github.com/DuarteSantos8/openGym/discussions/categories/ideas)** — features
worth talking through before anyone writes code.
- **[Show and tell](https://github.com/DuarteSantos8/openGym/discussions/categories/show-and-tell)**
— your setup, your plan templates, whatever you built on top.
- **[Issues](https://github.com/DuarteSantos8/openGym/issues)** — bugs, and work that's already
been agreed on.
## Contributing
Issues and PRs welcome — see [CONTRIBUTING.md](CONTRIBUTING.md). Good first issues: more starter
plans, exercise-data languages, import from other trackers. **A ⭐ helps more people find it.**
openGym is free and stays free: AGPL, no subscription, no paid tier, nothing held back for
sponsors. If it replaced a paid tracker for you and you want to chip in, the Sponsor button at the
top of the page is there — a star, a bug report or a PR is worth just as much.
## License
[GNU AGPL v3.0](LICENSE) — free and open source. You can self-host, use, modify and share it;
+149
View File
@@ -0,0 +1,149 @@
# Security policy
openGym is a self-hosted app: you run the server, you hold the data. This file says which
versions get fixes, how to report something privately, and — the part most people actually
need — what the app protects you from and what it doesn't.
## Supported versions
Only the **latest release**. Releases are semver tags (`v1.0.0` → `v1.2.3`, see
[CHANGELOG.md](CHANGELOG.md)); there is no LTS or maintenance branch and older tags are never
patched. A fix ships in the next release and in the `latest` images on ghcr.io.
Updating a self-hosted instance:
```bash
git pull && docker compose pull && docker compose up -d
```
## Reporting a vulnerability
Use GitHub's private vulnerability reporting — repo **Security** tab → **Report a vulnerability**:
<https://github.com/DuarteSantos8/openGym/security/advisories/new>
> Private reporting has to be switched on in the repository settings for that link to work
> (Settings → Advanced Security → Private vulnerability reporting). If it 404s, open a normal
> issue saying only *"I need a private channel for a security report"* — no details, no repro —
> and it will be enabled.
Please don't put a working exploit in a public issue if it can be used against other people's
instances. Everything else (a crash you can only trigger on your own box, a scanner warning)
is fine as a normal issue.
Useful in a report: the version or commit, whether you're running the prebuilt images or a
source build, your `RP_ID`/`ORIGIN` and what sits in front of the app, steps to reproduce, and
what an attacker gets out of it.
**On response times:** this is a hobby project maintained by one person alongside school. There
is no SLA and no bounty. Expect days rather than hours, and longer during exam periods. If a
week goes by with no reply, comment on the advisory thread — it's more likely to be a missed
notification than a decision. If a report goes unfixed and you want to disclose publicly, say so
in the thread; there's no objection, and no request to sit on it indefinitely.
## In scope
- **`api/server.js`** — forging or replaying a session cookie, bypassing passkey verification,
reading or writing another user's data through `/api/data`, reaching `/api/admin/*` without
being an admin, or creating a profile without a valid code while `INVITE_ONLY=1`.
- **Frontend** — XSS in the React app, or anything that lets a page on another origin read or
change a signed-in user's data.
- **Shipped deployment config** — `docker-compose.yml`, `web/nginx.conf`, the two Dockerfiles:
a default that exposes something a self-hoster wouldn't expect to be exposed.
- **The published images** `ghcr.io/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** (CSP, HSTS, X-Frame-Options) — `web/nginx.conf` sets none; TLS
and headers are the reverse proxy's job. A concrete attack that headers would have stopped is
still worth reporting.
- Instances served over plain `http://` on a LAN IP. Unsupported: passkeys don't work there and
the session cookie isn't marked `Secure`.
- Scanner output with no working exploit, and `npm audit` findings in build-time
devDependencies (Vite, Vitest, Capacitor CLI) that never reach a running instance.
- The GitHub Pages demo build — it has no backend at all, everything stays in that browser.
- Third-party content: the exercise image/GIF dataset and the CDN it's fetched from.
## Security model
Read this before hosting openGym for anyone other than yourself.
### What it does
- **Passkeys only.** No passwords, no email addresses, no reset flow. Registration and login are
verified server-side by `@simplewebauthn/server` against `expectedOrigin: ORIGIN` and
`expectedRPID: RP_ID`, and the authenticator's signature counter is stored and updated on every
login (`api/server.js:292-318`, `api/server.js:338-358`).
- **Sessions are a signed cookie.** `gymsid` carries `<uid>:<expiry>:<version>` plus an
HMAC-SHA256 tag over it, compared in constant time (`api/server.js:148-161`). The key is 32
random bytes generated on first run and written to `./data/secret` with mode `0600`
(`api/server.js:34-36`). The cookie is `HttpOnly` and `SameSite=Lax`, and gets `Secure` **only
when `ORIGIN` starts with `https:`** (`api/server.js:29`, `api/server.js:198-201`).
- **Any user can end every session they have.** `POST /api/logout/all` increments that account's
session version, and every authenticated request checks the version in the cookie against the
one on the user record (`api/server.js:167`, `api/server.js:187-188`), so every cookie ever
issued for the account — on every device, including a copy someone walked off with — stops
verifying at once. Passkeys are untouched; signing back in works immediately.
- **Data is isolated per user by the session's uid.** `GET`/`PUT /api/data` only ever touch
`state-<uid>.json` for the caller (`api/server.js:375-392`); no route lets a normal user name
another user.
- **Disabling an account takes effect immediately.** Every authenticated request and every login
is rejected for a disabled user (`api/server.js:184`, `api/server.js:357`).
### What it does not do
- **Nothing in `./data` is encrypted.** It holds `db.json` (users, passkey public keys, push
subscriptions, invite codes), one `state-<uid>.json` per user with their complete workout
history and body-weight log, `secret`, and `vapid.json`. Anyone who can read that folder — you,
whoever holds the backups, whoever gets into the host — can read every user's data, and with
`secret` can mint a valid session cookie for any account. **If you host openGym for other
people, they are trusting you exactly as much as they'd trust any server operator.**
- **Admins can read everything.** A user listed in `ADMIN_UIDS` (or flagged `admin: true` in
`db.json`) gets every user's full history and body weight, can disable accounts, and can create
or revoke invite codes (`api/server.js:460-540`). Off by default — a fresh instance has no admin.
- **Sessions can't be revoked one device at a time.** Revocation is per *account*, not per
session: `POST /api/logout/all` kills all of them at once and there is no device list to pick
from. `POST /api/logout` on its own only clears the cookie in that one browser
(`api/server.js:361`) — a copy taken beforehand keeps working. Sessions last **90 days** by
default, settable with `SESSION_DAYS` (`api/server.js:26`); each cookie carries the lifetime it
was issued with, so changing the setting doesn't reach cookies that are already out. Deleting
`./data/secret` and restarting still works as the instance-wide reset, and disabling an account
still locks out one user completely.
- **CSRF protection is `SameSite=Lax` and nothing else.** There are no CSRF tokens.
- **User verification is preferred, not required.** Both handshakes pass
`requireUserVerification: false` (`api/server.js:297`, `api/server.js:343`), so a passkey
released without a biometric or PIN is still accepted. In practice: unlocked device ≈ account
access.
- **One passkey per profile, and no recovery.** Every successful registration creates a *new*
profile (`api/server.js:309-319`); there is no route to attach a second passkey to an existing
one, and no email or reset path. Lose the passkey and that profile is unreachable — only direct
surgery on `./data` gets it back.
- **Disabling someone isn't a ban.** They can still register a fresh profile with a new passkey
unless `INVITE_ONLY=1` is set.
- **HTTPS is required and the app doesn't provide it.** The API container speaks plain HTTP and
nginx listens on `:80` (`web/nginx.conf`); TLS is your reverse proxy's job. Without it,
browsers won't do passkeys at all (except on `http://localhost`) and the session cookie is sent
in the clear.
- **No rate limiting anywhere.** Nothing throttles logins, registrations or writes, and
`POST /api/register/options` still answers whether an invite code is valid
(`api/server.js:272`), so an invite-only instance on the open internet should have a rate limit
in front of it. New invite codes are 16 hex characters — 64 bits (`api/server.js:525`) — which
makes guessing one impractical even unthrottled; codes generated by earlier versions are 8
characters / 32 bits and still work, so revoke and reissue any that are still unused. The only
hard limit
in the app is a 5 MB request body (`api/server.js:27`).
- **A few endpoints answer without a session:** `/api/health` (which includes the total user
count), `/api/config` (whether invite-only is on), `/api/push/public-key`, and the
register/login handshakes.
- **Changing `RP_ID` invalidates every existing passkey.** They were bound to the old hostname
and will fail verification against the new one. The data stays on disk but is unreachable until
each user registers again — as a *new* profile. Choose your hostname before anyone registers.
- **Guest mode never reaches the backend.** That data lives unencrypted in the browser's
`localStorage` and is gone when the browser storage is cleared.
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "gym-api",
"version": "1.2.3",
"version": "1.2.4",
"private": true,
"type": "module",
"main": "server.js",
+41 -10
View File
@@ -19,7 +19,11 @@ const RP_NAME = process.env.RP_NAME || 'openGym';
// code the admin generates. Both default off so a fresh self-hosted instance stays open.
const ADMIN_UIDS = (process.env.ADMIN_UIDS || '').split(',').map(s => s.trim()).filter(Boolean);
const INVITE_ONLY = /^(1|true|yes|on)$/i.test(process.env.INVITE_ONLY || '');
const SESSION_DAYS = 365;
// 90 days keeps someone who trains a few times a week permanently signed in without a stolen
// cookie staying good for a year. Overridable because a family instance and one on the open
// internet don't want the same number. Only affects cookies minted from now on — the expiry is
// baked into each cookie when it's issued, so lowering this never cuts an existing session short.
const SESSION_DAYS = Math.max(1, +(process.env.SESSION_DAYS || 90) || 90);
const MAX_BODY = 5 * 1024 * 1024;
// Secure cookies require HTTPS; over plain http://localhost the flag would drop the cookie
const SECURE = /^https:/i.test(ORIGIN) ? ' Secure;' : '';
@@ -155,9 +159,15 @@ function verifySig(token) {
} catch { return null; }
return payload;
}
function makeSession(uid) {
// Session payload is `<uid>:<expiry>:<version>`, where the version is the user's `sv` counter.
// Bumping `sv` (POST /api/logout/all) makes every cookie ever handed out for that account stop
// verifying, which is the only revocation there was before short of deleting ./data/secret and
// signing out the whole instance. Cookies minted before `sv` existed have no third field and are
// read as version 0, matching a user who has never bumped — they stay valid until they expire.
const sessionVersion = user => user.sv || 0;
function makeSession(user) {
const exp = Date.now() + SESSION_DAYS * 86400000;
return sign(uid + ':' + exp);
return sign(user.id + ':' + exp + ':' + sessionVersion(user));
}
function readSession(req) {
const cookies = Object.fromEntries((req.headers.cookie || '').split(';').map(c => {
@@ -167,10 +177,15 @@ function readSession(req) {
if (!tok) return null;
const payload = verifySig(tok);
if (!payload) return null;
const [uid, exp] = payload.split(':');
const [uid, exp, ver] = payload.split(':');
if (!uid || +exp < Date.now()) return null;
const user = db.users.find(u => u.id === uid) || null;
if (user && user.disabled) return null; // disabled accounts are locked out everywhere
if (!user) return null;
if (user.disabled) return null; // disabled accounts are locked out everywhere
// Missing third field = pre-versioning cookie = version 0. Anything non-numeric is a malformed
// payload (it still had to pass the HMAC, so this is belt-and-braces) and is refused outright.
const claimed = ver === undefined ? 0 : Number(ver);
if (!Number.isInteger(claimed) || claimed !== sessionVersion(user)) return null;
return user;
}
// Guard for /api/admin/* — resolves the caller and 401/403s if they aren't an admin.
@@ -180,8 +195,8 @@ function requireAdmin(req, res) {
if (!isAdmin(user)) { json(res, 403, { error: 'forbidden' }); return null; }
return user;
}
function sessionCookie(uid) {
return `gymsid=${makeSession(uid)}; Path=/; Max-Age=${SESSION_DAYS * 86400}; HttpOnly;${SECURE} SameSite=Lax`;
function sessionCookie(user) {
return `gymsid=${makeSession(user)}; Path=/; Max-Age=${SESSION_DAYS * 86400}; HttpOnly;${SECURE} SameSite=Lax`;
}
const clearCookie = `gymsid=; Path=/; Max-Age=0; HttpOnly;${SECURE} SameSite=Lax`;
@@ -301,7 +316,7 @@ const routes = {
transports: body.credential?.response?.transports || []
});
saveDb();
json(res, 200, { user: { id: user.id, name: user.name, admin: isAdmin(user) } }, { 'Set-Cookie': sessionCookie(user.id) });
json(res, 200, { user: { id: user.id, name: user.name, admin: isAdmin(user) } }, { 'Set-Cookie': sessionCookie(user) });
},
'POST /api/login/options': async (req, res) => {
@@ -340,11 +355,23 @@ const routes = {
const user = db.users.find(u => u.id === cred.userId);
if (!user) return json(res, 500, { error: 'user missing' });
if (user.disabled) return json(res, 403, { error: 'this account has been disabled' });
json(res, 200, { user: { id: user.id, name: user.name, admin: isAdmin(user) } }, { 'Set-Cookie': sessionCookie(user.id) });
json(res, 200, { user: { id: user.id, name: user.name, admin: isAdmin(user) } }, { 'Set-Cookie': sessionCookie(user) });
},
'POST /api/logout': async (req, res) => json(res, 200, { ok: true }, { 'Set-Cookie': clearCookie }),
// "Sign out everywhere" — bumps this user's session version, which invalidates every cookie
// ever issued for the account, on every device, including a copy someone else walked off with.
// The caller's own cookie is cleared here too, so the browser doing it doesn't sit on a token
// it no longer accepts. Passkeys are untouched: signing back in works immediately.
'POST /api/logout/all': async (req, res) => {
const user = readSession(req);
if (!user) return json(res, 401, { error: 'not signed in' });
user.sv = sessionVersion(user) + 1;
saveDb();
json(res, 200, { ok: true }, { 'Set-Cookie': clearCookie });
},
'GET /api/data': async (req, res) => {
const user = readSession(req);
if (!user) return json(res, 401, { error: 'not signed in' });
@@ -491,7 +518,11 @@ const routes = {
const admin = requireAdmin(req, res); if (!admin) return;
const body = await readBody(req);
let code;
do { code = crypto.randomBytes(4).toString('hex').toUpperCase(); } while (db.invites.some(i => i.code === code));
// 16 hex chars = 64 bits, up from 8 chars / 32 bits. The app has no rate limiting by design
// (that's the reverse proxy's job) and /api/register/options tells a caller whether a code is
// good, so the code itself has to be the thing that isn't worth guessing. Codes already in
// db.json keep working — validation is an exact string compare, never a length or format check.
do { code = crypto.randomBytes(8).toString('hex').toUpperCase(); } while (db.invites.some(i => i.code === code));
const invite = { code, note: String(body.note || '').slice(0, 60), createdBy: admin.id, created: new Date().toISOString() };
db.invites.push(invite);
saveDb();
+2 -2
View File
@@ -7,8 +7,8 @@ android {
applicationId "ch.duartesantos.opengym"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 4
versionName "1.2.3"
versionCode 5
versionName "1.2.4"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
aaptOptions {
// Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps.
+15 -11
View File
@@ -1,12 +1,12 @@
{
"name": "opengym-frontend",
"version": "1.2.3",
"version": "1.2.4",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "opengym-frontend",
"version": "1.2.3",
"version": "1.2.4",
"license": "AGPL-3.0-or-later",
"dependencies": {
"@capacitor/core": "^7.6.8",
@@ -15,7 +15,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": {
@@ -2504,6 +2504,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"
},
@@ -4757,9 +4758,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 +4780,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 +5204,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",
+2 -2
View File
@@ -1,7 +1,7 @@
{
"name": "opengym-frontend",
"private": true,
"version": "1.2.3",
"version": "1.2.4",
"type": "module",
"scripts": {
"dev": "vite",
@@ -19,7 +19,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": {
+57
View File
@@ -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.`)
+18 -5
View File
@@ -4,8 +4,15 @@ import { t } from '../lib/i18n.js'
const W = 340 // viewBox width; the svg stretches to its container, height comes from `h`
// points: [{ t: ms, y: num, d?: iso }] sorted by t. opts: { h, unit, color, axes, goal }
export default function LineChart({ points, h = 150, unit = '', color = 'var(--acc)', axes = true, goal = null }) {
// points: [{ t: ms, y: num, d?: iso, m?: 0..1, note?: str }] sorted by t.
// m marks the point — a second reading carried by the same dot (bigger and more solid =
// more of it). Used for effort on the weight curve, where the two belong on one line:
// the same weight with less left in the tank is not the same session.
// note extra text for that point's tooltip.
// opts: { h, unit, color, axes, goal, invert }
// invert flips the y axis, for a scale that counts down as it gets harder (RIR). Without it
// a curve of reps-in-reserve reads upside down, with the hardest sets at the floor.
export default function LineChart({ points, h = 150, unit = '', color = 'var(--acc)', axes = true, goal = null, invert = false }) {
const svgRef = useRef(null)
const wrapRef = useRef(null)
const tipRef = useRef(null)
@@ -42,7 +49,10 @@ export default function LineChart({ points, h = 150, unit = '', color = 'var(--a
const pad = (ymax - ymin) * 0.12; ymin -= pad; ymax += pad
const t0 = pts[0].t, t1 = pts[pts.length - 1].t || t0 + 1
const X = t => (t1 === t0 ? (P.l + W - P.r) / 2 : P.l + (t - t0) / (t1 - t0) * (W - P.l - P.r))
const Y = y => P.t + (1 - (y - ymin) / (ymax - ymin)) * (H - P.t - P.b)
const Y = y => {
const f = (y - ymin) / (ymax - ymin)
return P.t + (invert ? f : 1 - f) * (H - P.t - P.b)
}
const gridlines = []
if (axes) {
@@ -81,7 +91,8 @@ export default function LineChart({ points, h = 150, unit = '', color = 'var(--a
const poly = pts.map(p => X(p.t).toFixed(1) + ',' + Y(p.y).toFixed(1)).join(' ')
const last = pts[pts.length - 1]
const gid = 'g' + Math.round(t0 % 1e7) + '_' + H
const hoverPts = (single ? [points[0]] : points).map(p => ({ x: X(p.t), y: Y(p.y), iso: p.d || isoOf(new Date(p.t)), v: p.y }))
const hoverPts = (single ? [points[0]] : points).map(p => ({ x: X(p.t), y: Y(p.y), iso: p.d || isoOf(new Date(p.t)), v: p.y, note: p.note }))
const marked = points.some(p => p.m != null)
const onMove = e => {
const c = e.touches ? e.touches[0] : e
@@ -111,6 +122,8 @@ export default function LineChart({ points, h = 150, unit = '', color = 'var(--a
</>}
<polygon points={`${P.l},${H - P.b} ${poly} ${X(last.t).toFixed(1)},${H - P.b}`} fill={`url(#${gid})`} />
<polyline points={poly} fill="none" stroke={color} strokeWidth="2.5" strokeLinejoin="round" strokeLinecap="round" />
{marked && pts.map((p, i) => (p.m == null ? null :
<circle key={'m' + i} cx={X(p.t)} cy={Y(p.y)} r={2.4 + p.m * 3} fill={color} opacity={0.3 + p.m * 0.7} />))}
<circle cx={X(last.t)} cy={Y(last.y)} r="4" fill={color} />
{hover && <g>
<line className="cvl" x1={hover.x} y1={P.t} x2={hover.x} y2={H - P.b} stroke="var(--label-3)" strokeWidth="1" strokeDasharray="3 3" />
@@ -119,7 +132,7 @@ export default function LineChart({ points, h = 150, unit = '', color = 'var(--a
</g>}
</svg>
{hover && <div className="ctip" ref={tipRef}>
{fmtDate(hover.iso, true)} · {fmtNum(hover.v)}{unit ? ' ' + unit : ''}
{fmtDate(hover.iso, true)} · {fmtNum(hover.v)}{unit ? ' ' + unit : ''}{hover.note ? ' · ' + hover.note : ''}
</div>}
</div>
)
+8 -1
View File
@@ -233,7 +233,11 @@ h4.sec{
.lrow-m{flex:1;min-width:0;display:flex;flex-direction:column;gap:1px}
.lrow-t{font-size:17px;letter-spacing:-.012em;line-height:1.25}
.lrow-s{font-size:13px;color:var(--label-2);line-height:1.3}
.lrow-v{color:var(--label-2);font-size:17px;letter-spacing:-.012em;flex:none}
/* flex:none would let a long value ("Follow the routine (Linear progression)") run straight
through the title next to it, since the title's column is already free to shrink to nothing.
Letting the value shrink and ellipsise instead keeps the two out of each other's way. */
.lrow-v{color:var(--label-2);font-size:17px;letter-spacing:-.012em;flex:0 1 auto;min-width:0;
overflow:hidden;text-overflow:ellipsis;white-space:nowrap;text-align:right}
.lrow-c{color:var(--label);font-size:15px;flex:none;--icon-stroke:2.4}
.lrow-k{color:var(--acc);font-size:17px;flex:none;--icon-stroke:2.4}
.lrow.danger,.lrow.danger .lrow-t{color:var(--red)}
@@ -784,6 +788,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)}
+58 -5
View File
@@ -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'
}
}
+109
View File
@@ -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))
})
})
+139
View File
@@ -0,0 +1,139 @@
// 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'
// 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) 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 }
+175
View File
@@ -0,0 +1,175 @@
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 })
})
})
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
})
})
+7
View File
@@ -37,6 +37,13 @@ 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
+48 -7
View File
@@ -1,6 +1,7 @@
// Pure helpers over the state object S (ported 1:1 from the vanilla app).
import { todayISO, isoOf, weekKey, fmtNum } from './format.js'
import { isCardio } from './exercises.js'
import { isCardio, isBodyweightEq } from './exercises.js'
import { t } from './i18n.js'
// How an exercise is logged (issue #16). This used to be derived from the body part alone,
// which meant a plank or a farmer's carry could only be timed by filing it under cardio.
@@ -17,6 +18,28 @@ export function modeOf(cfg) {
}
export const isTimed = cfg => modeOf(cfg) === 'time'
// Two flags that ride on top of a mode rather than making new ones (issues #31/#32), because
// "bodyweight" and "per side" are true of a rep set and of a timed hold alike:
// bodyweight — the exercise carries no load of its own, so `w` means *added* weight and is
// asked for only once you say there is some. Seeded from the equipment field.
// Spelled out rather than `bw`, which a workout already uses for the weigh-in
// it was logged at — two different things one letter apart is a bug waiting.
// side — the exercise is unilateral. You still log what you did: 16, the total across
// both sides. The split is derived for planning ("8 per side"), never entered
// — a number that sometimes means one side and sometimes both is the thing
// that made this ambiguous in the first place, and one rep count that always
// means the same thing beats two that need a legend.
// Both are absent on every plan, workout and backup written before they existed, and absent
// reads as false, so nothing needs migrating.
export const isBw = cfg => (cfg && cfg.bodyweight != null ? !!cfg.bodyweight : isBodyweightEq(cfg && cfg.id))
export const isPerSide = cfg => !!(cfg && cfg.side)
// What one side did, for display only. Half of an odd total is shown as it falls (8.5) rather
// than rounded away: it means the sides were not even, which is worth seeing.
export const sideReps = reps => (reps || 0) / 2
// Unilateral work moves in pairs, so its rep target steps by two — 16, 18, 20 — and a total
// that stayed odd would put a rep on one side and not the other.
export const repStep = cfg => (isPerSide(cfg) ? 2 : 1)
// mm:ss for a work duration — seconds alone read badly past a minute ("90 s" vs "1:30").
export function fmtSec(sec) {
const n = Math.max(0, Math.round(Number(sec) || 0))
@@ -69,27 +92,43 @@ const effortTail = s => {
// One-line summary of a logged set. `cfg` carries the mode when the caller has it (a routine
// entry or a workout entry); passing an id alone keeps the old body-part behaviour.
export function setLabel(id, s, cfg) {
const mode = modeOf(cfg || { id })
const c = cfg || { id }
const mode = modeOf(c)
if (mode === 'cardio') return `${s.min || 0} min @ ${fmtNum(s.speed || 0)} km/h`
if (mode === 'time') return fmtSec(s.sec) + (s.w > 0 ? ` · ${fmtNum(s.w)}` : '')
return `${fmtNum(s.w || 0)}×${s.r || 0}` + effortTail(s)
// Bodyweight reads as what you did — "12", or "+10 × 12" once there is a belt involved —
// rather than "0×12", which says a set was performed with no weight and means nothing.
// A per-side set needs no mark here: the number logged is the total, the same as every
// other set in the app.
const reps = s.r || 0
if (isBw({ ...c, id: c.id ?? id })) {
const load = s.w > 0 ? `+${fmtNum(s.w)} × ` : ''
return `${load}${reps}` + effortTail(s)
}
return `${fmtNum(s.w || 0)}×${reps}` + effortTail(s)
}
// Default config for a freshly added exercise.
export function defaultConfig(id, mode) {
const m = mode || modeOf({ id })
if (m === 'cardio') return { sets: 1, min: 20, speed: 8 }
if (m === 'time') return { sets: 3, sec: 45, weight: 0, mode: 'time' }
return { sets: 3, reps: 10, weight: 0, mode: 'reps' }
// Written only when it is true, so a barbell config is byte-for-byte what it was before
// the flag existed and a plan file gains nothing it does not need.
const bw = isBodyweightEq(id) ? { bodyweight: true } : {}
if (m === 'time') return { sets: 3, sec: 45, weight: 0, mode: 'time', ...bw }
return { sets: 3, reps: 10, weight: 0, mode: 'reps', ...bw }
}
// One-line summary of a planned exercise ("3 × 10 · 60 kg"), shared by the routine editor
// and the plan export so a mode is described the same way everywhere.
export function exLine(cfg, unit) {
const mode = modeOf(cfg)
const n = cfg.sets || 1
const load = cfg.weight ? ' · ' + fmtNum(cfg.weight) + ' ' + unit : ''
// Added weight reads as added: "+10 kg" on a dip belt, "60 kg" on a barbell.
const load = cfg.weight ? ' · ' + (isBw(cfg) ? '+' : '') + fmtNum(cfg.weight) + ' ' + unit : ''
if (mode === 'cardio') return `${n} × ${cfg.min || 20} min @ ${fmtNum(cfg.speed || 8)} km/h`
if (mode === 'time') return `${n} × ${fmtSec(cfg.sec || 45)}${load}`
return `${n} × ${cfg.reps}${load}`
// This is the line with room for it, so the split is spelled out: "3 × 16 · 8/side".
const split = isPerSide(cfg) ? ' · ' + t('{0}/side', fmtNum(sideReps(cfg.reps))) : ''
return `${n} × ${cfg.reps}${load}${split}`
}
// Drop superset ids that no longer have an adjacent partner (after unlink/reorder/remove).
@@ -166,6 +205,8 @@ export function buildSets(S, cfg) {
}
export function workoutVolume(w) {
let v = 0
// No special case for unilateral work: a per-side set logs its total, so both sides are
// already in the rep count that arrives here.
w.entries.forEach(e => e.sets.forEach(s => { if (s.done) v += (s.w || 0) * (s.r || 0) }))
return v
}
+79 -2
View File
@@ -1,10 +1,13 @@
import { describe, it, expect } from 'vitest'
import { modeOf, isTimed, fmtSec, setLabel, defaultConfig, buildSets, exLine, workoutVolume, effortOf, stepEffort, capEffort } from './history.js'
import { modeOf, isTimed, fmtSec, setLabel, defaultConfig, buildSets, exLine, workoutVolume, effortOf, stepEffort, capEffort, isBw, isPerSide, sideReps, repStep } from './history.js'
import { EXDB } from './exercises.js'
// Real ids out of the shipped catalogue, so the body-part fallback is exercised for real.
const CARDIO = EXDB.find(e => e.bp === 'cardio').id
const LIFT = EXDB.find(e => e.bp !== 'cardio').id
// A *loaded* lift: the catalogue's first non-cardio entry is a sit-up, which since issue #32
// defaults to bodyweight and would quietly send every label test down the other path.
const LIFT = EXDB.find(e => e.bp !== 'cardio' && e.eq !== 'body weight').id
const BW = EXDB.find(e => e.eq === 'body weight').id
describe('modeOf', () => {
it('falls back to the body part when a plan has no mode — every existing plan keeps working', () => {
@@ -255,9 +258,73 @@ describe('defaultConfig', () => {
expect(defaultConfig(CARDIO)).toEqual({ sets: 1, min: 20, speed: 8 })
expect(defaultConfig(LIFT, 'time')).toEqual({ sets: 3, sec: 45, weight: 0, mode: 'time' })
})
it('seeds the bodyweight flag from the catalogue, and only when it is true', () => {
expect(defaultConfig(BW)).toEqual({ sets: 3, reps: 10, weight: 0, mode: 'reps', bodyweight: true })
expect(defaultConfig(BW, 'time')).toEqual({ sets: 3, sec: 45, weight: 0, mode: 'time', bodyweight: true })
expect('bodyweight' in defaultConfig(LIFT)).toBe(false)
})
})
/* ---------- bodyweight and per side (issues #31/#32/#33) ---------- */
describe('isBw', () => {
it('defaults from the catalogue so an existing plan needs no flag', () => {
expect(isBw({ id: BW })).toBe(true)
expect(isBw({ id: LIFT })).toBe(false)
})
it('lets the config win in both directions — a belt on a dip, a flag on a machine', () => {
expect(isBw({ id: BW, bodyweight: false })).toBe(false)
expect(isBw({ id: LIFT, bodyweight: true })).toBe(true)
})
})
describe('sideReps', () => {
it('halves the logged total, because the total is what was logged', () => {
expect(sideReps(16)).toBe(8)
expect(sideReps(0)).toBe(0)
})
it('shows an odd total as it falls rather than rounding the imbalance away', () => {
expect(sideReps(17)).toBe(8.5)
})
})
describe('exLine — per side never reaches a timed hold', () => {
it('ignores a stale side flag on a hold, which has no reps to split', () => {
expect(exLine({ id: LIFT, sets: 3, sec: 45, mode: 'time', side: true }, 'kg')).toBe('3 × 0:45')
})
})
describe('repStep', () => {
it('steps unilateral work in twos so the total stays splittable', () => {
expect(repStep({ side: true })).toBe(2)
expect(repStep({})).toBe(1)
expect(repStep(null)).toBe(1)
})
})
describe('setLabel — bodyweight', () => {
it('reads as reps alone, because "0×12" describes nothing', () => {
expect(setLabel(BW, { w: 0, r: 12 }, { id: BW })).toBe('12')
})
it('spells out a belt as an addition', () => {
expect(setLabel(BW, { w: 10, r: 8 }, { id: BW })).toBe('+10 × 8')
})
it('logs a per-side set as the plain total, like every other set in the app', () => {
expect(setLabel(BW, { w: 0, r: 16 }, { id: BW, side: true })).toBe('16')
expect(setLabel(LIFT, { w: 20, r: 16 }, { id: LIFT, side: true })).toBe('20×16')
})
it('keeps the effort tail', () => {
expect(setLabel(BW, { w: 0, r: 12, rir: 2 }, { id: BW })).toBe('12 (RIR 2)')
})
})
describe('exLine', () => {
it('shows the split where there is room for it, next to the total you log', () => {
expect(exLine({ id: LIFT, sets: 3, reps: 16, side: true }, 'kg')).toBe('3 × 16 · 8/side')
})
it('marks added weight as added', () => {
expect(exLine({ id: BW, sets: 3, reps: 8, weight: 10 }, 'kg')).toBe('3 × 8 · +10 kg')
})
it('summarises a planned exercise per mode', () => {
expect(exLine({ id: LIFT, sets: 3, reps: 10 }, 'kg')).toBe('3 × 10')
expect(exLine({ id: LIFT, sets: 3, reps: 10, weight: 60 }, 'kg')).toBe('3 × 10 · 60 kg')
@@ -318,4 +385,14 @@ describe('workoutVolume', () => {
] }
expect(workoutVolume(w)).toBe(600)
})
it('needs no per-side case — the logged reps are already both sides (issue #31)', () => {
const w = { entries: [{ id: LIFT, target: { side: true }, sets: [{ w: 20, r: 16, done: true }] }] }
expect(workoutVolume(w)).toBe(320)
})
it('leaves an unloaded bodyweight set at zero volume rather than inventing a number', () => {
const w = { entries: [{ id: BW, target: { bodyweight: true }, sets: [{ w: 0, r: 20, done: true }] }] }
expect(workoutVolume(w)).toBe(0)
})
})
+8 -3
View File
@@ -100,10 +100,15 @@ export function loadOf(items) {
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, sets: (e.sets || []).filter(s => s.done && (!pick || pick(s))).length }))))
/** Load a routine *would* produce, from its planned set counts. */
export const loadOfRoutine = routine =>
+11 -3
View File
@@ -8,8 +8,8 @@
// 2. A clean, printable page (Save as PDF) where a single exercise never splits across
// a page break — each exercise, and each routine that fits, stays in one place.
import { EXIDX } from './exercises.js'
import { modeOf, fmtSec } from './history.js'
import { EXIDX, isBodyweightEq } from './exercises.js'
import { modeOf, fmtSec, isBw, isPerSide, sideReps } from './history.js'
import { uid, todayISO, DAYN, fmtNum, exCount } from './format.js'
import { t } from './i18n.js'
@@ -33,11 +33,17 @@ function cleanEx(e) {
if (e.reps != null) o.reps = e.reps
if (e.weight) o.weight = e.weight
}
// How the exercise is logged travels too (issues #31/#32) — the bodyweight flag only when
// it disagrees with the catalogue, since agreeing is what the other end already assumes.
if (e.bodyweight != null && e.bodyweight !== isBodyweightEq(e.id)) o.bodyweight = e.bodyweight
// Only on reps work — `side` counts reps, and a timed hold has none to split.
if (e.side && mode !== 'time' && mode !== 'cardio') o.side = true
// Progression settings travel with the plan — a shared Greyskull routine that arrives
// without its rule is just a list of weights.
if (e.prog) o.prog = e.prog
if (e.inc > 0) o.inc = e.inc
if (e.repsMin != null) o.repsMin = e.repsMin
if (e.repsMax != null) o.repsMax = e.repsMax
if (e.sg) o.sg = e.sg
return o
}
@@ -145,7 +151,9 @@ function scheme(e, unit) {
return sets > 1 ? `${sets} × ${body}` : body
}
let s = mode === 'time' ? `${sets} × ${fmtSec(e.sec || 45)}` : `${sets} × ${e.reps ?? 10}`
if (e.weight) s += ` · ${fmtNum(e.weight)} ${unit}`
if (e.weight) s += ` · ${isBw(e) ? '+' : ''}${fmtNum(e.weight)} ${unit}`
// A printed plan is read at the rack, so the split earns its four characters.
if (mode !== 'time' && isPerSide(e)) s += ` · ${t('{0}/side', fmtNum(sideReps(e.reps ?? 10)))}`
return s
}
+40 -14
View File
@@ -16,7 +16,7 @@
// · fewer sets than prescribed → miss
// So a session that fell apart can never advance the load as though it had succeeded.
import { modeOf } from './history.js'
import { modeOf, repStep } from './history.js'
import { EXIDX } from './exercises.js'
export const POLICIES = ['off', 'linear', 'greyskull', 'double', 'time']
@@ -60,6 +60,9 @@ export function defaultIncrement(exId, unit) {
return heavy ? 5 : 2.5
}
export const DEFAULT_SEC_INCREMENT = 5
// Where adding another set of push-ups stops being progress and starts being a way to spend
// an evening. Past this the honest advice is load or a harder variation (issue #33).
export const MAX_BW_SETS = 6
// The policy in force for one exercise: its own override, else the routine's default, else
// the mode's default. Reps keeps behaving the way the app always did (all reps → add a step).
@@ -117,6 +120,7 @@ export function readSession(entry, fallback) {
return {
mode, goal, reps,
weight: Math.max(0, ...sets.filter(s => s.done).map(s => s.w || 0)),
count: reps.length, // the dimension bodyweight work grows (#33)
low: reps.length ? Math.min(...reps) : 0,
amrap: reps.length ? reps[reps.length - 1] : 0, // Greyskull's final set
ok: goal > 0 && enough && reps.length > 0 && reps.every(r => r >= goal)
@@ -179,14 +183,28 @@ export function nextPrescription(S, cfg, routine) {
const w = last.weight
// Bodyweight work carries no external load, so there is nothing to add or take away —
// "deload your push-ups to 2.5 kg" is not advice. Progress in reps instead. This runs
// ahead of the individual policies because it is true for all of them; a rep range set on
// top of it simply gets passed once you exceed it, which is the right moment to add load
// or move to a harder variation anyway.
// "deload your push-ups to 2.5 kg" is not advice. Progress in reps instead. This runs ahead
// of the individual policies because it is true for all of them. Note the trigger is the
// *logged* weight, not the `bw` flag: a dip done with a belt has a load to progress and
// belongs on the normal policies, and a barbell lift logged at 0 has nothing to add to.
if (w <= 0) {
const goal = last.goal || cfg.reps || 0
if (last.ok && goal > 0) return { policy, kind: 'up', weight: 0, reps: goal + 1, why: ['Bodyweight — every rep last time, so go for {0} this time.', goal + 1] }
return { policy, kind: 'hold', weight: 0, reps: goal || undefined, why: ['Bodyweight — same target again until every set is clean.'] }
if (!last.ok || goal <= 0) return { policy, kind: 'hold', weight: 0, reps: goal || undefined, why: ['Bodyweight — same target again until every set is clean.'] }
// A ceiling turns "+1 rep forever" into a plan (issue #33). Past the top of the range the
// reps go back to the bottom and a set is added instead, which is how bodyweight work
// actually progresses once a set of 30 push-ups stops being a strength stimulus.
const top = cfg.repsMax > 0 ? cfg.repsMax : 0
if (top > 0 && goal >= top) {
const sets = Math.max(1, cfg.sets || last.count || 1) + 1
const bottom = Math.max(1, Math.min(cfg.reps || top, top))
if (sets <= MAX_BW_SETS) return { policy, kind: 'up', weight: 0, reps: bottom, sets, why: ['{0} reps in every set — add a set and go back to {1}.', goal, bottom] }
// Out of sets worth adding: more volume is no longer the answer, load or a harder
// variation is — and that is a decision for a person, not a policy.
return { policy, kind: 'hold', weight: 0, reps: goal, why: ['{0} sets of {1} — time to add weight or move to a harder variation.', sets - 1, goal] }
}
// Unilateral work steps by two, so the total stays even and both sides get the rep.
const next = goal + repStep(cfg)
return { policy, kind: 'up', weight: 0, reps: next, why: ['Bodyweight — every rep last time, so go for {0} this time.', next] }
}
if (policy === 'double') {
const top = cfg.reps || last.goal || 10
@@ -196,7 +214,7 @@ export function nextPrescription(S, cfg, routine) {
const dw = deloadTo(w, inc)
return { policy, kind: 'deload', weight: dw, reps: bottom, why: ['Stalled {0} sessions — deload to {1} {2}.', stalls, dw, unit] }
}
const aim = Math.min(top, Math.max(bottom, last.low + 1))
const aim = Math.min(top, Math.max(bottom, last.low + repStep(cfg)))
return { policy, kind: 'hold', weight: w, reps: aim, why: ['Same weight — aim for {0} reps this time.', aim] }
}
@@ -231,12 +249,20 @@ export function nextPrescription(S, cfg, routine) {
*/
export function applyPrescription(sets, p) {
if (!p || p.kind === 'off' || p.kind === 'first') return sets
return sets.map(s => {
const out = sets.map(s => {
if (s.done) return s
const out = { ...s }
if (p.weight != null) out.w = p.weight
if (p.reps != null) out.r = p.reps
if (p.sec != null) out.sec = p.sec
return out
const o = { ...s }
if (p.weight != null) o.w = p.weight
if (p.reps != null) o.r = p.reps
if (p.sec != null) o.sec = p.sec
return o
})
// A policy that decided on a set count gets to grow the list — bodyweight progression adds
// a set where a barbell would have added a plate. Only ever upwards, and only by copying a
// row that is already there: a session in progress must not lose a set it has logged.
if (p.sets > out.length) {
const seed = out[out.length - 1]
while (out.length < p.sets) out.push({ ...seed, done: false })
}
return out
}
+60 -1
View File
@@ -1,7 +1,7 @@
import { describe, it, expect } from 'vitest'
import {
readSession, sessionsFor, stallCount, nextPrescription, applyPrescription,
policyFor, defaultIncrement, POLICIES_FOR, DELOAD_AFTER
policyFor, defaultIncrement, POLICIES_FOR, DELOAD_AFTER, MAX_BW_SETS
} from './progression.js'
import { EXDB } from './exercises.js'
@@ -189,6 +189,54 @@ describe('bodyweight exercises', () => {
expect(p.reps).toBe(11)
})
/* A ceiling turns "+1 rep forever" into a plan — issue #33. */
it('climbs to the ceiling one rep at a time', () => {
const p = nextPrescription(bw([[0, 10, 10, 10]]), { ...cfg, repsMax: 15 })
expect(p.kind).toBe('up')
expect(p.reps).toBe(11)
expect(p.sets).toBeUndefined()
})
it('adds a set and restarts the range once the ceiling is reached', () => {
const at15 = hist(LIFT, [[0, 15, 15, 15]], { sets: 3, reps: 15 })
const p = nextPrescription(at15, { ...cfg, reps: 10, repsMax: 15 })
expect(p.kind).toBe('up')
expect(p.sets).toBe(4)
expect(p.reps).toBe(10)
expect(p.weight).toBe(0)
})
it('stops adding sets at the cap and says what to do instead', () => {
const at15 = hist(LIFT, [[0, 15, 15, 15]], { sets: 3, reps: 15 })
const p = nextPrescription(at15, { ...cfg, sets: MAX_BW_SETS, reps: 10, repsMax: 15 })
expect(p.kind).toBe('hold')
expect(p.sets).toBeUndefined()
expect(p.why[0]).toMatch(/harder variation/)
})
it('leaves a belted set to the normal policies — there is a load to add now', () => {
const belted = hist(LIFT, [[10, 10, 10, 10]], { sets: 3, reps: 10 })
const p = nextPrescription(belted, { ...cfg, bodyweight: true, repsMax: 15 })
expect(p.kind).toBe('up')
expect(p.weight).toBeGreaterThan(10)
expect(p.sets).toBeUndefined()
})
it('steps a unilateral total by two, so it lands on 16, 18, 20 (issue #31)', () => {
const at16 = hist(LIFT, [[0, 16, 16, 16]], { sets: 3, reps: 16 })
expect(nextPrescription(at16, { ...cfg, reps: 16, side: true }).reps).toBe(18)
// and by one when it is not
expect(nextPrescription(at16, { ...cfg, reps: 16 }).reps).toBe(17)
})
it('keeps climbing reps forever when no ceiling was set — the old behaviour', () => {
const at30 = hist(LIFT, [[0, 30, 30, 30]], { sets: 3, reps: 30 })
const p = nextPrescription(at30, cfg)
expect(p.kind).toBe('up')
expect(p.reps).toBe(31)
expect(p.sets).toBeUndefined()
})
it('applies to every policy, not just linear', () => {
for (const prog of ['linear', 'greyskull', 'double']) {
const p = nextPrescription(bw([[0, 10, 10, 4], [0, 10, 10, 4], [0, 10, 10, 4]]), { ...cfg, prog })
@@ -390,4 +438,15 @@ describe('applyPrescription', () => {
const timed = [{ sec: 45, w: 0, done: false }]
expect(applyPrescription(timed, { kind: 'up', sec: 50 })).toEqual([{ sec: 50, w: 0, done: false }])
})
it('grows the list when the policy added a set (issue #33)', () => {
const three = [{ w: 0, r: 10, done: false }, { w: 0, r: 10, done: false }, { w: 0, r: 10, done: false }]
const out = applyPrescription(three, { kind: 'up', weight: 0, reps: 10, sets: 4 })
expect(out).toHaveLength(4)
expect(out[3]).toEqual({ w: 0, r: 10, done: false })
})
it('never shrinks a session that has already logged sets', () => {
expect(applyPrescription(sets, { kind: 'up', weight: 60, sets: 1 })).toHaveLength(sets.length)
})
})
+10 -3
View File
@@ -5,6 +5,13 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
// otherwise the tests pass against a one-shot implementation that dies on the first tab switch.
let requests, released, live, listeners, reject
// Node 21+ defines globalThis.navigator itself, as a getter with no setter — a plain
// assignment throws under ESM's strict mode. defineProperty works on both that and the older
// runtimes where the global simply doesn't exist. Production images are node:22-alpine, so
// the tests have to run there too.
const setNavigator = value =>
Object.defineProperty(globalThis, 'navigator', { value, configurable: true, writable: true })
function fakeBrowser() {
requests = 0; released = 0; live = null; reject = false
listeners = new Set()
@@ -13,7 +20,7 @@ function fakeBrowser() {
addEventListener: (type, fn) => { if (type === 'visibilitychange') listeners.add(fn) },
removeEventListener: (type, fn) => { if (type === 'visibilitychange') listeners.delete(fn) },
}
globalThis.navigator = {
setNavigator({
wakeLock: {
request: async () => {
requests++
@@ -24,7 +31,7 @@ function fakeBrowser() {
return s
},
},
}
})
}
const fire = () => listeners.forEach(fn => fn())
const settle = () => new Promise(r => setTimeout(r, 0))
@@ -42,7 +49,7 @@ afterEach(() => { delete globalThis.document; delete globalThis.navigator })
describe('wakeLockSupported', () => {
it('is false when the browser has no wakeLock at all', () => {
globalThis.navigator = {}
setNavigator({})
expect(wakeLockSupported()).toBe(false)
})
it('is true when it does', () => {
+40
View File
@@ -245,6 +245,12 @@ export default {
'Sign out?': 'Abmelden?',
'Your data is synced to your profile first, then cleared from this device.': 'Deine Daten werden erst mit dem Profil synchronisiert, dann von diesem Gerät entfernt.',
'Sign out': 'Abmelden',
'Sign out everywhere?': 'Überall abmelden?',
'Signs this profile out on every device, including this one. Your passkeys keep working — sign in with them again anytime.': 'Meldet dieses Profil auf allen Geräten ab, auch auf diesem. Deine Passkeys bleiben gültig — du kannst dich damit jederzeit wieder anmelden.',
'Sign out everywhere': 'Überall abmelden',
'Ends this profile’s sessions on all your devices.': 'Beendet die Sitzungen dieses Profils auf all deinen Geräten.',
'Signed out on all devices': 'Auf allen Geräten abgemeldet',
'Could not sign out everywhere — you are still signed in.': 'Abmelden auf allen Geräten fehlgeschlagen — du bist weiterhin angemeldet.',
'Guest mode — data lives only in this browser. Create a passkey profile to keep it safe and separate per person.': 'Gastmodus — Daten liegen nur in diesem Browser. Erstelle ein Passkey-Profil, um sie zu sichern und pro Person zu trennen.',
'Create passkey profile': 'Passkey-Profil erstellen',
'Passkeys not supported in this browser.': 'Passkeys werden in diesem Browser nicht unterstützt.',
@@ -531,4 +537,38 @@ export default {
'Easy — warm-up territory': 'Locker — Aufwärmbereich',
'RIR counts the reps you left; RPE reads the same effort off a 10-point scale — so RPE ≈ 10 − RIR. Pick the one you already think in.': 'RIR zählt die Wiederholungen, die du übrig lässt; RPE liest dieselbe Anstrengung auf einer 10er-Skala ab — also RPE ≈ 10 − RIR. Nimm die Skala, in der du ohnehin denkst.',
'The highlighted row is where most working sets land. Sets you have already logged keep their own scale, and nothing else reads the value — progression and estimated 1RM are unaffected.': 'Die hervorgehobene Zeile ist der Bereich, in dem die meisten Arbeitssätze landen. Bereits protokollierte Sätze behalten ihre eigene Skala, und sonst liest den Wert nichts — Progression und geschätztes 1RM bleiben unberührt.',
// --- effort in the stats ---
'Effort': 'Anstrengung',
'how close to failure': 'wie nah am Muskelversagen',
'by hard sets': 'nach harten Sätzen',
'Hard': 'Hart',
'no hard sets': 'keine harten Sätze',
'No hard sets in this period': 'Keine harten Sätze in diesem Zeitraum',
'Every muscle group got at least one hard set in this period.': 'Jede Muskelgruppe hat in diesem Zeitraum mindestens einen harten Satz bekommen.',
'No rated sets in this period.': 'Keine bewerteten Sätze in diesem Zeitraum.',
'average effort': 'durchschnittliche Anstrengung',
'at {0} {1} or harder': 'bei {0} {1} oder härter',
'{0} of {1} finished sets rated': '{0} von {1} erledigten Sätzen bewertet',
'Effort per set is switched off — turn it on in Settings to keep rating.': 'Anstrengung pro Satz ist ausgeschaltet — schalte sie in den Einstellungen ein, um weiter zu bewerten.',
'Week by week': 'Woche für Woche',
'Where the sets land': 'Wo die Sätze landen',
'Most working sets belong close to failure without living there — half at the floor and half at the top average out to a healthy-looking middle.': 'Die meisten Arbeitssätze gehören nah ans Muskelversagen, ohne dort zu wohnen — die Hälfte ganz unten und die Hälfte ganz oben mittelt sich zu einem gesund aussehenden Mittelwert.',
'Average effort per workout': 'Durchschnittliche Anstrengung pro Training',
'A fuller dot means less left in the tank — the same weight at a lower {0} is progress the line alone does not show.': 'Ein vollerer Punkt heißt: weniger im Tank — dasselbe Gewicht bei niedrigerem {0} ist Fortschritt, den die Linie allein nicht zeigt.',
// --- bodyweight & per side ---
'Bodyweight': 'Körpergewicht',
'No weight to enter — just log the reps.': 'Kein Gewicht einzutragen — nur die Wiederholungen.',
'Ask for a weight on every set.': 'Bei jedem Satz nach dem Gewicht fragen.',
'For dips or pull-ups with a belt. Progression then follows the weight.': 'Für Dips oder Klimmzüge mit Gürtel. Die Progression folgt dann dem Gewicht.',
'Reps per side': 'Wiederholungen pro Seite',
'For lunges, single-arm rows and the like.': 'Für Ausfallschritte, einarmiges Rudern und Ähnliches.',
'Top of the range': 'Oberes Ende',
'Reps climb by one whenever every set was clean. Set a ceiling to add sets instead of reps forever.': 'Die Wiederholungen steigen um eine, sobald jeder Satz sauber war. Setz ein oberes Ende, damit irgendwann ein Satz dazukommt statt immer mehr Wiederholungen.',
'Reps climb to {0}, then a set is added and the reps start over. At {1} sets it asks you to add weight instead.': 'Die Wiederholungen steigen bis {0}, dann kommt ein Satz dazu und die Wiederholungen starten neu. Bei {1} Sätzen wird stattdessen nach Zusatzgewicht gefragt.',
'Added ({0})': 'Zusatz ({0})',
'{0}/side': '{0}/Seite',
'{0} reps in every set — add a set and go back to {1}.': '{0} Wiederholungen in jedem Satz — ein Satz kommt dazu, zurück auf {1}.',
'{0} sets of {1} — time to add weight or move to a harder variation.': '{0} Sätze mit {1} — Zeit für Zusatzgewicht oder eine schwerere Variante.',
'{0} per side': '{0} pro Seite',
'You still log the total: {0} is {1} per side.': 'Du trägst weiterhin die Gesamtzahl ein: {0} sind {1} pro Seite.',
}
+41
View File
@@ -231,6 +231,12 @@ export default {
'Sign out?': '¿Cerrar sesión?',
'Your data is synced to your profile first, then cleared from this device.': 'Tus datos se sincronizan primero con tu perfil y luego se borran de este dispositivo.',
'Sign out': 'Cerrar sesión',
'Sign out everywhere?': '¿Cerrar sesión en todos los dispositivos?',
'Signs this profile out on every device, including this one. Your passkeys keep working — sign in with them again anytime.': 'Cierra la sesión de este perfil en todos los dispositivos, incluido este. Tus passkeys siguen funcionando — puedes volver a iniciar sesión con ellas cuando quieras.',
'Sign out everywhere': 'Cerrar sesión en todos los dispositivos',
'Ends this profile’s sessions on all your devices.': 'Termina las sesiones de este perfil en todos tus dispositivos.',
'Signed out on all devices': 'Sesión cerrada en todos los dispositivos',
'Could not sign out everywhere — you are still signed in.': 'No se pudo cerrar la sesión en todos los dispositivos — sigues con la sesión iniciada.',
'Guest mode — data lives only in this browser. Create a passkey profile to keep it safe and separate per person.': 'Modo invitado — los datos viven solo en este navegador. Crea un perfil con passkey para protegerlos y separarlos por persona.',
'Create passkey profile': 'Crear perfil con passkey',
'Passkeys not supported in this browser.': 'Passkeys no compatibles con este navegador.',
@@ -513,4 +519,39 @@ export default {
'Easy — warm-up territory': 'Fácil — zona de calentamiento',
'RIR counts the reps you left; RPE reads the same effort off a 10-point scale — so RPE ≈ 10 − RIR. Pick the one you already think in.': 'El RIR cuenta las repeticiones que dejas; el RPE lee ese mismo esfuerzo en una escala de 10 — así que RPE ≈ 10 − RIR. Elige la que ya usas para pensar.',
'The highlighted row is where most working sets land. Sets you have already logged keep their own scale, and nothing else reads the value — progression and estimated 1RM are unaffected.': 'La fila resaltada es donde cae la mayoría de las series efectivas. Las series ya registradas conservan su escala, y nada más lee el valor: la progresión y el 1RM estimado no cambian.',
// --- effort in the stats ---
'Effort': 'Esfuerzo',
'how close to failure': 'qué tan cerca del fallo',
'by hard sets': 'por series duras',
'Hard': 'Duras',
'no hard sets': 'sin series duras',
'No hard sets in this period': 'Sin series duras en este periodo',
'Every muscle group got at least one hard set in this period.': 'Todos los grupos musculares recibieron al menos una serie dura en este periodo.',
'No rated sets in this period.': 'Ninguna serie valorada en este periodo.',
'average effort': 'esfuerzo medio',
'at {0} {1} or harder': 'a {0} {1} o más duro',
'{0} of {1} finished sets rated': '{0} de {1} series completadas valoradas',
'Effort per set is switched off — turn it on in Settings to keep rating.': 'El esfuerzo por serie está desactivado — actívalo en Ajustes para seguir valorando.',
'Week by week': 'Semana a semana',
'Where the sets land': 'Dónde caen las series',
'Most working sets belong close to failure without living there — half at the floor and half at the top average out to a healthy-looking middle.': 'La mayoría de las series efectivas van cerca del fallo sin vivir allí — la mitad abajo y la mitad arriba dan una media que solo parece sana.',
'Average effort per workout': 'Esfuerzo medio por entrenamiento',
'A fuller dot means less left in the tank — the same weight at a lower {0} is progress the line alone does not show.': 'Un punto más lleno significa menos reserva — el mismo peso con un {0} más bajo es progreso que la línea por sí sola no muestra.',
// --- bodyweight & per side ---
'Bodyweight': 'Peso corporal',
'No weight to enter — just log the reps.': 'No hay peso que introducir — solo registra las reps.',
'Ask for a weight on every set.': 'Pedir un peso en cada serie.',
'For dips or pull-ups with a belt. Progression then follows the weight.': 'Para fondos o dominadas con cinturón. La progresión sigue entonces el peso.',
'Reps per side': 'Reps por lado',
'For lunges, single-arm rows and the like.': 'Para zancadas, remo a una mano y similares.',
'Top of the range': 'Tope del rango',
'Reps climb by one whenever every set was clean. Set a ceiling to add sets instead of reps forever.': 'Las reps suben de una en una cuando todas las series salen limpias. Fija un tope para añadir series en vez de reps para siempre.',
'Reps climb to {0}, then a set is added and the reps start over. At {1} sets it asks you to add weight instead.': 'Las reps suben hasta {0}, luego se añade una serie y las reps vuelven a empezar. Con {1} series te pedirá añadir peso.',
'Added ({0})': 'Extra ({0})',
'{0}/side': '{0}/lado',
'{0} reps in every set — add a set and go back to {1}.': '{0} reps en todas las series: añade una serie y vuelve a {1}.',
'{0} sets of {1} — time to add weight or move to a harder variation.': '{0} series de {1}: toca añadir peso o pasar a una variante más difícil.',
'{0} per side': '{0} por lado',
'You still log the total: {0} is {1} per side.': 'Sigues registrando el total: {0} son {1} por lado.',
}
+41
View File
@@ -231,6 +231,12 @@ export default {
'Sign out?': 'Se déconnecter ?',
'Your data is synced to your profile first, then cleared from this device.': 'Tes données sont d’abord synchronisées avec ton profil, puis effacées de cet appareil.',
'Sign out': 'Se déconnecter',
'Sign out everywhere?': 'Se déconnecter partout ?',
'Signs this profile out on every device, including this one. Your passkeys keep working — sign in with them again anytime.': 'Déconnecte ce profil sur tous les appareils, y compris celui-ci. Tes passkeys restent valides — tu peux te reconnecter avec elles à tout moment.',
'Sign out everywhere': 'Se déconnecter partout',
'Ends this profile’s sessions on all your devices.': 'Met fin aux sessions de ce profil sur tous tes appareils.',
'Signed out on all devices': 'Déconnecté sur tous les appareils',
'Could not sign out everywhere — you are still signed in.': 'Impossible de se déconnecter partout — tu es toujours connecté.',
'Guest mode — data lives only in this browser. Create a passkey profile to keep it safe and separate per person.': 'Mode invité — les données ne vivent que dans ce navigateur. Crée un profil passkey pour les protéger et les séparer par personne.',
'Create passkey profile': 'Créer un profil passkey',
'Passkeys not supported in this browser.': 'Passkeys non prises en charge par ce navigateur.',
@@ -513,4 +519,39 @@ export default {
'Easy — warm-up territory': 'Facile — zone d’échauffement',
'RIR counts the reps you left; RPE reads the same effort off a 10-point scale — so RPE ≈ 10 − RIR. Pick the one you already think in.': 'Le RIR compte les répétitions qu’il te restait ; le RPE lit le même effort sur une échelle de 10 — donc RPE ≈ 10 − RIR. Prends celle dans laquelle tu penses déjà.',
'The highlighted row is where most working sets land. Sets you have already logged keep their own scale, and nothing else reads the value — progression and estimated 1RM are unaffected.': 'La ligne mise en avant est celle où tombent la plupart des séries de travail. Les séries déjà enregistrées gardent leur échelle, et rien d’autre ne lit la valeur — la progression et le 1RM estimé ne changent pas.',
// --- effort in the stats ---
'Effort': 'Effort',
'how close to failure': 'à quel point près de l’échec',
'by hard sets': 'par séries dures',
'Hard': 'Dures',
'no hard sets': 'aucune série dure',
'No hard sets in this period': 'Aucune série dure sur cette période',
'Every muscle group got at least one hard set in this period.': 'Chaque groupe musculaire a eu au moins une série dure sur cette période.',
'No rated sets in this period.': 'Aucune série notée sur cette période.',
'average effort': 'effort moyen',
'at {0} {1} or harder': 'à {0} {1} ou plus dur',
'{0} of {1} finished sets rated': '{0} séries notées sur {1} terminées',
'Effort per set is switched off — turn it on in Settings to keep rating.': 'L’effort par série est désactivé — active-le dans les Réglages pour continuer à noter.',
'Week by week': 'Semaine par semaine',
'Where the sets land': 'Où tombent les séries',
'Most working sets belong close to failure without living there — half at the floor and half at the top average out to a healthy-looking middle.': 'La plupart des séries de travail se placent près de l’échec sans y vivre — la moitié tout en bas et la moitié tout en haut donnent une moyenne qui n’a l’air saine que sur le papier.',
'Average effort per workout': 'Effort moyen par séance',
'A fuller dot means less left in the tank — the same weight at a lower {0} is progress the line alone does not show.': 'Un point plus plein veut dire moins de réserve — le même poids à un {0} plus bas, c’est un progrès que la ligne seule ne montre pas.',
// --- bodyweight & per side ---
'Bodyweight': 'Poids du corps',
'No weight to enter — just log the reps.': 'Pas de poids à saisir — note simplement les répétitions.',
'Ask for a weight on every set.': 'Demander un poids à chaque série.',
'For dips or pull-ups with a belt. Progression then follows the weight.': 'Pour les dips ou les tractions avec une ceinture. La progression suit alors le poids.',
'Reps per side': 'Reps par côté',
'For lunges, single-arm rows and the like.': 'Pour les fentes, les rowings à un bras et compagnie.',
'Top of the range': 'Haut de la fourchette',
'Reps climb by one whenever every set was clean. Set a ceiling to add sets instead of reps forever.': 'Les répétitions montent d’une dès que toutes les séries sont propres. Fixe un plafond pour ajouter une série au lieu de monter les répétitions sans fin.',
'Reps climb to {0}, then a set is added and the reps start over. At {1} sets it asks you to add weight instead.': 'Les répétitions montent jusqu’à {0}, puis une série est ajoutée et les répétitions repartent du bas. À {1} séries, c’est du poids qu’il te demande d’ajouter.',
'Added ({0})': 'Ajouté ({0})',
'{0}/side': '{0}/côté',
'{0} reps in every set — add a set and go back to {1}.': '{0} répétitions sur toutes les séries — une série en plus, retour à {1}.',
'{0} sets of {1} — time to add weight or move to a harder variation.': '{0} séries de {1} — il est temps d’ajouter du poids ou de passer à une variante plus dure.',
'{0} per side': '{0} par côté',
'You still log the total: {0} is {1} per side.': 'Tu notes toujours le total : {0}, c’est {1} par côté.',
}
+41
View File
@@ -231,6 +231,12 @@ export default {
'Sign out?': 'साइन आउट करें?',
'Your data is synced to your profile first, then cleared from this device.': 'डेटा पहले प्रोफ़ाइल से सिंक होता है, फिर इस डिवाइस से हटता है।',
'Sign out': 'साइन आउट',
'Sign out everywhere?': 'हर जगह साइन आउट करें?',
'Signs this profile out on every device, including this one. Your passkeys keep working — sign in with them again anytime.': 'इस डिवाइस सहित सभी डिवाइस पर इस प्रोफ़ाइल को साइन आउट करता है। आपकी पासकी काम करती रहेंगी — उनसे कभी भी दोबारा साइन इन करें।',
'Sign out everywhere': 'हर जगह साइन आउट करें',
'Ends this profile’s sessions on all your devices.': 'आपके सभी डिवाइस पर इस प्रोफ़ाइल के सेशन खत्म करता है।',
'Signed out on all devices': 'सभी डिवाइस पर साइन आउट हो गया',
'Could not sign out everywhere — you are still signed in.': 'हर जगह साइन आउट नहीं हो सका — आप अभी भी साइन इन हैं।',
'Guest mode — data lives only in this browser. Create a passkey profile to keep it safe and separate per person.': 'गेस्ट मोड — डेटा केवल इस ब्राउज़र में रहता है। सुरक्षित रखने और हर व्यक्ति के लिए अलग रखने हेतु पासकी प्रोफ़ाइल बनाएँ।',
'Create passkey profile': 'पासकी प्रोफ़ाइल बनाएँ',
'Passkeys not supported in this browser.': 'इस ब्राउज़र में पासकी समर्थित नहीं।',
@@ -513,4 +519,39 @@ export default {
'Easy — warm-up territory': 'आसान — वॉर्म-अप का दायरा',
'RIR counts the reps you left; RPE reads the same effort off a 10-point scale — so RPE ≈ 10 − RIR. Pick the one you already think in.': 'RIR बचे हुए रेप्स गिनता है; RPE उसी मेहनत को 10 के पैमाने पर पढ़ता है — यानी RPE ≈ 10 − RIR. वही चुनें जिसमें आप पहले से सोचते हैं।',
'The highlighted row is where most working sets land. Sets you have already logged keep their own scale, and nothing else reads the value — progression and estimated 1RM are unaffected.': 'हाइलाइट की गई पंक्ति वह है जहाँ ज़्यादातर वर्किंग सेट आते हैं। पहले दर्ज किए सेट अपना पैमाना बनाए रखते हैं, और इस मान को और कुछ नहीं पढ़ता — प्रोग्रेशन और अनुमानित 1RM अछूते रहते हैं।',
// --- effort in the stats ---
'Effort': 'मेहनत',
'how close to failure': 'फेलियर के कितने पास',
'by hard sets': 'कठिन सेट के हिसाब से',
'Hard': 'कठिन',
'no hard sets': 'कोई कठिन सेट नहीं',
'No hard sets in this period': 'इस अवधि में कोई कठिन सेट नहीं',
'Every muscle group got at least one hard set in this period.': 'इस अवधि में हर मांसपेशी समूह को कम से कम एक कठिन सेट मिला।',
'No rated sets in this period.': 'इस अवधि में कोई आँका गया सेट नहीं।',
'average effort': 'औसत मेहनत',
'at {0} {1} or harder': '{0} {1} या उससे कठिन',
'{0} of {1} finished sets rated': '{1} पूरे किए सेट में से {0} आँके गए',
'Effort per set is switched off — turn it on in Settings to keep rating.': 'हर सेट की मेहनत बंद है — आँकना जारी रखने के लिए सेटिंग्स में चालू करें।',
'Week by week': 'हफ़्ते दर हफ़्ते',
'Where the sets land': 'सेट कहाँ गिरते हैं',
'Most working sets belong close to failure without living there — half at the floor and half at the top average out to a healthy-looking middle.': 'ज़्यादातर वर्किंग सेट फेलियर के पास होने चाहिए, पर वहीं बसे नहीं — आधे सबसे नीचे और आधे सबसे ऊपर मिलकर एक ऐसा औसत बनाते हैं जो सिर्फ़ देखने में सेहतमंद लगता है।',
'Average effort per workout': 'हर वर्कआउट की औसत मेहनत',
'A fuller dot means less left in the tank — the same weight at a lower {0} is progress the line alone does not show.': 'ज़्यादा भरा बिंदु मतलब टंकी में कम बचा — वही वज़न कम {0} पर उठाना वह प्रगति है जो अकेली लाइन नहीं दिखाती।',
// --- bodyweight & per side ---
'Bodyweight': 'बॉडीवेट',
'No weight to enter — just log the reps.': 'कोई वज़न नहीं डालना — बस रेप्स दर्ज करें।',
'Ask for a weight on every set.': 'हर सेट पर वज़न पूछें।',
'For dips or pull-ups with a belt. Progression then follows the weight.': 'बेल्ट के साथ डिप्स या पुल-अप्स के लिए। फिर प्रोग्रेशन वज़न के हिसाब से चलता है।',
'Reps per side': 'प्रति तरफ़ रेप्स',
'For lunges, single-arm rows and the like.': 'लंजेस, सिंगल-आर्म रो और ऐसे व्यायामों के लिए।',
'Top of the range': 'रेंज का ऊपरी सिरा',
'Reps climb by one whenever every set was clean. Set a ceiling to add sets instead of reps forever.': 'हर सेट साफ़ रहने पर रेप्स एक-एक बढ़ते हैं। ऊपरी सीमा तय करें ताकि रेप्स हमेशा बढ़ने के बजाय एक सेट जुड़ जाए।',
'Reps climb to {0}, then a set is added and the reps start over. At {1} sets it asks you to add weight instead.': 'रेप्स {0} तक बढ़ते हैं, फिर एक सेट जुड़ता है और रेप्स दोबारा शुरू होते हैं। {1} सेट पर यह वज़न बढ़ाने को कहता है।',
'Added ({0})': 'अतिरिक्त ({0})',
'{0}/side': '{0}/तरफ़',
'{0} reps in every set — add a set and go back to {1}.': 'हर सेट में {0} रेप्स — एक सेट जोड़ें और वापस {1} पर।',
'{0} sets of {1} — time to add weight or move to a harder variation.': '{1} रेप्स के {0} सेट — अब वज़न बढ़ाने या किसी कठिन वैरिएशन पर जाने का समय।',
'{0} per side': 'प्रति तरफ़ {0}',
'You still log the total: {0} is {1} per side.': 'आप कुल ही दर्ज करते हैं: {0} यानी प्रति तरफ़ {1}।',
}
+41
View File
@@ -231,6 +231,12 @@ export default {
'Sign out?': 'Uscire?',
'Your data is synced to your profile first, then cleared from this device.': 'I dati vengono prima sincronizzati col profilo, poi rimossi da questo dispositivo.',
'Sign out': 'Esci',
'Sign out everywhere?': 'Uscire ovunque?',
'Signs this profile out on every device, including this one. Your passkeys keep working — sign in with them again anytime.': 'Esce da questo profilo su tutti i dispositivi, incluso questo. Le tue passkey restano valide — puoi rientrare con loro quando vuoi.',
'Sign out everywhere': 'Esci ovunque',
'Ends this profile’s sessions on all your devices.': 'Chiude le sessioni di questo profilo su tutti i tuoi dispositivi.',
'Signed out on all devices': 'Uscito da tutti i dispositivi',
'Could not sign out everywhere — you are still signed in.': 'Impossibile uscire ovunque — sei ancora connesso.',
'Guest mode — data lives only in this browser. Create a passkey profile to keep it safe and separate per person.': 'Modalità ospite — i dati vivono solo in questo browser. Crea un profilo passkey per proteggerli e separarli per persona.',
'Create passkey profile': 'Crea profilo passkey',
'Passkeys not supported in this browser.': 'Passkey non supportate in questo browser.',
@@ -513,4 +519,39 @@ export default {
'Easy — warm-up territory': 'Facile — zona riscaldamento',
'RIR counts the reps you left; RPE reads the same effort off a 10-point scale — so RPE ≈ 10 − RIR. Pick the one you already think in.': 'Il RIR conta le ripetizioni che ti restavano; l’RPE legge lo stesso sforzo su una scala da 10 — quindi RPE ≈ 10 − RIR. Scegli quella con cui già ragioni.',
'The highlighted row is where most working sets land. Sets you have already logged keep their own scale, and nothing else reads the value — progression and estimated 1RM are unaffected.': 'La riga evidenziata è dove finisce la maggior parte delle serie di lavoro. Le serie già registrate mantengono la loro scala, e nient’altro legge il valore: progressione e 1RM stimato non cambiano.',
// --- effort in the stats ---
'Effort': 'Sforzo',
'how close to failure': 'quanto vicino al cedimento',
'by hard sets': 'per serie dure',
'Hard': 'Dure',
'no hard sets': 'nessuna serie dura',
'No hard sets in this period': 'Nessuna serie dura in questo periodo',
'Every muscle group got at least one hard set in this period.': 'Ogni gruppo muscolare ha avuto almeno una serie dura in questo periodo.',
'No rated sets in this period.': 'Nessuna serie valutata in questo periodo.',
'average effort': 'sforzo medio',
'at {0} {1} or harder': 'a {0} {1} o più duro',
'{0} of {1} finished sets rated': '{0} di {1} serie completate valutate',
'Effort per set is switched off — turn it on in Settings to keep rating.': 'Lo sforzo per serie è disattivato — attivalo nelle Impostazioni per continuare a valutare.',
'Week by week': 'Settimana per settimana',
'Where the sets land': 'Dove cadono le serie',
'Most working sets belong close to failure without living there — half at the floor and half at the top average out to a healthy-looking middle.': 'La maggior parte delle serie di lavoro sta vicino al cedimento senza viverci — metà in fondo e metà in cima danno una media che sembra sana solo all’apparenza.',
'Average effort per workout': 'Sforzo medio per allenamento',
'A fuller dot means less left in the tank — the same weight at a lower {0} is progress the line alone does not show.': 'Un punto più pieno significa meno riserva — lo stesso peso con un {0} più basso è progresso che la linea da sola non mostra.',
// --- bodyweight & per side ---
'Bodyweight': 'Corpo libero',
'No weight to enter — just log the reps.': 'Nessun peso da inserire — registra solo le ripetizioni.',
'Ask for a weight on every set.': 'Chiedi un peso a ogni serie.',
'For dips or pull-ups with a belt. Progression then follows the weight.': 'Per dip o trazioni con la cintura. La progressione segue poi il peso.',
'Reps per side': 'Ripetizioni per lato',
'For lunges, single-arm rows and the like.': 'Per affondi, rematori a un braccio e simili.',
'Top of the range': 'Massimo dell\'intervallo',
'Reps climb by one whenever every set was clean. Set a ceiling to add sets instead of reps forever.': 'Le ripetizioni salgono di una ogni volta che tutte le serie sono pulite. Imposta un massimo per aggiungere serie invece di ripetizioni all\'infinito.',
'Reps climb to {0}, then a set is added and the reps start over. At {1} sets it asks you to add weight instead.': 'Le ripetizioni salgono fino a {0}, poi viene aggiunta una serie e le ripetizioni ripartono da capo. A {1} serie ti chiede invece di aggiungere peso.',
'Added ({0})': 'Aggiunto ({0})',
'{0}/side': '{0}/lato',
'{0} reps in every set — add a set and go back to {1}.': '{0} ripetizioni in ogni serie — aggiungi una serie e torna a {1}.',
'{0} sets of {1} — time to add weight or move to a harder variation.': '{0} serie da {1} — è ora di aggiungere peso o passare a una variante più difficile.',
'{0} per side': '{0} per lato',
'You still log the total: {0} is {1} per side.': 'Registri sempre il totale: {0} sono {1} per lato.',
}
+41
View File
@@ -231,6 +231,12 @@ export default {
'Sign out?': '로그아웃할까요?',
'Your data is synced to your profile first, then cleared from this device.': '데이터를 먼저 프로필에 동기화한 뒤 이 기기에서 지웁니다.',
'Sign out': '로그아웃',
'Sign out everywhere?': '모든 기기에서 로그아웃할까요?',
'Signs this profile out on every device, including this one. Your passkeys keep working — sign in with them again anytime.': '이 기기를 포함해 모든 기기에서 이 프로필을 로그아웃합니다. 패스키는 그대로 사용할 수 있어 언제든 다시 로그인할 수 있습니다.',
'Sign out everywhere': '모든 기기에서 로그아웃',
'Ends this profile’s sessions on all your devices.': '모든 기기에서 이 프로필의 세션을 종료합니다.',
'Signed out on all devices': '모든 기기에서 로그아웃했습니다',
'Could not sign out everywhere — you are still signed in.': '모든 기기에서 로그아웃하지 못했습니다 — 아직 로그인 상태입니다.',
'Guest mode — data lives only in this browser. Create a passkey profile to keep it safe and separate per person.': '게스트 모드 — 데이터가 이 브라우저에만 저장됩니다. 패스키 프로필을 만들어 안전하게 보관하고 사람별로 분리하세요.',
'Create passkey profile': '패스키 프로필 만들기',
'Passkeys not supported in this browser.': '이 브라우저는 패스키를 지원하지 않습니다.',
@@ -513,4 +519,39 @@ export default {
'Easy — warm-up territory': '가벼움 — 웜업 구간',
'RIR counts the reps you left; RPE reads the same effort off a 10-point scale — so RPE ≈ 10 − RIR. Pick the one you already think in.': 'RIR은 남긴 횟수를 세고, RPE는 같은 노력을 10점 척도로 읽습니다 — 즉 RPE ≈ 10 − RIR. 평소에 쓰던 쪽을 고르세요.',
'The highlighted row is where most working sets land. Sets you have already logged keep their own scale, and nothing else reads the value — progression and estimated 1RM are unaffected.': '강조된 줄은 대부분의 본세트가 들어가는 구간입니다. 이미 기록한 세트는 원래 척도를 그대로 유지하며, 이 값을 읽는 곳은 없습니다 — 프로그레션과 예상 1RM은 영향을 받지 않습니다.',
// --- effort in the stats ---
'Effort': '강도',
'how close to failure': '실패 지점에 얼마나 가까운지',
'by hard sets': '힘든 세트 기준',
'Hard': '힘든 세트',
'no hard sets': '힘든 세트 없음',
'No hard sets in this period': '이 기간에 힘든 세트 없음',
'Every muscle group got at least one hard set in this period.': '이 기간에 모든 근육군이 최소 한 세트는 힘들게 훈련했습니다.',
'No rated sets in this period.': '이 기간에 평가된 세트가 없습니다.',
'average effort': '평균 강도',
'at {0} {1} or harder': '{0} {1} 이상',
'{0} of {1} finished sets rated': '완료한 {1}세트 중 {0}세트 평가됨',
'Effort per set is switched off — turn it on in Settings to keep rating.': '세트당 강도가 꺼져 있습니다 — 계속 평가하려면 설정에서 켜세요.',
'Week by week': '주별 변화',
'Where the sets land': '세트가 몰리는 곳',
'Most working sets belong close to failure without living there — half at the floor and half at the top average out to a healthy-looking middle.': '대부분의 본세트는 실패 지점 가까이에 있어야 하지만 거기 머물면 안 됩니다 — 절반은 바닥에 절반은 꼭대기에 있으면 평균만 건강해 보입니다.',
'Average effort per workout': '운동당 평균 강도',
'A fuller dot means less left in the tank — the same weight at a lower {0} is progress the line alone does not show.': '점이 진할수록 남은 여력이 적다는 뜻입니다 — 같은 무게를 더 낮은 {0}로 든 것은 선만 봐서는 알 수 없는 발전입니다.',
// --- bodyweight & per side ---
'Bodyweight': '맨몸 운동',
'No weight to enter — just log the reps.': '입력할 무게 없음 — 횟수만 기록합니다.',
'Ask for a weight on every set.': '세트마다 무게를 물어봅니다.',
'For dips or pull-ups with a belt. Progression then follows the weight.': '벨트를 차고 하는 딥스나 풀업용. 그러면 점진적 증가가 무게를 따라갑니다.',
'Reps per side': '한쪽당 횟수',
'For lunges, single-arm rows and the like.': '런지, 한팔 로우 같은 운동용.',
'Top of the range': '범위 상한',
'Reps climb by one whenever every set was clean. Set a ceiling to add sets instead of reps forever.': '모든 세트가 깔끔하면 횟수가 하나씩 올라갑니다. 상한을 정하면 횟수를 계속 늘리는 대신 세트를 추가합니다.',
'Reps climb to {0}, then a set is added and the reps start over. At {1} sets it asks you to add weight instead.': '횟수가 {0}회까지 오르면 세트가 하나 추가되고 횟수는 처음부터 다시 시작합니다. {1}세트가 되면 대신 무게를 올리라고 안내합니다.',
'Added ({0})': '추가 ({0})',
'{0}/side': '한쪽 {0}회',
'{0} reps in every set — add a set and go back to {1}.': '모든 세트 {0}회 달성 — 세트를 추가하고 {1}회로 돌아갑니다.',
'{0} sets of {1} — time to add weight or move to a harder variation.': '{1}회 {0}세트 — 이제 무게를 올리거나 더 어려운 동작으로 넘어가세요.',
'{0} per side': '한쪽당 {0}회',
'You still log the total: {0} is {1} per side.': '기록은 그대로 합계로 합니다: {0}회는 한쪽당 {1}회입니다.',
}
+41
View File
@@ -231,6 +231,12 @@ export default {
'Sign out?': 'Wylogować?',
'Your data is synced to your profile first, then cleared from this device.': 'Dane najpierw synchronizują się z profilem, potem są usuwane z urządzenia.',
'Sign out': 'Wyloguj',
'Sign out everywhere?': 'Wylogować wszędzie?',
'Signs this profile out on every device, including this one. Your passkeys keep working — sign in with them again anytime.': 'Wylogowuje ten profil na wszystkich urządzeniach, także na tym. Twoje passkey nadal działają — możesz się nimi zalogować w każdej chwili.',
'Sign out everywhere': 'Wyloguj wszędzie',
'Ends this profile’s sessions on all your devices.': 'Kończy sesje tego profilu na wszystkich Twoich urządzeniach.',
'Signed out on all devices': 'Wylogowano na wszystkich urządzeniach',
'Could not sign out everywhere — you are still signed in.': 'Nie udało się wylogować wszędzie — nadal jesteś zalogowany.',
'Guest mode — data lives only in this browser. Create a passkey profile to keep it safe and separate per person.': 'Tryb gościa — dane żyją tylko w tej przeglądarce. Utwórz profil passkey, aby je zabezpieczyć i rozdzielić na osoby.',
'Create passkey profile': 'Utwórz profil passkey',
'Passkeys not supported in this browser.': 'Passkey nieobsługiwane w tej przeglądarce.',
@@ -513,4 +519,39 @@ export default {
'Easy — warm-up territory': 'Lekko — poziom rozgrzewki',
'RIR counts the reps you left; RPE reads the same effort off a 10-point scale — so RPE ≈ 10 − RIR. Pick the one you already think in.': 'RIR liczy powtórzenia, które zostały w zapasie; RPE odczytuje ten sam wysiłek w skali 10 — czyli RPE ≈ 10 − RIR. Wybierz tę, w której już myślisz.',
'The highlighted row is where most working sets land. Sets you have already logged keep their own scale, and nothing else reads the value — progression and estimated 1RM are unaffected.': 'Wyróżniony wiersz to miejsce, w które trafia większość serii roboczych. Zapisane wcześniej serie zachowują swoją skalę, a wartości nic więcej nie czyta — progresja i szacowany 1RM pozostają bez zmian.',
// --- effort in the stats ---
'Effort': 'Wysiłek',
'how close to failure': 'jak blisko upadku',
'by hard sets': 'wg ciężkich serii',
'Hard': 'Ciężkie',
'no hard sets': 'brak ciężkich serii',
'No hard sets in this period': 'Brak ciężkich serii w tym okresie',
'Every muscle group got at least one hard set in this period.': 'Każda grupa mięśniowa dostała w tym okresie co najmniej jedną ciężką serię.',
'No rated sets in this period.': 'Brak ocenionych serii w tym okresie.',
'average effort': 'średni wysiłek',
'at {0} {1} or harder': 'przy {0} {1} lub ciężej',
'{0} of {1} finished sets rated': 'ocenione serie: {0} z {1} ukończonych',
'Effort per set is switched off — turn it on in Settings to keep rating.': 'Wysiłek na serię jest wyłączony — włącz go w Ustawieniach, aby dalej oceniać.',
'Week by week': 'Tydzień po tygodniu',
'Where the sets land': 'Gdzie lądują serie',
'Most working sets belong close to failure without living there — half at the floor and half at the top average out to a healthy-looking middle.': 'Większość serii roboczych należy blisko upadku, ale nie na nim — połowa na dole i połowa na górze uśrednia się do zdrowo wyglądającego środka.',
'Average effort per workout': 'Średni wysiłek na trening',
'A fuller dot means less left in the tank — the same weight at a lower {0} is progress the line alone does not show.': 'Pełniejsza kropka znaczy mniej zapasu — ten sam ciężar przy niższym {0} to postęp, którego sama linia nie pokazuje.',
// --- bodyweight & per side ---
'Bodyweight': 'Masa własna',
'No weight to enter — just log the reps.': 'Nie podajesz ciężaru — zapisujesz tylko powtórzenia.',
'Ask for a weight on every set.': 'Pytaj o ciężar przy każdej serii.',
'For dips or pull-ups with a belt. Progression then follows the weight.': 'Do dipów albo podciągania z pasem. Progresja idzie wtedy za ciężarem.',
'Reps per side': 'Powtórzenia na stronę',
'For lunges, single-arm rows and the like.': 'Do wykroków, wiosłowania jednorącz i podobnych.',
'Top of the range': 'Górna granica zakresu',
'Reps climb by one whenever every set was clean. Set a ceiling to add sets instead of reps forever.': 'Powtórzenia rosną o jedno, gdy każda seria jest czysta. Ustaw górną granicę, aby zamiast powtórzeń w nieskończoność dochodziły serie.',
'Reps climb to {0}, then a set is added and the reps start over. At {1} sets it asks you to add weight instead.': 'Powtórzenia rosną do {0}, potem dochodzi seria, a powtórzenia zaczynają od nowa. Przy {1} seriach aplikacja poprosi zamiast tego o dodanie ciężaru.',
'Added ({0})': 'Dodane ({0})',
'{0}/side': '{0}/str.',
'{0} reps in every set — add a set and go back to {1}.': 'Wszystkie serie po {0} powt. — dodaj serię i wróć do {1}.',
'{0} sets of {1} — time to add weight or move to a harder variation.': '{0} × {1} powt. — czas dodać ciężar albo przejść na trudniejszy wariant.',
'{0} per side': '{0} na stronę',
'You still log the total: {0} is {1} per side.': 'Nadal zapisujesz łączną liczbę: {0} to {1} na stronę.',
}
+41
View File
@@ -231,6 +231,12 @@ export default {
'Sign out?': 'Terminar sessão?',
'Your data is synced to your profile first, then cleared from this device.': 'Os teus dados são primeiro sincronizados com o perfil e depois apagados deste dispositivo.',
'Sign out': 'Terminar sessão',
'Sign out everywhere?': 'Terminar sessão em todos os dispositivos?',
'Signs this profile out on every device, including this one. Your passkeys keep working — sign in with them again anytime.': 'Termina a sessão deste perfil em todos os dispositivos, incluindo este. As tuas passkeys continuam a funcionar — podes voltar a entrar com elas quando quiseres.',
'Sign out everywhere': 'Terminar sessão em todos os dispositivos',
'Ends this profile’s sessions on all your devices.': 'Termina as sessões deste perfil em todos os teus dispositivos.',
'Signed out on all devices': 'Sessão terminada em todos os dispositivos',
'Could not sign out everywhere — you are still signed in.': 'Não foi possível terminar a sessão em todos os dispositivos — continuas com sessão iniciada.',
'Guest mode — data lives only in this browser. Create a passkey profile to keep it safe and separate per person.': 'Modo convidado — os dados vivem só neste navegador. Cria um perfil com passkey para os proteger e separar por pessoa.',
'Create passkey profile': 'Criar perfil com passkey',
'Passkeys not supported in this browser.': 'Passkeys não suportadas neste navegador.',
@@ -513,4 +519,39 @@ export default {
'Easy — warm-up territory': 'Fácil — zona de aquecimento',
'RIR counts the reps you left; RPE reads the same effort off a 10-point scale — so RPE ≈ 10 − RIR. Pick the one you already think in.': 'O RIR conta as repetições que deixaste; o RPE lê o mesmo esforço numa escala de 10 — ou seja, RPE ≈ 10 − RIR. Escolhe aquela em que já pensas.',
'The highlighted row is where most working sets land. Sets you have already logged keep their own scale, and nothing else reads the value — progression and estimated 1RM are unaffected.': 'A linha destacada é onde cai a maioria das séries de trabalho. As séries já registadas mantêm a sua escala, e mais nada lê o valor — a progressão e o 1RM estimado não mudam.',
// --- effort in the stats ---
'Effort': 'Esforço',
'how close to failure': 'quão perto da falha',
'by hard sets': 'por séries duras',
'Hard': 'Duras',
'no hard sets': 'sem séries duras',
'No hard sets in this period': 'Sem séries duras neste período',
'Every muscle group got at least one hard set in this period.': 'Todos os grupos musculares tiveram pelo menos uma série dura neste período.',
'No rated sets in this period.': 'Nenhuma série avaliada neste período.',
'average effort': 'esforço médio',
'at {0} {1} or harder': 'a {0} {1} ou mais duro',
'{0} of {1} finished sets rated': '{0} de {1} séries concluídas avaliadas',
'Effort per set is switched off — turn it on in Settings to keep rating.': 'O esforço por série está desligado — liga-o nas Definições para continuares a avaliar.',
'Week by week': 'Semana a semana',
'Where the sets land': 'Onde caem as séries',
'Most working sets belong close to failure without living there — half at the floor and half at the top average out to a healthy-looking middle.': 'A maioria das séries de trabalho fica perto da falha sem viver lá — metade no fundo e metade no topo dão uma média que só parece saudável.',
'Average effort per workout': 'Esforço médio por treino',
'A fuller dot means less left in the tank — the same weight at a lower {0} is progress the line alone does not show.': 'Um ponto mais cheio significa menos margem — o mesmo peso com um {0} mais baixo é progresso que a linha sozinha não mostra.',
// --- bodyweight & per side ---
'Bodyweight': 'Peso do corpo',
'No weight to enter — just log the reps.': 'Sem peso para introduzir — regista só as repetições.',
'Ask for a weight on every set.': 'Pedir um peso em cada série.',
'For dips or pull-ups with a belt. Progression then follows the weight.': 'Para dips ou pull-ups com cinto. A progressão passa então a seguir o peso.',
'Reps per side': 'Reps por lado',
'For lunges, single-arm rows and the like.': 'Para afundos, remadas a um braço e afins.',
'Top of the range': 'Topo do intervalo',
'Reps climb by one whenever every set was clean. Set a ceiling to add sets instead of reps forever.': 'As repetições sobem uma sempre que todas as séries saem limpas. Define um limite para acrescentar séries em vez de repetições para sempre.',
'Reps climb to {0}, then a set is added and the reps start over. At {1} sets it asks you to add weight instead.': 'As repetições sobem até {0}, depois acrescenta-se uma série e as repetições recomeçam. Com {1} séries passa a pedir-te peso extra.',
'Added ({0})': 'Extra ({0})',
'{0}/side': '{0}/lado',
'{0} reps in every set — add a set and go back to {1}.': '{0} repetições em todas as séries — acrescenta uma série e volta a {1}.',
'{0} sets of {1} — time to add weight or move to a harder variation.': '{0} séries de {1} — hora de acrescentar peso ou passar a uma variação mais difícil.',
'{0} per side': '{0} por lado',
'You still log the total: {0} is {1} per side.': 'Continuas a registar o total: {0} são {1} por lado.',
}
+41
View File
@@ -231,6 +231,12 @@ export default {
'Sign out?': 'Выйти?',
'Your data is synced to your profile first, then cleared from this device.': 'Данные сначала синхронизируются с профилем, затем удаляются с устройства.',
'Sign out': 'Выйти',
'Sign out everywhere?': 'Выйти на всех устройствах?',
'Signs this profile out on every device, including this one. Your passkeys keep working — sign in with them again anytime.': 'Завершает сеансы этого профиля на всех устройствах, включая это. Ключи доступа продолжают работать — по ним можно войти снова в любой момент.',
'Sign out everywhere': 'Выйти на всех устройствах',
'Ends this profile’s sessions on all your devices.': 'Завершает сеансы этого профиля на всех твоих устройствах.',
'Signed out on all devices': 'Выход выполнен на всех устройствах',
'Could not sign out everywhere — you are still signed in.': 'Не удалось выйти на всех устройствах — ты всё ещё в системе.',
'Guest mode — data lives only in this browser. Create a passkey profile to keep it safe and separate per person.': 'Гостевой режим — данные живут только в этом браузере. Создай профиль с ключом доступа, чтобы защитить их и разделить по людям.',
'Create passkey profile': 'Создать профиль с ключом доступа',
'Passkeys not supported in this browser.': 'Ключи доступа не поддерживаются в этом браузере.',
@@ -513,4 +519,39 @@ export default {
'Easy — warm-up territory': 'Легко — разминочная зона',
'RIR counts the reps you left; RPE reads the same effort off a 10-point scale — so RPE ≈ 10 − RIR. Pick the one you already think in.': 'RIR считает повторения, оставшиеся в запасе; RPE читает то же усилие по 10-балльной шкале — то есть RPE ≈ 10 − RIR. Выберите ту, в которой вы уже думаете.',
'The highlighted row is where most working sets land. Sets you have already logged keep their own scale, and nothing else reads the value — progression and estimated 1RM are unaffected.': 'Выделенная строка — это диапазон, в который попадает большинство рабочих подходов. Уже записанные подходы сохраняют свою шкалу, и больше это значение нигде не используется: прогрессия и расчётный 1ПМ не меняются.',
// --- effort in the stats ---
'Effort': 'Усилие',
'how close to failure': 'насколько близко к отказу',
'by hard sets': 'по тяжёлым подходам',
'Hard': 'Тяжёлые',
'no hard sets': 'нет тяжёлых подходов',
'No hard sets in this period': 'Нет тяжёлых подходов за этот период',
'Every muscle group got at least one hard set in this period.': 'За этот период каждая группа мышц получила хотя бы один тяжёлый подход.',
'No rated sets in this period.': 'Нет оценённых подходов за этот период.',
'average effort': 'среднее усилие',
'at {0} {1} or harder': 'при {0} {1} или тяжелее',
'{0} of {1} finished sets rated': 'оценено {0} из {1} выполненных подходов',
'Effort per set is switched off — turn it on in Settings to keep rating.': 'Усилие в подходе выключено — включи его в настройках, чтобы продолжать оценивать.',
'Week by week': 'Неделя за неделей',
'Where the sets land': 'Куда попадают подходы',
'Most working sets belong close to failure without living there — half at the floor and half at the top average out to a healthy-looking middle.': 'Большинство рабочих подходов должны идти близко к отказу, но не жить на нём — половина внизу и половина вверху дают среднее, которое лишь выглядит здоровым.',
'Average effort per workout': 'Среднее усилие за тренировку',
'A fuller dot means less left in the tank — the same weight at a lower {0} is progress the line alone does not show.': 'Более плотная точка означает меньше запаса — тот же вес при меньшем {0} это прогресс, которого одна линия не показывает.',
// --- bodyweight & per side ---
'Bodyweight': 'Собственный вес',
'No weight to enter — just log the reps.': 'Вес вводить не нужно — записывай только повторения.',
'Ask for a weight on every set.': 'Спрашивать вес в каждом подходе.',
'For dips or pull-ups with a belt. Progression then follows the weight.': 'Для отжиманий на брусьях или подтягиваний с поясом. Тогда прогрессия идёт по весу.',
'Reps per side': 'Повторения на сторону',
'For lunges, single-arm rows and the like.': 'Для выпадов, тяг одной рукой и тому подобного.',
'Top of the range': 'Верх диапазона',
'Reps climb by one whenever every set was clean. Set a ceiling to add sets instead of reps forever.': 'Повторения растут на одно, когда все подходы чистые. Задай потолок, чтобы вместо бесконечного роста повторений добавлялся подход.',
'Reps climb to {0}, then a set is added and the reps start over. At {1} sets it asks you to add weight instead.': 'Повторения растут до {0}, затем добавляется подход и повторения начинаются заново. Дойдя до {1} подходов, приложение предложит вместо этого добавить вес.',
'Added ({0})': 'Доп. ({0})',
'{0}/side': '{0}/стор.',
'{0} reps in every set — add a set and go back to {1}.': 'Во всех подходах {0} повт. — добавь подход и вернись к {1}.',
'{0} sets of {1} — time to add weight or move to a harder variation.': '{0} × {1} — пора добавить вес или перейти к более сложному варианту.',
'{0} per side': '{0} на сторону',
'You still log the total: {0} is {1} per side.': 'Ты по-прежнему записываешь общее число: {0} — это {1} на сторону.',
}
+41
View File
@@ -231,6 +231,12 @@ export default {
'Sign out?': 'Çıkış yapılsın mı?',
'Your data is synced to your profile first, then cleared from this device.': 'Verilerin önce profiline eşitlenir, sonra bu cihazdan silinir.',
'Sign out': 'Çıkış yap',
'Sign out everywhere?': 'Her yerden çıkış yapılsın mı?',
'Signs this profile out on every device, including this one. Your passkeys keep working — sign in with them again anytime.': 'Bu profili, bu cihaz dahil tüm cihazlarda oturumdan çıkarır. Geçiş anahtarların çalışmaya devam eder — istediğin zaman onlarla tekrar giriş yapabilirsin.',
'Sign out everywhere': 'Her yerden çıkış yap',
'Ends this profile’s sessions on all your devices.': 'Bu profilin tüm cihazlarındaki oturumlarını sonlandırır.',
'Signed out on all devices': 'Tüm cihazlarda çıkış yapıldı',
'Could not sign out everywhere — you are still signed in.': 'Her yerden çıkış yapılamadı — hâlâ giriş yapmış durumdasın.',
'Guest mode — data lives only in this browser. Create a passkey profile to keep it safe and separate per person.': 'Misafir modu — veriler sadece bu tarayıcıda yaşar. Güvende tutmak ve kişi başına ayırmak için geçiş anahtarlı profil oluştur.',
'Create passkey profile': 'Geçiş anahtarlı profil oluştur',
'Passkeys not supported in this browser.': 'Bu tarayıcıda geçiş anahtarları desteklenmiyor.',
@@ -513,4 +519,39 @@ export default {
'Easy — warm-up territory': 'Kolay — ısınma bölgesi',
'RIR counts the reps you left; RPE reads the same effort off a 10-point scale — so RPE ≈ 10 − RIR. Pick the one you already think in.': 'RIR yedekte bıraktığın tekrarları sayar; RPE aynı eforu 10’luk ölçekte okur — yani RPE ≈ 10 − RIR. Zaten hangisiyle düşünüyorsan onu seç.',
'The highlighted row is where most working sets land. Sets you have already logged keep their own scale, and nothing else reads the value — progression and estimated 1RM are unaffected.': 'Vurgulanan satır, çalışma setlerinin çoğunun denk geldiği yerdir. Daha önce kaydettiğin setler kendi ölçeğini korur ve bu değeri başka hiçbir şey okumaz — ilerleme ve tahmini 1RM etkilenmez.',
// --- effort in the stats ---
'Effort': 'Zorluk',
'how close to failure': 'tükenmeye ne kadar yakın',
'by hard sets': 'zor setlere göre',
'Hard': 'Zor',
'no hard sets': 'zor set yok',
'No hard sets in this period': 'Bu dönemde zor set yok',
'Every muscle group got at least one hard set in this period.': 'Bu dönemde her kas grubu en az bir zor set aldı.',
'No rated sets in this period.': 'Bu dönemde puanlanmış set yok.',
'average effort': 'ortalama zorluk',
'at {0} {1} or harder': '{0} {1} veya daha zor',
'{0} of {1} finished sets rated': '{1} tamamlanan setin {0} tanesi puanlandı',
'Effort per set is switched off — turn it on in Settings to keep rating.': 'Set başına zorluk kapalı — puanlamaya devam etmek için Ayarlar’dan aç.',
'Week by week': 'Hafta hafta',
'Where the sets land': 'Setler nereye düşüyor',
'Most working sets belong close to failure without living there — half at the floor and half at the top average out to a healthy-looking middle.': 'Çalışma setlerinin çoğu tükenmeye yakın olmalı ama orada yaşamamalı — yarısı en altta yarısı en üstte, ortalaması sağlıklı görünür.',
'Average effort per workout': 'Antrenman başına ortalama zorluk',
'A fuller dot means less left in the tank — the same weight at a lower {0} is progress the line alone does not show.': 'Daha dolu bir nokta depoda daha az kaldı demek — aynı ağırlığı daha düşük {0} ile kaldırmak, çizginin tek başına göstermediği bir ilerlemedir.',
// --- bodyweight & per side ---
'Bodyweight': 'Vücut ağırlığı',
'No weight to enter — just log the reps.': 'Girilecek ağırlık yok — sadece tekrarları kaydet.',
'Ask for a weight on every set.': 'Her sette ağırlık sorulsun.',
'For dips or pull-ups with a belt. Progression then follows the weight.': 'Kemerle yapılan dips veya barfiks için. İlerleme o zaman ağırlığı izler.',
'Reps per side': 'Taraf başına tekrar',
'For lunges, single-arm rows and the like.': 'Lunge, tek kol çekiş ve benzeri hareketler için.',
'Top of the range': 'Aralığın üst sınırı',
'Reps climb by one whenever every set was clean. Set a ceiling to add sets instead of reps forever.': 'Her set temiz çıktığında tekrarlar birer artar. Sonsuza kadar tekrar eklemek yerine set eklemek için bir üst sınır belirle.',
'Reps climb to {0}, then a set is added and the reps start over. At {1} sets it asks you to add weight instead.': 'Tekrarlar {0} değerine çıkar, sonra bir set eklenir ve tekrarlar baştan başlar. {1} sette ise bunun yerine ağırlık eklemen istenir.',
'Added ({0})': 'Ek ({0})',
'{0}/side': '{0}/taraf',
'{0} reps in every set — add a set and go back to {1}.': 'Her sette {0} tekrar — bir set ekle ve {1} tekrara dön.',
'{0} sets of {1} — time to add weight or move to a harder variation.': '{1} tekrarlık {0} set — ağırlık ekleme ya da daha zor bir varyasyona geçme zamanı.',
'{0} per side': 'Taraf başına {0}',
'You still log the total: {0} is {1} per side.': 'Toplamı kaydetmeye devam ediyorsun: {0}, taraf başına {1} demek.',
}
+41
View File
@@ -231,6 +231,12 @@ export default {
'Sign out?': '退出登录?',
'Your data is synced to your profile first, then cleared from this device.': '数据会先同步到档案,然后从本设备清除。',
'Sign out': '退出登录',
'Sign out everywhere?': '在所有设备上退出登录?',
'Signs this profile out on every device, including this one. Your passkeys keep working — sign in with them again anytime.': '让此档案在所有设备上退出登录,包括这台。通行密钥不受影响——随时可以用它们重新登录。',
'Sign out everywhere': '在所有设备上退出登录',
'Ends this profile’s sessions on all your devices.': '结束此档案在你所有设备上的会话。',
'Signed out on all devices': '已在所有设备上退出登录',
'Could not sign out everywhere — you are still signed in.': '无法在所有设备上退出登录——你仍处于登录状态。',
'Guest mode — data lives only in this browser. Create a passkey profile to keep it safe and separate per person.': '访客模式——数据只保存在此浏览器。创建通行密钥档案以保护数据并按人区分。',
'Create passkey profile': '创建通行密钥档案',
'Passkeys not supported in this browser.': '此浏览器不支持通行密钥。',
@@ -513,4 +519,39 @@ export default {
'Easy — warm-up territory': '轻松——热身区间',
'RIR counts the reps you left; RPE reads the same effort off a 10-point scale — so RPE ≈ 10 − RIR. Pick the one you already think in.': 'RIR 数的是你还留了几次;RPE 把同样的吃力程度换成 10 分制来读——所以 RPE ≈ 10 − RIR。选你习惯的那一种。',
'The highlighted row is where most working sets land. Sets you have already logged keep their own scale, and nothing else reads the value — progression and estimated 1RM are unaffected.': '高亮那一行是大多数正式组落在的位置。已经记录的组保留原来的标度,而且这个值不会被别处读取——进阶计划和预估 1RM 都不受影响。',
// --- effort in the stats ---
'Effort': '强度',
'how close to failure': '离力竭有多近',
'by hard sets': '按硬组',
'Hard': '硬组',
'no hard sets': '没有硬组',
'No hard sets in this period': '此期间没有硬组',
'Every muscle group got at least one hard set in this period.': '此期间每个肌群都至少练了一个硬组。',
'No rated sets in this period.': '此期间没有已评分的组。',
'average effort': '平均强度',
'at {0} {1} or harder': '{0} {1} 或更硬',
'{0} of {1} finished sets rated': '{1} 个已完成组中有 {0} 个已评分',
'Effort per set is switched off — turn it on in Settings to keep rating.': '每组强度已关闭——在设置中打开即可继续评分。',
'Week by week': '逐周变化',
'Where the sets land': '组都落在哪里',
'Most working sets belong close to failure without living there — half at the floor and half at the top average out to a healthy-looking middle.': '大多数正式组应该接近力竭,但不要一直待在那里——一半在最底、一半在最顶,平均下来只是看着健康。',
'Average effort per workout': '每次训练的平均强度',
'A fuller dot means less left in the tank — the same weight at a lower {0} is progress the line alone does not show.': '点越实,油箱里剩得越少——同样的重量配上更低的 {0},是曲线本身看不出的进步。',
// --- bodyweight & per side ---
'Bodyweight': '徒手动作',
'No weight to enter — just log the reps.': '无需输入重量——只记录次数。',
'Ask for a weight on every set.': '每组都询问重量。',
'For dips or pull-ups with a belt. Progression then follows the weight.': '用于系负重腰带做双杠臂屈伸或引体向上。此时进阶方式跟随重量。',
'Reps per side': '每侧次数',
'For lunges, single-arm rows and the like.': '用于弓步蹲、单臂划船之类的动作。',
'Top of the range': '次数上限',
'Reps climb by one whenever every set was clean. Set a ceiling to add sets instead of reps forever.': '每组都做干净,次数就加一。设置上限后,达到上限会加一组,而不是一直加次数。',
'Reps climb to {0}, then a set is added and the reps start over. At {1} sets it asks you to add weight instead.': '次数升到 {0} 后加一组,次数重新开始。到 {1} 组时会改为提示你加重量。',
'Added ({0})': '负重({0})',
'{0}/side': '{0}/侧',
'{0} reps in every set — add a set and go back to {1}.': '每组都做到 {0} 次——加一组,次数回到 {1}。',
'{0} sets of {1} — time to add weight or move to a harder variation.': '{0} 组 × {1} 次——该加重量或换更难的变式了。',
'{0} per side': '每侧 {0} 次',
'You still log the total: {0} is {1} per side.': '你记录的仍然是总数:{0} 表示每侧 {1} 次。',
}
+62 -10
View File
@@ -1,9 +1,9 @@
import { useEffect, useRef, useState } from 'react'
import { useStore } from './store/useStore.js'
import { useUI } from './store/useUI.js'
import { EXDB, EXIDX, BODYPARTS, isCardio, allExercises, equipmentOf } from './lib/exercises.js'
import { EXDB, EXIDX, BODYPARTS, isCardio, isBodyweightEq, allExercises, equipmentOf } from './lib/exercises.js'
import { fmtDate, fmtNum, fmtVol, fmtDur, durPart, todayISO, uid, exCount, DAYN, MONTHS_LONG, ACCENTS } from './lib/format.js'
import { lastEntryFor, bestWeightFor, buildSets, effectiveRoutineId, workoutVolume, setsDone, setsDoneActive, lastBW, supersetUnits, unitOf, setLabel, defaultConfig, cleanupSg, modeOf, effortOf } from './lib/history.js'
import { lastEntryFor, bestWeightFor, buildSets, effectiveRoutineId, workoutVolume, setsDone, setsDoneActive, lastBW, supersetUnits, unitOf, setLabel, defaultConfig, cleanupSg, modeOf, effortOf, isBw, isPerSide, sideReps } from './lib/history.js'
import { beep, vibrate } from './lib/sound.js'
import { t, instrFor, getLang, INSTR_LANGS } from './lib/i18n.js'
import { nav } from './lib/nav.js'
@@ -11,14 +11,14 @@ import { starterRoutines } from './lib/starter.js'
import Media, { Thumb } from './components/Media.jsx'
import Stepper from './components/Stepper.jsx'
import Icon from './components/Icon.jsx'
import { Button, Slider, Switch, Segmented, SelectRow } from './components/ui.jsx'
import { Button, Slider, Switch, Segmented, SelectRow, Row } from './components/ui.jsx'
import { glyphOf, GLYPH_GROUPS, DEFAULT_GLYPH } from './lib/glyphs.js'
import BodyMap from './components/BodyMap.jsx'
import { loadOfWorkouts } from './lib/muscles.js'
import { parseImport, mergeImport } from './lib/import-csv.js'
import { buildPlanBundle, parsePlan, mergePlan, printPlan } from './lib/plan-share.js'
import { estimate1RM, best1RM, is1RMRecord, REP_CAP } from './lib/onerm.js'
import { nextPrescription, applyPrescription, policyFor, defaultIncrement, POLICIES_FOR, POLICY_NAME, POLICY_DESC } from './lib/progression.js'
import { nextPrescription, applyPrescription, policyFor, defaultIncrement, POLICIES_FOR, POLICY_NAME, POLICY_DESC, MAX_BW_SETS } from './lib/progression.js'
import { MOBILE, shareExport } from './lib/mobile.js'
const S = () => useStore.getState().S
@@ -489,6 +489,9 @@ function ExConfig({ ex, existing, onSave, onDelete, close, routine }) {
// Cardio keeps its own duration+speed form; the reps/time choice (issue #16) is offered for
// everything else, which is where the gap was — planks, hangs, wall sits, loaded carries.
const mode = cardio ? 'cardio' : modeOf({ ...c, id: ex.id })
// Both default from the dataset and are then whatever the config says — see isBw.
const bw = !cardio && isBw({ ...c, id: ex.id })
const perSide = isPerSide(c)
// Keep whatever the other mode already had (sets, weight) and fill only what is missing.
const setMode = m => setC(x => ({ ...defaultConfig(ex.id, m), ...x, mode: m }))
const save = () => {
@@ -499,12 +502,24 @@ function ExConfig({ ex, existing, onSave, onDelete, close, routine }) {
const prog = {}
if (c.prog) prog.prog = c.prog
if (c.inc > 0) prog.inc = c.inc
// Written only when it differs from what the dataset already says, so a barbell config
// stays exactly the shape it was before these flags existed.
// `bodyweight` is true of a hold as much as of a set of reps; `side` is not — it counts
// reps, and a timed hold has none. Switching an exercise to Time therefore drops it
// rather than carrying a flag nothing downstream can read.
const flags = {}
if (bw !== isBodyweightEq(ex.id)) flags.bodyweight = bw
if (cardio) onSave({ sets, min: Math.max(1, Math.round(c.min) || 20), speed: Math.max(0, c.speed || 8) })
else if (mode === 'time') onSave({ sets, mode: 'time', sec: Math.max(1, Math.round(c.sec) || 45), weight: Math.max(0, c.weight || 0), ...prog })
else if (mode === 'time') onSave({ sets, mode: 'time', sec: Math.max(1, Math.round(c.sec) || 45), weight: Math.max(0, c.weight || 0), ...flags, ...prog })
else {
const reps = Math.max(1, Math.round(c.reps) || 10)
const out = { sets, mode: 'reps', reps, weight: Math.max(0, c.weight || 0), ...prog }
// A unilateral target is stored even: the split has to divide, and a typed 15 would
// otherwise plan seven reps on one side and eight on the other, every session.
const typed = Math.max(1, Math.round(c.reps) || 10)
const reps = perSide ? Math.ceil(typed / 2) * 2 : typed
const out = { sets, mode: 'reps', reps, weight: Math.max(0, c.weight || 0), ...flags, ...(perSide ? { side: true } : {}), ...prog }
if (policyFor({ ...c, id: ex.id }, routine, 'reps') === 'double') out.repsMin = Math.min(reps, Math.max(1, Math.round(c.repsMin) || Math.max(1, reps - 2)))
// A ceiling below the working reps would tell you to add a set on day one.
if (bw && !(out.weight > 0) && c.repsMax > 0) out.repsMax = Math.max(reps, Math.round(c.repsMax))
onSave(out)
}
}
@@ -531,13 +546,50 @@ function ExConfig({ ex, existing, onSave, onDelete, close, routine }) {
<Stepper label={t('Weight ({0})', st.unit)} value={c.weight} step={2.5} onChange={v => setC(x => ({ ...x, weight: v }))} />
</> : <>
<Stepper label={t('Sets')} value={c.sets} step={1} decimal={false} onChange={v => setC(x => ({ ...x, sets: v }))} />
<Stepper label={t('Reps')} value={c.reps} step={1} decimal={false} onChange={v => setC(x => ({ ...x, reps: v }))} />
<Stepper label={t('Weight ({0})', st.unit)} value={c.weight} step={2.5} onChange={v => setC(x => ({ ...x, weight: v }))} />
<Stepper label={t('Reps')} value={c.reps} step={perSide ? 2 : 1} decimal={false} onChange={v => setC(x => ({ ...x, reps: v }))} />
{/* On bodyweight work the weight stepper is the click #32 is about, so it is not here
until there is a belt to describe — see the added-weight row below. */}
{!bw && <Stepper label={t('Weight ({0})', st.unit)} value={c.weight} step={2.5} onChange={v => setC(x => ({ ...x, weight: v }))} />}
</>}
</div>
{mode === 'time' && <div className="small dim" style={{ marginBottom: 18 }}>
{mode === 'time' && !bw && <div className="small dim" style={{ marginBottom: 18 }}>
{t('A timer runs while you hold the set. Leave the weight at 0 for bodyweight holds.')}
</div>}
{/* ---------- bodyweight + per side (issues #31/#32/#33) ---------- */}
{!cardio && <div className="sect-b" style={{ marginBottom: 8 }}>
<Row icon="figureStrength" iconTint="var(--acc)" title={t('Bodyweight')}
subtitle={bw ? t('No weight to enter — just log the reps.') : t('Ask for a weight on every set.')}>
<Switch checked={bw} onChange={v => setC(x => ({ ...x, bodyweight: v, weight: v ? 0 : x.weight }))} />
</Row>
{mode === 'reps' && <Row icon="shuffle" iconTint="var(--blue)" title={t('Reps per side')}
subtitle={perSide ? t('You still log the total: {0} is {1} per side.', c.reps || 0, fmtNum(sideReps(c.reps))) : t('For lunges, single-arm rows and the like.')}>
{/* Turning it on rounds the target up to an even number, since half of an odd
total is a rep one side does not get. */}
<Switch checked={perSide} onChange={v => setC(x => ({ ...x, side: v || undefined, reps: v ? Math.ceil((x.reps || 0) / 2) * 2 : x.reps }))} />
</Row>}
</div>}
{/* A stepper is too wide to sit in a list row next to a label — it squeezes the text to
one word per line — so added weight gets the same full-width treatment as sets and
reps, with its explanation underneath. */}
{bw && <>
<div className="row cfgrow" style={{ marginBottom: 8 }}>
<Stepper label={t('Added ({0})', st.unit)} value={c.weight || 0} step={2.5}
onChange={v => setC(x => ({ ...x, weight: v }))} />
</div>
<div className="small dim" style={{ marginBottom: 18 }}>
{t('For dips or pull-ups with a belt. Progression then follows the weight.')}
</div>
</>}
{/* The rep ceiling only means something when there is no load to add instead. */}
{mode === 'reps' && bw && !(c.weight > 0) && <div className="row cfgrow" style={{ marginBottom: 18 }}>
<Stepper label={t('Top of the range')} value={c.repsMax || 0} step={1} decimal={false}
onChange={v => setC(x => ({ ...x, repsMax: v }))} />
</div>}
{mode === 'reps' && bw && !(c.weight > 0) && <div className="small dim" style={{ marginTop: -10, marginBottom: 18 }}>
{c.repsMax > 0
? t('Reps climb to {0}, then a set is added and the reps start over. At {1} sets it asks you to add weight instead.', c.repsMax, MAX_BW_SETS)
: t('Reps climb by one whenever every set was clean. Set a ceiling to add sets instead of reps forever.')}
</div>}
<ProgressionFields ex={ex} mode={mode} c={c} setC={setC} routine={routine} unit={st.unit} />
<Button variant="primary" onClick={save}>{existing ? t('Save') : t('Add to routine')}</Button>
{ex.custom && <><div style={{ height: 8 }} /><Button icon="pencil" onClick={() => { close(); customExSheet(ex) }}>{t('Edit or delete this exercise')}</Button></>}
+21 -5
View File
@@ -70,6 +70,15 @@ export const useStore = create((set, get) => {
}
})
// Everything a sign-out leaves behind on this device, whichever way it was triggered.
const clearLocalSession = () => {
get().setUser(null)
localStorage.removeItem('gym_guest')
localStorage.removeItem('gym_dirty')
localStorage.removeItem(KEY)
persist(clone(DEF), false)
}
return {
S: (() => { const s = loadState(); registerCustom(s.customEx); return s })(),
user: (() => { try { return JSON.parse(localStorage.getItem('gym_user')) || null } catch { return null } })(),
@@ -114,11 +123,18 @@ export const useStore = create((set, get) => {
async signOut() {
try { await get().pushState(); await api('/api/logout', { method: 'POST', body: '{}' }) } catch (e) { /* */ }
get().setUser(null)
localStorage.removeItem('gym_guest')
localStorage.removeItem('gym_dirty')
localStorage.removeItem(KEY)
persist(clone(DEF), false)
clearLocalSession()
},
// "Sign out everywhere": the server bumps this profile's session version, which kills every
// session it has on any device — this browser included, so the app has to end up exactly
// where a normal signOut leaves it. Unlike signOut the request is NOT swallowed: if it fails
// the sessions elsewhere are all still valid, and wiping this device's copy of the data
// would sign the user out of the one place the bump didn't reach. Caller reports the error.
async signOutAll() {
await get().pushState() // never throws — stores gym_dirty and moves on when offline
await api('/api/logout/all', { method: 'POST', body: '{}' })
clearLocalSession()
},
// Demo build only: drop the seeded example profile back in (Settings → "Reset demo data").
+29 -3
View File
@@ -4,7 +4,7 @@ import { useStore, DEF, hasData } from '../store/useStore.js'
import { useUI } from '../store/useUI.js'
import { ACCENTS, todayISO, localTZ } from '../lib/format.js'
import { effortOf } from '../lib/history.js'
import { webauthnOK, passkeyLogin, passkeyRegister, IS_ANDROID } from '../lib/api.js'
import { api, webauthnOK, passkeyLogin, passkeyRegister, IS_ANDROID } from '../lib/api.js'
import { pushSupported, enablePush, disablePush, sendTestPush } from '../lib/push.js'
import { wakeLockSupported } from '../lib/wakelock.js'
import { t, LANGS, INSTR_LANGS } from '../lib/i18n.js'
@@ -18,7 +18,7 @@ export default function Settings() {
const nav = useNavigate()
const S = useStore(s => s.S)
const user = useStore(s => s.user)
const { update, replaceState, setUser, pullState, pushState, signOut, resetDemo } = useStore()
const { update, replaceState, setUser, pullState, pushState, signOut, signOutAll, resetDemo } = useStore()
const toast = useUI(s => s.toast)
const fileRef = useRef(null)
const importRef = useRef(null)
@@ -53,6 +53,18 @@ export default function Settings() {
catch (e) { if (e.name !== 'NotAllowedError' && e.name !== 'AbortError') toast(e.message || t('Sign-in failed')) }
}
const registerHere = () => useUI.getState().openSheet(close => <RegisterInline close={close} setUser={setUser} pushState={pushState} pullState={pullState} toast={toast} />)
// Ends the profile's sessions on every device — this one included, so on success it lands in
// the same place as the plain sign-out above (home, local data cleared). On failure nothing
// local is touched: still signed in here, and say so rather than leaving a half-signed-out app.
const signOutEverywhere = () => confirmSheet({
title: t('Sign out everywhere?'),
message: t('Signs this profile out on every device, including this one. Your passkeys keep working — sign in with them again anytime.'),
confirmText: t('Sign out everywhere'), danger: true,
onConfirm: async () => {
try { await signOutAll(); nav('/home'); toast(t('Signed out on all devices')) }
catch (e) { toast(t('Could not sign out everywhere — you are still signed in.')) }
},
})
return <div className="narrow">
<div className="hdr">
@@ -76,6 +88,7 @@ export default function Settings() {
<Row icon="personCircle" iconTint="var(--grey)" title={user.name} subtitle={t('Signed in with passkey — data syncs to this profile.')} />
{user.admin && <Row icon="wrench" iconTint="var(--indigo)" title={t('Admin dashboard')} accessory="chevron" onClick={() => nav('/admin')} />}
<Row icon="signOut" iconTint="var(--red)" title={t('Sign out')} danger onClick={() => confirmSheet({ title: t('Sign out?'), message: t('Your data is synced to your profile first, then cleared from this device.'), confirmText: t('Sign out'), danger: true, onConfirm: () => { signOut(); nav('/home') } })} />
<Row icon="shield" iconTint="var(--red)" title={t('Sign out everywhere')} subtitle={t('Ends this profile’s sessions on all your devices.')} danger onClick={signOutEverywhere} />
</> : webauthnOK() ? <>
<Row icon="sparkles" iconTint="var(--acc)" title={t('Create passkey profile')} subtitle={t('Keeps your data safe and separate per person.')} accessory="chevron" onClick={registerHere} />
<Row icon="person" iconTint="var(--blue)" title={t('Sign in with passkey')} accessory="chevron" onClick={signInHere} />
@@ -314,13 +327,20 @@ function PushCard({ S, update, toast }) {
</>
}
// The same registration as the sign-in screen's, reached from Settings instead. It asks for
// the invite code on the same terms: an invite-only instance rejects a registration without
// one, so a form that cannot collect it is a form that cannot succeed.
function RegisterInline({ close, setUser, pushState, pullState, toast }) {
const nameRef = useRef(null)
const [code, setCode] = useState('')
const [inviteOnly, setInviteOnly] = useState(false)
useEffect(() => { api('/api/config').then(c => setInviteOnly(!!c.invite_only)).catch(() => {}) }, [])
const go = async () => {
const n = (nameRef.current.value || '').trim()
if (!n) { toast(t('Enter a name')); return }
if (inviteOnly && !code.trim()) { toast(t('An invite code is required')); return }
try {
const u = await passkeyRegister(n); setUser(u); close()
const u = await passkeyRegister(n, code.trim()); setUser(u); close()
if (hasData(useStore.getState().S)) { await pushState(); toast(t('Profile created — data moved into it')) }
else { await pullState(); toast(t('Welcome, {0}', u.name)) }
} catch (e) { if (e.name !== 'NotAllowedError' && e.name !== 'AbortError') toast(e.message || t('Registration failed')) }
@@ -329,6 +349,12 @@ function RegisterInline({ close, setUser, pushState, pullState, toast }) {
<h3>{t('Create your profile')}</h3>
<div className="muted small" style={{ marginBottom: 14 }}>{t('Pick a name, then confirm with your device.')}</div>
<TextField ref={nameRef} placeholder={t('Your name')} maxLength={40} />
{inviteOnly && <>
<div style={{ height: 10 }} />
<input className="input" placeholder={t('Invite code')} maxLength={40} value={code}
onChange={e => setCode(e.target.value.toUpperCase())} style={{ letterSpacing: '.14em', fontWeight: 600, textAlign: 'center' }} />
<div className="dim small" style={{ marginTop: 6 }}>{t('This app is invite-only — enter the code you were given.')}</div>
</>}
<div style={{ height: 12 }} /><Button variant="primary" onClick={go}>{t('Create passkey')}</Button>
</>
}
+111 -13
View File
@@ -2,7 +2,7 @@ import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useStore } from '../store/useStore.js'
import { EXIDX } from '../lib/exercises.js'
import { lastBW, streakWeeks, setLabel, modeOf } from '../lib/history.js'
import { lastBW, streakWeeks, setLabel, modeOf, effortOf } from '../lib/history.js'
import { fmtNum, fmtDate, fmtVol, todayISO, weekKey } from '../lib/format.js'
import { t } from '../lib/i18n.js'
import { bwSheet, goalSheet, calendarSheet, workoutDetailSheet, WorkoutRow, bwDeltaColor } from '../sheets.jsx'
@@ -12,26 +12,41 @@ import Icon from '../components/Icon.jsx'
import BodyMap, { BodyMapLegend } from '../components/BodyMap.jsx'
import { loadOfWorkouts, rankOf, MUSCLE_NAME } from '../lib/muscles.js'
import { e1rmSeries, best1RM } from '../lib/onerm.js'
import {
hasEffort, displayScale, scaleName, toScale, avgRir, effortSummary, effortWeeks,
effortHistogram, isHardSet, HARD_RIR
} from '../lib/effort.js'
import { Button, Segmented, SelectRow } from '../components/ui.jsx'
// Which muscles the training in a window actually hit — and, the point of the card,
// which ones it keeps missing. Shading is relative within the window (lib/muscles.js).
function MuscleBalance({ S }) {
const [win, setWin] = useState(7)
const [hard, setHard] = useState(false)
const [sel, setSel] = useState(null)
const now = Date.now()
const inWin = S.workouts.filter(w =>
win === 0 ? true
: win === 7 ? weekKey(w.d) === weekKey(todayISO())
: (w.start || new Date(w.d).getTime()) > now - win * 86400000)
const load = loadOfWorkouts(inWin)
// Counting only the sets taken near failure turns the map from "where did the volume go"
// into "where did the stimulus go" — a muscle can lead on sets and still never be trained
// hard. Offered only when the window holds ratings at all, since with none the hard map
// would just be empty and read as "you trained nothing".
const rated = inWin.some(w => w.entries.some(e => e.sets.some(s => s.done && isHardSet(s))))
const on = hard && rated
const load = loadOfWorkouts(inWin, on ? isHardSet : null)
const { worked, missed } = rankOf(load)
const top = worked.slice(0, 4)
const max = worked.length ? load[worked[0]] : 0
const sets = m => Math.round((load[m] || 0) * 10) / 10
return <div className="card">
<h2>{t('Muscle balance')} <span className="dim" style={{ textTransform: 'none', letterSpacing: 0 }}>· {t('by sets worked')}</span></h2>
<div className="row between" style={{ marginBottom: 8 }}>
<h2 style={{ margin: 0 }}>{t('Muscle balance')} <span className="dim" style={{ textTransform: 'none', letterSpacing: 0 }}>· {on ? t('by hard sets') : t('by sets worked')}</span></h2>
{rated && <Button size="sm" icon="flame" style={on ? { color: 'var(--yellow)' } : undefined}
onClick={() => { setHard(h => !h); setSel(null) }}>{on ? t('Hard') : t('All')}</Button>}
</div>
<Segmented className="seg-range" value={win} onChange={v => { setWin(v); setSel(null) }}
options={[{ value: 7, label: t('Week') }, { value: 30, label: '30d' }, { value: 90, label: '90d' }, { value: 0, label: t('All') }]} />
{inWin.length ? <>
@@ -40,23 +55,80 @@ function MuscleBalance({ S }) {
<BodyMapLegend />
{sel && <div className="mrow" style={{ borderTop: 'var(--hair) solid var(--sep)', marginTop: 4, paddingTop: 10 }}>
<span className="nm"><b>{t(MUSCLE_NAME[sel])}</b></span>
<span className="v">{sets(sel) ? t('{0} sets', sets(sel)) : t('not trained')}</span>
<span className="v">{sets(sel) ? t('{0} sets', sets(sel)) : on ? t('no hard sets') : t('not trained')}</span>
</div>}
{!sel && top.map(m => <div key={m} className="mrow">
<span className="nm">{t(MUSCLE_NAME[m])}</span>
<span className="bar"><i style={{ width: Math.round(load[m] / max * 100) + '%' }} /></span>
<span className="bar"><i style={{ width: Math.round(load[m] / max * 100) + '%', background: on ? 'var(--yellow)' : undefined }} /></span>
<span className="v">{t('{0} sets', sets(m))}</span>
</div>)}
{missed.length > 0 && <>
<h4 className="sec" style={{ marginTop: 12 }}>{t('Not trained in this period')}</h4>
<h4 className="sec" style={{ marginTop: 12 }}>{on ? t('No hard sets in this period') : t('Not trained in this period')}</h4>
<div className="mchips">{missed.map(m => <span key={m} className="mchip miss">{t(MUSCLE_NAME[m])}</span>)}</div>
</>}
{!missed.length && worked.length > 0 &&
<div className="muted small" style={{ marginTop: 10 }}>{t('Every muscle group got some work in this period.')}</div>}
<div className="muted small" style={{ marginTop: 10 }}>{on
? t('Every muscle group got at least one hard set in this period.')
: t('Every muscle group got some work in this period.')}</div>}
</> : <div className="muted small">{t('No workouts in this period yet.')}</div>}
</div>
}
// How hard the training was — the half of the picture a volume chart cannot show. Everything
// is computed in RIR (lib/effort.js) and converted to whichever scale this profile reads.
// Every number carries how much of the training it speaks for: rating is optional and off by
// default, so a partly rated history is the normal case, and an average without its
// denominator would quietly speak for sets that were never rated.
function EffortCard({ S }) {
const [win, setWin] = useState(90)
const kind = displayScale(S)
const hd = scaleName(kind)
const sum = effortSummary(S, win)
const weeks = effortWeeks(S, win)
const hist = effortHistogram(S, win)
const maxBin = Math.max(1, ...hist.map(b => b.n))
// The week's set count rides along in the tooltip, because the pair is the reading:
// volume up with effort up is fatigue piling up, volume up with effort flat is adaptation.
const pts = weeks.map(w => ({ t: w.t, y: toScale(kind, w.rir), note: t('{0} sets', w.sets) }))
// Bins run hardest-first in both scales: RIR 0 and RPE 10 are the same set.
const binLabel = b => kind === 'rpe' ? (b.tail ? '≤ 6' : String(10 - b.rir)) : (b.tail ? b.rir + '+' : String(b.rir))
return <div className="card">
<h2>{t('Effort')} <span className="dim" style={{ textTransform: 'none', letterSpacing: 0 }}>· {t('how close to failure')}</span></h2>
<Segmented className="seg-range" value={win} onChange={setWin}
options={[{ value: 30, label: '30d' }, { value: 90, label: '90d' }, { value: 365, label: '1Y' }, { value: 0, label: t('All') }]} />
{sum.rated === 0 ? <div className="muted small">{t('No rated sets in this period.')}</div> : <>
<div className="row between" style={{ alignItems: 'flex-end', gap: 12 }}>
<div>
<div className="stat-v">{sum.avg == null ? '—' : fmtNum(toScale(kind, sum.avg)) + ' ' + hd}</div>
<div className="small dim">{t('average effort')}</div>
</div>
<div style={{ textAlign: 'right' }}>
<div className="stat-v" style={{ color: 'var(--yellow)' }}>{sum.hardPct == null ? '—' : Math.round(sum.hardPct * 100) + '%'}</div>
<div className="small dim">{t('at {0} {1} or harder', hd, fmtNum(toScale(kind, HARD_RIR)))}</div>
</div>
</div>
<div className="small dim" style={{ marginTop: 8 }}>{t('{0} of {1} finished sets rated', sum.rated, sum.done)}</div>
{effortOf(S) === 'none' && <div className="small" style={{ color: 'var(--yellow)', marginTop: 4 }}>
{t('Effort per set is switched off — turn it on in Settings to keep rating.')}
</div>}
{pts.length > 1 && <>
<h4 className="sec" style={{ marginTop: 12 }}>{t('Week by week')}</h4>
<div className="chart"><LineChart points={pts} h={140} unit={hd} color="var(--yellow)" invert={kind === 'rir'} /></div>
</>}
<h4 className="sec" style={{ marginTop: 12 }}>{t('Where the sets land')}</h4>
{hist.map(b => <div key={b.rir} className="mrow">
<span className="nm">{hd} {binLabel(b)}</span>
<span className="bar"><i style={{ width: Math.round(b.n / maxBin * 100) + '%', background: b.rir <= HARD_RIR ? 'var(--yellow)' : 'var(--label-3)' }} /></span>
<span className="v">{b.n ? b.n + ' · ' + Math.round(b.pct * 100) + '%' : '—'}</span>
</div>)}
<div className="small dim" style={{ marginTop: 8 }}>
{t('Most working sets belong close to failure without living there — half at the floor and half at the top average out to a healthy-looking middle.')}
</div>
</>}
</div>
}
// Stats = the analytics hub: all charts, progress and history live here.
export default function Stats() {
const nav = useNavigate()
@@ -65,6 +137,9 @@ export default function Stats() {
const [exId, setExId] = useState(null)
const [exMetric, setExMetric] = useState('top')
const now = Date.now()
const anyEffort = hasEffort(S)
const kind = displayScale(S)
const hd = scaleName(kind)
const bwPts = S.bodyweight.filter(b => range === 0 || (b.t || new Date(b.d).getTime()) > now - range * 86400000)
.map(b => ({ t: b.t || new Date(b.d).getTime(), y: b.w, d: b.d }))
@@ -101,7 +176,23 @@ export default function Stats() {
const e1Pts = curEx ? e1rmSeries(S, curEx) : []
const e1Best = curEx ? best1RM(S, curEx) : null
const showE1 = e1Pts.length > 0
// Effort on this exercise, per session. It rides on the top-set curve as well as having a
// curve of its own, because the two only mean something together: the same weight moved
// with more left in the tank is progress a weight-only chart draws as a flat line.
const exRir = exPts.map(p => avgRir(p.sets))
const showEff = exRir.filter(v => v != null).length >= 3
const effPts = exPts.map((p, i) => (exRir[i] == null ? null : { t: p.t, y: toScale(kind, exRir[i]), d: p.d })).filter(Boolean)
const onE1 = showE1 && exMetric === 'e1rm'
const onEff = showEff && exMetric === 'effort'
const topPts = exPts.map((p, i) => ({
t: p.t, y: p.y, d: p.d,
// 0 RIR (nothing left) is a full dot, 4+ a faint one; unrated sessions keep the plain line.
m: exRir[i] == null ? null : 1 - Math.min(4, Math.max(0, exRir[i])) / 4,
note: exRir[i] == null ? undefined : hd + ' ' + fmtNum(toScale(kind, exRir[i]))
}))
const exOpts = [{ value: 'top', label: t('Top set') }]
if (showE1) exOpts.push({ value: 'e1rm', label: t('Est. 1RM') })
if (showEff) exOpts.push({ value: 'effort', label: t('Effort') })
return <>
<div className="hdr"><div><h1>{t('Stats')}</h1><div className="sub">{t('Progress & history')}</div></div>
@@ -120,6 +211,7 @@ export default function Stats() {
</div>
{S.workouts.length > 0 && <MuscleBalance S={S} />}
{anyEffort && <EffortCard S={S} />}
<div className="cols">
<div className="card">
@@ -142,18 +234,24 @@ export default function Stats() {
<SelectRow title={t('Exercise')} sheetTitle={t('Exercise progress')} value={curEx} onChange={setExId}
options={exHist.map(id => ({ value: id, label: EXIDX[id].n }))} />
</div>
{showE1 && <Segmented className="seg-range" value={exMetric} onChange={setExMetric}
options={[{ value: 'top', label: t('Top set') }, { value: 'e1rm', label: t('Est. 1RM') }]} />}
<div className="chart"><LineChart points={(onE1 ? e1Pts : exPts).map(p => ({ t: p.t, y: p.y, d: p.d }))} h={150} unit={exUnit} color="var(--blue)" /></div>
{exOpts.length > 1 && <Segmented className="seg-range" value={onEff ? 'effort' : onE1 ? 'e1rm' : 'top'} onChange={setExMetric} options={exOpts} />}
<div className="chart">
{onEff
? <LineChart points={effPts} h={150} unit={hd} color="var(--yellow)" invert={kind === 'rir'} />
: <LineChart points={onE1 ? e1Pts.map(p => ({ t: p.t, y: p.y, d: p.d })) : topPts} h={150} unit={exUnit} color="var(--blue)" />}
</div>
<div style={{ marginTop: 8 }}>{exList.map((p, i) => <div key={i} className="row between small" style={{ padding: '6px 0', borderBottom: 'var(--hair) solid var(--sep)' }}>
<span className="muted">{fmtDate(p.d, true)}</span><span>{p.sets.map(s => setLabel(curEx, s, p.target)).join(' ')}</span></div>)}</div>
<div className="small dim" style={{ marginTop: 8 }}>
{onE1 ? t('Estimated 1RM per workout') : curCardio ? t('Top speed per workout') : curTimed ? t('Longest hold per workout') : t('Best set weight per workout')} · {t('Best:')}
{' '}<b className="accent">{fmtNum(onE1 ? e1Best.est : exBest)} {onE1 ? S.unit : exUnit}</b>
{onEff ? t('Average effort per workout') : onE1 ? t('Estimated 1RM per workout') : curCardio ? t('Top speed per workout') : curTimed ? t('Longest hold per workout') : t('Best set weight per workout')}
{onEff ? '' : <> · {t('Best:')}{' '}<b className="accent">{fmtNum(onE1 ? e1Best.est : exBest)} {onE1 ? S.unit : exUnit}</b></>}
</div>
{showE1 && <div className="small dim" style={{ marginTop: 4 }}>
{onE1 && <div className="small dim" style={{ marginTop: 4 }}>
{t('Best estimate from {0} on {1} — an estimate, not a tested max.', fmtNum(e1Best.w) + ' ' + S.unit + ' × ' + e1Best.r, fmtDate(e1Best.d, true))}
</div>}
{!onEff && !onE1 && showEff && <div className="small dim" style={{ marginTop: 4 }}>
{t('A fuller dot means less left in the tank — the same weight at a lower {0} is progress the line alone does not show.', hd)}
</div>}
</> : <div className="muted small">{t('Finish your first workout to see progress curves here.')}</div>}
</div>
</div>
+24 -9
View File
@@ -3,7 +3,7 @@ import { useNavigate } from 'react-router-dom'
import { useStore } from '../store/useStore.js'
import { useUI } from '../store/useUI.js'
import { exOr } from '../lib/exercises.js'
import { effectiveRoutine, lastEntryFor, bestWeightFor, buildSets, setsDoneActive, supersetUnits, unitOf, setLabel, modeOf, EFFORT, effortOf, stepEffort, capEffort } from '../lib/history.js'
import { effectiveRoutine, lastEntryFor, bestWeightFor, buildSets, setsDoneActive, supersetUnits, unitOf, setLabel, modeOf, isBw, isPerSide, sideReps, repStep, EFFORT, effortOf, stepEffort, capEffort } from '../lib/history.js'
import { fmtNum, fmtDate, todayISO, exCount, DAYN } from '../lib/format.js'
import { beep, vibrate } from '../lib/sound.js'
import { t } from '../lib/i18n.js'
@@ -69,12 +69,22 @@ function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemov
// What the progression policy decided for this session, and why (issue #17). Computed when
// the session was built so the reason matches the numbers already in the rows.
const plan = entry.plan
// A bodyweight set has no weight to type, so the column is not there (issue #32) — one
// stepper instead of two, which is the whole point of the flag. Adding a belt weight in the
// config brings it back, now labelled as the addition it is.
const cfg = { ...(entry.target || {}), id: entry.id }
const bw = !cardio && isBw(cfg)
const added = bw && entry.sets.some(s => s.w > 0)
const loadCol = { f: 'w', step: 2.5, dec: true, hd: bw ? t('Added ({0})', S.unit) : t('Weight ({0})', S.unit) }
// The reps column is the total in every mode, unilateral included — the stepper walks in
// twos there so the number you land on is one you can actually split evenly.
const repCol = { f: 'r', step: repStep(cfg), dec: false, hd: t('Reps') }
const col1 = cardio ? { f: 'min', step: 1, dec: false, hd: t('Duration (min)') }
: timed ? { f: 'sec', step: 5, dec: false, hd: t('Seconds') }
: { f: 'w', step: 2.5, dec: true, hd: t('Weight ({0})', S.unit) }
: (bw && !added) ? repCol : loadCol
const col2 = cardio ? { f: 'speed', step: 0.5, dec: true, hd: t('Speed (km/h)') }
: timed ? { f: 'w', step: 2.5, dec: true, hd: t('Weight ({0})', S.unit) }
: { f: 'r', step: 1, dec: false, hd: t('Reps') }
: timed ? ((bw && !added) ? null : loadCol)
: (bw && !added) ? null : repCol
// Effort (RIR or RPE, whichever the profile logs) only makes sense for weighted rep sets,
// not cardio/timed holds, and is opt-in since it adds a third stepper to every row. `opt`
// because an unlogged effort is not the same as 0 — RIR 0 says the set went to failure.
@@ -106,6 +116,9 @@ function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemov
</div>
<div className="row" style={{ gap: 6, flexWrap: 'wrap', marginBottom: 8 }}>
{cardio && <span className="tag acc"><Icon name="figureRun" />{t('Cardio')}</span>}
{/* You log the total; this is the split, so the set in front of you is unambiguous
without the rep count having to mean two different things (issue #31). */}
{!cardio && !timed && isPerSide(cfg) && <span className="tag acc nocap"><Icon name="shuffle" />{t('{0} per side', fmtNum(sideReps(entry.sets.find(s => !s.done)?.r ?? entry.sets[0]?.r)))}</span>}
{(ex.tg || ex.bp) && <span className="tag">{t(ex.tg || ex.bp)}</span>}
{ex.eq && <span className="tag">{t(ex.eq)}</span>}
{best > 0 && <span className="tag nocap">{t('Best:')} {fmtNum(best)} {S.unit}</span>}
@@ -117,11 +130,11 @@ function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemov
</div>}
<div className="card" style={{ marginTop: 10, marginBottom: 0 }}>
{/* the header carries the same eff3 sizing as the rows, or the labels drift off their columns */}
<div className={'sethead' + (col3 ? ' eff3' : '')}><span className="n-sp" /><span className="w-sp">{col1.hd}</span><span className="r-sp">{col2.hd}</span>{col3 && <span className="eff-sp">{col3.hd}</span>}{timed && <span className="ck-sp" />}<span className="ck-sp" /></div>
<div className={'sethead' + (col3 ? ' eff3' : '')}><span className="n-sp" /><span className="w-sp">{col1.hd}</span>{col2 && <span className="r-sp">{col2.hd}</span>}{col3 && <span className="eff-sp">{col3.hd}</span>}{timed && <span className="ck-sp" />}<span className="ck-sp" /></div>
{entry.sets.map((s, i) => <div key={i} className={'setrow' + (s.done ? ' done' : '') + (col3 ? ' eff3' : '')}>
<div className="n">{i + 1}</div>
{cell(s, i, col1, 'w')}
{cell(s, i, col2, 'r')}
{col2 && cell(s, i, col2, 'r')}
{col3 && cell(s, i, col3, 'eff')}
{/* A timed set is started, not typed: the timer counts the hold down and checks the
set off itself. The checkbox stays for anyone who timed it on their own watch. */}
@@ -196,9 +209,11 @@ function ActiveWorkout() {
if (isLastExInUnit && !unitDone) startRest(S.restSec)
else if (unitDone) stopRest()
if (unitDone && isLastUnit) workoutDone = true // last exercise's last set → done
// Only reps training has a "working weight" worth confirming — a bodyweight plank
// has nothing to put in that slider.
if (e.sets.every(x => x.done)) { exJustDone = true; if (m === 'reps' && !e.asked) { e.asked = true; askTop = true } }
// Only loaded reps training has a "working weight" worth confirming — a bodyweight
// plank has nothing to put in that slider, and neither does a set of push-ups
// (issue #32: the fewest taps that still record what happened).
const loaded = m === 'reps' && !(isBw({ ...(e.target || {}), id: e.id }) && !e.sets.some(x => x.w > 0))
if (e.sets.every(x => x.done)) { exJustDone = true; if (loaded && !e.asked) { e.asked = true; askTop = true } }
}
})
// reps: topWeight first (it chains into the finish/continue prompt on the last unit).