Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f91cde15a1 | ||
|
|
90a1e8956a | ||
|
|
ae1c8fe8b2 | ||
|
|
22c2ff9d2c | ||
|
|
82646843c6 | ||
|
|
0345abc925 | ||
|
|
6aa43e7a06 | ||
|
|
542c3f493a | ||
|
|
f7b9a80a93 | ||
|
|
b5d55467d0 | ||
|
|
a7d710902c | ||
|
|
c04fd512d4 | ||
|
|
4f003073d0 | ||
|
|
9dcda4bfc2 | ||
|
|
1bb0806436 | ||
|
|
b9079c98db | ||
|
|
069cb6d9f9 | ||
|
|
1ee9970c71 | ||
|
|
6859624e0f | ||
|
|
d35ba5643b | ||
|
|
a0a44cb6c0 | ||
|
|
d302088c11 | ||
|
|
36123c0d19 | ||
|
|
668002b066 | ||
|
|
0fa35030ee | ||
|
|
145c668dd1 | ||
|
|
0b1072dbf8 | ||
|
|
cca8ecd848 | ||
|
|
d7bb67a1c0 | ||
|
|
185afe6a96 | ||
|
|
fcb2fc576a | ||
|
|
cb4fc99dcc | ||
|
|
6a86f54e4c | ||
|
|
1d6e49fb2b | ||
|
|
05d20b33e5 | ||
|
|
d7274bd202 | ||
|
|
ffc0ecf52e | ||
|
|
6358bef1ae | ||
|
|
6796e559d3 | ||
|
|
a54e4b6e8a | ||
|
|
6e39fbd4b4 | ||
|
|
5bbbffe138 | ||
|
|
8094a5131b | ||
|
|
f94f8ca320 | ||
|
|
2bf86a5318 | ||
|
|
cc116bdbcc | ||
|
|
10ff64b0e1 | ||
|
|
d0c7d40a68 | ||
|
|
5c3a9323b7 | ||
|
|
e20201a870 | ||
|
|
f9715d76d3 | ||
|
|
6e2dad2dc9 | ||
|
|
df76c21036 | ||
|
|
929e9155b4 | ||
|
|
55b9a29e66 | ||
|
|
83b2a140d6 | ||
|
|
0f7e3e1291 | ||
|
|
b95561e957 | ||
|
|
113e7ef755 | ||
|
|
10b9598af4 | ||
|
|
69fd4a8344 | ||
|
|
a41b0ca60f | ||
|
|
5007b05504 | ||
|
|
a98fb4d791 | ||
|
|
1849fc8c5f | ||
|
|
394f6d545a | ||
|
|
dc9f5d6a1a | ||
|
|
5eeec2a52a | ||
|
|
236492b78c | ||
|
|
df50287eac | ||
|
|
23cbb8d429 | ||
|
|
3a372b5744 | ||
|
|
298231a41c | ||
|
|
1a763b3e81 | ||
|
|
736d743043 | ||
|
|
a1b2d31e04 | ||
|
|
8b75ae9b30 | ||
|
|
a68a88d2da | ||
|
|
b30526e0e5 | ||
|
|
d8d7257d35 | ||
|
|
975c9f440b | ||
|
|
530c1bbe55 | ||
|
|
7abada3bfc | ||
|
|
e77be0ac3f | ||
|
|
46988c3bfc | ||
|
|
d7f0f0dbdb | ||
|
|
5a8873b919 | ||
|
|
33f4758a1c | ||
|
|
6a8d2288ae | ||
|
|
6e44e2f793 |
No files matched your search
@@ -113,6 +113,13 @@ RP_NAME=openGym
|
||||
# NGINX_PORT=80
|
||||
# BACKEND=api
|
||||
# PORT=3000
|
||||
#
|
||||
# Serving openGym under a subpath (https://example.com/gym/)? If your reverse
|
||||
# proxy strips the prefix before the container sees it, set nothing — the app
|
||||
# asks its own address for the API. If it passes the prefix through, name it
|
||||
# here without a trailing slash:
|
||||
#
|
||||
# BASE_PATH=/gym
|
||||
|
||||
# ── Notifications (optional) ───────────────────────────────────────────────
|
||||
# Push works out of the box — nothing to set. VAPID keys are generated on first
|
||||
|
||||
@@ -1,5 +1,104 @@
|
||||
# Changelog
|
||||
|
||||
## v1.3.8 — 2026-09-20
|
||||
|
||||
Twenty-four reports closed: the keyboard that would not stay open on iPhone and iPad, notifications
|
||||
that arrived with notifications switched off, reps you could not read on a narrow phone, and
|
||||
assisted pull-ups that recorded your progress backwards. Plus the four things this milestone
|
||||
promised — reorder your routines, a Smith machine with no bar, two-decimal weights, and deleting an
|
||||
account for real. Eleven community pull requests from six contributors. Web bundle, APK and API image.
|
||||
|
||||
**The fixes people actually hit**
|
||||
|
||||
- ⌨️ **The keyboard stays open** (FabianReitz, hectorroaz, #242). On iPhone and iPad, tapping a field
|
||||
threw the keyboard straight back out about four times in five — worst on "Create new profile",
|
||||
where a new user could not type a name. The page-alignment guard blurred the field you had just
|
||||
tapped, because its "is the keyboard open?" check compares two numbers that *both* move while the
|
||||
keyboard animates in. Measured on iOS 26.6: `innerHeight` fell 684 → 374 while the visual viewport
|
||||
sat at 158, so the keyboard read as closed ~100 ms after every tap. Nothing acts on that check
|
||||
while a text field has focus now.
|
||||
- 🔔 **Notifications respect the switch** (shibbrich1, #239). The rest-timer alert asked for the
|
||||
browser permission itself and then fired whether or not Push was on — and a permission cannot be
|
||||
handed back. Off is off.
|
||||
- 📱 **Reps are readable again on a narrow phone** (seals187, #235). A row with weight, reps, an
|
||||
effort column and the +/− buttons left the number nothing: at 320 px the reps field was empty and
|
||||
102.5 kg showed as "102". Every number field now reserves the widest value it shows and the
|
||||
buttons give way first — checked across 108 combinations of width, layout, effort mode and
|
||||
per-side rows.
|
||||
- 🏋️ **Assisted pull-ups and dips count the right way** (dpatrongomez, kvalev, #232, #176). The
|
||||
stack carries part of your weight, so less assistance is the harder set — but 30 kg stayed the
|
||||
record over 20 kg, and progression answered a clean session by offering *more* help. Eight
|
||||
catalogue exercises are affected, and `assisted` on a custom exercise marks any other.
|
||||
- 📋 **List view keeps your place** (xwr3, #224) — it opens at the exercise you are on, not at the
|
||||
top of the session.
|
||||
- ➕ **Extra sets stay out of the plan** (kvalev, #233). A heavier bonus set used to raise next
|
||||
session's weight, and a hard one taken short reported the whole session as missed.
|
||||
- 🌐 **Subpath deployments work** (leon332157, #238). Behind a proxy that strips its prefix there is
|
||||
nothing to configure; one that passes the prefix through takes `BASE_PATH=/gym`.
|
||||
|
||||
**The four this milestone promised**
|
||||
|
||||
- ↕️ **Reorder your routines** (hjeroen-git, #142) — arrows in Plan, and the Start screen, the
|
||||
day sheets and every picker follow the same order.
|
||||
- 🔩 **"No bar"** (Aoto Ideguchi, #138) — a Smith machine that carries its own carriage now counts
|
||||
plates from zero instead of snapping back to a 9 kg bar.
|
||||
- 🔢 **Two-decimal weights** (Aoto Ideguchi, #139) — Settings → Weight decimals, for quarter plates
|
||||
and microplates. 62.75 stays 62.75 instead of rounding to 62.8.
|
||||
- 🗑️ **Delete an account** (shibbrich1, #107) — the admin dashboard can remove a profile and
|
||||
everything attached to it, not just disable it. It asks twice and offers their data as a download
|
||||
first; it refuses to delete you or the last admin.
|
||||
|
||||
**Community pull requests**
|
||||
|
||||
- kurktchiev: the iOS Home Screen icon behind an auth proxy (#184), an unknown path no longer serves
|
||||
a shell that cannot load (#185), and a way back to the Start screen on a day that already has a
|
||||
plan (#237).
|
||||
- Space-Hermes: typo-tolerant exercise search (#206), Olympic-lift muscle groups (#207), shared plans
|
||||
keep their kg/lb unit (#210), and a Coach test that no longer fails around midnight (#208).
|
||||
- aaron-rai: the activity heatmap follows your week-start setting (#220).
|
||||
- ncbachh: rename a workout while it is running (#228).
|
||||
- Strazdonis: the big weight read-out can be typed into (#234).
|
||||
- mkoester: standard ß in the German pack (#190).
|
||||
|
||||
**Found by a QA sweep of every screen, and fixed**
|
||||
|
||||
- 🔍 Search: "wrist" returned 200 abdominal exercises, because the typo tolerance matched body parts
|
||||
and equipment as well as names. Fuzzy matching is now name-only, and only for words with no exact
|
||||
hit anywhere.
|
||||
- ⚖️ Switching kg ↔ lb left each workout's stored total and session body weight in the old unit, so
|
||||
History, the calendar and the heatmap showed kilo totals under a pound label. Body weight also
|
||||
converts at 0.1 now, not in plate steps, so a round trip comes home.
|
||||
- 📤 Sharing a plan stripped a custom exercise down to its name and body part: it arrived with no
|
||||
equipment, no muscles, and no way to edit or delete it.
|
||||
- 📥 Importing a second export re-created the custom exercises the first one had made, splitting the
|
||||
history in two; imported volume counted warm-up sets; hyphenated names ("Stiff-Legged Deadlift")
|
||||
were filed under the wrong body part.
|
||||
- 📊 Tapping an exercise in Stats → Strength threw instead of opening its history.
|
||||
- 🛠️ Admin: a profile whose stored file held a malformed entry blanked the whole dashboard, and that
|
||||
account could then not be disabled. The API answers 400 (or 413) for a request the client got
|
||||
wrong instead of 500 with a stack trace, and refuses an array as the state document — which used
|
||||
to wipe the profile and silently reset its revision.
|
||||
- 📐 Phone-width layout: the double-progression row wraps into pairs, list-row titles keep their
|
||||
width, page headers give way before their button, drop-set rows and cardio speeds are readable,
|
||||
and the column header lines up over per-side rows.
|
||||
- 🇷🇺 Muscle names no longer leak internal ids ("gluteal", "hip-flexors") into the picker, the config
|
||||
sheet or the Muscles list, and a day with one routine says "1 routine".
|
||||
|
||||
**Known and not fixed**: counts in Russian and the other Slavic packs use the English two-form plural
|
||||
rule, so "2 дней" where it should read "2 дня". It affects every counter in the app and is being
|
||||
done properly rather than patched here.
|
||||
|
||||
## v1.3.7 — 2026-09-12
|
||||
|
||||
The v1.3.6 tag's Android build failed on a double dash inside an XML comment, so the APK for everything in v1.3.6 is this one — plus the iPhone timer-sound fix that landed an hour later. Web bundle, APK and API image; v1.3.6 and v1.3.7 are the same code apart from the two items below.
|
||||
|
||||
- 📦 **The Android build builds again**: a comment in `styles.xml` (from the safe-area work in v1.3.6) contained `--`, which XML forbids inside comments.
|
||||
- 🔊 **Timer sounds on iOS** (kurktchiev, #183, #152): every tone resumes the audio context first
|
||||
(a lock or app switch leaves it suspended and silent), the context is unlocked from the taps that
|
||||
lead to a timer, and Settings → Sounds gains **Play sounds when the phone is on silent** (off by
|
||||
default, iOS 17+), which switches the page's audio session to playback so the ring/silent switch
|
||||
no longer mutes the beep — at the cost of pausing whatever else the phone was playing.
|
||||
|
||||
## v1.3.6 — 2026-09-12
|
||||
|
||||
Sync you can trust and a phone that behaves: signed in, the server's profile is always the truth, two devices merge instead of overwriting each other, the app polls for changes and works offline with a banner; reminders and push subscriptions heal themselves; chip rows, sheets under the notch and the tab bar are fixed on iOS; the twelve Astra findings, eleven community merges and a headless QA sweep of every screen. Web bundle, APK and API image.
|
||||
|
||||
@@ -214,11 +214,13 @@ host side of that volume, not the variable.
|
||||
|
||||
## Roadmap
|
||||
|
||||
The plan lives in [ROADMAP.md](ROADMAP.md) (the
|
||||
[GitLab milestones](https://gitlab.com/DuarteSantos8/opengym/-/milestones) track the same items): v1.3.7 programmes and
|
||||
progression (explicit warm-up/work phases, AMRAP driver selection, multi-week programmes, adaptive
|
||||
1RM), v1.3.8 accounts and sync (password and OIDC login, personal-trainer role, remote MCP), v1.3.9
|
||||
mobile (timer in the notification bar, widgets, Withings). Ideas and pull requests welcome.
|
||||
The plan lives in [ROADMAP.md](ROADMAP.md), and the
|
||||
[GitHub milestones](https://github.com/DuarteSantos8/openGym/milestones) hold the issues. **A release every
|
||||
two weeks**, each one small and themed: the promised items, editing finished workouts, the session queue,
|
||||
programmes and phases, the progression engine, cardio — then **v1.4.0, the foundation: storage moves to a
|
||||
database and search is rebuilt, the one compatibility break** — then accounts (password and OIDC login,
|
||||
trainer role, MCP write), the iOS app, the Android and health items, and what all of that unlocks
|
||||
(pictures for custom exercises, catalogue work, skins, social). Ideas and pull requests welcome.
|
||||
|
||||
## Tech
|
||||
|
||||
|
||||
@@ -1,16 +1,19 @@
|
||||
# Roadmap
|
||||
|
||||
Where openGym is going, in the order it is likely to land. Each block is a GitLab milestone; the
|
||||
issues and merge requests attached to it are the plan, this file is the readable summary. The
|
||||
dates are the order, not a promise: a one-maintainer self-hosted project ships a version when the
|
||||
branch has been used in a real gym for a while. Blocks are deliberately over-full — whatever is not
|
||||
done when a version ships rolls into the next one. Version numbers follow the release rule, not the
|
||||
size of the change: the next release is the last published one plus one patch (1.3.1 → 1.3.2), and a
|
||||
minor bump is reserved for something that breaks compatibility.
|
||||
Where openGym is going, in the order it is likely to land. Each block is a GitHub milestone; the
|
||||
issues and pull requests attached to it are the plan, this file is the readable summary.
|
||||
|
||||
- Board: https://gitlab.com/DuarteSantos8/opengym/-/boards — planned → in progress → in review → closed
|
||||
- Milestones: https://gitlab.com/DuarteSantos8/opengym/-/milestones
|
||||
- "In review" means: on a branch and deployed to gym-test.duarte-santos.ch, waiting for a real session.
|
||||
**A release every two weeks, on a Sunday.** Each one is small on purpose: a handful of issues, one
|
||||
theme, so a version is out before the branch has drifted and every fix reaches phones within a
|
||||
fortnight. Whatever is not merged and tested on gym-test by the Friday before rolls into the next
|
||||
block, the date does not move. Version numbers follow the release rule, not the size of the change:
|
||||
the next release is the last published one plus one patch (1.3.7 → 1.3.8), and a minor bump is
|
||||
reserved for something that breaks compatibility — that is v1.4.0, the database.
|
||||
|
||||
- Milestones: https://github.com/DuarteSantos8/openGym/milestones — every open issue sits in exactly one
|
||||
- Tracks, in order: promised items → history editing → queue and programmes → the progression
|
||||
engine → cardio → **the foundation (database, then search)** → accounts → the iOS app → Android
|
||||
and health → exercises → looks and social
|
||||
|
||||
---
|
||||
|
||||
@@ -57,7 +60,7 @@ Left over from this block:
|
||||
- A real pause for the workout timers (#29 asked for it)
|
||||
- Discord announcement (owner)
|
||||
|
||||
## v1.3.6 — Sync, push and the phone (released 2026-09-12)
|
||||
## v1.3.6 and v1.3.7 — Sync, push and the phone (released 2026-09-12)
|
||||
|
||||
Signed in, the server's profile is the truth: sign-in adopts it, two devices merge on a server
|
||||
revision instead of overwriting each other, the app polls for changes and works offline with a
|
||||
@@ -69,71 +72,142 @@ the phone, nginx resolver, custom-exercise equipment, per-side data, warm-up res
|
||||
QA sweep of every screen. Left over: routine reordering (#142), the Smith-bar "no bar" option
|
||||
(#138), two decimals (#139), delete user in the admin (#107).
|
||||
|
||||
## v1.3.7 — Programmes & progression (October 2026)
|
||||
## v1.3.8 — Promised items (released 2026-09-20, a week early)
|
||||
|
||||
**Theme: training structure beyond one weekly template.** Most of this is the Space-Hermes series.
|
||||
It changes the training model (per-set roles, explicit phases, normalisation on every persist), so
|
||||
it goes in one MR at a time, each rebased and tested on gym-test before the next.
|
||||
All four promises, plus the iOS keyboard, the assisted machines and a QA sweep of every screen —
|
||||
twenty-four reports in total. See the changelog for the full list.
|
||||
|
||||
- Explicit warm-up / work phases on every row, with legacy rows still readable (!76)
|
||||
- Per-phase settings during a workout: set count, targets, fixed or percentage loads (!56)
|
||||
- Choose which set drives AMRAP progression instead of "the last one" (!78)
|
||||
- Multi-week programmes: 1–52 weeks, normal/deload/rest weeks, several sessions per day,
|
||||
start/complete lifecycle, off by default (!98, #15)
|
||||
- Home: several routines on one day with a session chooser; date overrides as ordered lists (!74)
|
||||
- Per-exercise strength with an adaptive estimated 1RM; one point per workout and exact exercise (!50)
|
||||
- Import: kg/lb normalised per row to the profile unit, malformed rows reported before confirming;
|
||||
duration-only rows classified as timed strength or cardio (!53)
|
||||
- Plan sharing: versioned payload, custom exercises carried across, repeat imports idempotent (!49)
|
||||
- Resistance bands treated like bodyweight in config and progression (#39)
|
||||
- Exercise history and a progress chart from inside the workout (#43) — reachable from the ⋯ menu
|
||||
- Pictures for custom exercises: pick from the catalogue, later upload (#30)
|
||||
- Percentage / training-max programming (5/3/1 style) on top of the policy interface
|
||||
- Rest-pause and drop sets configurable in the routine editor, with adjustable rest (#17)
|
||||
- Catalogue cleanup: exercises that should not carry weight, incline and interval fields for
|
||||
cardio (#46); timers for planks and outdoor cardio are already there, document them (#45)
|
||||
- Reorder routines in Plan; the Start sheet follows that order (#142) ✅
|
||||
- "No bar" per exercise, so Smith-machine lifts calculate plates and drop sets from 0 (#138) ✅
|
||||
- Two decimals on weights, as a display toggle (#139) ✅
|
||||
- Delete a user from the admin dashboard: credentials, state file, subscriptions, Coach data (#107) ✅
|
||||
- Custom-exercise muscle order is fixed, not click order; the import fallback classifies "wrist
|
||||
curl", "row … neutral grip" and Romanian deadlifts correctly (Discord) ✅
|
||||
- The small open pull requests: unknown-path redirect (#185), manifest behind an auth proxy (#184),
|
||||
standard ß (#190) ✅ — the distance mode (#177, #178) moves to a later release
|
||||
|
||||
## v1.3.8 — Accounts & sync (November 2026)
|
||||
## v1.3.9 — Editing history (2026-10-11)
|
||||
|
||||
**Theme: who may sign in, and what else may read or write your data.**
|
||||
- **Edit a finished workout** — date, start time, duration, name, sets, weights, add or remove an
|
||||
exercise; progression and 1RM history re-read the corrected session (#143; GitLab !127 and !139
|
||||
as reference; Discord "edit finished workouts", "edit past workouts time", "change the date")
|
||||
- Save a logged workout as a routine, repeat a past workout from History, undo finish (#111, #58,
|
||||
GitLab !130; Discord "Historic tab")
|
||||
- Relabel an "Unknown" exercise after an import without losing its sets; copy a workout as text
|
||||
(Discord)
|
||||
- Auto-backup keeps the last N files (#161, first half); a "next step" hotkey independent of focus
|
||||
(#133); body measurements (PR #82), extra passkeys and the device link (PR #95)
|
||||
|
||||
- Optional username + password login next to passkeys, for devices without a passkey (#1)
|
||||
- OIDC login for people with an existing SSO such as PocketID or Authelia (#40)
|
||||
- Personal-trainer role: invite students by code, open a student in a read-only context, write
|
||||
their plan from a template library, assign in one tap (!79, #8)
|
||||
- Remote MCP over OAuth for hosted AI clients, with per-connection profile and read/write scopes,
|
||||
and compare-and-swap writes to the profile state (!88)
|
||||
- MCP write tools: create/update routines, correct a logged set, delete a duplicate session,
|
||||
manage equipment profiles (#24)
|
||||
- Switching kg ↔ lb converts stored values instead of relabelling them (#22)
|
||||
- Offline: saved routines and the active workout usable without the server, sync on return (#23)
|
||||
- Sync reports still waiting on details: routines created on the web not reaching the phone (#33),
|
||||
logged sessions lost after editing a routine (#25)
|
||||
## v1.3.10 — Session queue & rotation (2026-10-25)
|
||||
|
||||
- A free-running session queue beside the fixed week — the next session is the next undone one,
|
||||
whatever the weekday — with an in-app editor and automatic refill (#158, #69; PR #167 and the
|
||||
editor on top of it; Discord "not forced into a weekly plan")
|
||||
- Swipe between exercise cards during a workout (#113, GitLab !114)
|
||||
- Drag-and-drop exercise order that survives touch (#114 — the first version came out again on
|
||||
2026-09-07); the Start/Resume button as "next" during a workout (Discord)
|
||||
|
||||
## v1.3.11 — Programmes & phases (2026-11-08)
|
||||
|
||||
- Programmes: routines grouped into a named block over weeks, with deload and rest weeks, several
|
||||
per profile (#159, GitLab !98; Discord "Programme mode", "folders", "major good ideas" 1)
|
||||
- Session phases — mobility / work / accessory / cooldown — with completion-only exercises for
|
||||
stretching that stay out of volume and PRs (#57, #140; Discord "non-typed exercises")
|
||||
|
||||
## v1.3.12 — Progression engine I (2026-11-22)
|
||||
|
||||
- A universal AMRAP / "to failure" flag and rep or set ranges per set (#154; Discord "Sets to
|
||||
Failure", "More types of sets")
|
||||
- Triple progression, reps → sets → load (#179, #186; PR #181)
|
||||
- Multi-formula 1RM with Epley as the default shown (#155); assisted exercises as negative added
|
||||
weight (#176)
|
||||
|
||||
## v1.3.13 — Progression engine II (2026-12-06)
|
||||
|
||||
- Load as %1RM or auto with a stored training max, target RPE/RIR (#153)
|
||||
- Wave / percentage progression, 5/3/1 style (#70; PR #168)
|
||||
- A warm-up generator that picks the ramp from load and lift (#156)
|
||||
- Periodisation extras on top: mesocycle blocks, auto-regulation on RPE (#120)
|
||||
|
||||
## v1.3.14 — Cardio, alternatives, groups (2026-12-20)
|
||||
|
||||
- Cardio: incline and intervals (rounds × work/rest), interval programmes such as C25k, rucking as
|
||||
distance + pace + load (#132, #169; Discord "incline treadmill", "cardio programs", "rucking")
|
||||
- Exercise alternatives per routine slot, and Replace in the routine editor (#110; Discord)
|
||||
- Complexes and interval groups beside supersets (Discord)
|
||||
|
||||
## v1.4.0 — Foundation: database (2027-01-10)
|
||||
|
||||
**The one compatibility break.** Storage moves from one JSON file per profile to a database (#191):
|
||||
tables for workouts, sets, routines, weigh-ins, custom exercises, favourites, credentials, push
|
||||
subscriptions and Coach data; an idempotent migration on first start; the old files kept until the
|
||||
admin removes them. The state file stays the import/export and backup format, and the revision/merge
|
||||
contract from v1.3.6 stays the client contract. Which database is decided in the issue — embedded by
|
||||
default so `docker compose up` stays one line, a server database as an option (Discord
|
||||
"Postgres/SQLite"). Nothing else rides on this release; it gets the three-week slot over the holidays.
|
||||
|
||||
## v1.4.1 — Foundation: search (2027-01-24)
|
||||
|
||||
- Search rebuilt over catalogue names in every language, import aliases, custom exercises and
|
||||
history: typo tolerance (GitLab !122), a live result count (!31), filters that compose, built once
|
||||
per catalogue version (#192)
|
||||
- Shared custom exercises between accounts on one instance (#151)
|
||||
- "Different gyms": a location on a logged set, separate histories and PRs per location, bodyweight
|
||||
shared (Discord "How to deal with different gyms")
|
||||
- Admin: per-user export, invite management, audit log filters
|
||||
|
||||
## v1.3.9 — Mobile (December 2026)
|
||||
## v1.4.2 — Accounts: password & OIDC (2027-02-07)
|
||||
|
||||
**Theme: the Android app catches up with the web app.**
|
||||
- Optional username + password login next to passkeys (#118; Discord "Basic login", the
|
||||
password-manager thread)
|
||||
- OIDC login for PocketID / Authelia-style setups (#130, #72; GitLab !132 is the candidate)
|
||||
|
||||
- In-app update check against the GitLab releases, APK download with SHA-256 check and install (!40, #38, #9)
|
||||
- Rest timer as an ongoing notification and on the lock screen, with "next set" from there (#19, #26)
|
||||
- Home-screen widget for today's session
|
||||
- Body weight from Withings or the phone's health store (#31)
|
||||
- External links open in the system browser; Android back gesture across every screen
|
||||
- Play Store / F-Droid feasibility check (the app stays sideload-first)
|
||||
## v1.4.3 — Trainer & MCP write (2027-02-21)
|
||||
|
||||
## Later — ideas, not scheduled
|
||||
- Personal-trainer role: invite students by code, open a student read-only, write their plan (#119,
|
||||
GitLab !79; Discord "Trainer & Student Management")
|
||||
- MCP write tools — routines, log corrections, equipment — in pieces (#116); remote MCP over OAuth
|
||||
for hosted AI clients (GitLab !88)
|
||||
- Switching kg ↔ lb converts stored values instead of relabelling them (#22)
|
||||
|
||||
- Skins alongside the accent colour, default look untouched (#34); background wallpapers (#48)
|
||||
- Big-screen / kiosk layout for a wall display (#49) and a physical "next" button, keyboard first (#47)
|
||||
- Native NixOS module (!83) and Azure App Service deployment (!35) — only if someone maintains them
|
||||
- Arabic and right-to-left layout (!36) — needs a rebase, then a visual round
|
||||
- Periodisation extras: wave progression, auto-regulation on RPE, training-age based recommendations (#15)
|
||||
- Watch app / companion for the rest timer
|
||||
## v1.4.4 — iOS app (2027-03-07)
|
||||
|
||||
- App Store / TestFlight build of the existing Capacitor target, HealthKit weight and workout
|
||||
export, the Home Screen icon and timer-sound issues gone for good (#90; Discord "Google Health")
|
||||
- Apple Watch rest timer later, once the app is in the store
|
||||
|
||||
## v1.4.5 — Android & health (2027-03-21)
|
||||
|
||||
- Health Connect for weight and sessions (Discord "Use health connect"); Withings and other scales
|
||||
(#127)
|
||||
- The rest timer as an ongoing notification on the lock screen (#122); a home-screen widget (#125)
|
||||
- APK back under 10 MB with ABI filters (#136); the auto-backup directory picker (#161, second half)
|
||||
- Media for the routine's exercises cached on the phone, so a session works with no signal (#123;
|
||||
Discord "Download all videos")
|
||||
- Firefox-on-Windows QR and third-party passkey providers stay documented, not fixed — platform
|
||||
behaviour (#103, #101)
|
||||
|
||||
## v1.4.6 — Exercises & catalogue (2027-04-04)
|
||||
|
||||
- Pictures for custom exercises: pick from the catalogue, then upload; a video URL per exercise
|
||||
(#126, #170; Discord "custom images/GIFs", "upload videos")
|
||||
- Catalogue: bench as equipment with flat / adjustable, TRX / suspension, lats and the three delts
|
||||
as their own categories, exercises that should not carry weight, more routine icons (#132, #188;
|
||||
Discord)
|
||||
- Choose what the "last time" line shows on the logger (#173); one progress line per set number
|
||||
(#145); custom heatmap targets per muscle; a shareable image after a workout (Discord)
|
||||
|
||||
## v1.4.7 — Looks, social, plugins (2027-04-18)
|
||||
|
||||
- Skins alongside the accent colour, backgrounds as part of a skin, a big-screen layout (#129,
|
||||
#134, #135)
|
||||
- Social: friends, progress and plan sharing (PR #180); a plugin surface for integrations (Discord)
|
||||
- Native NixOS module (GitLab !83) and Azure deployment (!35) only if someone maintains them;
|
||||
Arabic and right-to-left (GitLab !36) once rebased
|
||||
|
||||
## How things move
|
||||
|
||||
An issue goes planned → in progress → in review → closed on the board. Contributor merge requests
|
||||
from returning contributors get their pipeline started here automatically; a first MR is started
|
||||
by hand after a look at the diff. Anything in review is on gym-test.duarte-santos.ch. Releases
|
||||
An issue sits in exactly one milestone; a milestone is a Sunday, and whatever is not merged and
|
||||
tested on gym-test by the Friday before rolls into the next one — the date stays. Contributor pull requests from returning contributors get their pipeline started here
|
||||
automatically; a first PR is started by hand after a look at the diff. Anything in review is on gym-test.duarte-santos.ch. Releases
|
||||
bundle whatever has passed that test, with a changelog section per contributor.
|
||||
@@ -6,7 +6,7 @@ openapi: 3.1.0
|
||||
|
||||
info:
|
||||
title: openGym API
|
||||
version: 1.3.6
|
||||
version: 1.3.8
|
||||
summary: Passkey (WebAuthn) auth + per-user state storage for openGym
|
||||
description: |
|
||||
The backend of [openGym](https://opengym.duarte-santos.ch) — a free, open-source
|
||||
@@ -50,7 +50,11 @@ info:
|
||||
- Errors are always `{"error": "<human-readable message>"}`.
|
||||
- Unknown method+path pairs return `404 {"error":"not found"}`; an unhandled
|
||||
exception returns `500 {"error":"server error"}`.
|
||||
- Request bodies are parsed as JSON regardless of Content-Type; max 5 MiB.
|
||||
- Request bodies are parsed as JSON regardless of Content-Type. A body that does
|
||||
not parse, or parses to anything but an object (`null`, a string, an array), is
|
||||
`400 {"error":"invalid json"}` on every route that reads one; an empty body counts
|
||||
as `{}`. A body over 5 MiB is `413 {"error":"body too large"}`; the rest of the
|
||||
upload is discarded so the answer reaches the client.
|
||||
- CORS: the request's `Origin` is reflected in `Access-Control-Allow-Origin`
|
||||
**without** `Allow-Credentials` — cross-origin callers can only ever
|
||||
authenticate with a Bearer token, never with the cookie.
|
||||
@@ -556,8 +560,10 @@ paths:
|
||||
- type: 'null'
|
||||
'400':
|
||||
description: >-
|
||||
`state` missing or not an object, or `workouts`/`routines` set to anything
|
||||
other than an array or null.
|
||||
`state` missing or not an object, `state` an array, or `workouts`/`routines`
|
||||
set to anything other than an array or null. Entries inside those two arrays
|
||||
that are not objects (`null`, numbers, nested arrays) are dropped before the
|
||||
write rather than refused, so a client with a damaged copy still syncs.
|
||||
content:
|
||||
application/json:
|
||||
schema: { $ref: '#/components/schemas/Error' }
|
||||
@@ -725,7 +731,8 @@ paths:
|
||||
operationId: pushRestTimer
|
||||
summary: Schedule a server-side rest-timer push
|
||||
description: |
|
||||
Schedules one push after `seconds` (clamped to 1–3600). One pending timer per
|
||||
Schedules one push after `seconds` (a number or numeric string ≥ 1, clamped to
|
||||
3600). One pending timer per
|
||||
device — `deviceId`, the same token the subscription was registered with; a
|
||||
new call from the same device replaces it, and the push goes only to that
|
||||
device's subscriptions. Without a `deviceId` there is one timer per account
|
||||
@@ -733,9 +740,6 @@ paths:
|
||||
on rest start/extend and cancels on skip or on-screen completion — the push
|
||||
only actually fires when the tab was backgrounded/suspended and never got to
|
||||
cancel it. Timers live in memory: an API restart drops them.
|
||||
|
||||
Note: the documented `400 seconds required` exists in the code but is
|
||||
unreachable — the clamp turns any missing/invalid value into 1.
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
@@ -759,6 +763,12 @@ paths:
|
||||
content:
|
||||
application/json:
|
||||
schema: { $ref: '#/components/schemas/Ok' }
|
||||
'400':
|
||||
description: '`seconds` missing, not numeric, or below 1. Nothing is scheduled.'
|
||||
content:
|
||||
application/json:
|
||||
schema: { $ref: '#/components/schemas/Error' }
|
||||
example: { error: "seconds required" }
|
||||
'401': { $ref: '#/components/responses/Unauthorized' }
|
||||
|
||||
/api/push/rest-timer/cancel:
|
||||
@@ -841,7 +851,8 @@ paths:
|
||||
summary: 'Admin: list all users'
|
||||
description: >-
|
||||
One row per user with workout counts, last sync, push status and live
|
||||
presence. Admin only.
|
||||
presence. `workouts` counts only the entries the drill-down can show.
|
||||
Admin only.
|
||||
responses:
|
||||
'200':
|
||||
description: All users.
|
||||
@@ -867,7 +878,10 @@ paths:
|
||||
summary: 'Admin: one user in detail'
|
||||
description: >-
|
||||
Drill-down — full workout history (newest first) and body-weight log for one
|
||||
user. Admin only.
|
||||
user. Admin only. Anything in `routines`, `bodyweight` or `workouts` that is not
|
||||
an object is left out, and a list that is not an array reads as empty: PUT
|
||||
/api/data drops those entries now, but a state file written before it did still
|
||||
has them and this route has to answer for it.
|
||||
parameters:
|
||||
- name: id
|
||||
in: query
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "gym-api",
|
||||
"version": "1.3.6",
|
||||
"version": "1.3.8",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "gym-api",
|
||||
"version": "1.3.6",
|
||||
"version": "1.3.8",
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"dependencies": {
|
||||
"@simplewebauthn/server": "^13.1.1",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "gym-api",
|
||||
"version": "1.3.6",
|
||||
"version": "1.3.8",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "server.js",
|
||||
|
||||
@@ -81,6 +81,16 @@ const stateFile = uid => path.join(DATA, 'state-' + uid.replace(/[^a-zA-Z0-9_-]/
|
||||
function readState(uid) {
|
||||
try { return JSON.parse(fs.readFileSync(stateFile(uid), 'utf8')); } catch { return null; }
|
||||
}
|
||||
// An entry is an object a reader can dereference, and `records` is every entry of a stored
|
||||
// list. PUT /api/data drops the rest on the way in — a null workout, a routine that is a
|
||||
// number — and refuses a list that is not an array at all, but a file written before it did
|
||||
// answers to nobody, and the readers below walk those lists (`r.id`, `w.d`, `.slice()`). One
|
||||
// throw inside an admin route is a 500 for that whole profile: the drill-down never leaves
|
||||
// "Loading…", the Disable button lives inside it, and the account an operator opened the
|
||||
// dashboard to stop is exactly the one they then cannot. Answering with the entries that are
|
||||
// there is the honest reading of such a file — what was dropped carried nothing to show.
|
||||
const record = x => !!x && typeof x === 'object' && !Array.isArray(x);
|
||||
const records = v => (Array.isArray(v) ? v.filter(record) : []);
|
||||
|
||||
/* ---------- push notifications (Web Push / VAPID) ---------- */
|
||||
const vapidFile = path.join(DATA, 'vapid.json');
|
||||
@@ -259,13 +269,14 @@ const deviceIdOf = v => (typeof v === 'string' && /^[A-Za-z0-9_-]{8,64}$/.test(v
|
||||
|
||||
// "Workout planned today" reminder — one per user per day, at their chosen time.
|
||||
// Duplicated (not imported) from frontend/src/lib/history.js effectiveRoutineId — tiny pure helper, not worth sharing across the two runtimes.
|
||||
// The `?.` on each entry is this copy's own: it reads whatever is on disk, including a file written before PUT /api/data dropped null entries.
|
||||
// A weekday can hold a routine-id list (combine routines); the reminder only needs the first.
|
||||
function effectiveRoutineId(S, iso) {
|
||||
const ov = S.dayPlan?.[iso];
|
||||
if (ov === 'rest') return null;
|
||||
if (ov && S.routines?.some(r => r.id === ov)) return ov;
|
||||
if (ov && S.routines?.some(r => r?.id === ov)) return ov;
|
||||
const wd = new Date(iso + 'T12:00:00').getDay();
|
||||
return [].concat(S.week?.[wd] || []).find(id => S.routines?.some(r => r.id === id)) || null;
|
||||
return [].concat(S.week?.[wd] || []).find(id => S.routines?.some(r => r?.id === id)) || null;
|
||||
}
|
||||
// Computes "now" in an arbitrary IANA zone (e.g. "Europe/Lisbon") instead of the server's own —
|
||||
// each user's reminder fires by their own clock, wherever they and their phone actually are.
|
||||
@@ -324,10 +335,10 @@ setInterval(() => {
|
||||
const late = minutesLate(S.reminder.time, now);
|
||||
if (!(late >= 0 && late <= REMINDER_WINDOW_MIN)) continue;
|
||||
if (user.lastReminder === now.date) continue;
|
||||
if ((S.workouts || []).some(w => w.d === now.date)) continue;
|
||||
if ((S.workouts || []).some(w => w?.d === now.date)) continue;
|
||||
const rid = effectiveRoutineId(S, now.date);
|
||||
if (!rid) continue; // rest day — nothing planned
|
||||
const routine = (S.routines || []).find(r => r.id === rid);
|
||||
const routine = (S.routines || []).find(r => r?.id === rid);
|
||||
console.log('reminder firing', user.id, rid);
|
||||
user.lastReminder = now.date;
|
||||
saveDb();
|
||||
@@ -513,21 +524,53 @@ function json(res, code, obj, extraHeaders) {
|
||||
res.writeHead(code, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store', ...(extraHeaders || {}) });
|
||||
res.end(body);
|
||||
}
|
||||
// A request the caller got wrong. The catch-all at the bottom answers it with this status and
|
||||
// message and does not log it: three of the routes below are reachable without a session, and a
|
||||
// stack trace per malformed body would let anyone fill the container log with noise that looks
|
||||
// like a crash. Anything else that escapes a handler is still a real 500 and still logged.
|
||||
class HttpError extends Error {
|
||||
constructor(status, message) { super(message); this.status = status; }
|
||||
}
|
||||
function readBody(req) {
|
||||
return new Promise((resolve, reject) => {
|
||||
let size = 0; const chunks = [];
|
||||
let size = 0, over = false; const chunks = [];
|
||||
req.on('data', d => {
|
||||
size += d.length;
|
||||
if (size > MAX_BODY) { reject(new Error('body too large')); req.destroy(); return; }
|
||||
if (over) {
|
||||
// The 413 is already on its way. The rest of the upload is read and thrown away rather
|
||||
// than the socket destroyed under it: closing with unread bytes on the wire makes the
|
||||
// kernel send a reset, and a client (node's own http client included) that hits the
|
||||
// reset before it has parsed the answer reports a dropped connection instead of the
|
||||
// 413. A client that keeps streaming past twice the cap is not a mistaken one, and is
|
||||
// cut off.
|
||||
if (size > 2 * MAX_BODY) req.destroy();
|
||||
return;
|
||||
}
|
||||
if (size > MAX_BODY) {
|
||||
over = true; chunks.length = 0;
|
||||
reject(new HttpError(413, 'body too large'));
|
||||
return;
|
||||
}
|
||||
chunks.push(d);
|
||||
});
|
||||
req.on('end', () => {
|
||||
try { resolve(chunks.length ? JSON.parse(Buffer.concat(chunks).toString('utf8')) : {}); }
|
||||
catch { reject(new Error('bad json')); }
|
||||
if (over) return;
|
||||
if (!chunks.length) return resolve({});
|
||||
let body;
|
||||
try { body = JSON.parse(Buffer.concat(chunks).toString('utf8')); }
|
||||
catch { return reject(new HttpError(400, 'invalid json')); }
|
||||
// Every handler reads fields off the result, so a JSON `null`, string, number or array is
|
||||
// as much a client mistake as unparseable text — refused once here rather than dereferenced
|
||||
// (and turned into a TypeError) in each route.
|
||||
if (!body || typeof body !== 'object' || Array.isArray(body)) return reject(new HttpError(400, 'invalid json'));
|
||||
resolve(body);
|
||||
});
|
||||
req.on('error', reject);
|
||||
});
|
||||
}
|
||||
// A caller-supplied field that is meant to be text. String() alone is not safe on a parsed body:
|
||||
// `{"code":{"toString":1}}` is valid JSON and String() throws on it.
|
||||
const text = v => (typeof v === 'string' ? v : typeof v === 'number' ? String(v) : '');
|
||||
const b64uToBuf = s => Buffer.from(s, 'base64url');
|
||||
|
||||
/* ---------- live presence (in-memory) ---------- */
|
||||
@@ -658,9 +701,9 @@ const routes = {
|
||||
|
||||
'POST /api/register/options': async (req, res) => {
|
||||
const body = await readBody(req);
|
||||
const name = String(body.name || '').trim().slice(0, 40);
|
||||
const name = text(body.name).trim().slice(0, 40);
|
||||
if (!name) return json(res, 400, { error: 'name required' });
|
||||
const code = String(body.code || '').trim().toUpperCase();
|
||||
const code = text(body.code).trim().toUpperCase();
|
||||
if (INVITE_ONLY && !db.invites.some(i => i.code === code && !i.usedBy && !i.revoked)) {
|
||||
// The rejected code itself is never recorded — a near-miss guess in the log is a liability.
|
||||
audit(req, 'auth.register.denied', { ok: false, name, msg: 'invite-rejected' });
|
||||
@@ -830,7 +873,7 @@ const routes = {
|
||||
// the code IS the credential, one-shot and 5-minute-lived like a WebAuthn challenge.
|
||||
'POST /api/pair/redeem': async (req, res) => {
|
||||
const body = await readBody(req);
|
||||
const code = String(body.code || '').trim().toUpperCase();
|
||||
const code = text(body.code).trim().toUpperCase();
|
||||
const p = pairings.get(code);
|
||||
if (p) pairings.delete(code);
|
||||
if (!p || p.exp < Date.now()) {
|
||||
@@ -871,9 +914,16 @@ const routes = {
|
||||
if (!body.state || typeof body.state !== 'object') return json(res, 400, { error: 'state required' });
|
||||
// The reminder tick and the admin routes iterate these two on the server's side, so a truthy
|
||||
// non-array would throw there on every pass for as long as it sat on disk. Absent or null is
|
||||
// fine — every client fills its own defaults.
|
||||
// fine — every client fills its own defaults. An array is `typeof 'object'` but no document:
|
||||
// `_rev` set on it is dropped by JSON.stringify, so the file would read back as rev 0 while
|
||||
// the response claimed the next revision.
|
||||
const list = v => v == null || Array.isArray(v);
|
||||
if (!list(body.state.workouts) || !list(body.state.routines)) return json(res, 400, { error: 'invalid state' });
|
||||
if (Array.isArray(body.state) || !list(body.state.workouts) || !list(body.state.routines)) return json(res, 400, { error: 'invalid state' });
|
||||
// The same readers walk every entry (`w.d`, `w.name`). They skip what is not an entry now
|
||||
// (`records` above), but nothing should be storing one. Dropped, not refused:
|
||||
// such an entry carries nothing worth keeping, whereas a 400 would strand a client whose own
|
||||
// copy is already malformed — it keeps re-sending the same document and never syncs again.
|
||||
for (const k of ['workouts', 'routines']) if (Array.isArray(body.state[k])) body.state[k] = records(body.state[k]);
|
||||
// Conditional write: a `baseRev` that is not the current revision means this client last
|
||||
// read an older document — another device has written since — and the copy it is about to
|
||||
// push would silently drop that write. The current document travels back with the 409, so
|
||||
@@ -954,8 +1004,13 @@ const routes = {
|
||||
const user = readSession(req);
|
||||
if (!user) return json(res, 401, { error: 'not signed in' });
|
||||
const body = await readBody(req);
|
||||
const sec = Math.max(1, Math.min(3600, Math.round(+body.seconds || 0)));
|
||||
if (!sec) return json(res, 400, { error: 'seconds required' });
|
||||
// Validated before it is clamped: the clamp used to run first, which turned a missing or
|
||||
// unusable value into a 1-second push and made the 400 below unreachable. `Number()` only
|
||||
// on a number or a string — on an object it can throw.
|
||||
const raw = body.seconds;
|
||||
const n = typeof raw === 'number' || typeof raw === 'string' ? Number(raw) : NaN;
|
||||
if (!(n >= 1)) return json(res, 400, { error: 'seconds required' });
|
||||
const sec = Math.min(3600, Math.round(n));
|
||||
scheduleRestTimer(user.id, deviceIdOf(body.deviceId), sec, readState(user.id)?.lang);
|
||||
json(res, 200, { ok: true });
|
||||
},
|
||||
@@ -975,7 +1030,7 @@ const routes = {
|
||||
const body = await readBody(req);
|
||||
if (body.active) {
|
||||
presence.set(user.id, {
|
||||
name: String(body.name || '').slice(0, 60),
|
||||
name: text(body.name).slice(0, 60),
|
||||
exIdx: +body.exIdx || 0, exTotal: +body.exTotal || 0,
|
||||
setsDone: +body.setsDone || 0, setsTotal: +body.setsTotal || 0,
|
||||
startedAt: +body.startedAt || Date.now(),
|
||||
@@ -991,7 +1046,7 @@ const routes = {
|
||||
if (!requireAdmin(req, res)) return;
|
||||
const users = db.users.map(u => {
|
||||
const S = readState(u.id) || {};
|
||||
const workouts = S.workouts || [];
|
||||
const workouts = records(S.workouts);
|
||||
const last = workouts[workouts.length - 1];
|
||||
return {
|
||||
id: u.id, name: u.name, created: u.created || null,
|
||||
@@ -1017,9 +1072,9 @@ const routes = {
|
||||
user: { id: u.id, name: u.name, created: u.created || null, disabled: !!u.disabled, admin: isAdmin(u), invitedBy: u.invitedBy || null },
|
||||
unit: S.unit || 'kg',
|
||||
lastSync: S._ts || null,
|
||||
routines: (S.routines || []).map(r => ({ id: r.id, name: r.name, emoji: r.emoji, count: (r.ex || []).length })),
|
||||
bodyweight: S.bodyweight || [],
|
||||
workouts: (S.workouts || []).slice().reverse() // newest first for display
|
||||
routines: records(S.routines).map(r => ({ id: r.id, name: r.name, emoji: r.emoji, count: records(r.ex).length })),
|
||||
bodyweight: records(S.bodyweight),
|
||||
workouts: records(S.workouts).reverse() // records() already copied, so this reverse is ours: newest first for display
|
||||
});
|
||||
},
|
||||
|
||||
@@ -1036,6 +1091,33 @@ const routes = {
|
||||
json(res, 200, { ok: true, id: u.id, disabled: u.disabled });
|
||||
},
|
||||
|
||||
// Disable locks an account out; this removes it. The one destructive action in the app, so the
|
||||
// client asks twice and this end refuses the two cases that cannot be undone from the UI
|
||||
// afterwards: an admin deleting themselves, and the last admin standing (issue #107).
|
||||
// The invite code that let them in stays burned — it was used, and freeing it would quietly
|
||||
// widen an invite-only instance. `GET /api/admin/user` is the export: the dashboard offers it
|
||||
// before the confirm, so the training history can be kept if anyone wants it.
|
||||
'POST /api/admin/user/delete': async (req, res) => {
|
||||
const admin = requireAdmin(req, res); if (!admin) return;
|
||||
const body = await readBody(req);
|
||||
const u = db.users.find(x => x.id === body.id);
|
||||
if (!u) return json(res, 404, { error: 'no such user' });
|
||||
if (u.id === admin.id) return json(res, 400, { error: 'you cannot delete your own account' });
|
||||
if (isAdmin(u) && db.users.filter(isAdmin).length <= 1) return json(res, 400, { error: 'cannot delete the last admin' });
|
||||
const name = u.name;
|
||||
db.users = db.users.filter(x => x.id !== u.id);
|
||||
db.creds = (db.creds || []).filter(c => c.userId !== u.id);
|
||||
db.subs = (db.subs || []).filter(x => x.userId !== u.id);
|
||||
presence.delete(u.id);
|
||||
// The training history and any Coach credential of theirs, both outside db.json.
|
||||
try { fs.unlinkSync(stateFile(u.id)); } catch { /* already gone */ }
|
||||
try { coachConfig.clearProfileAuth(u.id); } catch { /* nothing stored */ }
|
||||
saveDb();
|
||||
// Logged with the name, because the id is about to mean nothing to anyone reading this back.
|
||||
audit(req, 'admin.user.delete', { user: admin, msg: name });
|
||||
json(res, 200, { ok: true, id: u.id });
|
||||
},
|
||||
|
||||
'GET /api/admin/invites': async (req, res) => {
|
||||
if (!requireAdmin(req, res)) return;
|
||||
// resolve usedBy uid → name for display
|
||||
@@ -1054,7 +1136,7 @@ const routes = {
|
||||
// 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() };
|
||||
const invite = { code, note: text(body.note).slice(0, 60), createdBy: admin.id, created: new Date().toISOString() };
|
||||
db.invites.push(invite);
|
||||
saveDb();
|
||||
audit(req, 'admin.invite.create', { user: admin, msg: code });
|
||||
@@ -1064,7 +1146,7 @@ const routes = {
|
||||
'POST /api/admin/invites/revoke': async (req, res) => {
|
||||
const admin = requireAdmin(req, res); if (!admin) return;
|
||||
const body = await readBody(req);
|
||||
const inv = db.invites.find(i => i.code === String(body.code || '').toUpperCase());
|
||||
const inv = db.invites.find(i => i.code === text(body.code).toUpperCase());
|
||||
if (!inv) return json(res, 404, { error: 'no such code' });
|
||||
if (inv.usedBy) return json(res, 400, { error: 'already used — cannot revoke' });
|
||||
db.invites = db.invites.filter(i => i.code !== inv.code);
|
||||
@@ -1166,6 +1248,10 @@ http.createServer(async (req, res) => {
|
||||
}
|
||||
try { await handler(req, res); }
|
||||
catch (e) {
|
||||
if (e instanceof HttpError) {
|
||||
if (!res.headersSent) json(res, e.status, { error: e.message });
|
||||
return;
|
||||
}
|
||||
console.error(key, e);
|
||||
if (!res.headersSent) json(res, 500, { error: 'server error' });
|
||||
}
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
/* Issue #107: disabling locks an account out but deliberately leaves state-<uid>.json and the
|
||||
credential record in place, so "no data remains" was not reachable from the dashboard. Delete
|
||||
removes the user, their credentials, their push subscriptions, their training history and any
|
||||
Coach credential — and refuses the two cases nothing in the UI could undo afterwards. Real
|
||||
server.js in a child, same harness as server-admin-state.test.js. */
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import crypto from 'node:crypto';
|
||||
import net from 'node:net';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { spawn } from 'node:child_process';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const API = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const SECRET = crypto.randomBytes(32).toString('hex');
|
||||
const mintSession = uid => {
|
||||
const payload = `${uid}:${Date.now() + 86400000}:0`;
|
||||
return payload + '.' + crypto.createHmac('sha256', SECRET).update(payload).digest('base64url');
|
||||
};
|
||||
const ADMIN = 'u_adm_1', ADMIN2 = 'u_adm_2', VICTIM = 'u_vic_1';
|
||||
const as = uid => ({ Cookie: `gymsid=${mintSession(uid)}`, 'Content-Type': 'application/json' });
|
||||
const freePort = () => new Promise(r => {
|
||||
const s = net.createServer(); s.listen(0, '127.0.0.1', () => { const p = s.address().port; s.close(() => r(p)); });
|
||||
});
|
||||
|
||||
async function startServer(t, { twoAdmins = false } = {}) {
|
||||
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gym-del-'));
|
||||
fs.writeFileSync(path.join(dataDir, 'secret'), SECRET, { mode: 0o600 });
|
||||
const users = [
|
||||
{ id: ADMIN, name: 'Adminna', created: new Date().toISOString(), admin: true },
|
||||
{ id: VICTIM, name: 'Mallory', created: new Date().toISOString(), invitedBy: 'CODE1' },
|
||||
];
|
||||
if (twoAdmins) users.push({ id: ADMIN2, name: 'Second', created: new Date().toISOString(), admin: true });
|
||||
fs.writeFileSync(path.join(dataDir, 'db.json'), JSON.stringify({
|
||||
users,
|
||||
creds: [{ id: 'c-victim', userId: VICTIM, publicKey: 'x' }, { id: 'c-admin', userId: ADMIN, publicKey: 'y' }],
|
||||
subs: [{ endpoint: 'https://push/victim', userId: VICTIM }, { endpoint: 'https://push/admin', userId: ADMIN }],
|
||||
invites: [{ code: 'CODE1', usedBy: VICTIM, usedAt: new Date().toISOString() }],
|
||||
}));
|
||||
fs.writeFileSync(path.join(dataDir, `state-${VICTIM}.json`), JSON.stringify({ unit: 'kg', workouts: [], _rev: 3 }));
|
||||
const port = await freePort();
|
||||
const child = spawn(process.execPath, ['server.js'], {
|
||||
cwd: API, stdio: ['ignore', 'pipe', 'pipe'],
|
||||
env: { ...process.env, PORT: String(port), DATA_DIR: dataDir, ORIGIN: 'http://localhost:8080', RP_ID: 'localhost' },
|
||||
});
|
||||
const h = { api: `http://127.0.0.1:${port}`, log: '', dataDir };
|
||||
child.stdout.on('data', d => h.log += d);
|
||||
child.stderr.on('data', d => h.log += d);
|
||||
t.after(() => { child.kill('SIGKILL'); fs.rmSync(dataDir, { recursive: true, force: true }); });
|
||||
let up = false;
|
||||
for (let i = 0; i < 100 && !up; i++) {
|
||||
try { up = (await fetch(`${h.api}/api/health`)).ok; } catch { /* not up yet */ }
|
||||
if (!up) await new Promise(r => setTimeout(r, 100));
|
||||
}
|
||||
assert.ok(up, `server never came up:\n${h.log}`);
|
||||
h.del = async (id, uid = ADMIN) => {
|
||||
const r = await fetch(`${h.api}/api/admin/user/delete`, { method: 'POST', headers: { ...as(uid), Origin: 'http://localhost:8080' }, body: JSON.stringify({ id }) });
|
||||
return { status: r.status, body: await r.json() };
|
||||
};
|
||||
h.db = () => JSON.parse(fs.readFileSync(path.join(h.dataDir, 'db.json'), 'utf8'));
|
||||
h.stackFrames = () => h.log.split('\n').filter(l => /^\s+at /.test(l)).length;
|
||||
return h;
|
||||
}
|
||||
|
||||
test('removes the account and everything attached to it', async t => {
|
||||
const h = await startServer(t);
|
||||
assert.ok(fs.existsSync(path.join(h.dataDir, `state-${VICTIM}.json`)));
|
||||
const res = await h.del(VICTIM);
|
||||
assert.equal(res.status, 200);
|
||||
|
||||
const db = h.db();
|
||||
assert.deepEqual(db.users.map(u => u.id), [ADMIN], 'the user is gone');
|
||||
assert.deepEqual(db.creds.map(c => c.userId), [ADMIN], 'their passkeys are gone');
|
||||
assert.deepEqual(db.subs.map(s => s.userId), [ADMIN], 'their push subscriptions are gone');
|
||||
assert.equal(fs.existsSync(path.join(h.dataDir, `state-${VICTIM}.json`)), false, 'their history is gone');
|
||||
// The code they joined with stays burned: it was used, and freeing it would quietly widen
|
||||
// an invite-only instance.
|
||||
assert.equal(db.invites[0].usedBy, VICTIM);
|
||||
assert.equal(h.stackFrames(), 0, `no stack traces:\n${h.log}`);
|
||||
});
|
||||
|
||||
test('their session stops working immediately', async t => {
|
||||
const h = await startServer(t);
|
||||
const before = await fetch(`${h.api}/api/me`, { headers: as(VICTIM) });
|
||||
assert.equal(before.status, 200);
|
||||
await h.del(VICTIM);
|
||||
const after = await fetch(`${h.api}/api/me`, { headers: as(VICTIM) });
|
||||
assert.equal(after.status, 401, 'a cookie for a deleted account is worthless');
|
||||
});
|
||||
|
||||
test('refuses the two deletions that cannot be undone', async t => {
|
||||
const h = await startServer(t);
|
||||
const self = await h.del(ADMIN);
|
||||
assert.equal(self.status, 400);
|
||||
assert.match(self.body.error, /your own account/);
|
||||
|
||||
const last = await h.del(ADMIN, ADMIN); // ADMIN is also the only admin
|
||||
assert.equal(last.status, 400);
|
||||
assert.equal(h.db().users.length, 2, 'nothing was removed');
|
||||
});
|
||||
|
||||
test('another admin can be deleted while one remains', async t => {
|
||||
const h = await startServer(t, { twoAdmins: true });
|
||||
const res = await h.del(ADMIN2);
|
||||
assert.equal(res.status, 200);
|
||||
assert.deepEqual(h.db().users.map(u => u.id).sort(), [ADMIN, VICTIM].sort());
|
||||
});
|
||||
|
||||
test('says so plainly when the account is not there, and needs an admin', async t => {
|
||||
const h = await startServer(t);
|
||||
const missing = await h.del('nobody');
|
||||
assert.equal(missing.status, 404);
|
||||
const asVictim = await h.del(ADMIN, VICTIM);
|
||||
assert.equal(asVictim.status, 403, 'an ordinary user cannot delete anyone');
|
||||
assert.equal(h.db().users.length, 2);
|
||||
});
|
||||
@@ -0,0 +1,130 @@
|
||||
/* The admin routes read state files nobody validated. PUT /api/data drops null and shapeless
|
||||
entries and refuses a non-array `workouts`/`routines` (QA C16/C19), but a document written
|
||||
before it did still sits on disk and answers to nobody — and every one of these routes walks
|
||||
those lists and dereferences what it finds. One throw is a 500 for the whole drill-down: the
|
||||
sheet never leaves "Loading…", and the Disable button lives inside that sheet, so the account
|
||||
an operator opened the dashboard to stop stays un-disableable. Real server.js in a child. */
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import crypto from 'node:crypto';
|
||||
import net from 'node:net';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { spawn } from 'node:child_process';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const API = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const SECRET = crypto.randomBytes(32).toString('hex');
|
||||
|
||||
// Same construction as server.js makeSession(): payload `uid:exp:sv`, HMAC-SHA256 over SECRET.
|
||||
function mintSession(uid) {
|
||||
const payload = `${uid}:${Date.now() + 86400000}:0`;
|
||||
return payload + '.' + crypto.createHmac('sha256', SECRET).update(payload).digest('base64url');
|
||||
}
|
||||
const ADMIN = 'u_adm_1', VICTIM = 'u_vic_1';
|
||||
const asAdmin = { Cookie: `gymsid=${mintSession(ADMIN)}`, 'Content-Type': 'application/json' };
|
||||
|
||||
const freePort = () => new Promise(r => {
|
||||
const s = net.createServer(); s.listen(0, '127.0.0.1', () => { const p = s.address().port; s.close(() => r(p)); });
|
||||
});
|
||||
|
||||
async function startServer(t) {
|
||||
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gym-admin-'));
|
||||
fs.writeFileSync(path.join(dataDir, 'secret'), SECRET, { mode: 0o600 });
|
||||
fs.writeFileSync(path.join(dataDir, 'db.json'), JSON.stringify({
|
||||
users: [
|
||||
{ id: ADMIN, name: 'Adminna', created: new Date().toISOString(), admin: true },
|
||||
{ id: VICTIM, name: 'Mallory', created: new Date().toISOString() }
|
||||
], creds: [], subs: [], invites: []
|
||||
}));
|
||||
const port = await freePort();
|
||||
const child = spawn(process.execPath, ['server.js'], {
|
||||
cwd: API, stdio: ['ignore', 'pipe', 'pipe'],
|
||||
env: { ...process.env, PORT: String(port), DATA_DIR: dataDir, ORIGIN: 'http://localhost:8080', RP_ID: 'localhost' }
|
||||
});
|
||||
const h = { api: `http://127.0.0.1:${port}`, log: '', dataDir };
|
||||
child.stdout.on('data', d => h.log += d);
|
||||
child.stderr.on('data', d => h.log += d);
|
||||
t.after(() => { child.kill('SIGKILL'); fs.rmSync(dataDir, { recursive: true, force: true }); });
|
||||
let up = false;
|
||||
for (let i = 0; i < 100 && !up; i++) {
|
||||
try { up = (await fetch(`${h.api}/api/health`)).ok; } catch { /* not up yet */ }
|
||||
if (!up) await new Promise(r => setTimeout(r, 100));
|
||||
}
|
||||
assert.ok(up, `server never came up:\n${h.log}`);
|
||||
// The boot line is fine; anything that looks like a stack frame after this is a defect.
|
||||
h.stackFrames = () => h.log.split('\n').filter(l => /^\s+at /.test(l)).length;
|
||||
h.plant = S => fs.writeFileSync(path.join(h.dataDir, `state-${VICTIM}.json`), JSON.stringify(S));
|
||||
h.get = async p => { const r = await fetch(`${h.api}${p}`, { headers: asAdmin }); return { status: r.status, body: await r.json() }; };
|
||||
return h;
|
||||
}
|
||||
|
||||
// One good entry of each kind, so every case below can say what survived as well as what did not.
|
||||
const okW = { id: 'w1', name: 'Fine', d: '2026-09-18', start: 1, end: 2, entries: [{ id: 'e', sets: [{ w: 10, r: 5, done: true }] }] };
|
||||
const okR = { id: 'r1', name: 'Full body', emoji: '💪', ex: [{ id: '0001', sets: 3, reps: 10 }] };
|
||||
const okB = { d: '2026-09-01', w: 80 };
|
||||
|
||||
/* The shapes v1.3.7 accepted through PUT /api/data, one per line. `null` is the one the field
|
||||
reports came in with; the rest are the same mistake one field over. */
|
||||
const DOCS = {
|
||||
'a null routine entry': { workouts: [okW], routines: [null, okR], bodyweight: [okB], unit: 'kg' },
|
||||
'shapeless routine entries': { workouts: [okW], routines: [7, 'x', [], okR], bodyweight: [okB], unit: 'kg' },
|
||||
'a null workout entry': { workouts: [null, okW], routines: [okR], bodyweight: [okB], unit: 'kg' },
|
||||
'shapeless workout entries': { workouts: ['x', [], okW], routines: [okR], bodyweight: [okB], unit: 'kg' },
|
||||
'a null body-weight entry': { workouts: [okW], routines: [okR], bodyweight: [null, okB], unit: 'kg' },
|
||||
'shapeless body-weight entries': { workouts: [okW], routines: [okR], bodyweight: ['x', 7, [], okB], unit: 'kg' },
|
||||
'a null customEx entry': { workouts: [okW], routines: [okR], bodyweight: [okB], customEx: [null], unit: 'kg' },
|
||||
'lists that are objects, not arrays': { workouts: { a: 1 }, routines: { a: 1 }, bodyweight: { a: 1 }, unit: 'kg' },
|
||||
'lists that are null': { workouts: null, routines: null, bodyweight: null, unit: 'kg' },
|
||||
'no lists at all': { unit: 'kg' }
|
||||
};
|
||||
|
||||
test('GET /api/admin/user opens a profile whose stored state predates the entry filter', async t => {
|
||||
const h = await startServer(t);
|
||||
for (const [what, doc] of Object.entries(DOCS)) {
|
||||
h.plant(doc);
|
||||
const r = await h.get(`/api/admin/user?id=${VICTIM}`);
|
||||
assert.equal(r.status, 200, `${what}: ${JSON.stringify(r.body)}`);
|
||||
// Every list the sheet counts and walks comes back usable — the drill-down renders it
|
||||
// without a guard of its own for anything but the workout entries.
|
||||
for (const k of ['routines', 'bodyweight', 'workouts']) {
|
||||
assert.ok(Array.isArray(r.body[k]), `${what}: ${k} is an array`);
|
||||
assert.equal(r.body[k].some(x => !x || typeof x !== 'object' || Array.isArray(x)), false, `${what}: ${k} holds only entries`);
|
||||
}
|
||||
}
|
||||
// The good entries are still there, and a routine's exercise count is a number in every case.
|
||||
h.plant(DOCS['a null routine entry']);
|
||||
let r = await h.get(`/api/admin/user?id=${VICTIM}`);
|
||||
assert.deepEqual(r.body.routines, [{ id: 'r1', name: 'Full body', emoji: '💪', count: 1 }]);
|
||||
assert.deepEqual(r.body.workouts.map(w => w.id), ['w1']);
|
||||
assert.deepEqual(r.body.bodyweight, [okB]);
|
||||
h.plant({ routines: [{ id: 'r2', name: 'Broken', ex: 'nope' }] });
|
||||
r = await h.get(`/api/admin/user?id=${VICTIM}`);
|
||||
assert.deepEqual(r.body.routines, [{ id: 'r2', name: 'Broken', count: 0 }]); // an `ex` that is not a list counts as no exercises
|
||||
assert.equal(h.stackFrames(), 0, `stack traces in the log:\n${h.log}`);
|
||||
});
|
||||
|
||||
test('the user list and the disable switch survive the same document', async t => {
|
||||
const h = await startServer(t);
|
||||
for (const [what, doc] of Object.entries(DOCS)) {
|
||||
h.plant(doc);
|
||||
const r = await h.get('/api/admin/users');
|
||||
assert.equal(r.status, 200, what);
|
||||
const row = r.body.users.find(u => u.id === VICTIM);
|
||||
// "Workouts" is a count of what the drill-down will show, so it is a number, and it does
|
||||
// not count entries the sheet drops.
|
||||
assert.equal(typeof row.workouts, 'number', `${what}: workouts is a number`);
|
||||
assert.equal(row.workouts, Array.isArray(doc.workouts) ? doc.workouts.filter(w => w && typeof w === 'object' && !Array.isArray(w)).length : 0, what);
|
||||
}
|
||||
// The end state the whole thing is about: the account can be stopped from the dashboard.
|
||||
h.plant(DOCS['a null routine entry']);
|
||||
const r = await fetch(`${h.api}/api/admin/user/disable`, { method: 'POST', headers: asAdmin, body: JSON.stringify({ id: VICTIM, disabled: true }) });
|
||||
assert.equal(r.status, 200);
|
||||
assert.equal(JSON.parse(fs.readFileSync(path.join(h.dataDir, 'db.json'), 'utf8')).users.find(u => u.id === VICTIM).disabled, true);
|
||||
// …and the audit log still reads back, with that change in it.
|
||||
const a = await h.get('/api/admin/audit?limit=10&cat=');
|
||||
assert.equal(a.status, 200);
|
||||
assert.ok(a.body.events.some(e => e.ev === 'admin.user.disable'), JSON.stringify(a.body.events));
|
||||
assert.equal(h.stackFrames(), 0, `stack traces in the log:\n${h.log}`);
|
||||
});
|
||||
@@ -0,0 +1,183 @@
|
||||
/* A client's mistake is a 400 (or a 413), never a 500 with a stack trace in the log: unparseable
|
||||
or non-object JSON bodies, a state document that is an array, null entries inside it, and a
|
||||
rest-timer request without a usable `seconds` (QA C17, C19, C20). Real server.js in a child. */
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import crypto from 'node:crypto';
|
||||
import net from 'node:net';
|
||||
import http from 'node:http';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { spawn } from 'node:child_process';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const API = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const SECRET = crypto.randomBytes(32).toString('hex');
|
||||
|
||||
// Same construction as server.js makeSession(): payload `uid:exp:sv`, HMAC-SHA256 over SECRET.
|
||||
function mintSession(uid, sv = 0) {
|
||||
const payload = `${uid}:${Date.now() + 86400000}:${sv}`;
|
||||
return payload + '.' + crypto.createHmac('sha256', SECRET).update(payload).digest('base64url');
|
||||
}
|
||||
const UID = 'u_bad_1';
|
||||
const authed = { Cookie: `gymsid=${mintSession(UID)}`, 'Content-Type': 'application/json' };
|
||||
const anon = { 'Content-Type': 'application/json' };
|
||||
|
||||
const freePort = () => new Promise(r => {
|
||||
const s = net.createServer(); s.listen(0, '127.0.0.1', () => { const p = s.address().port; s.close(() => r(p)); });
|
||||
});
|
||||
|
||||
async function startServer(t) {
|
||||
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gym-bad-'));
|
||||
fs.writeFileSync(path.join(dataDir, 'secret'), SECRET, { mode: 0o600 });
|
||||
fs.writeFileSync(path.join(dataDir, 'db.json'), JSON.stringify({
|
||||
users: [{ id: UID, name: 'One', created: new Date().toISOString() }], creds: [], subs: [], invites: []
|
||||
}));
|
||||
const port = await freePort();
|
||||
const child = spawn(process.execPath, ['server.js'], {
|
||||
cwd: API, stdio: ['ignore', 'pipe', 'pipe'],
|
||||
env: { ...process.env, PORT: String(port), DATA_DIR: dataDir, ORIGIN: 'http://localhost:8080', RP_ID: 'localhost' }
|
||||
});
|
||||
const h = { api: `http://127.0.0.1:${port}`, log: '', dataDir };
|
||||
child.stdout.on('data', d => h.log += d);
|
||||
child.stderr.on('data', d => h.log += d);
|
||||
t.after(() => { child.kill('SIGKILL'); fs.rmSync(dataDir, { recursive: true, force: true }); });
|
||||
let up = false;
|
||||
for (let i = 0; i < 100 && !up; i++) {
|
||||
try { up = (await fetch(`${h.api}/api/health`)).ok; } catch { /* not up yet */ }
|
||||
if (!up) await new Promise(r => setTimeout(r, 100));
|
||||
}
|
||||
assert.ok(up, `server never came up:\n${h.log}`);
|
||||
// The boot line is fine; anything that looks like a stack frame after this is a defect.
|
||||
h.stackFrames = () => h.log.split('\n').filter(l => /^\s+at /.test(l)).length;
|
||||
return h;
|
||||
}
|
||||
|
||||
const send = (h, method, p, headers, body) => fetch(`${h.api}${p}`, { method, headers, body });
|
||||
const status = async (h, method, p, headers, body) => {
|
||||
const r = await send(h, method, p, headers, body);
|
||||
return { status: r.status, body: await r.json() };
|
||||
};
|
||||
|
||||
test('malformed and non-object JSON bodies are a 400 with no stack trace, on every route', async t => {
|
||||
const h = await startServer(t);
|
||||
const bad = ['not json', '{bad', 'null', '"str"', '42', '[]'];
|
||||
const routes = [
|
||||
['POST', '/api/register/options', anon],
|
||||
['POST', '/api/register/verify', anon],
|
||||
['POST', '/api/pair/redeem', anon],
|
||||
['PUT', '/api/data', authed],
|
||||
['POST', '/api/push/rest-timer', authed]
|
||||
];
|
||||
for (const [method, p, headers] of routes) {
|
||||
for (const b of bad) {
|
||||
const r = await status(h, method, p, headers, b);
|
||||
assert.equal(r.status, 400, `${method} ${p} with body ${b}`);
|
||||
assert.equal(r.body.error, 'invalid json', `${method} ${p} with body ${b}`);
|
||||
}
|
||||
}
|
||||
// A field whose toString is not callable is valid JSON; String() on it used to throw.
|
||||
let r = await status(h, 'POST', '/api/register/options', anon, JSON.stringify({ name: 'x', code: { toString: 1 } }));
|
||||
assert.notEqual(r.status, 500);
|
||||
r = await status(h, 'POST', '/api/pair/redeem', anon, JSON.stringify({ code: { toString: 1 } }));
|
||||
assert.equal(r.status, 400);
|
||||
r = await status(h, 'POST', '/api/register/options', anon, JSON.stringify({ name: { toString: 1 } }));
|
||||
assert.equal(r.status, 400);
|
||||
assert.equal(r.body.error, 'name required');
|
||||
// An empty body is still "no fields", as the routes that send none rely on.
|
||||
r = await status(h, 'POST', '/api/logout', { Cookie: authed.Cookie });
|
||||
assert.equal(r.status, 200);
|
||||
// Well-formed controls keep their own answers.
|
||||
r = await status(h, 'POST', '/api/register/options', anon, '{}');
|
||||
assert.deepEqual(r, { status: 400, body: { error: 'name required' } });
|
||||
r = await status(h, 'PUT', '/api/data', authed, JSON.stringify({ state: { workouts: [], routines: [] }, baseRev: 0 }));
|
||||
assert.equal(r.status, 200);
|
||||
assert.equal(h.stackFrames(), 0, `stack traces in the log:\n${h.log}`);
|
||||
assert.doesNotMatch(h.log, /bad json|TypeError/);
|
||||
});
|
||||
|
||||
// node's own http client, writing the whole body in one go on a keep-alive socket: the client
|
||||
// the QA proxy (and any node-side caller) is, and the one that used to report a reset instead
|
||||
// of the 413 when the server closed the socket under the still-running upload.
|
||||
const rawPut = (h, agent, body) => new Promise((resolve, reject) => {
|
||||
const rq = http.request(`${h.api}/api/data`, { method: 'PUT', headers: authed, agent }, res => {
|
||||
let data = ''; res.on('data', d => data += d); res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(data) }));
|
||||
});
|
||||
rq.on('error', reject);
|
||||
rq.end(body);
|
||||
});
|
||||
|
||||
test('a body over the 5 MiB cap is a 413 that every client gets to read, and nothing is written', async t => {
|
||||
const h = await startServer(t);
|
||||
const big = JSON.stringify({ state: { workouts: [], routines: [], pad: 'x'.repeat(6 * 1024 * 1024) }, baseRev: 0 });
|
||||
let r = await status(h, 'PUT', '/api/data', authed, big);
|
||||
assert.equal(r.status, 413);
|
||||
assert.equal(r.body.error, 'body too large');
|
||||
assert.equal(fs.existsSync(path.join(h.dataDir, `state-${UID}.json`)), false, 'nothing was written');
|
||||
const agent = new http.Agent({ keepAlive: true, maxSockets: 1 });
|
||||
t.after(() => agent.destroy());
|
||||
for (let i = 0; i < 3; i++) {
|
||||
r = await rawPut(h, agent, big);
|
||||
assert.equal(r.status, 413, `node client, attempt ${i + 1}`);
|
||||
}
|
||||
// The same keep-alive socket, and the server as a whole, are still fine afterwards.
|
||||
r = await rawPut(h, agent, JSON.stringify({ state: { workouts: [], routines: [] }, baseRev: 0 }));
|
||||
assert.equal(r.status, 200);
|
||||
// Past twice the cap the upload is cut off rather than drained: the 413 may or may not
|
||||
// arrive, but the process must not be left reading, and must still serve.
|
||||
const huge = 'x'.repeat(11 * 1024 * 1024);
|
||||
await rawPut(h, new http.Agent(), huge).catch(() => {});
|
||||
r = await status(h, 'GET', '/api/health', {});
|
||||
assert.equal(r.status, 200);
|
||||
assert.equal(h.stackFrames(), 0, `stack traces in the log:\n${h.log}`);
|
||||
});
|
||||
|
||||
test('PUT /api/data: an array is not a document, and null entries never reach the disk', async t => {
|
||||
const h = await startServer(t);
|
||||
const put = body => status(h, 'PUT', '/api/data', authed, JSON.stringify(body));
|
||||
const onDisk = () => JSON.parse(fs.readFileSync(path.join(h.dataDir, `state-${UID}.json`), 'utf8'));
|
||||
|
||||
let r = await put({ state: { _ts: 100, workouts: [{ id: 'w1', d: '2026-09-01' }], routines: [], unit: 'kg' }, baseRev: 0 });
|
||||
assert.equal(r.status, 200);
|
||||
assert.equal(r.body.rev, 1);
|
||||
|
||||
// An array passes `typeof === 'object'`; it used to be written as `[]`, losing the document
|
||||
// and, since `_rev` cannot live on an array, resetting the revision to 0 while the response
|
||||
// claimed rev 2.
|
||||
r = await put({ state: [], baseRev: 1 });
|
||||
assert.equal(r.status, 400);
|
||||
assert.equal(r.body.error, 'invalid state');
|
||||
assert.equal(onDisk()._rev, 1);
|
||||
assert.deepEqual(onDisk().workouts.map(w => w.id), ['w1']);
|
||||
r = await status(h, 'GET', '/api/data/rev', authed);
|
||||
assert.deepEqual(r.body, { rev: 1 });
|
||||
|
||||
// Null and other non-object entries are dropped: every server-side reader of the document
|
||||
// (reminder tick, admin drill-down) dereferences the entries, and a 400 would strand a client
|
||||
// whose own copy is already malformed.
|
||||
r = await put({ state: { workouts: [null, { id: 'w2', d: '2026-09-02' }, 7, 'x', [], { id: 'w3', d: '2026-09-03' }], routines: [null, { id: 'r1', name: 'A', ex: [] }] }, baseRev: 1 });
|
||||
assert.equal(r.status, 200);
|
||||
assert.equal(r.body.rev, 2);
|
||||
assert.deepEqual(onDisk().workouts.map(w => w.id), ['w2', 'w3']);
|
||||
assert.deepEqual(onDisk().routines.map(x => x.id), ['r1']);
|
||||
// Absent lists stay absent — every client fills its own defaults.
|
||||
r = await put({ state: { unit: 'kg' }, baseRev: 2 });
|
||||
assert.equal(r.status, 200);
|
||||
assert.equal('workouts' in onDisk(), false);
|
||||
assert.equal(h.stackFrames(), 0, `stack traces in the log:\n${h.log}`);
|
||||
});
|
||||
|
||||
test('POST /api/push/rest-timer: a missing or invalid `seconds` is a 400, never a 1-second timer', async t => {
|
||||
const h = await startServer(t);
|
||||
const post = b => status(h, 'POST', '/api/push/rest-timer', authed, b);
|
||||
for (const b of ['{}', '{"seconds":"abc"}', '{"seconds":0}', '{"seconds":-5}', '{"seconds":null}', '{"seconds":0.4}', '{"seconds":{"valueOf":1}}', '{"seconds":[90]}']) {
|
||||
const r = await post(b);
|
||||
assert.deepEqual(r, { status: 400, body: { error: 'seconds required' } }, `body ${b}`);
|
||||
}
|
||||
for (const b of ['{"seconds":90}', '{"seconds":"90"}', '{"seconds":1}', '{"seconds":99999}']) {
|
||||
const r = await post(b);
|
||||
assert.deepEqual(r, { status: 200, body: { ok: true } }, `body ${b}`);
|
||||
}
|
||||
assert.equal(h.stackFrames(), 0, `stack traces in the log:\n${h.log}`);
|
||||
});
|
||||
@@ -163,3 +163,22 @@ test('a reminder 20 minutes past is not delivered late, and a day already traine
|
||||
await wait(1500);
|
||||
assert.equal(firings(h.log), 0, `a trained day must stay silent:\n${h.log}`);
|
||||
});
|
||||
|
||||
/* A null entry inside an otherwise fine list is not a shape the tick can refuse at the door:
|
||||
PUT /api/data drops those now, but a file written before it did still has them, and the tick
|
||||
walks both lists (`w.d`, `r.id`). It threw on the first entry and skipped the user — every
|
||||
day, silently, for as long as the file stayed that way. The entries are skipped; the reminder
|
||||
is not. */
|
||||
test('a null entry in workouts or routines does not cost that profile its reminder', async t => {
|
||||
const late = hhmmMinusMinutes(2);
|
||||
if (!late.sameDay) return t.skip('just after midnight UTC — a same-day window cannot be set up');
|
||||
const h = await startServer(t, [sub]);
|
||||
fs.writeFileSync(path.join(h.dataDir, 'state-u_test_1.json'), goodState(late.hhmm, {
|
||||
workouts: [null, { id: 'w1', d: '2026-01-01' }],
|
||||
routines: [null, { id: 'r1', name: 'Full body', emoji: '💪', ex: [] }]
|
||||
}));
|
||||
const deadline = Date.now() + 30000;
|
||||
while (Date.now() < deadline && !firings(h.log)) await wait(300);
|
||||
assert.equal(firings(h.log), 1, h.log);
|
||||
assert.doesNotMatch(h.log, /reminder tick u_test_1 TypeError/, h.log);
|
||||
});
|
||||
|
Before Width: | Height: | Size: 187 KiB After Width: | Height: | Size: 200 KiB |
|
Before Width: | Height: | Size: 320 KiB After Width: | Height: | Size: 300 KiB |
|
Before Width: | Height: | Size: 166 KiB After Width: | Height: | Size: 279 KiB |
|
Before Width: | Height: | Size: 296 KiB After Width: | Height: | Size: 247 KiB |
|
Before Width: | Height: | Size: 246 KiB After Width: | Height: | Size: 383 KiB |
|
After Width: | Height: | Size: 105 KiB |
@@ -85,6 +85,10 @@ services:
|
||||
# Empty drops the CF-Connecting-IP header, so a direct client cannot forge the address
|
||||
# the activity log records. Cloudflare users set CF_CONNECTING_IP=$$http_cf_connecting_ip.
|
||||
- CF_CONNECTING_IP=${CF_CONNECTING_IP:-}
|
||||
# Subpath deployments behind a proxy that passes its prefix through ("/gym", no trailing
|
||||
# slash). Empty serves the app at the site root, which is what it has always done; a proxy
|
||||
# that strips the prefix needs nothing set (docs/SELF_HOSTING.md §5).
|
||||
- BASE_PATH=${BASE_PATH:-}
|
||||
volumes:
|
||||
- ./media/img:/usr/share/nginx/html/img:ro
|
||||
- ./media/gif:/usr/share/nginx/html/gif:ro
|
||||
@@ -159,6 +159,16 @@ same device.
|
||||
Prefer to keep the whole thing off the open internet? A VPN or an auth proxy (Authelia, Cloudflare
|
||||
Access…) in front still works, and composes with the above.
|
||||
|
||||
Behind an auth proxy, let three files through without a login: `/icon-180.png`, `/icon-512.png`
|
||||
and `/manifest.json` — the app's icon and its manifest, nothing personal in them. iOS fetches the
|
||||
Home Screen icon outside the page, without your session cookie, so a gated icon comes back as the
|
||||
proxy's login page and iOS 26 draws a letter tile instead of the dumbbell (observed on iOS 26.6
|
||||
behind Teleport; Authelia users know the same from favicons and manifests). Authelia: a `bypass`
|
||||
rule for those paths; Authentik: unauthenticated paths; Cloudflare Access: a bypass policy;
|
||||
oauth2-proxy: `skip_auth_routes`. A proxy that cannot exempt a path (Teleport) has to serve the
|
||||
icons inline as `data:` URLs instead — Safari 26 accepts those, older iOS does not, which is why
|
||||
that is not the default here.
|
||||
|
||||
## 5. Fitting it into an existing stack
|
||||
|
||||
The defaults assume openGym is the only thing here: a service called `api` on port 3000, and nginx
|
||||
@@ -172,6 +182,7 @@ NGINX_PORT=80 # port the web container listens on, inside the conta
|
||||
BACKEND=api # name of the API service that /api is proxied to
|
||||
PORT=3000 # port the API listens on; web proxies to the same value
|
||||
RESOLVER=127.0.0.11 # DNS nginx resolves BACKEND with — Docker's, unless you are not on Docker
|
||||
BASE_PATH= # subpath openGym is served under, e.g. /gym — see below; empty = site root
|
||||
SESSION_DAYS=90 # how long a sign-in lasts
|
||||
```
|
||||
|
||||
@@ -190,6 +201,40 @@ Note the difference from `VITE_IMG_BASE` / `VITE_GIF_BASE` (see Troubleshooting)
|
||||
build-time values baked into the frontend bundle, and setting them next to `docker compose` does
|
||||
nothing to an image you pulled.
|
||||
|
||||
### Serving openGym under a subpath
|
||||
|
||||
openGym can live at `https://example.com/gym/` rather than on a host of its own. Which of the two
|
||||
setups below you need depends on one thing: whether your reverse proxy strips the prefix before
|
||||
the container sees the request.
|
||||
|
||||
**The proxy strips the prefix** (Caddy's `handle_path`, Traefik's `StripPrefix` middleware,
|
||||
nginx `proxy_pass` with a trailing slash). Nothing to configure. The app's assets are relative
|
||||
and it asks its own address for the API, so everything stays inside the prefix on its own:
|
||||
|
||||
```caddy
|
||||
example.com {
|
||||
handle_path /gym/* {
|
||||
reverse_proxy opengym-web:80
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**The proxy passes the prefix through.** Tell the web container what it is, without a trailing
|
||||
slash:
|
||||
|
||||
```bash
|
||||
BASE_PATH=/gym
|
||||
```
|
||||
|
||||
That is a start-up setting like the others above, so it works on a prebuilt image. Forward only
|
||||
the prefix to the container — openGym does not serve itself at the site root as well, and a copy
|
||||
reached there would look for an API that is not on that path.
|
||||
|
||||
Either way, keep `ORIGIN` and `RP_ID` pointing at the address in the browser's bar
|
||||
(`ORIGIN=https://example.com`, `RP_ID=example.com`). Passkeys key on the host, not the path, so a
|
||||
subpath changes nothing about section 2 — but it does mean two instances under one hostname share
|
||||
a passkey scope and can see each other's credentials. Give each its own hostname if that matters.
|
||||
|
||||
## 6. Backups
|
||||
|
||||
Everything is in `./data`:
|
||||
|
||||
@@ -7,8 +7,8 @@ android {
|
||||
applicationId "ch.duartesantos.opengym"
|
||||
minSdkVersion rootProject.ext.minSdkVersion
|
||||
targetSdkVersion rootProject.ext.targetSdkVersion
|
||||
versionCode 20
|
||||
versionName "1.3.6"
|
||||
versionCode 22
|
||||
versionName "1.3.8"
|
||||
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
||||
aaptOptions {
|
||||
// Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps.
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
android:label="@string/app_name"
|
||||
android:roundIcon="@mipmap/ic_launcher_round"
|
||||
android:supportsRtl="true"
|
||||
android:networkSecurityConfig="@xml/network_security_config"
|
||||
android:theme="@style/AppTheme">
|
||||
<activity
|
||||
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|smallestScreenSize|screenLayout|uiMode|navigation"
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
<item name="windowNoTitle">true</item>
|
||||
<item name="android:background">@null</item>
|
||||
<!-- Draw into the camera cutout like iOS does under the notch: the WebView then reports a
|
||||
real env(safe-area-inset-top) and the sheets keep clear of it (index.css --sat). -->
|
||||
real env(safe-area-inset-top) and the sheets keep clear of it (the sat variable in index.css). -->
|
||||
<item name="android:windowLayoutInDisplayCutoutMode">shortEdges</item>
|
||||
</style>
|
||||
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Issue #213: a self-hosted server behind a private CA (Caddy "tls internal", a home PKI).
|
||||
Since API 24 an app trusts system CAs only, so the WebView refused the handshake while
|
||||
Chrome on the same phone, which honours user-installed CAs, opened the server fine.
|
||||
Trust both. A user CA is something the owner of the phone installed on purpose, behind a
|
||||
system warning; this is the same trust the browser already gives it. Cleartext is left at
|
||||
the platform default (off). -->
|
||||
<network-security-config>
|
||||
<base-config>
|
||||
<trust-anchors>
|
||||
<certificates src="system" />
|
||||
<certificates src="user" />
|
||||
</trust-anchors>
|
||||
</base-config>
|
||||
</network-security-config>
|
||||
@@ -10,7 +10,10 @@
|
||||
<meta name="mobile-web-app-capable" content="yes">
|
||||
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
|
||||
<meta name="apple-mobile-web-app-title" content="openGym">
|
||||
<link rel="manifest" href="manifest.json">
|
||||
<!-- use-credentials: browsers fetch the manifest without cookies, even same-origin; behind an auth
|
||||
proxy (Authelia, Cloudflare Access, Teleport…) that fetch is a login redirect and the Home Screen
|
||||
icon comes out generic. iOS 26 reads the icon from the manifest, so this is where it shows. -->
|
||||
<link rel="manifest" href="manifest.json" crossorigin="use-credentials">
|
||||
<link rel="apple-touch-icon" href="icon-180.png">
|
||||
<link rel="icon" type="image/png" href="icon-180.png">
|
||||
</head>
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "opengym-frontend",
|
||||
"version": "1.3.6",
|
||||
"version": "1.3.8",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "opengym-frontend",
|
||||
"version": "1.3.6",
|
||||
"version": "1.3.8",
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"dependencies": {
|
||||
"@aparajita/capacitor-secure-storage": "^7.1.6",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "opengym-frontend",
|
||||
"private": true,
|
||||
"version": "1.3.6",
|
||||
"version": "1.3.8",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
|
||||
@@ -3,8 +3,9 @@ import { HashRouter, Routes, Route, Navigate, useNavigate, useLocation, useNavig
|
||||
import { useStore } from './store/useStore.js'
|
||||
import { useUI } from './store/useUI.js'
|
||||
import { bindUI } from './components/ui.jsx'
|
||||
import { ACCENTS } from './lib/format.js'
|
||||
import { ACCENTS, setWeightDecimals } from './lib/format.js'
|
||||
import { setLang, useLang } from './lib/i18n.js'
|
||||
import { setPlayOnSilent } from './lib/sound.js'
|
||||
import { setNav } from './lib/nav.js'
|
||||
import { initBackButton } from './lib/back.js'
|
||||
import { useWakeLock } from './lib/wakelock.js'
|
||||
@@ -61,6 +62,9 @@ function Shell() {
|
||||
const loc = useLocation()
|
||||
const navType = useNavigationType()
|
||||
const { S, user, ready } = useStore()
|
||||
// iOS: whether timer sounds get past the ring/silent switch (Settings → Sounds). Page-level,
|
||||
// so it is applied here on load and on change rather than at each beep.
|
||||
useEffect(() => { setPlayOnSilent(!!S.soundOnSilent) }, [S.soundOnSilent])
|
||||
const isGuest = useStore(s => s.isGuest())
|
||||
const needsMobileOnboarding = useStore(s => s.needsMobileOnboarding)
|
||||
const langV = useLang() // re-renders the whole shell when the language (pack) changes
|
||||
@@ -77,11 +81,13 @@ function Shell() {
|
||||
return () => mql.removeEventListener('change', onChange)
|
||||
}, [S.theme, S.accent])
|
||||
useEffect(() => { setLang(S.lang || 'en') }, [S.lang])
|
||||
// Same shape as the language: a module-level display setting, pushed when it changes (#139).
|
||||
useEffect(() => { setWeightDecimals(S.wdec) }, [S.wdec])
|
||||
useEffect(() => { document.documentElement.lang = S.lang || 'en' }, [langV, S.lang])
|
||||
// Forward navigation starts at the top; going back lands where you left off.
|
||||
// The position is recorded from scroll events rather than read at route
|
||||
// change, because by then a shorter page may already have clamped it.
|
||||
const pathRef = useRef(loc.pathname)
|
||||
const pathRef = useRef(null)
|
||||
// iOS leaves the page displaced after the keyboard goes away (see lib/viewport-guard.js).
|
||||
useEffect(() => installViewportGuard(), [])
|
||||
// Click-drag a horizontal chip strip to scroll it sideways (lib/hchips.js) — on a desktop
|
||||
@@ -104,8 +110,16 @@ function Shell() {
|
||||
return () => window.removeEventListener('scroll', onScroll)
|
||||
}, [])
|
||||
useLayoutEffect(() => {
|
||||
const samePath = pathRef.current === loc.pathname
|
||||
pathRef.current = loc.pathname
|
||||
if (navType !== 'POP') { window.scrollTo(0, 0); return }
|
||||
// A POP that stays on the route we are on is not a back-navigation: it is the history
|
||||
// entry a sheet pushed (Modals.jsx, #63) being unwound as the sheet closes. Nothing new
|
||||
// mounted, Modals puts the page back where it was itself, and a view that scrolled on
|
||||
// purpose because the sheet closed — the workout list going to the current exercise after
|
||||
// ⋯ → Layout → List (#224) — must not be dragged back to a position recorded before that
|
||||
// scroll's event had even been dispatched.
|
||||
if (samePath) return
|
||||
const y = scrollPositions.get(loc.pathname) || 0
|
||||
// the restored view needs a layout pass before it is tall enough to scroll to y
|
||||
const frame = window.requestAnimationFrame(() => window.scrollTo(0, y))
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useEffect, useRef } from 'react'
|
||||
import { fmtVol, isoOf, todayISO, MONTHS } from '../lib/format.js'
|
||||
import { fmtVol, isoOf, todayISO, MONTHS, weekStartOf, weekDayOffset } from '../lib/format.js'
|
||||
import { t } from '../lib/i18n.js'
|
||||
import { tappable } from '../lib/use-sheet-keyboard.js'
|
||||
|
||||
@@ -20,9 +20,15 @@ export default function Heatmap({ S, onDay }) {
|
||||
const level = a => !a ? 0 : !a.min ? 1 : a.min >= t3 ? 4 : a.min >= t2 ? 3 : a.min >= t1 ? 2 : 1
|
||||
|
||||
const today = new Date(); today.setHours(12, 0, 0, 0)
|
||||
const end = new Date(today); end.setDate(today.getDate() - ((today.getDay() + 6) % 7))
|
||||
const ws = weekStartOf(S)
|
||||
const end = new Date(today); end.setDate(today.getDate() - weekDayOffset(today.getDay(), ws))
|
||||
const start = new Date(end); start.setDate(end.getDate() - 52 * 7)
|
||||
|
||||
const dayLabels = Array(7).fill(null)
|
||||
dayLabels[weekDayOffset(1, ws)] = 'Mon'
|
||||
dayLabels[weekDayOffset(3, ws)] = 'Wed'
|
||||
dayLabels[weekDayOffset(5, ws)] = 'Fri'
|
||||
|
||||
const months = [], cols = []
|
||||
let lastMonth = -1
|
||||
for (let wk = 0; wk <= 52; wk++) {
|
||||
@@ -48,7 +54,7 @@ export default function Heatmap({ S, onDay }) {
|
||||
<div className="hm-wrap" ref={wrapRef}>
|
||||
<div className="hm-months" style={{ marginLeft: 30 }}>{months}</div>
|
||||
<div className="hm-body">
|
||||
<div className="hm-days"><span>{t('Mon')}</span><span /><span>{t('Wed')}</span><span /><span>{t('Fri')}</span><span /><span /></div>
|
||||
<div className="hm-days">{dayLabels.map((lbl, i) => <span key={i}>{lbl ? t(lbl) : ''}</span>)}</div>
|
||||
<div className="hm-grid">{cols}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
// @vitest-environment happy-dom
|
||||
// The heatmap used to hardcode Monday-first weeks. It should follow S.weekStart like every
|
||||
// other "this week" surface (see lib/week-start.test.js and views/week-start.test.jsx).
|
||||
import React, { act } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
|
||||
import Heatmap from './Heatmap.jsx'
|
||||
import { isoOf } from '../lib/format.js'
|
||||
|
||||
globalThis.IS_REACT_ACT_ENVIRONMENT = true
|
||||
|
||||
let container, root
|
||||
beforeEach(() => {
|
||||
container = document.createElement('div')
|
||||
document.body.appendChild(container)
|
||||
root = createRoot(container)
|
||||
})
|
||||
afterEach(() => {
|
||||
act(() => root.unmount())
|
||||
container.remove()
|
||||
})
|
||||
|
||||
const baseS = { workouts: [], unit: 'kg' }
|
||||
const render = weekStart => act(() => root.render(<Heatmap S={{ ...baseS, weekStart }} onDay={() => {}} />))
|
||||
const dayLabels = () => [...container.querySelectorAll('.hm-days span')].map(s => s.textContent)
|
||||
const lastColumn = () => {
|
||||
const cols = container.querySelectorAll('.hm-grid .hm-col')
|
||||
return [...cols[cols.length - 1].querySelectorAll('.hm-c')]
|
||||
}
|
||||
|
||||
describe('Heatmap — week start', () => {
|
||||
it('rows read Mon/Wed/Fri for a Monday-first week (default)', () => {
|
||||
render(undefined)
|
||||
expect(dayLabels()).toEqual(['Mon', '', 'Wed', '', 'Fri', '', ''])
|
||||
})
|
||||
|
||||
it('shifts the same three labels down a row for a Sunday-first week', () => {
|
||||
render(0)
|
||||
expect(dayLabels()).toEqual(['', 'Mon', '', 'Wed', '', 'Fri', ''])
|
||||
})
|
||||
|
||||
it('the current (rightmost) column starts on the chosen week-start day and includes today', () => {
|
||||
render(1)
|
||||
let cells = lastColumn()
|
||||
expect(new Date(cells[0].title.slice(0, 10) + 'T12:00:00').getDay()).toBe(1)
|
||||
expect(cells.map(c => c.title.slice(0, 10))).toContain(isoOf(new Date()))
|
||||
|
||||
render(0)
|
||||
cells = lastColumn()
|
||||
expect(new Date(cells[0].title.slice(0, 10) + 'T12:00:00').getDay()).toBe(0)
|
||||
expect(cells.map(c => c.title.slice(0, 10))).toContain(isoOf(new Date()))
|
||||
})
|
||||
})
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useEffect, useRef } from 'react'
|
||||
import { useUI } from '../store/useUI.js'
|
||||
import { keyboardOpen } from '../lib/viewport-guard.js'
|
||||
|
||||
// One bottom sheet (or centered dialog) with swipe-to-dismiss.
|
||||
function Sheet({ sheet }) {
|
||||
@@ -180,6 +181,12 @@ export default function Modals() {
|
||||
// iOS scrolls the page again while the keyboard dismisses — after the line above ran.
|
||||
// Ask once more when that animation is over. The window-level guard in
|
||||
// lib/viewport-guard.js covers the keyboard closing while a sheet stays open.
|
||||
// Only with the keyboard up, though: without one there is nothing to undo, and a late
|
||||
// restore would overwrite a scroll the page behind made on purpose because the sheet
|
||||
// closed — the workout list going to the current exercise after ⋯ → Layout → List
|
||||
// (issue #224). At this point the sheet's field is already out of the DOM but the
|
||||
// keyboard has not started to go, so the visual viewport still tells the truth.
|
||||
if (!keyboardOpen()) return
|
||||
window.setTimeout(() => { if (document.body.style.position !== 'fixed') window.scrollTo(0, y) }, 350)
|
||||
}
|
||||
}, [sheets.length > 0])
|
||||
|
||||
@@ -292,3 +292,38 @@ describe('Modals drag axis lock and dismiss', () => {
|
||||
expect(mocks.state.sheets).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('Modals scroll restore on close', () => {
|
||||
// The body is pinned while a sheet is open and the page is put back where it was on close.
|
||||
// The second, delayed restore exists for one reason — iOS scrolling the page again while the
|
||||
// keyboard dismisses — so it must only be armed when the keyboard is actually up (QA C1).
|
||||
async function openAndClose() {
|
||||
dom.scrollY = 320
|
||||
await setSheets([sheet('menu')])
|
||||
expect(document.body.style.position).toBe('fixed')
|
||||
dom.scrollTo.mockClear()
|
||||
await setSheets([])
|
||||
}
|
||||
|
||||
it('restores the position once and leaves a scroll the page made afterwards alone', async () => {
|
||||
vi.useFakeTimers()
|
||||
await openAndClose()
|
||||
expect(dom.scrollTo).toHaveBeenCalledTimes(1)
|
||||
expect(dom.scrollTo).toHaveBeenCalledWith(0, 320)
|
||||
await act(async () => { vi.advanceTimersByTime(400) })
|
||||
expect(dom.scrollTo).toHaveBeenCalledTimes(1)
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('restores again after the keyboard dismiss animation when the sheet closed with the keyboard up', async () => {
|
||||
vi.useFakeTimers()
|
||||
dom.innerHeight = 800
|
||||
dom.visualViewport = { height: 460 }
|
||||
await openAndClose()
|
||||
expect(dom.scrollTo).toHaveBeenCalledTimes(1)
|
||||
await act(async () => { vi.advanceTimersByTime(400) })
|
||||
expect(dom.scrollTo).toHaveBeenCalledTimes(2)
|
||||
expect(dom.scrollTo).toHaveBeenLastCalledWith(0, 320)
|
||||
vi.useRealTimers()
|
||||
})
|
||||
})
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useMemo, useState } from 'react'
|
||||
import { useStore } from '../store/useStore.js'
|
||||
import { BODYPARTS, allExercises, equipmentOf, matchExercise } from '../lib/exercises.js'
|
||||
import { BODYPARTS, allExercises, equipmentOf, searchExercises } from '../lib/exercises.js'
|
||||
import { activeProfile, exAvailable } from '../lib/equipment.js'
|
||||
import { bestWeightFor } from '../lib/history.js'
|
||||
import { fmtNum } from '../lib/format.js'
|
||||
@@ -35,7 +35,7 @@ export default function MuscleExplorer({ onPick, onDetail, onPlan }) {
|
||||
])), [catalog])
|
||||
const pick = muscle => { setSelected(muscle === selected ? null : muscle); setEq(''); setShown(40) }
|
||||
const targeted = selected ? catalog.filter(e => musclesOf(e)[selected]) : []
|
||||
const base = targeted.filter(e => (!bp || e.bp === bp) && matchExercise(e, q))
|
||||
const base = searchExercises(targeted.filter(e => !bp || e.bp === bp), q)
|
||||
const eqOpts = equipmentOf(base)
|
||||
const eqOn = eqOpts.includes(eq) ? eq : ''
|
||||
// Favourites float to the top of whatever the filters left (issue #6), the rest keeps its order.
|
||||
@@ -84,7 +84,7 @@ export default function MuscleExplorer({ onPick, onDetail, onPlan }) {
|
||||
const primary = musclesOf(e)[selected] === 1
|
||||
return <div key={e.id} className="item" {...tappable(() => choose(e))}>
|
||||
<Thumb ex={e} />
|
||||
<div className="grow"><div className="tt capitalize">{isFav(S, e.id) && <Icon name="starFill" className="fav-star" />}{exerciseNameFor(e)}</div><div className="ss">{t(primary ? 'Primary target' : 'Also trains')} · <span className="capitalize">{t(e.tg || e.bp)} · {t(e.eq)}</span></div></div>
|
||||
<div className="grow"><div className="tt capitalize">{isFav(S, e.id) && <Icon name="starFill" className="fav-star" />}{exerciseNameFor(e)}</div><div className="ss">{t(primary ? 'Primary target' : 'Also trains')} · <span className="capitalize">{t(MUSCLE_NAME[e.tg] || e.tg || e.bp)} · {t(e.eq)}</span></div></div>
|
||||
{onPick ? <Icon name="plus" className="chev" /> : <>
|
||||
{best > 0 && <span className="tag acc">{fmtNum(best)}</span>}
|
||||
<Button size="sm" variant="tinted" icon="plus" onClick={ev => { ev.stopPropagation(); onPlan(e) }}>{t('Plan')}</Button>
|
||||
|
||||
@@ -18,12 +18,18 @@ import Icon from './Icon.jsx'
|
||||
|
||||
/* ============================ text ============================ */
|
||||
|
||||
// Width of a numeric string in `ch`, for a field sized to its own digits (NumberField's
|
||||
// `fit`): with tabular numerals every digit is exactly one ch, a decimal point roughly half.
|
||||
export const numWidthCh = s => Math.max(1, [...s].reduce((n, c) => n + (c === '.' ? 0.5 : 1), 0))
|
||||
|
||||
// Numeric input accepting "," as decimal separator — iOS decimal keypads in many
|
||||
// locales only offer a comma, and type="number" reports "" for it (value snaps to
|
||||
// 0). Keeps a local string draft while focused so partial input like "33," survives.
|
||||
// `nullable` is for fields where "nothing entered" and 0 mean different things (RIR: a
|
||||
// logged 0 is a set taken to failure). Those clear back to null instead of snapping to 0.
|
||||
export function NumberField({ value, onChange, decimal = true, nullable = false, className = '', ...rest }) {
|
||||
// `fit` sizes the field to the digits on screen instead of filling its cell — for the big
|
||||
// weight read-out, where the unit sits right beside the number.
|
||||
export function NumberField({ value, onChange, decimal = true, nullable = false, fit = false, className = '', ...rest }) {
|
||||
const [draft, setDraft] = useState(null)
|
||||
const committed = useRef(null)
|
||||
// null and undefined are the same "empty" here — a nullable field's key is dropped once cleared.
|
||||
@@ -37,12 +43,16 @@ export function NumberField({ value, onChange, decimal = true, nullable = false,
|
||||
setDraft(s)
|
||||
onChange(n)
|
||||
}
|
||||
const shown = draft ?? (value ?? '')
|
||||
return (
|
||||
<input
|
||||
type="text"
|
||||
inputMode={decimal ? 'decimal' : 'numeric'}
|
||||
className={'num ' + className}
|
||||
value={draft ?? (value ?? '')}
|
||||
value={shown}
|
||||
// `fit` hugs the digits on screen — a big read-out with its unit sitting right beside
|
||||
// it — where the default fills whatever cell the field is in.
|
||||
style={fit ? { width: numWidthCh(String(shown)) + 'ch' } : undefined}
|
||||
onFocus={e => e.target.select()}
|
||||
onChange={e => commit(e.target.value)}
|
||||
onBlur={() => { setDraft(null); committed.current = null }}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
// @vitest-environment happy-dom
|
||||
import React, { act } from 'react'
|
||||
import React, { act, useState } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { Slider, Stepper, SLIDER_GRAB_PX } from './ui.jsx'
|
||||
import { Slider, Stepper, NumberField, numWidthCh, SLIDER_GRAB_PX } from './ui.jsx'
|
||||
|
||||
globalThis.IS_REACT_ACT_ENVIRONMENT = true
|
||||
|
||||
@@ -106,3 +106,41 @@ describe('Stepper', () => {
|
||||
expect(onChange).toHaveBeenCalledWith(11)
|
||||
})
|
||||
})
|
||||
|
||||
describe('NumberField fit', () => {
|
||||
// A field that hugs its digits, for the big weight read-out where the unit sits right beside
|
||||
// the number. Digits are one ch each under tabular numerals; a decimal point is narrower.
|
||||
it('measures digits as one ch and a decimal point as half', () => {
|
||||
expect(numWidthCh('82')).toBe(2)
|
||||
expect(numWidthCh('82.5')).toBe(3.5)
|
||||
expect(numWidthCh('')).toBe(1)
|
||||
})
|
||||
|
||||
// The width follows what is on screen while typing (the draft), not the last committed
|
||||
// number — otherwise clearing the field would leave a 2ch-wide box around a lone caret and
|
||||
// the digits typed next would be clipped until the parent caught up.
|
||||
it('tracks the draft on screen while typing, and stays unsized without fit', () => {
|
||||
const type = (el, value) => {
|
||||
Object.getOwnPropertyDescriptor(el.constructor.prototype, 'value').set.call(el, value)
|
||||
el.dispatchEvent(new Event('input', { bubbles: true }))
|
||||
}
|
||||
function Harness({ fit }) {
|
||||
const [v, setV] = useState(70)
|
||||
return <NumberField fit={fit} value={v} onChange={setV} />
|
||||
}
|
||||
act(() => root.render(<Harness fit />))
|
||||
const input = host.querySelector('input')
|
||||
expect(input.style.width).toBe('2ch')
|
||||
|
||||
act(() => type(input, ''))
|
||||
expect(input.value).toBe('')
|
||||
expect(input.style.width).toBe('1ch')
|
||||
|
||||
act(() => type(input, '82,5'))
|
||||
expect(input.value).toBe('82.5')
|
||||
expect(input.style.width).toBe('3.5ch')
|
||||
|
||||
act(() => root.render(<Harness fit={false} />))
|
||||
expect(host.querySelector('input').style.width).toBe('')
|
||||
})
|
||||
})
|
||||
@@ -182,7 +182,21 @@ body.resting #app{padding-bottom:calc(206px + var(--sab))}
|
||||
.sync-banner .icn,.sync-banner svg{flex:none;font-size:16px;color:var(--label-2)}
|
||||
/* large title, the way a nav bar does it */
|
||||
.hdr{display:flex;align-items:flex-end;justify-content:space-between;gap:12px;margin:8px 0 18px}
|
||||
.hdr h1{font-size:34px;line-height:1.06;font-weight:700;letter-spacing:-.028em}
|
||||
/* The title block gives way, the button on the right never does: a flex item will not shrink
|
||||
below its longest word, so "Упражнения" at 34px or "Hi Bartholomew_Jones" used to push the
|
||||
gear / "By muscle" past the screen edge. Two things follow from letting it shrink. Below 420px
|
||||
— every phone width we test — the title drops a step to 30px, because the 95 to 125px the
|
||||
Library button leaves the Polish and Russian titles is less than half of "Ćwiczenia" or
|
||||
"Упражнения" at 34px and they came apart into three lines; at 30px all 14 packs take two at
|
||||
most. And a word that still does not fit is broken with overflow-wrap:break-word, which moves
|
||||
the whole word to the next line first and breaks it only if it does not fit there either —
|
||||
`anywhere` broke "Bartholomew_Jones" mid-word even at 412px, where a line of its own was
|
||||
waiting for it. hyphens:auto goes with them: the hyphen costs a character's worth of width in
|
||||
a box this tight, and that is what turned "Упражнения" into "Упра / жнен / ия". */
|
||||
.hdr>div{min-width:0}
|
||||
.hdr>.btn{flex:none}
|
||||
.hdr h1{font-size:34px;line-height:1.06;font-weight:700;letter-spacing:-.028em;overflow-wrap:break-word}
|
||||
@media (max-width:420px){.hdr h1{font-size:30px}}
|
||||
.hdr .sub{color:var(--label-2);font-size:15px;letter-spacing:-.006em;margin-top:4px}
|
||||
|
||||
.iconbtn{
|
||||
@@ -214,6 +228,11 @@ h4.sec{
|
||||
.grid2{display:grid;grid-template-columns:1fr 1fr;gap:10px}
|
||||
.row{display:flex;align-items:center;gap:12px}
|
||||
.row.between{justify-content:space-between}
|
||||
/* The body-weight card header (Home and Stats): title on the left, Goal + Log on the right. In
|
||||
German the title and the two buttons ("Ziel", "+ Eintragen") outgrow a 320px card by about
|
||||
55px, so the button pair may drop to a second line — still flush right, hence the auto margin. */
|
||||
.bw-head{flex-wrap:wrap;row-gap:8px}
|
||||
.bw-head>.row{margin-left:auto}
|
||||
|
||||
/* ----------------------------------------------------------------- card -- */
|
||||
.card{
|
||||
@@ -247,11 +266,20 @@ h4.sec{
|
||||
display:flex;align-items:center;justify-content:center;
|
||||
background:var(--tint,var(--acc));color:#fff;
|
||||
}
|
||||
.lrow-m{flex:1;min-width:0;display:flex;flex-direction:column;gap:1px}
|
||||
/* The title column never shrinks below its own longest word. With a basis of 0 and min-width:0 it
|
||||
only got what a capped value left over, and on a 320px phone "Progression" (96px) was painted over
|
||||
by "Linear progression" in a 37px box; min-width:auto — the flex default — is exactly the floor
|
||||
that case wants. A fixed 104px floor fixed that row and starved the rest: the backfill sheet's Date
|
||||
and Start-time rows have nothing but the title to give, so the floor shoved their fixed-width
|
||||
.timef off a 320px screen, and a short title like "Routine" (63px) took 104px away from the value
|
||||
beside it until "Freies Training" ellipsised. Asking only for the longest word takes nothing a row
|
||||
did not already owe the title. .lrow-t does not ellipsise on purpose — long settings titles wrap
|
||||
onto a second line — and the value next to it shrinks and ellipsises instead (below). */
|
||||
.lrow-m{flex:1;min-width:auto;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}
|
||||
/* 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.
|
||||
through the title next to it, since the title's column only holds out for its longest word.
|
||||
Letting the value shrink and ellipsise instead keeps the two out of each other's way.
|
||||
The cap is max-width, not flex-basis: .lrow-m is flex:1, so its basis is 0 and it absorbs
|
||||
none of the shrink — a long value would otherwise take the whole row and squeeze the title
|
||||
@@ -569,6 +597,13 @@ body.chips-dragging *{cursor:inherit}
|
||||
background:var(--surface-2);border:none;border-radius:8px;padding:6px 10px;
|
||||
font-size:16px;color:var(--label);outline:none;font-variant-numeric:tabular-nums;
|
||||
}
|
||||
/* A date or time field is as wide as the browser draws it and will not give way, and neither will
|
||||
the title beside it once that is down to its longest word: the Polish "Godzina rozpoczęcia" plus
|
||||
the clock leaves a 320px row 17px short, and the field then hangs over the edge of the card with
|
||||
its picker icon. Such a row wraps the field onto a line of its own under the title instead, still
|
||||
flush right — the same way a row carrying an inline segmented control does. */
|
||||
.lrow:has(.timef){flex-wrap:wrap}
|
||||
.lrow>.timef{margin-left:auto}
|
||||
.timef::-webkit-calendar-picker-indicator{filter:invert(.5)}
|
||||
:root[data-theme="light"] .timef::-webkit-calendar-picker-indicator{filter:none}
|
||||
|
||||
@@ -701,7 +736,32 @@ body.chips-dragging *{cursor:inherit}
|
||||
}
|
||||
.setrow .stp.w{flex:1.4;min-width:0}
|
||||
.setrow .stp.r{flex:1;min-width:0}
|
||||
/* The number outranks the buttons in every set row, not only the ones with an effort column
|
||||
that #235 covered: a 320 px phone left 0–6 px for the reps number and showed 102.5 as "102",
|
||||
and the cardio row's 10.5 km/h read "10" at 368 px (QA C2, C21, C24). The field reserves the
|
||||
widest value it shows at its font — "227.5" kg, "100" reps or "10.5" km/h (`--num`, incl.
|
||||
the field's 4 px padding and 2 px against font rounding) — and the two buttons give up width
|
||||
first, down to an 18 px floor, before anything is clipped. The cell itself is never narrower
|
||||
than number + two floors, so the row's flex hands a starving cell width from the others
|
||||
instead of clipping its buttons. */
|
||||
.setrow .stp button{width:32px;height:40px}
|
||||
/* Only the weight/reps buttons: `.effcell-stp` is a `.stp` too, and its value is a `<button>`,
|
||||
so a rule on `.setrow .stp button` would outrank `.effcell-stp .val` and stop the value from
|
||||
filling the cell (it bunched left with dead space next to it at desktop widths). */
|
||||
.setrow .stp.w button,.setrow .stp.r button{flex:0 1 auto;min-width:var(--btn-floor)}
|
||||
.setrow .stp.w,.sethead .w-sp{--num:48px}
|
||||
.setrow .stp.r,.sethead .r-sp{--num:39px}
|
||||
.setrow .stp.w,.setrow .stp.r,.sethead .w-sp,.sethead .r-sp{--btn-floor:18px;min-width:calc(var(--num) + 2*var(--btn-floor))}
|
||||
/* no buttons (Workout controls → steppers off): the number alone is the floor. The header
|
||||
carries the same `plain` so its columns freeze where the cells do. */
|
||||
.setrow .stp.plain,.sethead.plain .w-sp,.sethead.plain .r-sp{--btn-floor:0px}
|
||||
.setrow .stp.w .val,.setrow .stp.r .val{min-width:var(--num)}
|
||||
/* A timed hold logs the seconds in the first column and the load in the second, so the two
|
||||
columns swap roles: the load carries "227.5" and needs the wider reserve and the bigger share,
|
||||
the seconds column "120". Without the swap the load input was 35 px for a 41.7 px "102.5" at
|
||||
368 and 412 px — "102.5 kg" read "102.!" — while the seconds column sat on 67 px for "120". */
|
||||
.setrow.timed .stp.w,.sethead.timed .w-sp{flex:1;--num:39px}
|
||||
.setrow.timed .stp.r,.sethead.timed .r-sp{flex:1.4;--num:48px}
|
||||
/* The effort column is a single tap-to-pick button, not a stepper. It is a direct flex child
|
||||
of the row (like the .stp cells), carrying its own column width via flex. `align-self` and
|
||||
a fixed height stop the row from stretching it taller than the weight/reps cells; it is NOT
|
||||
@@ -711,6 +771,11 @@ body.chips-dragging *{cursor:inherit}
|
||||
the generic `.empty` (which is a full-page empty-state with 44px padding — sharing that name
|
||||
inflated the cell to ~90px). */
|
||||
.setrow .effcell,.sethead .eff-sp{flex:.8 1 0;min-width:0}
|
||||
/* The whole effort column — empty cell, logged cell and header label alike, so the row does not
|
||||
jump when a rating is added and the label does not drift — never goes below what the logged
|
||||
stepper needs at its floor: 28 px value + two 16 px buttons + the 1.5 px borders. The row's
|
||||
flex hands the difference back to weight and reps, whose own buttons shrink for it. */
|
||||
.setrow .effcell,.setrow .effcell-stp,.setrow.eff3 .effcell-stp,.sethead .eff-sp{min-width:64px}
|
||||
.effcell{
|
||||
box-sizing:border-box;height:44px;border-radius:10px;
|
||||
background:var(--surface-2);border:1.5px solid transparent;
|
||||
@@ -731,16 +796,19 @@ body.chips-dragging *{cursor:inherit}
|
||||
}
|
||||
.effcell-stp button{color:inherit}
|
||||
.effcell-stp>button[aria-label="Decrease"],
|
||||
.effcell-stp>button[aria-label="Increase"]{width:26px;height:44px;font-size:15px;opacity:.85}
|
||||
.effcell-stp>button[aria-label="Increase"]{width:26px;height:44px;font-size:15px;opacity:.85;flex:0 1 auto;min-width:16px}
|
||||
/* the value is the tap target for the picker, so it keeps a 28 px finger's width for "8.5" and
|
||||
the −/+ shrink first — on a 368 px phone it had collapsed to 4 px under its own digits, and a
|
||||
tap on the number stepped the rating instead of opening the picker (QA C22) */
|
||||
.effcell-stp .val{
|
||||
flex:1;min-width:0;display:flex;align-items:center;justify-content:center;
|
||||
flex:1;min-width:28px;display:flex;align-items:center;justify-content:center;
|
||||
font-size:15px;font-weight:600;letter-spacing:-.01em;
|
||||
font-variant-numeric:tabular-nums;line-height:1;align-self:stretch;color:inherit;
|
||||
}
|
||||
.effcell-stp .val:active{background:var(--surface-3)}
|
||||
/* the effort cell needs less room now (one short value, no +/- buttons), so weight/reps keep
|
||||
more of the row on narrow phones than they did when three steppers had to share it */
|
||||
.setrow .effcell-stp,.setrow.eff3 .effcell-stp{flex:.8 1 0;min-width:0}
|
||||
.setrow .effcell-stp,.setrow.eff3 .effcell-stp{flex:.8 1 0}
|
||||
.setrow.eff3 .effcell-stp{flex:.7 1 0}
|
||||
.setrow.eff3,.sethead.eff3{gap:6px}
|
||||
.setrow.eff3 .stp.w,.sethead.eff3 .w-sp{flex:1.4}
|
||||
@@ -748,6 +816,9 @@ body.chips-dragging *{cursor:inherit}
|
||||
.setrow.eff3 .effcell,.sethead.eff3 .eff-sp{flex:.7 1 0}
|
||||
.setrow.eff3 .stp.w button,.setrow.eff3 .stp.r button{width:26px}
|
||||
.setrow.eff3 .stp .num{font-size:14px}
|
||||
/* the same reserved widths as a plain row's, at the smaller font */
|
||||
.setrow.eff3 .stp.w,.sethead.eff3 .w-sp{--num:41px}
|
||||
.setrow.eff3 .stp.r,.sethead.eff3 .r-sp{--num:30px}
|
||||
.setrow.eff3 .effcell-stp>button[aria-label="Decrease"],
|
||||
.setrow.eff3 .effcell-stp>button[aria-label="Increase"]{width:22px}
|
||||
.setrow.eff3 .effcell-stp .val{font-size:14px}
|
||||
@@ -783,17 +854,120 @@ body.chips-dragging *{cursor:inherit}
|
||||
width:24px;height:24px;border-radius:8px;background:var(--surface-2);color:var(--label-3);
|
||||
display:flex;align-items:center;justify-content:center;font-size:11px;font-weight:600;flex:none;
|
||||
}
|
||||
/* A one-sided row with an effort column is the tightest line in the app: set number, L/R badge,
|
||||
two steppers, effort, tick. On a narrow phone the reps stepper's two buttons took all of its
|
||||
width and the number between them was gone (issue #235, 368 px). The number outranks the
|
||||
buttons here: slimmer buttons, tighter gaps, and reps gets the same share as the weight. */
|
||||
.setrow-side .setrow.side.eff3{gap:4px}
|
||||
.setrow-side .setrow.side.eff3 .stp.r{flex:1.4}
|
||||
.setrow-side .setrow.side.eff3 .effcell,.setrow-side .setrow.side.eff3 .effcell-stp{flex:.6 1 0}
|
||||
.setrow-side .setrow.side.eff3 .stp.w button,.setrow-side .setrow.side.eff3 .stp.r button{width:20px}
|
||||
/* The header is laid out like a straight row, but in front of an L/R row's weight cell sit the
|
||||
set number, its gap AND the side badge, so over per-side rows the labels stood 17–23 px left
|
||||
of their cells (QA C5). `.per-side` (set by Workout.jsx) widens the number slot by the badge
|
||||
and takes the badge's gap as its own, so header and rows share one column track; with an
|
||||
effort column it also mirrors the side rows' own shares (reps 1.4, effort .6). */
|
||||
.sethead.per-side .n-sp{width:56px}
|
||||
.sethead.per-side.eff3{gap:4px}
|
||||
.sethead.per-side.eff3 .r-sp{flex:1.4}
|
||||
.sethead.per-side.eff3 .eff-sp{flex:.6 1 0}
|
||||
@media (max-width:400px){
|
||||
/* the same squeeze on a plain row, where the list view's own inset costs the last pixels */
|
||||
.setrow.eff3 .stp.w button,.setrow.eff3 .stp.r button{width:21px}
|
||||
.setrow.eff3 .stp.r,.sethead.eff3 .r-sp{flex:1.25}
|
||||
.setrow-side{gap:5px}
|
||||
/* and on every L/R row, with or without an effort column — the default profile (no effort,
|
||||
buttons on) lost the per-side reps number the same way at 320 and 368 px (QA C2, C3) */
|
||||
.setrow-side .setrow.side{gap:4px}
|
||||
.setrow-side .setrow.side .sidetag{width:20px}
|
||||
.setrow-side .setrow.side .stp .num{font-size:14px}
|
||||
.setrow-side .setrow.side .stp.w,.sethead.per-side .w-sp{--num:41px}
|
||||
.setrow-side .setrow.side .stp.r,.sethead.per-side .r-sp{--num:30px}
|
||||
.setrow-side .side-rows .setrow.side .stp.w button,.setrow-side .side-rows .setrow.side .stp.r button{width:18px}
|
||||
/* number 24 + gap 5 + badge 20; the row's 4 px gap is the header's too */
|
||||
.sethead.per-side{gap:4px}
|
||||
.sethead.per-side .n-sp{width:49px}
|
||||
}
|
||||
/* The effort column steps down twice on the way to a narrow screen, not once. Its −/+ are gone
|
||||
below 360 px (see the 359 px query), and from 366 px an L/R row carries them at full size in a
|
||||
sets card two insets deep — in a list unit, or in a superset card. In between it could do
|
||||
neither: the 64 px the pill needs for a 28 px value and two 16 px button floors left the row
|
||||
6, 5, 4, 3, 2 and 1 px wider than its card's content box at 360–365 px, so its done tick sat
|
||||
in the card's side padding. The −/+ give way there too, to a 12 px floor — they are what the
|
||||
cell sheds first, a pixel further down they go altogether — and the row keeps everything that
|
||||
carries meaning: the rating stays a 28 px tap target, the weight and reps columns keep their
|
||||
numbers, their buttons and their floors, and the header keeps its single line ("WEIGHT (KG)"
|
||||
has 1.5 px to spare in a 77 px column and would wrap if the weight column paid instead).
|
||||
An L/R row in a superset in the list view has no −/+ to shrink below 430 px; the rule for it
|
||||
below is more specific and keeps the cell at 34 px. */
|
||||
@media (min-width:360px) and (max-width:365px){
|
||||
.setrow.side .effcell,.setrow.side .effcell-stp,.sethead.per-side .eff-sp{min-width:56px}
|
||||
.setrow.side .effcell-stp>button[aria-label="Decrease"],
|
||||
.setrow.side .effcell-stp>button[aria-label="Increase"]{min-width:12px}
|
||||
}
|
||||
/* An L/R row with an effort column inside a superset in the list view sits behind three insets
|
||||
(unit, superset card, sets card): at 412 px the row is 260 px wide, and with the logged
|
||||
effort's −/+ its cells want 277 (badge, tick and gaps, weight 77, reps 66, effort 64). The
|
||||
−/+ give way; the value stays, still opens the picker on tap, and the picker's exact row steps
|
||||
in halves as before. The header's effort slot follows the cell's floor.
|
||||
Only while the row is that narrow — the insets are fixed, so it is 1 px short at 428 px and
|
||||
fits from 430 px up, where it keeps the −/+ like the plain row above it. The 34 px floor
|
||||
belongs to the same query: on its own it clips the cell by 27 px. */
|
||||
@media (max-width:429px){
|
||||
.wl-unit .ss-card .setrow.side .effcell-stp>button[aria-label="Decrease"],
|
||||
.wl-unit .ss-card .setrow.side .effcell-stp>button[aria-label="Increase"]{display:none}
|
||||
.wl-unit .ss-card .setrow.side .effcell,.wl-unit .ss-card .setrow.side .effcell-stp,.wl-unit .ss-card .sethead.per-side .eff-sp{min-width:34px}
|
||||
}
|
||||
/* Below 360 px a row with an effort column cannot hold three numbers and six buttons: with the
|
||||
set number, tick and gaps gone a card leaves ~178 px, and 102.5 / 12 / 8.5 at their floors need
|
||||
~197. The effort −/+ give way there on every row — the value stays (26 px for "8.5" plus the
|
||||
border), still opens the picker on tap, and the picker's exact row steps in halves as before;
|
||||
weight and reps keep their buttons. */
|
||||
@media (max-width:359px){
|
||||
.setrow .effcell-stp>button[aria-label="Decrease"],.setrow .effcell-stp>button[aria-label="Increase"]{display:none}
|
||||
.setrow .effcell,.setrow .effcell-stp,.setrow.eff3 .effcell-stp,.sethead .eff-sp,
|
||||
.wl-unit .ss-card .setrow.side .effcell,.wl-unit .ss-card .setrow.side .effcell-stp,.wl-unit .ss-card .sethead.per-side .eff-sp{min-width:29px}
|
||||
.setrow .effcell-stp .val{min-width:26px}
|
||||
/* an L/R row with an effort column is still over by 14 px in a card at 320 px (badge 20, 77 + 66 +
|
||||
29 for the three cells, tick 30, four gaps): one notch further there — 16 px button floors
|
||||
and a 13 px number — and it fits with two pixels to spare. Not with the buttons off (`plain`),
|
||||
where the number alone is the floor. */
|
||||
.setrow-side .setrow.side.eff3 .stp.w:not(.plain),.setrow-side .setrow.side.eff3 .stp.r:not(.plain),.sethead.per-side.eff3:not(.plain) .w-sp,.sethead.per-side.eff3:not(.plain) .r-sp{--btn-floor:16px}
|
||||
.setrow-side .setrow.side.eff3 .stp .num{font-size:13px}
|
||||
.setrow-side .setrow.side.eff3 .stp.w,.sethead.per-side.eff3 .w-sp{--num:38px}
|
||||
.setrow-side .setrow.side.eff3 .stp.r,.sethead.per-side.eff3 .r-sp{--num:28px}
|
||||
/* A weighted timed hold has one control more than a straight row (the play button before the
|
||||
tick) and was 15 px over at 320 px with the full-size floors: seconds ("120") and the load
|
||||
("102.5") at the 14 px size and 16 px button floors, as an effort row does. */
|
||||
.setrow.timed .stp .num{font-size:14px}
|
||||
.setrow.timed .stp.w,.sethead.timed .w-sp{--num:30px}
|
||||
.setrow.timed .stp.r,.sethead.timed .r-sp{--num:41px}
|
||||
.setrow.timed .stp.w:not(.plain),.setrow.timed .stp.r:not(.plain),.sethead.timed:not(.plain) .w-sp,.sethead.timed:not(.plain) .r-sp{--btn-floor:16px}
|
||||
}
|
||||
.setrow.side.done .sidetag{background:var(--acc);color:var(--on-acc)}
|
||||
.setrow.side.done{opacity:.45}
|
||||
|
||||
/* drop-set drops / rest-pause bursts riding on a work row, editable like the row itself
|
||||
(issue: drop-sets & rest-pause) */
|
||||
.subrow{display:flex;align-items:center;gap:6px;padding:3px 0 3px 32px}
|
||||
/* Under an L/R row the set number already sits outside the .side-rows box, so the indent that
|
||||
tucks a straight row's drops under its number would be paid twice — at 320 px both number
|
||||
fields of a per-side drop collapsed to 0 px (QA C3). The label starts under the badge instead. */
|
||||
.setrow-side .side-rows .subrow{padding-left:0}
|
||||
.subrow .subn{font-size:11px;color:var(--label-3);flex:none;width:46px}
|
||||
.subrow .stp.mini{flex:1;min-width:0}
|
||||
.subrow .stp.mini button{width:26px;height:30px}
|
||||
/* the number outranks the buttons here as in the row above: room for "227.5" (a drop's weight)
|
||||
or "100" (the second mini is always reps) at 13 px, and the buttons shrink to 16 px first */
|
||||
.subrow .stp.mini{flex:1;--num:38px;min-width:calc(var(--num) + 32px)}
|
||||
.subrow .stp.mini+.stp.mini{--num:28px}
|
||||
.subrow .stp.mini button{width:26px;height:30px;flex:0 1 auto;min-width:16px}
|
||||
.subrow .stp.mini .val{min-width:var(--num)}
|
||||
.subrow .stp.mini .num{font-size:13px;min-height:30px}
|
||||
.subrow .iconbtn{width:26px;height:26px;font-size:11px;flex:none}
|
||||
/* label 46, two minis at their floors 70 + 60, the ✕ and three gaps: 252 px with the indent — the
|
||||
whole row at 320 px. The label starts under the number circle's inner edge there instead. */
|
||||
@media (max-width:359px){
|
||||
.subrow{padding-left:24px}
|
||||
}
|
||||
/* The number is the set's menu (drop / burst / remove); a 24px circle needs a finger-sized hit area. */
|
||||
.setrow .n::before{content:'';position:absolute;inset:-10px}
|
||||
/* No +/- buttons: the number field takes the whole cell and is the tap target. */
|
||||
@@ -833,6 +1007,15 @@ body.chips-dragging *{cursor:inherit}
|
||||
.cfgrow>div{flex:1;min-width:0}
|
||||
.cfgrow .stp button{width:30px}
|
||||
.cfgrow .stp-l{white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||||
/* The double-progression row holds four (Step / Reps from / Reps up to / Deload 1RM). Each stepper
|
||||
already spends 64px on its two buttons, so four abreast left the input 1px at 320 and 13px at
|
||||
368 — "1.25" showed as "1.2", "90" as "9(". Below 480px the row wraps into two pairs instead;
|
||||
from there up four abreast still leaves the input 40px or more. The basis is half the row minus
|
||||
half the gap, so each line takes exactly two. */
|
||||
@media (max-width:479px){
|
||||
.cfgrow.cfgrow-4{flex-wrap:wrap}
|
||||
.cfgrow.cfgrow-4>div{flex-basis:calc(50% - 4px)}
|
||||
}
|
||||
|
||||
/* --- rest timer --- */
|
||||
#timer{
|
||||
@@ -961,6 +1144,12 @@ body.chips-dragging *{cursor:inherit}
|
||||
font-variant-numeric:tabular-nums;line-height:1;
|
||||
}
|
||||
.bw-read .u{font-size:19px;color:var(--label-2);font-weight:400;letter-spacing:-.01em}
|
||||
.bw-read .num{
|
||||
display:inline-block;vertical-align:baseline;background:none;border:none;outline:none;
|
||||
padding:0;margin:0;color:inherit;font:inherit;letter-spacing:inherit;
|
||||
font-variant-numeric:tabular-nums;text-align:center;cursor:text;
|
||||
-moz-appearance:textfield;appearance:textfield;
|
||||
}
|
||||
.bwin{display:flex;align-items:baseline;justify-content:center;gap:7px;margin:16px 0}
|
||||
.bwin input{
|
||||
width:150px;background:none;border:none;outline:none;text-align:right;
|
||||
@@ -1132,9 +1321,25 @@ body.chips-dragging *{cursor:inherit}
|
||||
/* A superset nests a card inside the page's own gutter, so its inset is paid twice. On a
|
||||
narrow phone that left the weight and reps steppers too tight to show a three-digit
|
||||
number — reported as "the reps textbox becomes too small when superset on mobile". The
|
||||
card only gives up its own padding; the rows inside keep their spacing. */
|
||||
@media (max-width:400px){
|
||||
card only gives up its own padding; the rows inside keep their spacing.
|
||||
The give-back runs to 404 px rather than 400, because it may not end before the full insets
|
||||
fit: at 401 px they snapped back to 16 + 14 + 14 per side and took 48 px off the row while the
|
||||
screen had gained one, so a plain row with an effort column in a superset in the list view —
|
||||
285 px of cells in a 281 px card — was 4, 3, 2 and 1 px wider than its card's content box at
|
||||
401–404 px and its done tick sat in the card's side padding. 405 px is the width where those
|
||||
285 px and the three full insets first add up to the screen, so that is where it ends. */
|
||||
@media (max-width:404px){
|
||||
.ss-card{padding:10px 8px}
|
||||
/* The sets card nested in a superset card or a list unit pays a second inset, and in a superset
|
||||
in the list view a third; with an L/R row's set number, badge, two steppers, effort and tick
|
||||
it is the line that decides whether the numbers fit. 8 px each, and the superset card inside
|
||||
a unit keeps 4 (none below 360), so every set row has the same 256 px at 320 as in a plain
|
||||
card, and 296–304 at 368. */
|
||||
.wl-unit .card,.ss-card .card{padding-left:8px;padding-right:8px}
|
||||
.wl-unit .ss-card{padding-left:4px;padding-right:4px}
|
||||
}
|
||||
@media (max-width:359px){
|
||||
.wl-unit .ss-card{padding-left:0;padding-right:0}
|
||||
}
|
||||
.ss-hd{
|
||||
font-size:12px;font-weight:600;color:var(--acc);margin-bottom:12px;
|
||||
@@ -1144,14 +1349,22 @@ body.chips-dragging *{cursor:inherit}
|
||||
.ss-amp{text-align:center;font-size:15px;font-weight:600;color:var(--acc);margin:14px 0 8px}
|
||||
|
||||
/* --- workout list view: every unit stacked, the current one outlined --- */
|
||||
.workout-list{display:grid;gap:14px}
|
||||
/* minmax(0, …): a grid's default `auto` track is at least as wide as its widest content, so a set
|
||||
row whose cells have floors (see .setrow .stp) would widen the whole unit past the screen and
|
||||
push the ticks off it. Capped, a row that does not fit overflows its own card instead. */
|
||||
.workout-list{display:grid;grid-template-columns:minmax(0,1fr);gap:14px}
|
||||
.wl-unit{
|
||||
border-radius:var(--r-lg);padding:14px 14px 4px;
|
||||
background:var(--surface-2);
|
||||
}
|
||||
/* scrolled to when the list opens (#224): clear the sticky header above it. Workout.jsx
|
||||
measures the header (--whdr-h on .workout-list, safe area included) because it grows when
|
||||
the session name wraps; the fallback is the height of a one-line header. */
|
||||
.wl-unit{scroll-margin-top:calc(var(--whdr-h, var(--sat) + 80px) + 16px)}
|
||||
.wl-unit.cur{box-shadow:inset 0 0 0 1.5px var(--acc-line)}
|
||||
.wl-hd{display:flex;align-items:center;justify-content:space-between;gap:8px;margin-bottom:10px}
|
||||
@media (max-width:400px){
|
||||
/* part of the give-back above — one edge for all three insets of a row in the list view */
|
||||
@media (max-width:404px){
|
||||
.wl-unit{padding:10px 8px 2px}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
// @vitest-environment happy-dom
|
||||
// Issue #238: openGym behind a reverse proxy that serves it under a subpath. The assets were
|
||||
// already relative; the API call was not, so it went to the proxy's own root where nothing
|
||||
// answers it. The base is read from where the app is being served.
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { appBase } from './api.js'
|
||||
|
||||
const at = pathname => appBase({ pathname })
|
||||
|
||||
describe('the app knows where it is served from', () => {
|
||||
it('is the site root for an ordinary deployment', () => {
|
||||
expect(at('/')).toBe('/')
|
||||
expect(at('/index.html')).toBe('/')
|
||||
})
|
||||
|
||||
it('keeps the proxy prefix of a subpath deployment', () => {
|
||||
expect(at('/myGym/')).toBe('/myGym/')
|
||||
expect(at('/myGym/index.html')).toBe('/myGym/')
|
||||
expect(at('/a/b/c/')).toBe('/a/b/c/')
|
||||
})
|
||||
|
||||
it('drops a stale deep path rather than inventing a base from it', () => {
|
||||
// nginx sends these back to the app root before React boots; this is the belt and braces.
|
||||
expect(at('/myGym/plan/r/x')).toBe('/myGym/plan/r/')
|
||||
expect(at('/plan')).toBe('/')
|
||||
})
|
||||
|
||||
it('survives a missing or odd location', () => {
|
||||
expect(appBase(null)).toBe('/')
|
||||
expect(at('')).toBe('/')
|
||||
})
|
||||
})
|
||||
@@ -15,10 +15,31 @@ let remoteBase = ''
|
||||
let remoteToken = null
|
||||
export function setRemoteAuth(base, token) { remoteBase = base || ''; remoteToken = token || null }
|
||||
|
||||
/* Where this copy of the app is served from, e.g. "/" or "/myGym/" (issue #238).
|
||||
*
|
||||
* The app routes behind the hash and its assets are relative (vite `base: './'`), so the only
|
||||
* thing that assumed the site root was the API call. A reverse proxy that puts openGym under a
|
||||
* subpath — and strips that prefix before the container sees it, which is what Caddy's
|
||||
* `handle_path` and its equivalents do — got `/api/...` at the proxy's own root, where there is
|
||||
* nothing to answer it.
|
||||
*
|
||||
* `location.pathname` is the base because the router never leaves it: every screen is a hash,
|
||||
* and a path that is not a file is sent back to the app's root before React boots
|
||||
* (web/nginx.conf.template). Anything after the last slash is therefore index.html or a stale
|
||||
* deep link, and is dropped.
|
||||
*/
|
||||
export function appBase(loc = typeof location !== 'undefined' ? location : null) {
|
||||
const path = (loc && loc.pathname) || '/'
|
||||
return path.slice(0, path.lastIndexOf('/') + 1) || '/'
|
||||
}
|
||||
|
||||
export async function api(path, opts) {
|
||||
const headers = Object.assign({ 'Content-Type': 'application/json' }, opts && opts.headers)
|
||||
if (remoteToken) headers.Authorization = 'Bearer ' + remoteToken
|
||||
const r = await fetch(remoteBase + path, Object.assign({}, opts, { headers }))
|
||||
// A paired phone has an absolute base of its own; everyone else is relative to where the app
|
||||
// is served, so a subpath deployment reaches its own API instead of the proxy's root.
|
||||
const url = remoteBase ? remoteBase + path : appBase().replace(/\/$/, '') + path
|
||||
const r = await fetch(url, Object.assign({}, opts, { headers }))
|
||||
const data = await r.json().catch(() => ({}))
|
||||
// The body rides along on the error: a 409 from /api/data carries the server's document.
|
||||
if (!r.ok) { const e = new Error(data.error || ('HTTP ' + r.status)); e.status = r.status; e.data = data; throw e }
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
// Issue #232: an assistance machine carries part of your body weight, so LESS load is the
|
||||
// harder set, the record, and what progression should aim for. The reporter's case: 30 kg of
|
||||
// assistance, then 20 kg — the 20 is the new best, and the next session should ask for less.
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { isAssisted, betterWeight, beatsWeight, EXIDX } from './exercises.js'
|
||||
import { bestWeightFor, bestWeightForEntry } from './history.js'
|
||||
import { readSession, nextPrescription } from './progression.js'
|
||||
import { bestSetOf, e1rmSeries, is1RMRecord } from './onerm.js'
|
||||
|
||||
const ASSISTED = '0017' // assisted pull-up, leverage machine
|
||||
const PLAIN = '0025' // barbell bench press
|
||||
const set = (w, r, done = true) => ({ w, r, done })
|
||||
const workout = (d, id, sets) => ({ d, start: Date.parse(d + 'T10:00:00Z'), entries: [{ id, target: { mode: 'reps', sets: 1, reps: 8, weight: sets[0].w }, sets }] })
|
||||
|
||||
describe('which exercises count as assisted', () => {
|
||||
it('takes the leverage machine whose name says assisted, and nothing else', () => {
|
||||
expect(isAssisted(ASSISTED)).toBe(true)
|
||||
expect(EXIDX[ASSISTED].eq).toBe('leverage machine')
|
||||
expect(isAssisted(PLAIN)).toBe(false)
|
||||
// a partner holding your legs, a medicine ball, a band, your own body — ordinary load
|
||||
for (const id of ['0011', '1708', '0014', '0970', '0697']) expect(isAssisted(id), id).toBe(false)
|
||||
})
|
||||
|
||||
it('lets an exercise or a routine config say so outright', () => {
|
||||
expect(isAssisted({ id: PLAIN, assisted: true })).toBe(true)
|
||||
expect(isAssisted({ id: ASSISTED, assisted: false })).toBe(false)
|
||||
expect(isAssisted({ id: PLAIN, target: { assisted: true } })).toBe(true)
|
||||
expect(isAssisted({ n: 'My gym’s assisted dip', eq: 'leverage machine' })).toBe(true)
|
||||
})
|
||||
|
||||
it('folds and compares loads the right way round', () => {
|
||||
expect(betterWeight(ASSISTED, 30, 20)).toBe(20)
|
||||
expect(betterWeight(PLAIN, 30, 20)).toBe(30)
|
||||
expect(beatsWeight(ASSISTED, 20, 30)).toBe(true)
|
||||
expect(beatsWeight(ASSISTED, 40, 30)).toBe(false)
|
||||
expect(beatsWeight(ASSISTED, 30, 0)).toBe(true) // nothing logged yet
|
||||
expect(beatsWeight(ASSISTED, 0, 30)).toBe(false) // no load logged is not a record
|
||||
})
|
||||
})
|
||||
|
||||
describe('the record is the lightest assistance', () => {
|
||||
const S = { unit: 'kg', workouts: [workout('2026-09-01', ASSISTED, [set(30, 8)]), workout('2026-09-08', ASSISTED, [set(20, 8)])] }
|
||||
|
||||
it('reports the smallest load as the best, across history and within a session', () => {
|
||||
expect(bestWeightFor(S, ASSISTED)).toBe(20)
|
||||
expect(bestWeightForEntry({ id: ASSISTED, sets: [set(30, 8), set(20, 8)] })).toBe(20)
|
||||
expect(bestWeightForEntry({ id: PLAIN, sets: [set(30, 8), set(20, 8)] })).toBe(30)
|
||||
})
|
||||
|
||||
it('ignores an unlogged load instead of calling 0 the best', () => {
|
||||
expect(bestWeightForEntry({ id: ASSISTED, sets: [set(0, 8), set(25, 8)] })).toBe(25)
|
||||
})
|
||||
})
|
||||
|
||||
describe('progression asks for less help', () => {
|
||||
const cfg = { id: ASSISTED, sets: 1, reps: 8, weight: 30, prog: 'linear', inc: 5 }
|
||||
const hist = w => ({ unit: 'kg', workouts: [{ d: '2026-09-08', start: 1, entries: [{ id: ASSISTED, target: { ...cfg, weight: w }, sets: [set(w, 8)] }] }] })
|
||||
|
||||
it('takes assistance away after a clean session', () => {
|
||||
const p = nextPrescription(hist(30), cfg)
|
||||
expect(p.kind).toBe('up')
|
||||
expect(p.weight).toBe(25)
|
||||
expect(p.why.join(' ')).toMatch(/less help/)
|
||||
})
|
||||
|
||||
it('never goes below no assistance at all', () => {
|
||||
const p = nextPrescription(hist(5), { ...cfg, weight: 5 })
|
||||
expect(p.weight).toBeGreaterThanOrEqual(0)
|
||||
})
|
||||
|
||||
it('reads the lightest completed set as the session load', () => {
|
||||
const read = readSession({ id: ASSISTED, target: { mode: 'reps', sets: 2, reps: 8 }, sets: [set(30, 8), set(20, 8)] })
|
||||
expect(read.weight).toBe(20)
|
||||
})
|
||||
|
||||
it('still adds weight on an ordinary lift', () => {
|
||||
const plain = { id: PLAIN, sets: 1, reps: 8, weight: 60, prog: 'linear', inc: 5 }
|
||||
const S = { unit: 'kg', workouts: [{ d: '2026-09-08', start: 1, entries: [{ id: PLAIN, target: plain, sets: [set(60, 8)] }] }] }
|
||||
expect(nextPrescription(S, plain).weight).toBe(65)
|
||||
})
|
||||
})
|
||||
|
||||
describe('no one-rep max for an assistance machine', () => {
|
||||
it('leaves it out of the estimate, the curve and the record check', () => {
|
||||
const entry = { id: ASSISTED, sets: [set(30, 8)] }
|
||||
expect(bestSetOf(entry)).toBe(null)
|
||||
const S = { unit: 'kg', workouts: [workout('2026-09-01', ASSISTED, [set(30, 8)])] }
|
||||
expect(e1rmSeries(S, ASSISTED)).toEqual([])
|
||||
expect(is1RMRecord(S, ASSISTED, entry)).toBe(null)
|
||||
// the ordinary lift still gets one
|
||||
expect(bestSetOf({ id: PLAIN, sets: [set(100, 5)] })).not.toBe(null)
|
||||
})
|
||||
})
|
||||
|
||||
describe('a sync does not hand the help back', () => {
|
||||
it('keeps the smaller assistance and the larger ordinary load', async () => {
|
||||
const { mergeStates } = await import('./sync-merge.js')
|
||||
const phone = { _ts: 2000, exWeights: { [ASSISTED]: { w: 20, d: '2026-09-08' }, [PLAIN]: { w: 100, d: '2026-09-08' } } }
|
||||
const server = { _ts: 1000, exWeights: { [ASSISTED]: { w: 30, d: '2026-09-01' }, [PLAIN]: { w: 90, d: '2026-09-01' } } }
|
||||
expect(mergeStates(phone, server).exWeights[ASSISTED].w).toBe(20)
|
||||
expect(mergeStates(phone, server).exWeights[PLAIN].w).toBe(100)
|
||||
// and the other way round, so it does not depend on which copy is newer
|
||||
expect(mergeStates(server, phone).exWeights[ASSISTED].w).toBe(20)
|
||||
expect(mergeStates(server, phone).exWeights[PLAIN].w).toBe(100)
|
||||
})
|
||||
})
|
||||
@@ -21,8 +21,14 @@ const LABELS = {
|
||||
'auth.register.denied': 'Signup refused',
|
||||
'auth.logout': 'Signed out',
|
||||
'auth.logout.all': 'Signed out everywhere',
|
||||
// Device pairing (Settings → "Pair the mobile app"): the code is minted in a signed-in browser
|
||||
// tab and redeemed by the app, so "ok" is the phone coming online, not a sign-in.
|
||||
'auth.pair.create': 'Created a pairing code',
|
||||
'auth.pair.ok': 'Paired a phone',
|
||||
'auth.pair.fail': 'Pairing failed',
|
||||
'admin.user.disable': 'Disabled an account',
|
||||
'admin.user.enable': 'Re-enabled an account',
|
||||
'admin.user.delete': 'Deleted an account',
|
||||
'admin.invite.create': 'Created an invite code',
|
||||
'admin.invite.revoke': 'Revoked an invite code',
|
||||
'admin.audit.clear': 'Cleared the activity log',
|
||||
@@ -41,7 +47,9 @@ const REASONS = {
|
||||
'account-disabled': 'the account is disabled',
|
||||
'credential-exists': 'that passkey already belongs to a profile',
|
||||
'invite-invalid': 'the invite code was used or revoked in the meantime',
|
||||
'invite-rejected': 'wrong or already-used invite code'
|
||||
'invite-rejected': 'wrong or already-used invite code',
|
||||
'code-invalid': 'wrong or expired pairing code',
|
||||
'user-unavailable': 'the profile behind the pairing code is disabled or gone'
|
||||
}
|
||||
export const auditReason = msg => REASONS[msg] || (msg ? String(msg) : '')
|
||||
|
||||
|
||||
@@ -1,19 +1,15 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { auditCat, auditLabel, auditReason, auditLine, fmtWhen } from './audit.js'
|
||||
|
||||
// Every event name and reason code the server can emit (api/server.js, the audit block).
|
||||
// Every event name and reason code the server can emit, read off api/server.js itself rather
|
||||
// than kept as a second list here: the hand-kept copy silently missed the three pairing events
|
||||
// for several releases, and the dashboard printed 'auth.pair.create' at the operator (QA C18).
|
||||
// If a new one is added there without a label here, the first test fails rather than the
|
||||
// dashboard quietly printing a dotted identifier at a person.
|
||||
const EVENTS = [
|
||||
'auth.login.ok', 'auth.login.fail', 'auth.register.ok', 'auth.register.fail',
|
||||
'auth.register.denied', 'auth.logout', 'auth.logout.all',
|
||||
'admin.user.disable', 'admin.user.enable', 'admin.invite.create',
|
||||
'admin.invite.revoke', 'admin.audit.clear', 'admin.denied'
|
||||
]
|
||||
const REASONS = [
|
||||
'challenge-expired', 'unknown-credential', 'verify-error', 'not-verified',
|
||||
'user-missing', 'account-disabled', 'credential-exists', 'invite-invalid', 'invite-rejected'
|
||||
]
|
||||
const SERVER = readFileSync(new URL('../../../api/server.js', import.meta.url), 'utf8')
|
||||
const EVENTS = [...new Set([...SERVER.matchAll(/audit\(req, '([a-z.]+)'/g)].map(m => m[1]))]
|
||||
const REASONS = [...new Set([...SERVER.matchAll(/msg: '([a-z-]+)'/g)].map(m => m[1]))]
|
||||
|
||||
describe('auditLabel', () => {
|
||||
it('has a sentence for every event the server emits', () => {
|
||||
@@ -58,6 +54,14 @@ describe('auditReason', () => {
|
||||
})
|
||||
|
||||
describe('auditLine', () => {
|
||||
it('reads the server lists off api/server.js, pairing events included', () => {
|
||||
// Guards the extraction itself: an empty match would make the two loops above vacuous.
|
||||
expect(EVENTS).toEqual(expect.arrayContaining(['auth.login.ok', 'auth.pair.create', 'auth.pair.ok', 'auth.pair.fail', 'admin.audit.clear']))
|
||||
expect(REASONS).toEqual(expect.arrayContaining(['challenge-expired', 'code-invalid', 'user-unavailable']))
|
||||
expect(auditLine({ ev: 'auth.pair.fail', ok: false, msg: 'code-invalid' })).toEqual({ title: 'Pairing failed', sub: 'unknown caller · wrong or expired pairing code' })
|
||||
expect(auditLine({ ev: 'auth.pair.ok', ok: true, name: 'Verifier' })).toEqual({ title: 'Paired a phone', sub: 'Verifier' })
|
||||
})
|
||||
|
||||
it('names the person who did it', () => {
|
||||
expect(auditLine({ ev: 'auth.login.ok', ok: true, uid: 'u1', name: 'Duarte' }))
|
||||
.toEqual({ title: 'Signed in', sub: 'Duarte' })
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
// Issue #138: a Smith machine that counterbalances its carriage puts nothing in your hands, but
|
||||
// 0 in the bar field meant "clear the override" and snapped back to the 9 kg default — so the
|
||||
// plate math and the drop-set steps were computed from a bar that is not there.
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { barWeightFor, hasBarOverride, isNoBar, plateSplit, defaultBarWeight } from './bar.js'
|
||||
|
||||
const smith = { id: 'sm', eq: 'smith machine' }
|
||||
const bb = { id: 'bb', eq: 'barbell' }
|
||||
const S = over => ({ unit: 'kg', barWeights: { ...over } })
|
||||
|
||||
describe('no bar at all', () => {
|
||||
it('keeps a stored 0 instead of falling back to the bar type default', () => {
|
||||
expect(barWeightFor(S({ sm: 0 }), smith)).toBe(0)
|
||||
expect(defaultBarWeight('smith machine', 'kg')).toBe(9)
|
||||
expect(barWeightFor(S({}), smith)).toBe(9) // no entry still means "use the default"
|
||||
})
|
||||
|
||||
it('tells "no bar" apart from "nothing set"', () => {
|
||||
expect(isNoBar(S({ sm: 0 }), 'sm')).toBe(true)
|
||||
expect(isNoBar(S({ sm: 15 }), 'sm')).toBe(false)
|
||||
expect(isNoBar(S({}), 'sm')).toBe(false)
|
||||
expect(hasBarOverride(S({ sm: 0 }), 'sm')).toBe(true)
|
||||
expect(hasBarOverride(S({}), 'sm')).toBe(false)
|
||||
})
|
||||
|
||||
it('counts every plate when there is no bar', () => {
|
||||
expect(plateSplit(100, 0)).toBe(50)
|
||||
expect(plateSplit(100, 20)).toBe(40)
|
||||
expect(plateSplit(0, 0)).toBe(null)
|
||||
expect(plateSplit(100, null)).toBe(null) // not a bar exercise at all
|
||||
})
|
||||
|
||||
it('leaves an ordinary barbell alone', () => {
|
||||
expect(barWeightFor(S({ bb: 25 }), bb)).toBe(25)
|
||||
expect(barWeightFor(S({}), bb)).toBe(20)
|
||||
})
|
||||
})
|
||||
@@ -30,8 +30,20 @@ export const usesBar = exOrId => BAR_EQ.has(exOf(exOrId)?.eq)
|
||||
export const defaultBarWeight = (eq, unit) =>
|
||||
(unit === 'lb' ? DEFAULT_BAR_LB : DEFAULT_BAR_KG)[eq] ?? null
|
||||
|
||||
/** True when the user has set their own bar weight for this exercise. */
|
||||
export const hasBarOverride = (S, exId) => ((S?.barWeights || {})[exId] || 0) > 0
|
||||
/**
|
||||
* A stored 0 is "no bar", not "unset" (issue #138). Smith machines that counterbalance their
|
||||
* carriage put nothing in your hands, so the plate math and the drop-set steps have to start
|
||||
* from the weight you logged, not from a 9 kg bar that is not there. The key being absent is
|
||||
* what means "use the default for this bar type" — which is why the editor clears the key
|
||||
* rather than writing a 0 when you ask for the default back.
|
||||
*/
|
||||
export const isNoBar = (S, exId) => (S?.barWeights || {})[exId] === 0
|
||||
|
||||
/** True when the user has set their own bar weight for this exercise — including "no bar". */
|
||||
export const hasBarOverride = (S, exId) => {
|
||||
const own = (S?.barWeights || {})[exId]
|
||||
return own === 0 || own > 0
|
||||
}
|
||||
|
||||
/**
|
||||
* Effective bar weight for one exercise, in the profile unit: the explicit
|
||||
@@ -42,6 +54,7 @@ export function barWeightFor(S, exOrId) {
|
||||
const ex = exOf(exOrId)
|
||||
if (!BAR_EQ.has(ex?.eq)) return null
|
||||
const own = (S?.barWeights || {})[ex.id]
|
||||
if (own === 0) return 0
|
||||
if (own > 0) return own
|
||||
return defaultBarWeight(ex.eq, S?.unit)
|
||||
}
|
||||
@@ -51,6 +64,8 @@ export function barWeightFor(S, exOrId) {
|
||||
* sensible to show — a missing number, or a total at or below the bar itself.
|
||||
*/
|
||||
export function plateSplit(total, bar) {
|
||||
if (!(total > 0) || !(bar > 0) || total <= bar) return null
|
||||
// `bar` of 0 is a real answer, not a missing one: with no bar every kilo you logged is on the
|
||||
// ends, so the split is simply half of it (issue #138).
|
||||
if (!(total > 0) || !(bar >= 0) || bar === null || bar === undefined || total <= bar) return null
|
||||
return Math.round(((total - bar) / 2) * 100) / 100
|
||||
}
|
||||
@@ -55,12 +55,15 @@ describe('barWeightFor', () => {
|
||||
expect(hasBarOverride(S, barbell)).toBe(false)
|
||||
})
|
||||
|
||||
test('a cleared (deleted or zeroed) override falls back to the default', () => {
|
||||
test('a deleted override falls back to the default, but a stored 0 is "no bar"', () => {
|
||||
const S = { unit: 'kg', barWeights: { [ez]: 12.5 } }
|
||||
delete S.barWeights[ez]
|
||||
expect(barWeightFor(S, ez)).toBe(10)
|
||||
expect(barWeightFor({ unit: 'kg', barWeights: { [ez]: 0 } }, ez)).toBe(10)
|
||||
expect(hasBarOverride({ unit: 'kg', barWeights: { [ez]: 0 } }, ez)).toBe(false)
|
||||
// Changed with issue #138: 0 used to mean "clear this override". It now means the exercise
|
||||
// has no bar (a counterbalanced Smith carriage), which is a value of its own — the editor
|
||||
// deletes the key to ask for the default back.
|
||||
expect(barWeightFor({ unit: 'kg', barWeights: { [ez]: 0 } }, ez)).toBe(0)
|
||||
expect(hasBarOverride({ unit: 'kg', barWeights: { [ez]: 0 } }, ez)).toBe(true)
|
||||
})
|
||||
|
||||
test('is null for anything without a bar', () => {
|
||||
@@ -86,7 +89,7 @@ describe('plateSplit', () => {
|
||||
expect(plateSplit(20, 20)).toBe(null) // bar only
|
||||
expect(plateSplit(15, 20)).toBe(null) // below the bar
|
||||
expect(plateSplit(0, 20)).toBe(null)
|
||||
expect(plateSplit(100, 0)).toBe(null)
|
||||
// 100 with no bar is 50 a side, not "nothing to show" (issue #138) — see bar-nobar.test.js
|
||||
expect(plateSplit(null, 20)).toBe(null)
|
||||
expect(plateSplit(100, null)).toBe(null)
|
||||
expect(plateSplit(undefined, undefined)).toBe(null)
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
// the apply engine accepts. Also the three things this mode has to get right on its own: the
|
||||
// daily cap, the key never touching S, and a proposal surviving in the device file.
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { todayISO } from './format.js'
|
||||
|
||||
// The device file and the secret store are in-memory here; nativeFetch is the script.
|
||||
const device = { data: null }
|
||||
@@ -149,7 +150,7 @@ describe('the Coach on a phone with its own key', () => {
|
||||
await expect(local.localReview(state())).rejects.toMatchObject({ code: 'busy' })
|
||||
await settle()
|
||||
|
||||
await saveCoachDevice({ daily: { d: new Date().toISOString().slice(0, 10), n: local.LOCAL_DAILY_CAP } })
|
||||
await saveCoachDevice({ daily: { d: todayISO(), n: local.LOCAL_DAILY_CAP } })
|
||||
await expect(local.localReview(state())).rejects.toMatchObject({ code: 'cap' })
|
||||
expect((await local.localStatus()).cap).toEqual({ used: local.LOCAL_DAILY_CAP, limit: local.LOCAL_DAILY_CAP })
|
||||
})
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import batch from './exercise-muscle-batch-1.json' with { type: 'json' }
|
||||
import olympic from './exercise-muscle-olympic.json' with { type: 'json' }
|
||||
import { MACHINE_BATCH_2 } from './exercise-muscle-batch-2.js'
|
||||
|
||||
/**
|
||||
@@ -6,6 +7,7 @@ import { MACHINE_BATCH_2 } from './exercise-muscle-batch-2.js'
|
||||
* untouched; exercises.js applies this layer to the runtime index.
|
||||
*/
|
||||
export const COMPOUND_LIFT_BATCH_1 = Object.freeze(batch)
|
||||
export const OLYMPIC_LIFT_METADATA = Object.freeze(olympic)
|
||||
|
||||
// Keep the phase-2 artifact in its own module for auditing while preserving the phase-1 resolver
|
||||
// interface consumed by exercises.js and downstream muscle helpers.
|
||||
@@ -22,6 +24,7 @@ export function exerciseMuscleMetadataFor(id) {
|
||||
return {
|
||||
...(COMPOUND_LIFT_BATCH_1[id] || {}),
|
||||
...(MACHINE_BATCH_2[id] || {}),
|
||||
...(OLYMPIC_LIFT_METADATA[id] || {}),
|
||||
...(USER_EXERCISE_MUSCLE_OVERRIDES[id] || {})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
{
|
||||
"0295": {
|
||||
"bp": "full body",
|
||||
"primaries": ["quadriceps", "gluteal", "hamstring", "trapezius"],
|
||||
"secondaries": ["calves", "forearm", "deltoids", "lower-back", "abs", "obliques"]
|
||||
},
|
||||
"0518": {
|
||||
"bp": "full body",
|
||||
"primaries": ["quadriceps", "gluteal", "hamstring", "trapezius"],
|
||||
"secondaries": ["calves", "forearm", "deltoids", "lower-back", "abs", "obliques"]
|
||||
},
|
||||
"0525": {
|
||||
"bp": "full body",
|
||||
"primaries": ["quadriceps", "gluteal", "hamstring", "trapezius"],
|
||||
"secondaries": ["calves", "forearm", "deltoids", "lower-back", "abs", "obliques"]
|
||||
},
|
||||
"0526": {
|
||||
"bp": "full body",
|
||||
"primaries": ["quadriceps", "gluteal", "hamstring", "trapezius"],
|
||||
"secondaries": ["calves", "forearm", "deltoids", "lower-back", "abs", "obliques"]
|
||||
},
|
||||
"0535": {
|
||||
"bp": "full body",
|
||||
"primaries": ["quadriceps", "gluteal", "hamstring", "trapezius"],
|
||||
"secondaries": ["calves", "forearm", "deltoids", "lower-back", "abs", "obliques"]
|
||||
},
|
||||
"0552": {
|
||||
"bp": "full body",
|
||||
"primaries": ["quadriceps", "gluteal", "hamstring", "trapezius"],
|
||||
"secondaries": ["calves", "forearm", "deltoids", "lower-back", "abs", "obliques"]
|
||||
},
|
||||
"0648": {
|
||||
"bp": "full body",
|
||||
"primaries": ["quadriceps", "gluteal", "hamstring", "trapezius"],
|
||||
"secondaries": ["calves", "forearm", "deltoids", "lower-back", "abs", "obliques"]
|
||||
},
|
||||
"0067": {
|
||||
"bp": "full body",
|
||||
"primaries": ["quadriceps", "gluteal", "hamstring", "trapezius", "deltoids"],
|
||||
"secondaries": ["calves", "forearm", "triceps", "lower-back", "abs", "obliques"]
|
||||
},
|
||||
"3888": {
|
||||
"bp": "full body",
|
||||
"primaries": ["quadriceps", "gluteal", "hamstring", "trapezius", "deltoids"],
|
||||
"secondaries": ["calves", "forearm", "triceps", "lower-back", "abs", "obliques"]
|
||||
},
|
||||
"0529": {
|
||||
"bp": "full body",
|
||||
"primaries": ["quadriceps", "gluteal", "hamstring", "trapezius", "deltoids"],
|
||||
"secondaries": ["calves", "forearm", "triceps", "lower-back", "abs", "obliques"]
|
||||
},
|
||||
"0542": {
|
||||
"bp": "full body",
|
||||
"primaries": ["quadriceps", "gluteal", "hamstring", "trapezius", "deltoids"],
|
||||
"secondaries": ["calves", "forearm", "triceps", "lower-back", "abs", "obliques"]
|
||||
},
|
||||
"0028": {
|
||||
"bp": "full body",
|
||||
"primaries": ["quadriceps", "gluteal", "hamstring", "trapezius", "deltoids", "triceps"],
|
||||
"secondaries": ["calves", "forearm", "lower-back", "abs", "obliques"]
|
||||
},
|
||||
"0537": {
|
||||
"bp": "full body",
|
||||
"primaries": ["quadriceps", "gluteal", "hamstring", "trapezius", "deltoids", "triceps"],
|
||||
"secondaries": ["calves", "forearm", "lower-back", "abs", "obliques"]
|
||||
},
|
||||
"0527": {
|
||||
"bp": "full body",
|
||||
"primaries": ["quadriceps", "gluteal", "deltoids", "triceps"],
|
||||
"secondaries": ["hamstring", "calves", "trapezius", "forearm", "lower-back", "abs", "obliques"]
|
||||
},
|
||||
"0538": {
|
||||
"bp": "full body",
|
||||
"primaries": ["quadriceps", "gluteal", "deltoids", "triceps"],
|
||||
"secondaries": ["hamstring", "calves", "trapezius", "forearm", "lower-back", "abs", "obliques"]
|
||||
},
|
||||
"0776": {
|
||||
"bp": "full body",
|
||||
"primaries": ["quadriceps", "gluteal", "hamstring", "trapezius"],
|
||||
"secondaries": ["calves", "forearm", "deltoids", "lower-back", "abs", "obliques"]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import { afterEach, expect, it } from 'vitest'
|
||||
import { CATALOGUE, EXDB, EXIDX, registerCustom } from './exercises.js'
|
||||
import { OLYMPIC_LIFT_METADATA } from './exercise-muscle-batch-1.js'
|
||||
import { musclesOf, MUSCLES } from './muscles.js'
|
||||
|
||||
afterEach(() => registerCustom([]))
|
||||
|
||||
const catalogueNames = {
|
||||
'0295': 'dumbbell clean',
|
||||
'0518': 'kettlebell alternating hang clean',
|
||||
'0525': 'kettlebell bottoms up clean from the hang position',
|
||||
'0526': 'kettlebell double alternating hang clean',
|
||||
'0535': 'kettlebell hang clean',
|
||||
'0552': 'kettlebell two arm clean',
|
||||
'0648': 'power clean',
|
||||
'0067': 'barbell one arm snatch',
|
||||
'3888': 'dumbbell one arm snatch',
|
||||
'0529': 'kettlebell double snatch',
|
||||
'0542': 'kettlebell one arm snatch',
|
||||
'0028': 'barbell clean and press',
|
||||
'0537': 'kettlebell one arm clean and jerk',
|
||||
'0527': 'kettlebell double jerk',
|
||||
'0538': 'kettlebell one arm jerk',
|
||||
'0776': 'snatch pull'
|
||||
}
|
||||
|
||||
it('matches current catalogue names and classifies the audited lift family', () => {
|
||||
expect(Object.keys(OLYMPIC_LIFT_METADATA)).toEqual(Object.keys(catalogueNames))
|
||||
for (const [id, name] of Object.entries(catalogueNames)) {
|
||||
expect(EXDB.find(exercise => exercise.id === id)?.n, id).toBe(name)
|
||||
expect(CATALOGUE.find(exercise => exercise.id === id)).toMatchObject(OLYMPIC_LIFT_METADATA[id])
|
||||
expect(OLYMPIC_LIFT_METADATA[id].bp).toBe('full body')
|
||||
}
|
||||
})
|
||||
|
||||
it('keeps every overlay mapping canonical, multi-primary, and weighted for the lower body', () => {
|
||||
for (const [id, mapping] of Object.entries(OLYMPIC_LIFT_METADATA)) {
|
||||
expect(mapping.primaries.length, id).toBeGreaterThan(1)
|
||||
expect(mapping.primaries.every(muscle => MUSCLES.includes(muscle)), id).toBe(true)
|
||||
expect(mapping.secondaries.every(muscle => MUSCLES.includes(muscle) && !mapping.primaries.includes(muscle)), id).toBe(true)
|
||||
expect(new Set([...mapping.primaries, ...mapping.secondaries]).size, id).toBe(mapping.primaries.length + mapping.secondaries.length)
|
||||
expect(musclesOf(EXIDX[id]), id).toMatchObject({ quadriceps: 1, gluteal: 1 })
|
||||
}
|
||||
})
|
||||
|
||||
it('distinguishes overhead pressing from a pull and keeps trunk bracing secondary', () => {
|
||||
expect(EXIDX['0028'].primaries).toContain('triceps')
|
||||
expect(EXIDX['0776'].primaries).not.toContain('triceps')
|
||||
expect(EXIDX['0067'].primaries).toContain('deltoids')
|
||||
expect(EXIDX['0648'].secondaries).toContain('abs')
|
||||
expect(EXIDX['0648'].primaries).not.toContain('abs')
|
||||
})
|
||||
|
||||
it('preserves raw catalogue records and user corrections instead of overwriting saved metadata', () => {
|
||||
const raw = EXDB.find(exercise => exercise.id === '0648')
|
||||
expect(raw.bp).toBe('upper legs')
|
||||
expect(raw.primaries).toBeUndefined()
|
||||
registerCustom([{ ...raw, primaries: ['hamstring'], secondaries: [], bp: 'upper legs' }])
|
||||
expect(EXIDX['0648']).toMatchObject({ primaries: ['hamstring'], secondaries: [], bp: 'upper legs' })
|
||||
registerCustom([])
|
||||
expect(EXIDX['0648']).toMatchObject(OLYMPIC_LIFT_METADATA['0648'])
|
||||
})
|
||||
|
||||
it('does not classify clean-grip squats as Olympic clean movements or duplicate covered jerk metadata', () => {
|
||||
expect(OLYMPIC_LIFT_METADATA['0029']).toBeUndefined()
|
||||
expect(OLYMPIC_LIFT_METADATA['1433']).toBeUndefined()
|
||||
expect(OLYMPIC_LIFT_METADATA['0786']).toBeUndefined()
|
||||
expect(EXIDX['0786'].primaries).toContain('deltoids')
|
||||
})
|
||||
@@ -149,6 +149,44 @@ const BODYWEIGHT_EQ = new Set(['body weight', 'band', 'resistance band'])
|
||||
export const isBodyweightEq = idOrEx =>
|
||||
BODYWEIGHT_EQ.has((typeof idOrEx === 'string' ? EXIDX[idOrEx] : idOrEx)?.eq)
|
||||
|
||||
/* Assistance machines run the other way round: the stack carries part of your body weight, so
|
||||
* a smaller number is the harder set and the record (issue #232). Getting the set wrong is
|
||||
* worse than not having the feature — inverting a normal lift would hide real progress — so the
|
||||
* rule is deliberately narrow: the machine that takes load off you is the leverage machine whose
|
||||
* name says "assisted". That is eight exercises in the catalogue (assisted pull-up, chin-up,
|
||||
* chest dip, triceps dip and their variants) and nothing else.
|
||||
*
|
||||
* The name alone is not enough. Twenty-nine catalogue entries say "assisted": partner-assisted
|
||||
* stretches, a medicine-ball twist, band and bodyweight leg curls. On those the weight is
|
||||
* ordinary load — heavier is harder — and inverting them would be the same bug pointed the
|
||||
* other way. Equipment is what separates the two.
|
||||
*
|
||||
* `assisted: true` (or `false`) on a custom exercise or on a routine's config overrides the
|
||||
* rule in either direction, which is how anything the catalogue does not know gets marked.
|
||||
*/
|
||||
const ASSISTED_EQ = 'leverage machine'
|
||||
const assistedName = n => /\bassist(ed)?\b/i.test(String(n || ''))
|
||||
|
||||
// The catalogue entry itself carries an `id`, so this never recurses through it — one lookup,
|
||||
// then the shape is read directly.
|
||||
const assistedShape = ex => (typeof ex?.assisted === 'boolean' ? ex.assisted : ex?.eq === ASSISTED_EQ && assistedName(ex?.n))
|
||||
|
||||
export function isAssisted(idOrEx) {
|
||||
if (!idOrEx) return false
|
||||
if (typeof idOrEx === 'string') return !!assistedShape(EXIDX[idOrEx])
|
||||
if (typeof idOrEx.assisted === 'boolean') return idOrEx.assisted
|
||||
if (typeof idOrEx.target?.assisted === 'boolean') return idOrEx.target.assisted
|
||||
const known = idOrEx.id ? EXIDX[idOrEx.id] : null
|
||||
return !!assistedShape(known || idOrEx)
|
||||
}
|
||||
|
||||
/** The better of two loads for this exercise: less assistance, or more weight. */
|
||||
export const betterWeight = (idOrEx, a, b) => (isAssisted(idOrEx) ? Math.min(a, b) : Math.max(a, b))
|
||||
|
||||
/** Is `w` a better load than `prev`? `prev` of 0 means nothing logged yet. */
|
||||
export const beatsWeight = (idOrEx, w, prev) =>
|
||||
w > 0 && (prev <= 0 || (isAssisted(idOrEx) ? w < prev : w > prev))
|
||||
|
||||
// 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
|
||||
@@ -172,30 +210,77 @@ export const normalizeStr = s => (s || '')
|
||||
// is the i18n version (bumped by every setLang), so switching language rebuilds the translated
|
||||
// terms. Custom exercises are re-cached automatically — the store clones state on update, so an
|
||||
// edited exercise arrives as a new object the WeakMap has never seen.
|
||||
//
|
||||
// Each entry keeps the full corpus for substring matching and, separately, the words of the
|
||||
// name (English and localized) that the typo tolerance below is allowed to compare against.
|
||||
const corpusCache = new WeakMap()
|
||||
|
||||
function corpusOf(e) {
|
||||
const v = getVersion()
|
||||
const hit = corpusCache.get(e)
|
||||
if (hit && hit.v === v) return hit.s
|
||||
if (hit && hit.v === v) return hit
|
||||
const sm = Array.isArray(e?.sm) ? e.sm : []
|
||||
const name = normalizeStr(exerciseNameSearchText(e))
|
||||
const s = normalizeStr([
|
||||
exerciseNameSearchText(e),
|
||||
name,
|
||||
e?.tg || '', t(e?.tg || ''),
|
||||
e?.eq || '', t(e?.eq || ''),
|
||||
e?.bp || '', t(e?.bp || ''),
|
||||
...sm, ...sm.map(m => t(m)),
|
||||
e?.desc || ''
|
||||
].join(' '))
|
||||
corpusCache.set(e, { v, s })
|
||||
return s
|
||||
const entry = { v, s, nameWords: name.split(/\s+/).filter(Boolean) }
|
||||
corpusCache.set(e, entry)
|
||||
return entry
|
||||
}
|
||||
|
||||
// Allow one missing, extra or substituted character, or an adjacent transposition, in long
|
||||
// query tokens. Short tokens stay exact/substring-only: words such as "row" and "curl" are too
|
||||
// common for fuzzy matching to be useful.
|
||||
//
|
||||
// Only the exercise's own name words are ever compared this way. Body part, target and
|
||||
// equipment words are shared by a whole slice of the catalogue, so one accidental neighbour
|
||||
// ("wrist" ~ "waist", "power" ~ "lower arms", "drucken" ~ "rucken") would list hundreds of
|
||||
// unrelated exercises ahead of the real hits (QA C26).
|
||||
function nearWord(a, b) {
|
||||
if (a.length < 5 || Math.abs(a.length - b.length) > 1) return false
|
||||
let i = 0
|
||||
while (i < a.length && a[i] === b[i]) i++
|
||||
if (i === a.length) return b.length - i <= 1
|
||||
if (a.length === b.length) {
|
||||
return a.slice(i + 1) === b.slice(i + 1) ||
|
||||
(a[i] === b[i + 1] && a[i + 1] === b[i] && a.slice(i + 2) === b.slice(i + 2))
|
||||
}
|
||||
return a.length > b.length ? a.slice(i + 1) === b.slice(i) : a.slice(i) === b.slice(i + 1)
|
||||
}
|
||||
|
||||
const queryTokens = query => normalizeStr(query || '').split(/\s+/).filter(Boolean)
|
||||
|
||||
// Every token has to appear in the corpus; a token listed in `fuzzy` may instead be one edit
|
||||
// away from a name word.
|
||||
const matchTokens = (e, tokens, fuzzy) => {
|
||||
const { s, nameWords } = corpusOf(e)
|
||||
return tokens.every(tok => s.includes(tok) || (fuzzy.has(tok) && nameWords.some(word => nearWord(tok, word))))
|
||||
}
|
||||
|
||||
// Single-exercise check, used where the list is filtered one option at a time (the exercise
|
||||
// progress picker). Every token may fall back to the typo tolerance; lists go through
|
||||
// searchExercises below, which knows whether a token needs it at all.
|
||||
export function matchExercise(e, query) {
|
||||
if (!query) return true
|
||||
const tokens = normalizeStr(query).split(/\s+/).filter(Boolean)
|
||||
const tokens = queryTokens(query)
|
||||
if (!tokens.length) return true
|
||||
if (!e || typeof e !== 'object') return false
|
||||
const corpus = corpusOf(e)
|
||||
return tokens.every(tok => corpus.includes(tok))
|
||||
return matchTokens(e, tokens, new Set(tokens))
|
||||
}
|
||||
|
||||
// Search a list, exact hits first: a token that appears literally in at least one exercise is
|
||||
// taken at its word for the whole list, and only a token with no exact hit anywhere ("bnech",
|
||||
// "dumbell", "wirst") is allowed the typo tolerance. Otherwise a correctly spelled query such
|
||||
// as "squat" or "clean" would also drag in "squad" and "lean", and since the callers keep
|
||||
// catalogue order those strays would land ahead of the real matches (QA C26).
|
||||
export function searchExercises(list, query) {
|
||||
const tokens = queryTokens(query)
|
||||
if (!tokens.length) return list
|
||||
const fuzzy = new Set(tokens.filter(tok => !list.some(e => corpusOf(e).s.includes(tok))))
|
||||
return list.filter(e => matchTokens(e, tokens, fuzzy))
|
||||
}
|
||||
@@ -29,13 +29,29 @@ export const durPart = ms => (ms >= 60000 ? [fmtDur(ms)] : [])
|
||||
// Exercise names are stored lower-case and shown through CSS `capitalize`; text that has no
|
||||
// element of its own (a toast) capitalises here instead.
|
||||
export const capWords = s => String(s || '').replace(/(^|[\s(\-\/])(\p{Ll})/gu, (m, pre, ch) => pre + ch.toUpperCase())
|
||||
export const fmtNum = n => (Math.round(n * 10) / 10).toLocaleString(dateLocale())
|
||||
/* How many decimals a weight is shown with. One is enough for plate-loadable numbers, but a
|
||||
* per-side figure from kg plates lands on .25 and .75 and reading those as .3 and .8 is the
|
||||
* complaint in issue #139 — as is microplate work. The setting is read here rather than passed
|
||||
* through sixty-odd call sites, the same way the date locale is; App.jsx pushes it whenever
|
||||
* `S.wdec` changes.
|
||||
*
|
||||
* It only ever adds precision that is really there: a whole number still prints whole, and
|
||||
* 62.5 is 62.5 either way. Nothing rounds differently in storage — this is display only.
|
||||
*/
|
||||
let decimals = 1
|
||||
export const setWeightDecimals = n => { decimals = n === 2 ? 2 : 1 }
|
||||
export const weightDecimals = () => decimals
|
||||
export const fmtNum = n => {
|
||||
const p = decimals === 2 ? 100 : 10
|
||||
return (Math.round(n * p) / p).toLocaleString(dateLocale(), { maximumFractionDigits: decimals })
|
||||
}
|
||||
// Volume stays in the profile's unit throughout: the old shorthand turned anything over
|
||||
// 10 000 into "t", which is wrong for a pound profile and made one list mix "18.8t" with
|
||||
// "7'535 kg" — two numbers you can't compare at a glance.
|
||||
export const fmtVol = (v, unit) => fmtNum(v) + ' ' + unit
|
||||
// Plural forms are not automatic when the English string is the key.
|
||||
export const exCount = n => t(n === 1 ? '{0} exercise' : '{0} exercises', n)
|
||||
export const routineCount = n => t(n === 1 ? '{0} routine' : '{0} routines', n)
|
||||
|
||||
/* ---------------------------------------------------------------- week start --
|
||||
Where a week begins is a local convention, not a fact: most of Europe starts on
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// Pure helpers over the state object S (ported 1:1 from the vanilla app).
|
||||
import { todayISO, isoOf, weekKey, weekStartOf, fmtNum } from './format.js'
|
||||
import { isCardio, isBodyweightEq } from './exercises.js'
|
||||
import { isCardio, isBodyweightEq, isAssisted, betterWeight } from './exercises.js'
|
||||
import { phaseForSet, modeForSet, modeForEntry, isWarmupRow, normalizeMode, completedVolumeOf, nextDropWeight, splitBurstReps, makeSideSet, isSideSet, syncSideAggregate } from './workout-model.js'
|
||||
const objectOf = value => value && typeof value === 'object' && !Array.isArray(value) ? value : {}
|
||||
// Completed-state-independent work rows whose authoritative mode matches the requested mode.
|
||||
@@ -297,9 +297,12 @@ export function freestyleConfig(S, cfg) {
|
||||
}
|
||||
}
|
||||
export function bestWeightFor(S, exId) {
|
||||
// 0 means "nothing logged with a load yet" and must not win a min() for an assisted machine.
|
||||
let best = 0
|
||||
S.workouts.forEach(w => w.entries.forEach(e => {
|
||||
if (e.id === exId) best = Math.max(best, bestWeightForEntry(e))
|
||||
if (e.id !== exId) return
|
||||
const entryBest = bestWeightForEntry(e)
|
||||
if (entryBest > 0) best = best > 0 ? betterWeight(exId, best, entryBest) : entryBest
|
||||
}))
|
||||
return best
|
||||
}
|
||||
@@ -717,13 +720,21 @@ export function bestWeightForEntry(entry = {}) {
|
||||
const completedRows = repsRows.length
|
||||
? repsRows
|
||||
: workRows.filter(set => set?.done === true && !isWarmupRow(set))
|
||||
// On an assistance machine the smallest load is the best set, so "best" folds the other way
|
||||
// (issue #232). Everything below still returns a plain number — the caller does not branch.
|
||||
const assisted = isAssisted(entry.id ? { id: entry.id } : entry)
|
||||
let best = 0
|
||||
let hasUsableWeight = false
|
||||
completedRows.forEach(set => {
|
||||
const weight = Number(set?.w)
|
||||
if (!Number.isFinite(weight)) return
|
||||
// A 0 on an assistance machine is a row with no load entered, not a set done with no help
|
||||
// at all — folding it in as "the least assistance ever" would invent a record nobody did
|
||||
// and then ask for negative help next time. Anyone truly needing none has left the machine
|
||||
// behind and should log the unassisted exercise instead.
|
||||
if (assisted && !(weight > 0)) return
|
||||
best = hasUsableWeight ? betterWeight(entry.id, best, weight) : weight
|
||||
hasUsableWeight = true
|
||||
if (weight > best) best = weight
|
||||
})
|
||||
|
||||
// A real completed row, including an explicit zero for an unloaded bodyweight set, always
|
||||
@@ -736,7 +747,7 @@ export function bestWeightForEntry(entry = {}) {
|
||||
const topWeight = Number(entry.topW)
|
||||
// topW predates phase-tagged warm-ups. It remains a fallback for legacy all-work records,
|
||||
// but cannot override resolved work rows once any warm-up marker exists.
|
||||
if (parentMode === 'reps' && !hasNonRepsWorkRow && !hasWarmupRow
|
||||
&& Number.isFinite(topWeight) && topWeight > best) best = topWeight
|
||||
if (parentMode === 'reps' && !hasNonRepsWorkRow && !hasWarmupRow && Number.isFinite(topWeight)
|
||||
&& (best <= 0 || (assisted ? topWeight > 0 && topWeight < best : topWeight > best))) best = topWeight
|
||||
return best
|
||||
}
|
||||
@@ -265,19 +265,34 @@ export function matchHevyTitle(name) {
|
||||
// Hevy exports no category column, so every invented exercise fell through to the
|
||||
// 'upper legs' default and a third of an imported history was attributed to the legs in
|
||||
// the muscle map. When there is no category, read the body part off the name instead.
|
||||
// Order is the rule: the first match wins, so the specific word has to come before the broad one.
|
||||
// A grip is a modifier on a row or a pulldown, never the movement ("Chest Supported T Row Neutral
|
||||
// Grip" is a back exercise); a wrist or reverse curl is a forearm exercise that happens to say
|
||||
// "curl"; a leg curl is not an arm curl; and a Romanian or stiff-leg deadlift trains the legs where
|
||||
// the conventional pull is filed under the back. "grip" alone still reads as forearms — last.
|
||||
const NAME_BP = [
|
||||
[/\b(curl|bicep|biceps|tricep|triceps|skullcrusher|pushdown)\b/, 'upper arms'],
|
||||
[/\b(wrist|forearm|forearms|grip)\b/, 'lower arms'],
|
||||
[/\b(wrist|forearm|forearms|reverse curl)\b/, 'lower arms'],
|
||||
[/\b(leg curl|leg curls|hamstring curl|nordic)\b/, 'upper legs'],
|
||||
[/\b(romanian|rdl|stiff leg|stiff legged|straight leg)\b.*\bdeadlifts?\b|\brdl\b/, 'upper legs'],
|
||||
[/\b(curl|curls|bicep|biceps|tricep|triceps|skullcrusher|pushdown)\b/, 'upper arms'],
|
||||
[/\bchest supported\b/, 'back'], // where the chest rests, not what it trains
|
||||
[/\b(bench|chest|pec|fly|flye|crossover|crossovers|dip)\b/, 'chest'],
|
||||
[/\b(row|pulldown|pullup|pull up|chin up|lat|lats|back|deadlift|shrug)\b/, 'back'],
|
||||
[/\b(row|rows|pulldown|pullup|pull up|chin up|lat|lats|back|deadlift|deadlifts|shrug)\b/, 'back'],
|
||||
[/\b(shoulder|delt|delts|overhead|lateral raise|front raise|face pull|press up)\b/, 'shoulders'],
|
||||
[/\b(calf|calves)\b/, 'lower legs'],
|
||||
[/\b(squat|lunge|leg|glute|hamstring|quad|hip thrust|deadlift)\b/, 'upper legs'],
|
||||
[/\b(squat|lunge|leg|glute|hamstring|quad|hip thrust)\b/, 'upper legs'],
|
||||
[/\b(ab|abs|core|plank|crunch|sit up|oblique|russian twist)\b/, 'waist'],
|
||||
[/\b(run|running|jog|bike|cycling|rope|ropes|jump|jacks|burpee|sprint|treadmill|stair)\b/, 'cardio'],
|
||||
[/\bneck\b/, 'neck'],
|
||||
[/\bgrip\b/, 'lower arms'],
|
||||
]
|
||||
const bpFromName = name => (NAME_BP.find(([re]) => re.test(name)) || [])[1] || null
|
||||
// Hyphens, underscores and slashes read as spaces first: "Stiff-Legged Deadlift" and
|
||||
// "Chest-Supported Row" are the same names the rules above spell with a space, and the
|
||||
// matcher (wordsOf) already treats the two spellings as one exercise — the body part has to agree.
|
||||
export const bpFromName = name => {
|
||||
const n = String(name || '').toLowerCase().replace(/[-_/]+/g, ' ').replace(/\s+/g, ' ').trim()
|
||||
return (NAME_BP.find(([re]) => re.test(n)) || [])[1] || null
|
||||
}
|
||||
|
||||
// Categories the exporters use -> the dataset's body parts, for exercises we invent.
|
||||
const CATEGORY_BP = {
|
||||
@@ -483,7 +498,9 @@ export function parseWorkoutCSV(text, { unit = 'kg' } = {}) {
|
||||
id: 'iw' + uid(), d, start, end: end > start ? end : start,
|
||||
routineId: null, name: day.name || 'Imported', entries, prs: [],
|
||||
}
|
||||
w.vol = entries.reduce((a, e) => a + e.sets.reduce((b, s) => b + (s.w || 0) * (s.r || 0), 0), 0)
|
||||
// Work sets only, like `workoutVolume` for a workout finished in the app: warm-ups are
|
||||
// promised to stay out of the volume, and this number is stored with the workout for good.
|
||||
w.vol = entries.reduce((a, e) => a + e.sets.reduce((b, s) => b + (isWarmupRow(s) ? 0 : (s.w || 0) * (s.r || 0)), 0), 0)
|
||||
return w
|
||||
})
|
||||
|
||||
@@ -580,10 +597,23 @@ export function mergeImport(S, parsed) {
|
||||
return { added: fresh.length, skipped: parsed.bodyweight.length - fresh.length }
|
||||
}
|
||||
const have = new Set(S.workouts.map(w => w.d))
|
||||
// Every parse invents fresh ids for the names it cannot match, and a later export of the same
|
||||
// account names those exercises again. So a custom exercise is looked up by name among the ones
|
||||
// already here — from an earlier import or made by hand — and the new days are pointed at it,
|
||||
// the way mergeHevyRoutines and mergePlan do; otherwise the Library lists "Grip Trainer" twice,
|
||||
// each with half the history. Only a name with no match becomes a new exercise.
|
||||
S.customEx = S.customEx || []
|
||||
const nameKey = n => String(n || '').toLowerCase().replace(/\s+/g, ' ').trim()
|
||||
const exIdMap = {}
|
||||
parsed.customEx.forEach(c => {
|
||||
const same = S.customEx.find(x => x.id !== c.id && nameKey(x.n) === nameKey(c.n))
|
||||
if (same) exIdMap[c.id] = same.id
|
||||
})
|
||||
const fresh = parsed.workouts.filter(w => !have.has(w.d))
|
||||
.map(w => ({ ...w, entries: w.entries.map(e => (exIdMap[e.id] ? { ...e, id: exIdMap[e.id] } : e)) }))
|
||||
const used = new Set(fresh.flatMap(w => w.entries.map(e => e.id)))
|
||||
const customs = parsed.customEx.filter(c => used.has(c.id) && !EXIDX[c.id])
|
||||
S.customEx = [...(S.customEx || []), ...customs]
|
||||
S.customEx = [...S.customEx, ...customs]
|
||||
S.workouts = [...S.workouts, ...fresh].sort((a, b) => (a.d < b.d ? -1 : 1))
|
||||
// seed the weight suggestions from the newest imported set of each lift
|
||||
fresh.forEach(w => w.entries.forEach(e => {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { parseWorkoutCSV } from './import-csv.js'
|
||||
import { parseWorkoutCSV, mergeImport } from './import-csv.js'
|
||||
import { workoutVolume } from './history.js'
|
||||
|
||||
const CSV = [
|
||||
'Date,Exercise,Weight,Reps,Set Type',
|
||||
@@ -50,3 +51,57 @@ describe('gravl export', () => {
|
||||
expect(cardio.entries[0].sets).toEqual([{ min: 0.4, speed: 0, done: true }])
|
||||
})
|
||||
})
|
||||
|
||||
// A finished workout stores `vol = workoutVolume(w)`, which leaves warm-ups out; an imported one
|
||||
// wrote the sum of every set, so the History row, the heatmap and the month totals read a number
|
||||
// the app's own arithmetic never produces — and it stays wrong forever (QA C14).
|
||||
const HEVY_WARMUPS = [
|
||||
'title,start_time,end_time,description,exercise_title,superset_id,exercise_notes,set_index,set_type,weight_kg,reps,distance_km,duration_seconds,rpe',
|
||||
'"QA","03 Mar 2025, 18:00","03 Mar 2025, 19:00","","Bench Press (Barbell)",,"",0,warmup,20,10,,,',
|
||||
'"QA","03 Mar 2025, 18:00","03 Mar 2025, 19:00","","Bench Press (Barbell)",,"",1,normal,60,5,,,',
|
||||
'"QA","03 Mar 2025, 18:00","03 Mar 2025, 19:00","","Bench Press (Barbell)",,"",2,normal,60,5,,,',
|
||||
'"QA","03 Mar 2025, 18:00","03 Mar 2025, 19:00","","Squat (Barbell)",,"",0,warmup,40,5,,,',
|
||||
'"QA","03 Mar 2025, 18:00","03 Mar 2025, 19:00","","Squat (Barbell)",,"",1,normal,100,5,,,',
|
||||
].join('\n')
|
||||
|
||||
describe('imported volume', () => {
|
||||
it('stores the work-set volume, the same number workoutVolume computes', () => {
|
||||
const [w] = parseWorkoutCSV(HEVY_WARMUPS, { unit: 'kg' }).workouts
|
||||
expect(w.vol).toBe(1100)
|
||||
expect(w.vol).toBe(workoutVolume(w))
|
||||
})
|
||||
})
|
||||
|
||||
// Two exports of the same account, the second one a week later. Each parse invents fresh ids for
|
||||
// the names it cannot match, so the merge has to find the custom exercise the first import created
|
||||
// — otherwise the Library lists "Zorb Roller" twice with half the history each (QA C12).
|
||||
const hevyDay = (title, day, name, w, r) =>
|
||||
`"${title}","${day} Mar 2025, 18:00","${day} Mar 2025, 19:00","","${name}",,"",0,normal,${w},${r},,,`
|
||||
const HEVY_HEAD = HEVY_WARMUPS.split('\n')[0]
|
||||
const EXPORT_A = [HEVY_HEAD, hevyDay('Day A', '02', 'Zorb Roller', 49, 8), hevyDay('Day A', '02', 'Bench Press (Barbell)', 80, 5)].join('\n')
|
||||
const EXPORT_B = [HEVY_HEAD, hevyDay('Day A', '02', 'Zorb Roller', 49, 8), hevyDay('Day B', '09', 'Zorb Roller', 30, 15)].join('\n')
|
||||
|
||||
describe('mergeImport and custom exercises', () => {
|
||||
const fresh = () => ({ workouts: [], customEx: [], exWeights: {}, bodyweight: [] })
|
||||
|
||||
it('reuses the custom exercise an earlier import created for the same name', () => {
|
||||
const S = fresh()
|
||||
mergeImport(S, parseWorkoutCSV(EXPORT_A, { unit: 'kg' }))
|
||||
const [zorb] = S.customEx
|
||||
expect(zorb.n).toBe('zorb roller')
|
||||
|
||||
expect(mergeImport(S, parseWorkoutCSV(EXPORT_B, { unit: 'kg' }))).toEqual({ added: 1, skipped: 1 })
|
||||
expect(S.customEx).toHaveLength(1)
|
||||
// The new day points at the existing exercise, so its history is one line, not two.
|
||||
expect(S.workouts.map(w => w.entries[0].id)).toEqual([zorb.id, zorb.id])
|
||||
expect(S.exWeights[zorb.id]).toEqual({ w: 30, d: '2025-03-09' })
|
||||
})
|
||||
|
||||
it('matches the name regardless of case and spacing, including one the user made by hand', () => {
|
||||
const S = fresh()
|
||||
S.customEx.push({ id: 'mine', n: 'Zorb Roller ', bp: 'waist', custom: true })
|
||||
mergeImport(S, parseWorkoutCSV(EXPORT_A, { unit: 'kg' }))
|
||||
expect(S.customEx).toHaveLength(1)
|
||||
expect(S.workouts[0].entries.map(e => e.id)).toEqual(['mine', '0025'])
|
||||
})
|
||||
})
|
||||
@@ -267,7 +267,8 @@ export function parseHevyWorkouts(workouts, templates, { unit = 'kg' } = {}) {
|
||||
id: 'iw' + uid(), d, start: startMs, end: endMs > startMs ? endMs : startMs,
|
||||
routineId: null, name: day.name || 'Imported', entries, prs: [],
|
||||
}
|
||||
workout.vol = entries.reduce((a, e) => a + e.sets.reduce((b, s) => b + (s.w || 0) * (s.r || 0), 0), 0)
|
||||
// Work sets only, the number `workoutVolume` gives a workout finished in the app; it is stored for good.
|
||||
workout.vol = entries.reduce((a, e) => a + e.sets.reduce((b, s) => b + (isWarmupRow(s) ? 0 : (s.w || 0) * (s.r || 0)), 0), 0)
|
||||
return workout
|
||||
})
|
||||
|
||||
|
||||
@@ -124,6 +124,9 @@ describe('parseHevyWorkouts', () => {
|
||||
expect(pulldown.topW).toBe(52)
|
||||
expect(parsed.warmups).toBe(1)
|
||||
expect(parsed.rpeSets).toBe(1)
|
||||
// The stored volume leaves the warm-up out, like a workout finished in the app (QA C14):
|
||||
// 52×15 + 52×10 + 20×12 = 1,540, not 1,915.
|
||||
expect(parsed.workouts[0].vol).toBe(1540)
|
||||
|
||||
const custom = entries.find(e => String(e.id).startsWith('im'))
|
||||
expect(custom).toBeTruthy()
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
// The fallback that reads a body part off an exercise name when the export has no category
|
||||
// column (Hevy). First match wins, so the order of the rules is the behaviour — reported on
|
||||
// Discord by rubik_97 with the three cases below.
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { bpFromName } from './import-csv.js'
|
||||
|
||||
const bp = name => bpFromName(name.toLowerCase())
|
||||
|
||||
describe('body part from an exercise name', () => {
|
||||
it('reads a grip as a modifier, not as the movement', () => {
|
||||
expect(bp('Chest Supported T Row Neutral Grip')).toBe('back')
|
||||
expect(bp('Wide Grip Lat Pulldown')).toBe('back')
|
||||
expect(bp('Close Grip Bench Press')).toBe('chest')
|
||||
})
|
||||
|
||||
it('files wrist and reverse curls under the forearms, not the upper arms', () => {
|
||||
expect(bp('Wrist Curl')).toBe('lower arms')
|
||||
expect(bp('Barbell Reverse Curl')).toBe('lower arms')
|
||||
expect(bp('Hammer Curl')).toBe('upper arms')
|
||||
})
|
||||
|
||||
it('keeps leg curls and the hamstring deadlifts on the legs', () => {
|
||||
expect(bp('Lying Leg Curl')).toBe('upper legs')
|
||||
expect(bp('Romanian Deadlift')).toBe('upper legs')
|
||||
expect(bp('Stiff Leg Deadlift')).toBe('upper legs')
|
||||
expect(bp('RDL')).toBe('upper legs')
|
||||
expect(bp('Deadlift')).toBe('back')
|
||||
})
|
||||
|
||||
// The rules are written with spaces, but people hyphenate these names as often as not (QA C28).
|
||||
// The matcher already treats "chest-supported row" and "chest supported row" as one exercise;
|
||||
// the body-part fallback has to agree with it, or the two spellings land on different maps.
|
||||
it('reads the hyphenated, underscored and slashed spellings like the spaced ones', () => {
|
||||
expect(bp('Stiff-Legged Deadlift')).toBe('upper legs')
|
||||
expect(bp('Straight-Leg Deadlift')).toBe('upper legs')
|
||||
expect(bp('Stiff_Leg Deadlift')).toBe('upper legs')
|
||||
expect(bp('Chest-Supported Row')).toBe('back')
|
||||
expect(bp('Chest-Supported T-Bar Row')).toBe('back')
|
||||
expect(bp('Chest/Supported Row')).toBe('back')
|
||||
expect(bp('Sit-Up')).toBe('waist')
|
||||
})
|
||||
|
||||
it('still reads a bare grip exercise as forearms, and the rest as before', () => {
|
||||
expect(bp('Grip Trainer')).toBe('lower arms')
|
||||
expect(bp('Back Squat')).toBe('back') // unchanged: "back" is matched before "squat"
|
||||
expect(bp('Standing Calf Raise')).toBe('lower legs')
|
||||
expect(bp('Something Unheard Of')).toBe(null)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,18 @@
|
||||
// A custom exercise used to store its muscles in the order the chips were tapped, so the same
|
||||
// exercise read differently depending on how it was built (Discord, luckapow).
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { inMuscleOrder, MUSCLES } from './muscles.js'
|
||||
|
||||
describe('muscles in the map order', () => {
|
||||
it('is the same list whatever order it was picked in', () => {
|
||||
expect(inMuscleOrder(['triceps', 'chest', 'deltoids'])).toEqual(['deltoids', 'chest', 'triceps'])
|
||||
expect(inMuscleOrder(['chest', 'deltoids', 'triceps'])).toEqual(['deltoids', 'chest', 'triceps'])
|
||||
})
|
||||
it('follows MUSCLES, leaves unknown names at the end and the input alone', () => {
|
||||
const picked = ['calves', 'made-up', 'abs']
|
||||
expect(inMuscleOrder(picked)).toEqual(['abs', 'calves', 'made-up'])
|
||||
expect(picked).toEqual(['calves', 'made-up', 'abs'])
|
||||
expect(inMuscleOrder([...MUSCLES].reverse())).toEqual(MUSCLES)
|
||||
expect(inMuscleOrder(undefined)).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -21,16 +21,25 @@ export const MUSCLES = [
|
||||
'calves', 'tibialis',
|
||||
]
|
||||
|
||||
// A picked list in the map's own order rather than the order the chips were tapped in — two
|
||||
// people building the same exercise get the same exercise. Unknown names keep their place at the end.
|
||||
export const inMuscleOrder = list => {
|
||||
const at = m => { const i = MUSCLES.indexOf(m); return i < 0 ? MUSCLES.length : i }
|
||||
return [...(list || [])].sort((a, b) => at(a) - at(b))
|
||||
}
|
||||
|
||||
// Drawn as the silhouette, never shaded: they carry no training load.
|
||||
export const INERT = ['head', 'hair', 'neck', 'hands', 'feet', 'knees', 'ankles']
|
||||
|
||||
// English display names; these strings are the i18n keys (see lib/i18n.js).
|
||||
// English display names; these strings are the i18n keys (see lib/i18n.js). The packs know
|
||||
// the cardio pseudo-muscle only under the dataset's own lowercase spelling, and every place
|
||||
// that shows it capitalises with CSS — a capitalised key here rendered English everywhere.
|
||||
export const MUSCLE_NAME = {
|
||||
trapezius: 'Traps', deltoids: 'Shoulders', chest: 'Chest', 'upper-back': 'Upper back',
|
||||
serratus: 'Serratus', biceps: 'Biceps', triceps: 'Triceps', forearm: 'Forearms',
|
||||
abs: 'Abs', obliques: 'Obliques', 'lower-back': 'Lower back', gluteal: 'Glutes',
|
||||
quadriceps: 'Quads', hamstring: 'Hamstrings', adductors: 'Adductors',
|
||||
'hip-flexors': 'Hip flexors', calves: 'Calves', tibialis: 'Shins', 'cardiovascular system': 'Cardiovascular system',
|
||||
'hip-flexors': 'Hip flexors', calves: 'Calves', tibialis: 'Shins', 'cardiovascular system': 'cardiovascular system',
|
||||
}
|
||||
|
||||
// Every spelling that occurs in the dataset's `tg` and `sm` fields. null = not drawable.
|
||||
|
||||
@@ -210,3 +210,17 @@ describe('muscle balance windows and ranking', () => {
|
||||
expect(loadOfWorkouts([{ entries: [deleted] }])).toEqual({ chest: 1 })
|
||||
})
|
||||
})
|
||||
|
||||
// MUSCLE_NAME values are the i18n keys — a value no pack defines renders English in every
|
||||
// language. The Library list showed "Cardiovascular system" untranslated for every cardio
|
||||
// exercise (QA copy): the packs only ever had the dataset's own lowercase spelling.
|
||||
describe('MUSCLE_NAME as i18n keys', () => {
|
||||
const packs = import.meta.glob('../locales/*.js', { eager: true })
|
||||
it('every display name is a key in every locale pack', () => {
|
||||
expect(Object.keys(packs).length).toBe(14)
|
||||
for (const [file, mod] of Object.entries(packs)) {
|
||||
const missing = Object.values(MUSCLE_NAME).filter(name => !(name in mod.default))
|
||||
expect(missing, file).toEqual([])
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -1,4 +1,5 @@
|
||||
import { isWarmupRow } from './workout-model.js'
|
||||
import { isAssisted } from './exercises.js'
|
||||
// Estimated one-rep max (issue #18).
|
||||
//
|
||||
// Deliberately knows nothing about the exercise database: an estimate needs a weight AND a
|
||||
@@ -43,6 +44,10 @@ export function estimate1RM(w, r, formula = DEFAULT_FORMULA) {
|
||||
// `topW` is ignored on purpose: it records the working weight a user confirmed after the
|
||||
// exercise, with no rep count attached, so it cannot produce an estimate.
|
||||
export function bestSetOf(entry, formula = DEFAULT_FORMULA) {
|
||||
// An assistance machine has no one-rep max to estimate: the load is the help you were given,
|
||||
// so Epley on it would rise as you got weaker and call that a record (issue #232). These
|
||||
// exercises stay out of the estimate, the curve and the strength list entirely.
|
||||
if (isAssisted(entry?.id ? { id: entry.id } : entry)) return null
|
||||
let best = null
|
||||
;(entry?.sets || []).forEach(s => {
|
||||
if (!s.done || isWarmupRow(s)) return
|
||||
@@ -55,6 +60,7 @@ export function bestSetOf(entry, formula = DEFAULT_FORMULA) {
|
||||
// One point per workout in which the exercise produced an estimate — feeds the trend chart.
|
||||
// Chronological, matching the order workouts are appended in.
|
||||
export function e1rmSeries(S, exId, formula = DEFAULT_FORMULA) {
|
||||
if (isAssisted(exId)) return []
|
||||
const pts = []
|
||||
;(S.workouts || []).forEach(w => {
|
||||
const entry = w.entries.find(e => e.id === exId)
|
||||
|
||||
@@ -13,10 +13,51 @@ import { modeOf, fmtSec, isBw, isPerSide, sideReps, MAX_PLANNED_WARMUPS } from '
|
||||
import { deriveSessionName } from './session-merge.js'
|
||||
import { uid, todayISO, DAYN, weekOrder, weekStartOf, fmtNum, exCount } from './format.js'
|
||||
import { t, exerciseNameFor } from './i18n-core.js'
|
||||
import { convertWeight } from './units.js'
|
||||
import { MUSCLES, inMuscleOrder } from './muscles.js'
|
||||
|
||||
const PLAN_FMT = 1
|
||||
const WEEK_DAYS = [1, 2, 3, 4, 5, 6, 0] // every getDay() index; only the reader's own
|
||||
// screen puts them in an order (see weekOrder)
|
||||
const PLAN_UNITS = new Set(['kg', 'lb'])
|
||||
|
||||
// A plan's numbers are in the unit that wrote it. Missing unit is deliberately legacy-compatible:
|
||||
// old files were read as already being in the recipient's unit, so keep their values unchanged.
|
||||
const planUnit = value => value === 'lbs' ? 'lb' : PLAN_UNITS.has(value) ? value : null
|
||||
const unitError = () => { throw new Error(t('this isn’t an openGym plan file')) }
|
||||
|
||||
function declaredPlanUnit(data) {
|
||||
let declared = null
|
||||
for (const key of ['unit', 'weightUnit']) {
|
||||
if (data[key] == null) continue
|
||||
const unit = planUnit(data[key])
|
||||
if (!unit || (declared && declared !== unit)) unitError()
|
||||
declared = unit
|
||||
}
|
||||
return declared
|
||||
}
|
||||
|
||||
function convertedExercise(e, sourceUnit, destinationUnit) {
|
||||
if (!sourceUnit || sourceUnit === destinationUnit) return e
|
||||
const out = { ...e }
|
||||
if (out.weight != null) out.weight = convertWeight(out.weight, sourceUnit, destinationUnit)
|
||||
// A timed increment is seconds, not a load. Rep-mode increments are load overrides.
|
||||
if (modeOf(out) === 'reps' && out.inc > 0) out.inc = convertWeight(out.inc, sourceUnit, destinationUnit)
|
||||
return out
|
||||
}
|
||||
|
||||
function convertedBundle(bundle, destinationUnit) {
|
||||
const sourceUnit = declaredPlanUnit(bundle)
|
||||
if (!sourceUnit || sourceUnit === destinationUnit) return bundle
|
||||
return {
|
||||
...bundle,
|
||||
unit: destinationUnit,
|
||||
routines: (bundle.routines || []).map(r => ({
|
||||
...r,
|
||||
ex: (r.ex || []).map(e => convertedExercise(e, sourceUnit, destinationUnit))
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
// Keep only the meaningful config fields, so the file stays small and readable.
|
||||
function cleanEx(e) {
|
||||
@@ -93,8 +134,36 @@ function cleanIntensifier(x) {
|
||||
return null
|
||||
}
|
||||
|
||||
// The muscles the map can draw, plus the one label the form gives a cardio exercise.
|
||||
const CUSTOM_MUSCLES = new Set([...MUSCLES, 'cardiovascular system'])
|
||||
const muscleList = v => inMuscleOrder([...new Set((Array.isArray(v) ? v : []).filter(m => CUSTOM_MUSCLES.has(m)))])
|
||||
|
||||
/** A custom exercise with its own metadata — equipment, muscles, description — in the shape
|
||||
* CustomExForm writes, minus the recipient-side `custom`/`sm` fields mergePlan adds. The bundle
|
||||
* used to carry only {id, n, bp}, so the exercise arrived with an empty equipment tag, no muscle
|
||||
* credit, and (stored without `custom: true`) no way to edit or delete it (QA C7). The same gate
|
||||
* runs on the way in as on the way out, since a plan file is someone else's data: only muscles the
|
||||
* map can draw, a secondary never repeating a primary, the way the form itself enforces. Fields
|
||||
* that are empty stay absent, so a file written before this change reads the same as one after. */
|
||||
function cleanCustom(c) {
|
||||
const o = { id: c.id, n: c.n, bp: c.bp }
|
||||
if (c.desc) o.desc = c.desc
|
||||
if (typeof c.eq === 'string' && c.eq) o.eq = c.eq
|
||||
const prim = muscleList(c.primaries)
|
||||
const sm = muscleList(c.secondaries).filter(m => !prim.includes(m))
|
||||
// `tg` is the legacy single primary; the form keeps it equal to the first primary.
|
||||
const tg = prim[0] || (CUSTOM_MUSCLES.has(c.tg) ? c.tg : '')
|
||||
if (tg) o.tg = tg
|
||||
if (prim.length) o.primaries = prim
|
||||
if (sm.length) o.secondaries = sm
|
||||
if (prim.length || sm.length) o.muscleGroups = [...prim, ...sm]
|
||||
return o
|
||||
}
|
||||
|
||||
/** Build the shareable bundle: every routine, the week schedule, referenced customs. */
|
||||
export function buildPlanBundle(S, name) {
|
||||
const unit = planUnit(S.unit == null ? 'kg' : S.unit)
|
||||
if (!unit) unitError()
|
||||
const routines = (S.routines || []).map(r => ({
|
||||
id: r.id, name: r.name, emoji: r.emoji,
|
||||
...(r.prog ? { prog: r.prog } : {}),
|
||||
@@ -104,13 +173,13 @@ export function buildPlanBundle(S, name) {
|
||||
const usedIds = new Set(routines.flatMap(r => r.ex.map(e => e.id)))
|
||||
const customEx = (S.customEx || [])
|
||||
.filter(c => usedIds.has(c.id))
|
||||
.map(c => ({ id: c.id, n: c.n, bp: c.bp, ...(c.desc ? { desc: c.desc } : {}) }))
|
||||
.map(cleanCustom)
|
||||
// A weekday can hold several routines (merge order preserved). `[].concat` normalises a
|
||||
// legacy scalar id to a one-element list, so a bundle written before this change and one
|
||||
// written after are read the same way at the other end.
|
||||
const week = {}
|
||||
WEEK_DAYS.forEach(d => { if (S.week?.[d]?.length) week[d] = [].concat(S.week[d]) })
|
||||
return { opengym_plan: PLAN_FMT, exported: todayISO(), name: name || '', week, routines, customEx }
|
||||
return { opengym_plan: PLAN_FMT, exported: todayISO(), name: name || '', unit, week, routines, customEx }
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -122,11 +191,13 @@ export function buildPlanBundle(S, name) {
|
||||
* would sit invisibly in the routine and only surface as a blank screen when the routine
|
||||
* is trained.
|
||||
*/
|
||||
export function parsePlan(raw) {
|
||||
export function parsePlan(raw, destinationUnit = 'kg') {
|
||||
const data = typeof raw === 'string' ? JSON.parse(raw) : raw
|
||||
if (!data || !data.opengym_plan || !Array.isArray(data.routines)) {
|
||||
const destination = planUnit(destinationUnit)
|
||||
if (!data || typeof data !== 'object' || Array.isArray(data) || !data.opengym_plan || !Array.isArray(data.routines) || !destination) {
|
||||
throw new Error(t('this isn’t an openGym plan file'))
|
||||
}
|
||||
const sourceUnit = declaredPlanUnit(data)
|
||||
const customEx = (Array.isArray(data.customEx) ? data.customEx : []).filter(c => c && c.id)
|
||||
const known = new Set(customEx.map(c => c.id))
|
||||
let dropped = 0
|
||||
@@ -144,7 +215,7 @@ export function parsePlan(raw) {
|
||||
const rest = cleanRestSec(e.restSec)
|
||||
const warmRest = cleanRestSec(e.warmupRestSec)
|
||||
const { warmupSets, intensifier, restSec, warmupRestSec, ...passthrough } = e
|
||||
return { ...passthrough, ...(warm ? { warmupSets: warm } : {}), ...(intens ? { intensifier: intens } : {}), ...(rest ? { restSec: rest } : {}), ...(warmRest ? { warmupRestSec: warmRest } : {}) }
|
||||
return convertedExercise({ ...passthrough, ...(warm ? { warmupSets: warm } : {}), ...(intens ? { intensifier: intens } : {}), ...(rest ? { restSec: rest } : {}), ...(warmRest ? { warmupRestSec: warmRest } : {}) }, sourceUnit || destination, destination)
|
||||
})
|
||||
}))
|
||||
return {
|
||||
@@ -155,7 +226,12 @@ export function parsePlan(raw) {
|
||||
dropped,
|
||||
routineCount: routines.length,
|
||||
exerciseCount: routines.reduce((n, r) => n + r.ex.length, 0),
|
||||
scheduledDays: WEEK_DAYS.filter(d => data.week?.[d]?.length).length
|
||||
scheduledDays: WEEK_DAYS.filter(d => data.week?.[d]?.length).length,
|
||||
// `unit` is the unit of the returned prescriptions. `sourceUnit` is null for a legacy file;
|
||||
// that absence means its numbers were intentionally treated as already in `destination`.
|
||||
unit: destination,
|
||||
sourceUnit: sourceUnit || null,
|
||||
destinationUnit: destination
|
||||
}
|
||||
}
|
||||
|
||||
@@ -167,17 +243,23 @@ export function parsePlan(raw) {
|
||||
* leaves empty become rest days — a half-overwritten week would silently mix two plans)
|
||||
*/
|
||||
export function mergePlan(s, bundle, { schedule } = {}) {
|
||||
const destination = planUnit(s.unit == null ? 'kg' : s.unit)
|
||||
if (!destination) unitError()
|
||||
const source = convertedBundle(bundle, destination)
|
||||
s.customEx = s.customEx || []
|
||||
const exIdMap = {}
|
||||
;(bundle.customEx || []).forEach(c => {
|
||||
;(source.customEx || []).forEach(c => {
|
||||
const same = s.customEx.find(x => (x.n || '').toLowerCase() === (c.n || '').toLowerCase() && x.bp === c.bp)
|
||||
if (same) { exIdMap[c.id] = same.id; return }
|
||||
const nid = uid()
|
||||
exIdMap[c.id] = nid
|
||||
s.customEx.push({ id: nid, n: c.n, bp: c.bp, ...(c.desc ? { desc: c.desc } : {}) })
|
||||
// Stored exactly as the form would have created it — `custom: true` is what lets the recipient
|
||||
// edit or delete it, and `sm` mirrors the secondaries the way the form writes them.
|
||||
const clean = cleanCustom(c)
|
||||
s.customEx.push({ ...clean, id: nid, ...(clean.secondaries ? { sm: clean.secondaries } : {}), custom: true })
|
||||
})
|
||||
const ridMap = {}
|
||||
bundle.routines.forEach(r => {
|
||||
source.routines.forEach(r => {
|
||||
const nid = uid()
|
||||
ridMap[r.id] = nid
|
||||
s.routines.push({
|
||||
@@ -191,7 +273,7 @@ export function mergePlan(s, bundle, { schedule } = {}) {
|
||||
})
|
||||
if (schedule) {
|
||||
WEEK_DAYS.forEach(d => { delete s.week[d] })
|
||||
Object.entries(bundle.week || {}).forEach(([d, val]) => {
|
||||
Object.entries(source.week || {}).forEach(([d, val]) => {
|
||||
// `[].concat` tolerates a pre-upgrade scalar bundle value. An element whose routine id
|
||||
// didn't survive parsing is dropped, not written as undefined; a day that ends up empty
|
||||
// is left absent rather than stored as `[]`.
|
||||
@@ -199,7 +281,7 @@ export function mergePlan(s, bundle, { schedule } = {}) {
|
||||
if (ids.length) s.week[d] = ids
|
||||
})
|
||||
}
|
||||
return { routines: bundle.routines.length }
|
||||
return { routines: source.routines.length }
|
||||
}
|
||||
|
||||
/* ------------------------------- printable PDF ------------------------------- */
|
||||
|
||||
@@ -9,6 +9,57 @@ const stateWith = ex => ({
|
||||
})
|
||||
const roundTrip = ex => parsePlan(JSON.stringify(buildPlanBundle(stateWith(ex), 'Plan'))).routines[0].ex[0]
|
||||
|
||||
describe('plan-share units', () => {
|
||||
it('exports a unit and converts every load prescription at the import boundary', () => {
|
||||
const source = {
|
||||
unit: 'kg', week: {}, customEx: [],
|
||||
routines: [{ id: 'r', name: 'Strength', ex: [
|
||||
{ id: '0025', mode: 'reps', sets: 3, reps: 5, weight: 60, inc: 2.5 },
|
||||
{ id: '0007', mode: 'time', sets: 1, sec: 30, weight: 20, inc: 5 },
|
||||
] }],
|
||||
}
|
||||
const bundle = buildPlanBundle(source, 'Strength')
|
||||
expect(bundle.unit).toBe('kg')
|
||||
const imported = parsePlan(bundle, 'lb')
|
||||
expect(imported.unit).toBe('lb')
|
||||
expect(imported.routines[0].ex[0]).toMatchObject({ weight: 132.5, inc: 5.5 })
|
||||
expect(imported.routines[0].ex[1]).toMatchObject({ weight: 44, inc: 5 })
|
||||
})
|
||||
|
||||
it('converts pounds back to kilograms and merges the converted prescription', () => {
|
||||
const source = {
|
||||
unit: 'lb', week: {}, customEx: [],
|
||||
routines: [{ id: 'r', name: 'Strength', ex: [{ id: '0025', sets: 3, reps: 5, weight: 135, inc: 10 }] }],
|
||||
}
|
||||
const bundle = buildPlanBundle(source, 'Strength')
|
||||
const target = { unit: 'kg', routines: [], customEx: [], week: {} }
|
||||
mergePlan(target, bundle)
|
||||
expect(target.routines[0].ex[0]).toMatchObject({ weight: 61.25, inc: 4.5 })
|
||||
})
|
||||
|
||||
it('keeps valid legacy bundles without a unit in their destination-unit semantics', () => {
|
||||
const legacy = {
|
||||
opengym_plan: 1, name: 'Legacy', summary: 'old export',
|
||||
week: { 1: 'r' }, customEx: [],
|
||||
routines: [{ id: 'r', name: 'Strength', ex: [{ id: '0025', sets: 3, reps: 5, weight: 60, inc: 2.5 }] }],
|
||||
}
|
||||
const parsed = parsePlan(legacy, 'lb')
|
||||
expect(parsed.unit).toBe('lb')
|
||||
expect(parsed.routines[0].ex[0]).toMatchObject({ weight: 60, inc: 2.5 })
|
||||
})
|
||||
|
||||
it('accepts legacy root omissions and the older weightUnit marker', () => {
|
||||
const legacy = {
|
||||
opengym_plan: 1, weightUnit: 'lbs', legacyNote: 'kept as metadata',
|
||||
routines: [{ id: 'r', name: 'Strength', ex: [{ id: '0025', sets: 3, reps: 5, weight: 135, inc: 10 }] }],
|
||||
}
|
||||
const parsed = parsePlan(legacy, 'kg')
|
||||
expect(parsed.routines[0].ex[0]).toMatchObject({ weight: 61.25, inc: 4.5 })
|
||||
expect(parsed.week).toEqual({})
|
||||
expect(parsed.customEx).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('what survives a shared plan', () => {
|
||||
it('carries a drop-set prescription', () => {
|
||||
expect(roundTrip({ intensifier: { type: 'dropset', count: 2, pct: 20 } }).intensifier)
|
||||
@@ -144,3 +195,64 @@ describe('week schedule as a routine-id list', () => {
|
||||
expect(parsePlan({ opengym_plan: 1, routines: [], customEx: [], week: { 1: ['a'], 2: [], 4: 'b' } }).scheduledDays).toBe(2)
|
||||
})
|
||||
})
|
||||
|
||||
// ---- custom exercises travel whole (QA C7) ----
|
||||
// The bundle used to carry only {id, n, bp} and mergePlan stored exactly that: the recipient's copy
|
||||
// showed an empty equipment tag, no muscle credit, and — without `custom: true` — no Edit or Delete,
|
||||
// so a wrong import could only be fixed by hand-editing localStorage.
|
||||
describe('custom exercises in a shared plan', () => {
|
||||
// The shape CustomExForm writes, in the map's order.
|
||||
const landmine = {
|
||||
id: 'c1', n: 'QA Landmine Row', bp: 'back', desc: 'Bar in the corner', tg: 'upper-back', sm: ['biceps'],
|
||||
muscleGroups: ['upper-back', 'biceps'], primaries: ['upper-back'], secondaries: ['biceps'], eq: 'barbell', custom: true,
|
||||
}
|
||||
const source = {
|
||||
routines: [{ id: 'r', name: 'Back day', ex: [{ id: 'c1', sets: 3, reps: 8, weight: 40 }] }],
|
||||
week: {}, customEx: [landmine],
|
||||
}
|
||||
|
||||
it('exports equipment, muscles and description with the custom exercise', () => {
|
||||
expect(buildPlanBundle(source, 'Plan').customEx[0]).toEqual({
|
||||
id: 'c1', n: 'QA Landmine Row', bp: 'back', desc: 'Bar in the corner', eq: 'barbell', tg: 'upper-back',
|
||||
primaries: ['upper-back'], secondaries: ['biceps'], muscleGroups: ['upper-back', 'biceps'],
|
||||
})
|
||||
})
|
||||
|
||||
it('stores the imported custom exercise the way the form would have created it', () => {
|
||||
const parsed = parsePlan(JSON.stringify(buildPlanBundle(source, 'Plan')))
|
||||
const target = { routines: [], week: {}, customEx: [] }
|
||||
mergePlan(target, parsed)
|
||||
const stored = target.customEx[0]
|
||||
expect(stored).toMatchObject({ ...landmine, id: stored.id })
|
||||
expect(stored.id).not.toBe('c1')
|
||||
expect(target.routines[0].ex[0].id).toBe(stored.id)
|
||||
})
|
||||
|
||||
// A file written before the metadata travelled has only a name and a body part; it still imports,
|
||||
// and the recipient can now add the equipment and muscles themselves.
|
||||
it('keeps importing an old name-plus-body-part file, editable at the other end', () => {
|
||||
const legacy = { opengym_plan: 1, routines: [{ id: 'r', name: 'R', ex: [{ id: 'x', sets: 3, reps: 5 }] }], customEx: [{ id: 'x', n: 'Old one', bp: 'legs' }] }
|
||||
const target = { routines: [], week: {}, customEx: [] }
|
||||
mergePlan(target, parsePlan(legacy))
|
||||
expect(target.customEx[0]).toEqual({ id: target.customEx[0].id, n: 'Old one', bp: 'legs', custom: true })
|
||||
expect(target.routines[0].ex[0].id).toBe(target.customEx[0].id)
|
||||
})
|
||||
|
||||
// A plan file is someone else's data: only muscles the map can draw are kept, and a muscle listed
|
||||
// as both primary and secondary counts once, as the form itself enforces.
|
||||
it('drops muscles it cannot draw and a secondary that repeats a primary', () => {
|
||||
const bundle = { opengym_plan: 1, routines: [], customEx: [{ id: 'x', n: 'Odd', bp: 'back', eq: 'barbell', primaries: ['upper-back', 'wings'], secondaries: ['upper-back', 'biceps', 7] }] }
|
||||
const target = { routines: [], week: {}, customEx: [] }
|
||||
mergePlan(target, parsePlan(bundle))
|
||||
expect(target.customEx[0]).toMatchObject({ primaries: ['upper-back'], secondaries: ['biceps'], muscleGroups: ['upper-back', 'biceps'], tg: 'upper-back', sm: ['biceps'] })
|
||||
})
|
||||
|
||||
it('still reuses a custom the recipient already has under the same name and body part', () => {
|
||||
const parsed = parsePlan(JSON.stringify(buildPlanBundle(source, 'Plan')))
|
||||
const mine = { id: 'mine', n: 'qa landmine row', bp: 'back', eq: 'landmine', custom: true }
|
||||
const target = { routines: [], week: {}, customEx: [mine] }
|
||||
mergePlan(target, parsed)
|
||||
expect(target.customEx).toEqual([mine])
|
||||
expect(target.routines[0].ex[0].id).toBe('mine')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,53 @@
|
||||
// Issue #233: a set logged on top of the plan is extra work, not part of the prescription.
|
||||
// Before this, one heavier bonus set pulled the next session's weight up with it, and a bonus
|
||||
// set taken short of the target reps reported the whole session as missed.
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { readSession } from './progression.js'
|
||||
|
||||
const set = (w, r, done = true) => ({ w, r, done })
|
||||
const entry = (target, sets) => ({ id: '0025', target, sets })
|
||||
const plan = { mode: 'reps', sets: 3, reps: 8, weight: 60 }
|
||||
|
||||
describe('extra sets stay out of the progression read', () => {
|
||||
it('ignores a heavier bonus set when reading the weight', () => {
|
||||
const done = readSession(entry(plan, [set(60, 8), set(60, 8), set(60, 8), set(80, 8)]))
|
||||
expect(done.weight).toBe(60)
|
||||
expect(done.ok).toBe(true)
|
||||
})
|
||||
|
||||
it('does not call the session missed because a bonus set fell short', () => {
|
||||
const done = readSession(entry(plan, [set(60, 8), set(60, 8), set(60, 8), set(80, 3)]))
|
||||
expect(done.ok).toBe(true)
|
||||
expect(done.low).toBe(8)
|
||||
expect(done.count).toBe(3)
|
||||
// Greyskull reads the last set of the plan, not whatever was tacked on after it
|
||||
expect(done.amrap).toBe(8)
|
||||
})
|
||||
|
||||
it('still reports a short session as short, and still reads every planned set', () => {
|
||||
const short = readSession(entry(plan, [set(60, 8), set(60, 5), set(60, 8)]))
|
||||
expect(short.ok).toBe(false)
|
||||
expect(short.low).toBe(5)
|
||||
const missing = readSession(entry(plan, [set(60, 8), set(60, 8)]))
|
||||
expect(missing.ok).toBe(false)
|
||||
})
|
||||
|
||||
it('reads everything when the plan names no set count (freestyle)', () => {
|
||||
const free = readSession(entry({ mode: 'reps', reps: 8 }, [set(60, 8), set(80, 8)]))
|
||||
expect(free.weight).toBe(80)
|
||||
expect(free.count).toBe(2)
|
||||
})
|
||||
|
||||
it('leaves warm-ups out before counting, so a warm-up does not eat a planned slot', () => {
|
||||
const warm = readSession(entry(plan, [{ w: 20, r: 10, done: true, phase: 'warmup' }, set(60, 8), set(60, 8), set(60, 8), set(90, 8)]))
|
||||
expect(warm.weight).toBe(60)
|
||||
expect(warm.ok).toBe(true)
|
||||
})
|
||||
|
||||
it('applies the same rule to a timed hold', () => {
|
||||
const timed = { mode: 'time', sets: 2, sec: 30, weight: 0 }
|
||||
const held = readSession(entry(timed, [{ sec: 30, done: true }, { sec: 30, done: true }, { sec: 12, done: true }]))
|
||||
expect(held.ok).toBe(true)
|
||||
expect(held.best).toBe(30)
|
||||
})
|
||||
})
|
||||
@@ -17,7 +17,7 @@
|
||||
// So a session that fell apart can never advance the load as though it had succeeded.
|
||||
|
||||
import { modeOf, repStep, rerampWarmups, isBw, isPerSide, entryExcluded } from './history.js'
|
||||
import { EXIDX } from './exercises.js'
|
||||
import { EXIDX, isAssisted } from './exercises.js'
|
||||
import { isWarmupRow, isSideSet, syncSideAggregate, makeSideSet } from './workout-model.js'
|
||||
import { normalizeRepRange } from './rep-range.js'
|
||||
|
||||
@@ -214,21 +214,38 @@ export function selectDeloadCandidate({ currentWeight, targetWeight, targetReps,
|
||||
* entry without its own target is judged against `fallback`, the exercise's current plan,
|
||||
* which is exactly what the app's old weight hint compared against.
|
||||
*/
|
||||
// The load the session is judged by. On an assistance machine less is harder, so the set that
|
||||
// counts is the one with the least help — and a 0 there means "no load logged", not "best ever"
|
||||
// (issue #232).
|
||||
function loadOf(entry, sets) {
|
||||
const done = sets.filter(s => s.done).map(s => s.w || 0)
|
||||
if (!isAssisted(entry && entry.id ? { id: entry.id } : entry)) return Math.max(0, ...done)
|
||||
const loaded = done.filter(w => w > 0)
|
||||
return loaded.length ? Math.min(...loaded) : 0
|
||||
}
|
||||
|
||||
export function readSession(entry, fallback) {
|
||||
const target = (entry && entry.target) || fallback || {}
|
||||
const mode = modeOf({ ...target, id: entry && entry.id })
|
||||
// Warm-up rows are prep, not the session: one filtered read beats guarding every consumer
|
||||
// below (an undone warm-up otherwise poisons `ok` forever and its reps drag `low`/`count`).
|
||||
const sets = ((entry && entry.sets) || []).filter(s => !isWarmupRow(s))
|
||||
const planned = target.sets || sets.length
|
||||
const enough = sets.length >= planned
|
||||
const logged = ((entry && entry.sets) || []).filter(s => !isWarmupRow(s))
|
||||
const planned = target.sets || logged.length
|
||||
const enough = logged.length >= planned
|
||||
// Only the sets the plan asked for decide what happens next (issue #233). A set added on top
|
||||
// is extra work, and it used to be read as part of the prescription: one heavier bonus set
|
||||
// raised the weight for next time, and a hard one taken short of the target reps reported the
|
||||
// whole session as missed. Extra sets still count everywhere else — volume, PRs, history —
|
||||
// they just do not move the plan. The plan's own sets are the ones it laid out first, so the
|
||||
// read stops at that many; a session with fewer than planned is short either way (`enough`).
|
||||
const sets = logged.slice(0, Math.max(1, planned))
|
||||
|
||||
if (mode === 'time') {
|
||||
const goal = target.sec || 0
|
||||
const held = sets.map(s => (s.done ? (s.sec || 0) : 0))
|
||||
return {
|
||||
mode, target, goal, held,
|
||||
weight: Math.max(0, ...sets.filter(s => s.done).map(s => s.w || 0)),
|
||||
weight: loadOf(entry, sets),
|
||||
best: Math.max(0, ...held),
|
||||
ok: goal > 0 && enough && held.length > 0 && held.every(h => h >= goal)
|
||||
}
|
||||
@@ -237,7 +254,7 @@ export function readSession(entry, fallback) {
|
||||
const reps = sets.map(s => (s.done ? (s.r || 0) : 0))
|
||||
return {
|
||||
mode, target, goal, reps,
|
||||
weight: Math.max(0, ...sets.filter(s => s.done).map(s => s.w || 0)),
|
||||
weight: loadOf(entry, sets),
|
||||
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
|
||||
@@ -306,6 +323,13 @@ export function nextPrescription(S, cfg, routine) {
|
||||
? (cfg.inc > 0 ? cfg.inc : DEFAULT_SEC_INCREMENT)
|
||||
: weightIncrement(cfg, unit)
|
||||
if (policy === 'off') return { policy, kind: 'off' }
|
||||
// An assistance machine progresses downwards: the stack carries part of your weight, so the
|
||||
// reward for a clean session is less help, and a stall means taking more (issue #232). Only
|
||||
// the direction changes — the step, the grid and the stall counting are the same.
|
||||
const assisted = isAssisted(cfg)
|
||||
const harder = (weight, step) => (assisted ? Math.max(0, addStep(weight, -step, inc)) : addStep(weight, step, inc))
|
||||
const easier = weight => (assisted ? addStep(weight, inc, inc) : deloadTo(weight, inc))
|
||||
|
||||
|
||||
const sessions = sessionsFor(S, cfg.id, cfg).filter(s => s.mode === mode)
|
||||
const last = sessions[sessions.length - 1]
|
||||
@@ -356,6 +380,8 @@ export function nextPrescription(S, cfg, routine) {
|
||||
// session that stalled (falling back field-by-field to the current config), while the logged
|
||||
// weight remains the hard upper bound for the selected candidate.
|
||||
const epleyDeload = () => {
|
||||
// Epley reads load as the work done; on an assistance machine it is the work taken away.
|
||||
if (assisted) return null
|
||||
if (mode !== 'reps' || (policy !== 'linear' && policy !== 'double')) return null
|
||||
const previous = last.target || {}
|
||||
const target = {
|
||||
@@ -403,12 +429,22 @@ export function nextPrescription(S, cfg, routine) {
|
||||
const range = normalizeRepRange(cfg.reps || last.goal || 10, cfg.repsMin, repStep(cfg))
|
||||
const top = range.reps
|
||||
const bottom = range.repsMin
|
||||
if (last.ok) return { policy, kind: 'up', weight: addStep(w, inc, inc), reps: bottom, why: ['Top of the rep range in every set — {0} {1} more, back to {2} reps.', inc, unit, bottom] }
|
||||
if (last.ok) return {
|
||||
policy, kind: 'up', weight: harder(w, inc), reps: bottom,
|
||||
why: assisted
|
||||
? ['Top of the rep range in every set — {0} {1} less help, back to {2} reps.', inc, unit, bottom]
|
||||
: ['Top of the rep range in every set — {0} {1} more, back to {2} reps.', inc, unit, bottom]
|
||||
}
|
||||
if (stalls >= deloadAt) {
|
||||
const selected = epleyDeload()
|
||||
if (selected) return selected
|
||||
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 dw = easier(w)
|
||||
return {
|
||||
policy, kind: 'deload', weight: dw, reps: bottom,
|
||||
why: assisted
|
||||
? ['Stalled {0} sessions — back to {1} {2} of help and build up again.', stalls, dw, unit]
|
||||
: ['Stalled {0} sessions — deload to {1} {2}.', stalls, dw, unit]
|
||||
}
|
||||
}
|
||||
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] }
|
||||
@@ -421,21 +457,25 @@ export function nextPrescription(S, cfg, routine) {
|
||||
const dbl = policy === 'greyskull' && last.goal > 0 && last.amrap >= last.goal * 2
|
||||
const step = dbl ? inc * 2 : inc
|
||||
return {
|
||||
policy, kind: 'up', weight: addStep(w, step, inc),
|
||||
policy, kind: 'up', weight: harder(w, step),
|
||||
why: dbl
|
||||
? ['Last set hit {0} reps — twice the target, so take a double jump of {1} {2}.', last.amrap, step, unit]
|
||||
: ['Every rep last time — {0} {1} more.', step, unit]
|
||||
: assisted
|
||||
? ['Every rep last time — {0} {1} less help.', step, unit]
|
||||
: ['Every rep last time — {0} {1} more.', step, unit]
|
||||
}
|
||||
}
|
||||
if (stalls >= deloadAt) {
|
||||
const selected = epleyDeload()
|
||||
if (selected) return selected
|
||||
const dw = deloadTo(w, inc)
|
||||
const dw = easier(w)
|
||||
return {
|
||||
policy, kind: 'deload', weight: dw,
|
||||
why: stalls > 1
|
||||
? ['Missed reps {0} sessions running — reset to {1} {2} and work back up.', stalls, dw, unit]
|
||||
: ['Missed reps — reset to {0} {1} and work back up.', dw, unit]
|
||||
why: assisted
|
||||
? ['Missed reps — {0} {1} of help while you build back up.', dw, unit]
|
||||
: stalls > 1
|
||||
? ['Missed reps {0} sessions running — reset to {1} {2} and work back up.', stalls, dw, unit]
|
||||
: ['Missed reps — reset to {0} {1} and work back up.', dw, unit]
|
||||
}
|
||||
}
|
||||
return { policy, kind: 'hold', weight: w, why: ['Missed reps last time — same weight again ({0} of {1} to go).', deloadAt - stalls, deloadAt] }
|
||||
|
||||
@@ -5,9 +5,12 @@ import {
|
||||
deloadFactorOf, DELOAD_FACTOR, POLICIES_FOR, DELOAD_AFTER, MAX_BW_SETS
|
||||
} from './progression.js'
|
||||
import { entryExcluded } from './history.js'
|
||||
import { EXDB } from './exercises.js'
|
||||
import { EXDB, isAssisted } from './exercises.js'
|
||||
|
||||
const LIFT = EXDB.find(e => e.bp !== 'cardio' && !['upper legs', 'lower legs', 'back', 'hips', 'glutes'].includes(e.bp) && !['body weight', 'band', 'resistance band'].includes(e.eq)).id
|
||||
// A plainly loaded lift: more weight is harder. The first match used to be `assisted chest dip`,
|
||||
// whose stack takes weight off you and which therefore progresses downwards (issue #232) — these
|
||||
// tests are about the ordinary direction, so the assistance machines are excluded by name here.
|
||||
const LIFT = EXDB.find(e => e.bp !== 'cardio' && !['upper legs', 'lower legs', 'back', 'hips', 'glutes'].includes(e.bp) && !['body weight', 'band', 'resistance band'].includes(e.eq) && !isAssisted(e.id)).id
|
||||
const HEAVY = EXDB.find(e => e.bp === 'upper legs').id
|
||||
const CARDIO = EXDB.find(e => e.bp === 'cardio').id
|
||||
|
||||
|
||||
@@ -27,11 +27,11 @@ describe('Brazilian Portuguese locale', () => {
|
||||
.sort(byCodeUnit)
|
||||
const fingerprint = createHash('sha256').update(JSON.stringify(inherited)).digest('hex')
|
||||
|
||||
expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(642)
|
||||
expect(inherited).toHaveLength(647)
|
||||
expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(645)
|
||||
expect(inherited).toHaveLength(660)
|
||||
// If this fails, review the changed keys and wording before accepting a new hash. From
|
||||
// frontend/: node scripts/pt-br-inheritance-fingerprint.mjs --list
|
||||
expect(fingerprint, 'pt-PT inheritance changed; review the inherited pt-BR wording').toBe('185cca3dfbc438a4a2177956d1d18da2bbdc907281c5eb4c858ba34afaf9f38e')
|
||||
expect(fingerprint, 'pt-PT inheritance changed; review the inherited pt-BR wording').toBe('a2027d64b3944dcef644b11b4d9688b88fe5cff0693acf04c73f0667e2b86825')
|
||||
})
|
||||
|
||||
test('does not leak European Portuguese UI terms', () => {
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { describe, expect, it, beforeEach, afterEach } from 'vitest'
|
||||
import React, { act } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import { useStore } from '../store/useStore.js'
|
||||
import { useUI } from '../store/useUI.js'
|
||||
import { renameWorkoutSheet, addRoutineToSessionSheet } from '../sheets.jsx'
|
||||
import { buildCompletedWorkout } from './finish-workout.js'
|
||||
|
||||
const mounted = []
|
||||
function render(open) {
|
||||
open()
|
||||
const sheet = useUI.getState().sheets.at(-1)
|
||||
const host = document.createElement('div')
|
||||
document.body.appendChild(host)
|
||||
const root = createRoot(host)
|
||||
mounted.push(root)
|
||||
act(() => root.render(sheet.render(() => useUI.getState().closeSheet(sheet.id))))
|
||||
return host
|
||||
}
|
||||
|
||||
const type = (el, value) => {
|
||||
Object.getOwnPropertyDescriptor(el.constructor.prototype, 'value').set.call(el, value)
|
||||
el.dispatchEvent(new Event('input', { bubbles: true }))
|
||||
}
|
||||
|
||||
const unmountAll = () => act(() => { mounted.splice(0).forEach(r => r.unmount()) })
|
||||
|
||||
describe('rename workout', () => {
|
||||
beforeEach(() => {
|
||||
globalThis.IS_REACT_ACT_ENVIRONMENT = true
|
||||
useUI.setState({ sheets: [] })
|
||||
document.body.innerHTML = ''
|
||||
})
|
||||
afterEach(unmountAll)
|
||||
|
||||
it('renames an active workout and disables save on empty input', () => {
|
||||
useStore.setState(s => ({
|
||||
S: {
|
||||
...s.S,
|
||||
active: { id: 'w1', d: '2026-08-25', start: 1, name: 'Leg Day', entries: [] },
|
||||
},
|
||||
}))
|
||||
|
||||
const host = render(() => renameWorkoutSheet())
|
||||
const input = host.querySelector('input')
|
||||
const saveBtn = [...host.querySelectorAll('button')].find(b => /save/i.test(b.textContent))
|
||||
|
||||
expect(input.value).toBe('Leg Day')
|
||||
expect(saveBtn.disabled).toBe(false)
|
||||
|
||||
// Type blank whitespace
|
||||
act(() => { type(input, ' ') })
|
||||
expect(saveBtn.disabled).toBe(true)
|
||||
|
||||
// Type a new title and save
|
||||
act(() => { type(input, 'Heavy Squats & Core') })
|
||||
expect(saveBtn.disabled).toBe(false)
|
||||
act(() => { saveBtn.click() })
|
||||
|
||||
const active = useStore.getState().S.active
|
||||
expect(active.name).toBe('Heavy Squats & Core')
|
||||
expect(active.customName).toBe(true)
|
||||
|
||||
// Survives completion
|
||||
const completed = buildCompletedWorkout(active, { end: 2 })
|
||||
expect(completed.name).toBe('Heavy Squats & Core')
|
||||
})
|
||||
|
||||
it('submits on Enter key press', () => {
|
||||
useStore.setState(s => ({
|
||||
S: {
|
||||
...s.S,
|
||||
active: { id: 'w1', d: '2026-08-25', start: 1, name: 'Upper A', entries: [] },
|
||||
},
|
||||
}))
|
||||
|
||||
const host = render(() => renameWorkoutSheet())
|
||||
const input = host.querySelector('input')
|
||||
|
||||
act(() => { type(input, 'Upper Power') })
|
||||
act(() => {
|
||||
input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true }))
|
||||
})
|
||||
|
||||
const active = useStore.getState().S.active
|
||||
expect(active.name).toBe('Upper Power')
|
||||
expect(active.customName).toBe(true)
|
||||
})
|
||||
|
||||
it('preserves custom renamed title when another routine is added to the session', () => {
|
||||
useStore.setState(s => ({
|
||||
S: {
|
||||
...s.S,
|
||||
routines: [
|
||||
{ id: 'r1', name: 'Routine 1', ex: [{ id: 'bench_press' }] },
|
||||
{ id: 'r2', name: 'Routine 2', ex: [{ id: 'squat' }] },
|
||||
],
|
||||
active: {
|
||||
id: 'w1',
|
||||
d: '2026-08-25',
|
||||
start: 1,
|
||||
name: 'My Special Workout',
|
||||
customName: true,
|
||||
routineIds: ['r1'],
|
||||
entries: [{ id: 'bench_press', sets: [] }],
|
||||
},
|
||||
},
|
||||
}))
|
||||
|
||||
const host = render(() => addRoutineToSessionSheet())
|
||||
// Click on Routine 2
|
||||
const items = [...host.querySelectorAll('.item')].filter(el => !el.classList.contains('disabled'))
|
||||
expect(items.length).toBeGreaterThan(0)
|
||||
act(() => { items[0].click() })
|
||||
|
||||
const active = useStore.getState().S.active
|
||||
// The name should remain 'My Special Workout' instead of being overwritten with 'Routine 1 + Routine 2'
|
||||
expect(active.name).toBe('My Special Workout')
|
||||
expect(active.routineIds).toContain('r2')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,70 @@
|
||||
import { expect, it } from 'vitest'
|
||||
import { EXDB, matchExercise, normalizeStr, searchExercises } from './exercises.js'
|
||||
|
||||
const benchPress = {
|
||||
n: 'dumbbell bench press', bp: 'chest', tg: 'pectorals', eq: 'dumbbell',
|
||||
sm: ['triceps', 'deltoids'], desc: 'Classic chest exercise using a barbell on a flat bench.',
|
||||
}
|
||||
|
||||
it('allows one edit or adjacent transposition in long query tokens', () => {
|
||||
for (const query of ['dumbell bench', 'dumbbel bench', 'dummbell bench', 'bnech press', 'presss bench']) {
|
||||
expect(matchExercise(benchPress, query), query).toBe(true)
|
||||
}
|
||||
})
|
||||
|
||||
it('keeps short tokens and multiple edits out of fuzzy matching', () => {
|
||||
const squat = { n: 'barbell squat', bp: 'legs', eq: 'barbell' }
|
||||
for (const [exercise, query] of [[squat, 'sqat'], [squat, 'roww'], [benchPress, 'dunbell'], [benchPress, 'dumbell unrelated'], [benchPress, 'bn ech']]) {
|
||||
expect(matchExercise(exercise, query), query).toBe(false)
|
||||
}
|
||||
})
|
||||
|
||||
it('keeps existing exact substring and all-token behavior', () => {
|
||||
expect(matchExercise(benchPress, 'bench pres')).toBe(true)
|
||||
expect(matchExercise(benchPress, 'press bench')).toBe(true)
|
||||
expect(matchExercise(benchPress, 'bench squat')).toBe(false)
|
||||
})
|
||||
|
||||
// QA C26: a correctly spelled word one edit away from a body part / target / equipment word
|
||||
// used to pull in that whole body part ("wrist" ~ "waist" listed every abs exercise first).
|
||||
it('never fuzzy-matches body part, target, equipment or description words', () => {
|
||||
const sitUp = { n: '3/4 sit-up', bp: 'waist', tg: 'abs', eq: 'body weight', sm: [], desc: 'Keep the lower back flat.' }
|
||||
for (const query of ['wrist', 'power', 'bodz weight']) {
|
||||
expect(matchExercise(sitUp, query), query).toBe(false)
|
||||
}
|
||||
// The exact substring path still covers those fields.
|
||||
expect(matchExercise(sitUp, 'waist')).toBe(true)
|
||||
expect(matchExercise(sitUp, 'lower')).toBe(true)
|
||||
})
|
||||
|
||||
it('searchExercises takes a word literally when it hits anything exactly, and only then falls back to typos', () => {
|
||||
const list = [
|
||||
{ n: 'band wrist curl', bp: 'lower arms', eq: 'band' },
|
||||
{ n: 'waist twist', bp: 'waist', eq: 'body weight' },
|
||||
{ n: 'all fours squad stretch', bp: 'upper legs', eq: 'body weight' },
|
||||
{ n: 'barbell squat', bp: 'upper legs', eq: 'barbell' },
|
||||
{ n: 'side plank', bp: 'waist', eq: 'body weight' },
|
||||
{ n: 'slide lunge', bp: 'upper legs', eq: 'body weight' },
|
||||
benchPress,
|
||||
]
|
||||
const names = q => searchExercises(list, q).map(e => e.n)
|
||||
expect(names('wrist')).toEqual(['band wrist curl'])
|
||||
expect(names('squat')).toEqual(['barbell squat'])
|
||||
expect(names('slide')).toEqual(['slide lunge'])
|
||||
// No exact hit anywhere: the typo-tolerant path finds the exercise, name words only.
|
||||
expect(names('wirst')).toEqual(['band wrist curl'])
|
||||
expect(names('bnech press')).toEqual(['dumbbell bench press'])
|
||||
expect(names('dumbell bench')).toEqual(['dumbbell bench press'])
|
||||
expect(names('sqat')).toEqual([])
|
||||
expect(searchExercises(list, ' ')).toBe(list)
|
||||
})
|
||||
|
||||
it('searchExercises over the real catalogue returns only exact hits for correctly spelled words', () => {
|
||||
const plain = (e, q) => normalizeStr([e.n, e.tg, e.eq, e.bp, ...(e.sm || [])].join(' ')).includes(q)
|
||||
for (const q of ['wrist', 'power', 'slide', 'thigh', 'squat', 'clean']) {
|
||||
const got = searchExercises(EXDB, q)
|
||||
expect(got.length, q).toBe(EXDB.filter(e => plain(e, q)).length)
|
||||
expect(got.every(e => plain(e, q)), q).toBe(true)
|
||||
}
|
||||
expect(searchExercises(EXDB, 'wrist')[0].n).toBe('band reverse wrist curl')
|
||||
})
|
||||
@@ -1,17 +1,90 @@
|
||||
// WebAudio beeps + haptics (ported from the vanilla app). `enabled` gates sound.
|
||||
//
|
||||
// iOS needs three things a desktop browser does not (#152, "flash but no beep"):
|
||||
// 1. The ring/silent switch mutes Web Audio. WebKit gives a page whose only audio is Web Audio
|
||||
// the Ambient category, and Ambient obeys the switch — at a gym the phone is usually on
|
||||
// silent, so the timer was mute exactly where it mattered. The only way out is the
|
||||
// 'playback' audio-session type (iOS 17+), which is exclusive: it pauses whatever else the
|
||||
// phone is playing, and WebKit never tells that app it may resume. Hence a setting
|
||||
// (setPlayOnSilent), off by default, rather than something done for everyone.
|
||||
// 2. Locking the screen or switching apps moves a running context to 'interrupted'. WebKit
|
||||
// only brings it back by itself if it was running when the interruption began; a context
|
||||
// that was suspended comes back suspended, and a suspended context makes no sound. So every
|
||||
// tone resumes the context first — allowed without a tap once the context has started
|
||||
// inside one.
|
||||
// 3. A context created outside a tap starts 'suspended' and no timer tick can start it.
|
||||
// unlock() runs from the taps that lead to a timer (set check, hold start, turning Sounds
|
||||
// on) so the context has started before any tick needs it.
|
||||
//
|
||||
// The context is suspended again a second after the last tone: an idle context otherwise keeps
|
||||
// rendering silence for the rest of the page, and under 'playback' keeps the phone's audio
|
||||
// session busy. (Suspending does NOT hand the phone back to a paused music app — see 1.)
|
||||
let audioCtx = null
|
||||
let idleTm = null
|
||||
let idleAt = 0
|
||||
|
||||
const ctxFor = () => {
|
||||
if (!audioCtx || audioCtx.state === 'closed') audioCtx = new (window.AudioContext || window.webkitAudioContext)()
|
||||
return audioCtx
|
||||
}
|
||||
|
||||
const wake = () => {
|
||||
const ctx = ctxFor()
|
||||
if (ctx.state !== 'running') { const p = ctx.resume(); if (p && p.catch) p.catch(() => {}) }
|
||||
return ctx
|
||||
}
|
||||
|
||||
// Suspend once every scheduled tone is over. A burst schedules several tones in one go; the
|
||||
// latest end wins, and a tone scheduled while the timer is pending pushes it out.
|
||||
const sleepAfter = endSec => {
|
||||
const at = Date.now() + endSec * 1000 + 1000
|
||||
if (at <= idleAt && idleTm) return
|
||||
idleAt = at
|
||||
clearTimeout(idleTm)
|
||||
idleTm = setTimeout(() => {
|
||||
idleTm = null
|
||||
try { if (audioCtx && audioCtx.state === 'running') { const p = audioCtx.suspend(); if (p && p.catch) p.catch(() => {}) } } catch (e) { /* */ }
|
||||
}, at - Date.now())
|
||||
}
|
||||
|
||||
export function beep(enabled, freq, dur, when) {
|
||||
if (!enabled) return
|
||||
try {
|
||||
audioCtx = audioCtx || new (window.AudioContext || window.webkitAudioContext)()
|
||||
const o = audioCtx.createOscillator(), g = audioCtx.createGain()
|
||||
o.connect(g); g.connect(audioCtx.destination)
|
||||
const ctx = wake()
|
||||
const o = ctx.createOscillator(), g = ctx.createGain()
|
||||
o.connect(g); g.connect(ctx.destination)
|
||||
o.frequency.value = freq || 880; o.type = 'sine'
|
||||
const t0 = audioCtx.currentTime + (when || 0)
|
||||
const t0 = ctx.currentTime + (when || 0)
|
||||
g.gain.setValueAtTime(0.001, t0)
|
||||
g.gain.exponentialRampToValueAtTime(0.35, t0 + 0.02)
|
||||
g.gain.exponentialRampToValueAtTime(0.001, t0 + (dur || 0.18))
|
||||
o.start(t0); o.stop(t0 + (dur || 0.18) + 0.05)
|
||||
sleepAfter((when || 0) + (dur || 0.18) + 0.05)
|
||||
} catch (e) { /* */ }
|
||||
}
|
||||
|
||||
// Call from inside a tap. Gets the context created and running while the browser still counts
|
||||
// this as a user gesture; it goes back to sleep on its own. Nothing audible.
|
||||
export function unlock(enabled) {
|
||||
if (!enabled) return
|
||||
try { wake(); sleepAfter(0) } catch (e) { /* */ }
|
||||
}
|
||||
|
||||
// Settings → "Play sounds when the phone is on silent". Offered only where it means something:
|
||||
// a WebKit with the audio-session API (iOS 17+) on a device that has a ring/silent switch or its
|
||||
// Control Centre equivalent — iPhone, or an iPad (which reports itself as a Mac with a touch
|
||||
// screen). macOS Safari has the API but no switch, and other browsers have neither.
|
||||
// 'playback' ignores the switch; 'auto' is the browser's own choice (Ambient for a page like
|
||||
// this one). Applied by App.jsx whenever the setting is loaded or changed.
|
||||
export const playOnSilentSupported = () => {
|
||||
if (typeof navigator === 'undefined' || !navigator.audioSession) return false
|
||||
const ua = navigator.userAgent || ''
|
||||
return /iPhone|iPad|iPod/.test(ua) || (/Macintosh/.test(ua) && navigator.maxTouchPoints > 1)
|
||||
}
|
||||
export function setPlayOnSilent(on) {
|
||||
if (!playOnSilentSupported()) return
|
||||
try { navigator.audioSession.type = on ? 'playback' : 'auto' } catch (e) { /* */ }
|
||||
}
|
||||
|
||||
|
||||
export function vibrate(p) { try { navigator.vibrate && navigator.vibrate(p) } catch (e) { /* */ } }
|
||||
@@ -0,0 +1,198 @@
|
||||
// @vitest-environment happy-dom
|
||||
// lib/sound.js keeps one AudioContext per page; each test gets a fresh module so that state
|
||||
// does not leak. The fake context records what the real one would be asked to do.
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
class FakeCtx {
|
||||
constructor() {
|
||||
this.state = 'suspended' // what every browser hands back outside a user gesture
|
||||
this.currentTime = 0
|
||||
this.destination = {}
|
||||
this.tones = []
|
||||
this.resumes = 0
|
||||
this.suspends = 0
|
||||
FakeCtx.instances.push(this)
|
||||
}
|
||||
resume() { this.resumes++; this.state = 'running'; return Promise.resolve() }
|
||||
suspend() { this.suspends++; this.state = 'suspended'; return Promise.resolve() }
|
||||
createGain() { return { connect() {}, gain: { setValueAtTime() {}, exponentialRampToValueAtTime() {} } } }
|
||||
createOscillator() {
|
||||
const ctx = this
|
||||
const o = { frequency: { value: 0 }, type: '', connect() {}, start(at) { ctx.tones.push({ freq: o.frequency.value, at }) }, stop() {} }
|
||||
return o
|
||||
}
|
||||
}
|
||||
FakeCtx.instances = []
|
||||
|
||||
let sound
|
||||
let session
|
||||
const ctx = () => FakeCtx.instances[0]
|
||||
const IPHONE = 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148'
|
||||
const MAC = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Safari/605.1.15'
|
||||
const setDevice = (userAgent, maxTouchPoints = 0) => {
|
||||
Object.defineProperty(navigator, 'userAgent', { value: userAgent, configurable: true })
|
||||
Object.defineProperty(navigator, 'maxTouchPoints', { value: maxTouchPoints, configurable: true })
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.useFakeTimers()
|
||||
FakeCtx.instances = []
|
||||
window.AudioContext = FakeCtx
|
||||
session = { type: 'auto' }
|
||||
Object.defineProperty(navigator, 'audioSession', { value: session, configurable: true, writable: true })
|
||||
setDevice(IPHONE)
|
||||
vi.resetModules()
|
||||
sound = await import('./sound.js')
|
||||
})
|
||||
afterEach(() => { vi.useRealTimers() })
|
||||
|
||||
describe('sounds off', () => {
|
||||
it('creates no audio context and leaves the audio session alone', () => {
|
||||
sound.beep(false, 880, 0.15)
|
||||
sound.unlock(false)
|
||||
expect(FakeCtx.instances).toHaveLength(0)
|
||||
expect(session.type).toBe('auto')
|
||||
})
|
||||
})
|
||||
|
||||
describe('iOS: silent switch and interruptions (#152)', () => {
|
||||
it('the first tone gets the context running and leaves the audio session type alone', () => {
|
||||
sound.beep(true, 880, 0.15)
|
||||
expect(ctx().resumes).toBe(1)
|
||||
expect(ctx().state).toBe('running')
|
||||
expect(ctx().tones).toEqual([{ freq: 880, at: 0 }])
|
||||
expect(session.type).toBe('auto') // the silent-switch override is the setting's job
|
||||
})
|
||||
|
||||
it('resumes a context that a lock or app switch left suspended before scheduling the tone', () => {
|
||||
sound.beep(true, 880, 0.15)
|
||||
ctx().state = 'interrupted' // what iOS does on screen lock / app switch
|
||||
sound.beep(true, 660, 0.1)
|
||||
expect(ctx().resumes).toBe(2)
|
||||
expect(ctx().state).toBe('running')
|
||||
expect(ctx().tones).toHaveLength(2)
|
||||
})
|
||||
|
||||
// A real context reports 'suspended' until its resume() settles, so a burst can issue one
|
||||
// resume() per tone in a browser — harmless. What this pins is the guard itself.
|
||||
it('skips resume when the context already reports running', () => {
|
||||
sound.beep(true, 880, 0.15)
|
||||
sound.beep(true, 880, 0.15, 0.25)
|
||||
expect(ctx().resumes).toBe(1)
|
||||
})
|
||||
|
||||
it('replaces a context the browser has closed', () => {
|
||||
sound.beep(true, 880, 0.15)
|
||||
ctx().state = 'closed'
|
||||
sound.beep(true, 880, 0.15)
|
||||
expect(FakeCtx.instances).toHaveLength(2)
|
||||
expect(FakeCtx.instances[1].tones).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('works in a browser without navigator.audioSession', () => {
|
||||
Object.defineProperty(navigator, 'audioSession', { value: undefined, configurable: true, writable: true })
|
||||
sound.beep(true, 880, 0.15)
|
||||
expect(ctx().tones).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('the context sleeps between beeps', () => {
|
||||
it('suspends about a second after the last tone of a burst has ended', () => {
|
||||
sound.beep(true, 880, 0.25, 0); sound.beep(true, 1320, 0.5, 0.35) // last tone ends at 0.35 + 0.5 + 0.05 = 0.9s
|
||||
vi.advanceTimersByTime(1500)
|
||||
expect(ctx().state).toBe('running')
|
||||
vi.advanceTimersByTime(500)
|
||||
expect(ctx().state).toBe('suspended')
|
||||
expect(ctx().suspends).toBe(1)
|
||||
})
|
||||
|
||||
it('a later tone pushes the sleep out instead of cutting itself short', () => {
|
||||
sound.beep(true, 660, 0.1) // 3
|
||||
vi.advanceTimersByTime(1000)
|
||||
sound.beep(true, 660, 0.1) // 2
|
||||
vi.advanceTimersByTime(1000)
|
||||
sound.beep(true, 660, 0.1) // 1
|
||||
vi.advanceTimersByTime(1000)
|
||||
sound.beep(true, 880, 0.15, 0); sound.beep(true, 880, 0.15, 0.25) // 0: last tone ends at 0.25 + 0.15 + 0.05 = 0.45s
|
||||
expect(ctx().suspends).toBe(0)
|
||||
vi.advanceTimersByTime(1400)
|
||||
expect(ctx().state).toBe('running')
|
||||
vi.advanceTimersByTime(100)
|
||||
expect(ctx().state).toBe('suspended')
|
||||
expect(ctx().suspends).toBe(1)
|
||||
})
|
||||
|
||||
it('a short tone scheduled during a longer one does not shorten the longer one\'s sleep', () => {
|
||||
sound.beep(true, 880, 0.5) // ends 0.55s → sleep at 1.55s
|
||||
sound.beep(true, 660, 0.1) // ends 0.15s → must not pull the sleep to 1.15s
|
||||
vi.advanceTimersByTime(1200)
|
||||
expect(ctx().state).toBe('running')
|
||||
vi.advanceTimersByTime(400)
|
||||
expect(ctx().state).toBe('suspended')
|
||||
})
|
||||
})
|
||||
|
||||
describe('unlock from a tap', () => {
|
||||
it('gets the context created and running, without a tone', () => {
|
||||
sound.unlock(true)
|
||||
expect(FakeCtx.instances).toHaveLength(1)
|
||||
expect(ctx().state).toBe('running')
|
||||
expect(ctx().tones).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('lets the context sleep again on its own', () => {
|
||||
sound.unlock(true)
|
||||
vi.advanceTimersByTime(1000)
|
||||
expect(ctx().state).toBe('suspended')
|
||||
})
|
||||
|
||||
it('a tick after the tap finds a context it can resume rather than one it must create', () => {
|
||||
sound.unlock(true)
|
||||
vi.advanceTimersByTime(1000)
|
||||
sound.beep(true, 660, 0.1)
|
||||
expect(FakeCtx.instances).toHaveLength(1)
|
||||
expect(ctx().state).toBe('running')
|
||||
})
|
||||
})
|
||||
|
||||
describe('play on silent (Settings switch, WebKit only)', () => {
|
||||
it('is offered on an iPhone with the audio-session API', () => {
|
||||
expect(sound.playOnSilentSupported()).toBe(true)
|
||||
})
|
||||
|
||||
it('is offered on an iPad, which calls itself a Mac with a touch screen', () => {
|
||||
setDevice(MAC, 5)
|
||||
expect(sound.playOnSilentSupported()).toBe(true)
|
||||
})
|
||||
|
||||
it('is not offered on macOS Safari: it has the API but no ring/silent switch', () => {
|
||||
setDevice(MAC, 0)
|
||||
expect(sound.playOnSilentSupported()).toBe(false)
|
||||
})
|
||||
|
||||
it('is not offered where navigator.audioSession does not exist', () => {
|
||||
Object.defineProperty(navigator, 'audioSession', { value: undefined, configurable: true, writable: true })
|
||||
expect(sound.playOnSilentSupported()).toBe(false)
|
||||
})
|
||||
|
||||
it("on: the page's audio session becomes 'playback', which ignores the ring/silent switch", () => {
|
||||
sound.setPlayOnSilent(true)
|
||||
expect(session.type).toBe('playback')
|
||||
})
|
||||
|
||||
it("off: hands the choice back to the browser ('auto')", () => {
|
||||
sound.setPlayOnSilent(true)
|
||||
sound.setPlayOnSilent(false)
|
||||
expect(session.type).toBe('auto')
|
||||
})
|
||||
|
||||
it('is a no-op in a browser without navigator.audioSession', () => {
|
||||
Object.defineProperty(navigator, 'audioSession', { value: undefined, configurable: true, writable: true })
|
||||
expect(() => sound.setPlayOnSilent(true)).not.toThrow()
|
||||
})
|
||||
|
||||
it('survives a browser that rejects the type', () => {
|
||||
Object.defineProperty(navigator, 'audioSession', { value: Object.freeze({ type: 'auto' }), configurable: true, writable: true })
|
||||
expect(() => sound.setPlayOnSilent(true)).not.toThrow()
|
||||
})
|
||||
})
|
||||
@@ -12,8 +12,9 @@
|
||||
* of an id that both have; workouts sorted by day and start like every other writer
|
||||
* - bodyweight: union by day, the later-edited (`t`) entry of a day that both have
|
||||
* - favEx: ordered set union, the newer copy first
|
||||
* - exWeights: union by exercise, the larger `w` (the app itself only ever raises it — a PR
|
||||
* logged on the other device must not be forgotten); exNotes, barWeights: key union
|
||||
* - exWeights: union by exercise, the better `w` for that exercise — larger for an ordinary
|
||||
* lift, smaller on an assistance machine (a PR logged on the other device must not be
|
||||
* forgotten, whichever way it runs); exNotes, barWeights: key union
|
||||
* - `_ts`: the later of the two; `_rev` dropped (the server sets it); `active` left to the caller
|
||||
*
|
||||
* Known limit: with no record of what each side deleted, an entry removed on one device inside
|
||||
@@ -21,6 +22,8 @@
|
||||
* on resume and every push is conditional), and a resurrected entry beats a lost one. Tombstones
|
||||
* would close it.
|
||||
*/
|
||||
import { beatsWeight } from './exercises.js'
|
||||
|
||||
const clone = o => JSON.parse(JSON.stringify(o))
|
||||
const list = v => (Array.isArray(v) ? v : [])
|
||||
|
||||
@@ -58,10 +61,16 @@ export function mergeBodyweight(a = [], b = []) {
|
||||
return [...byDay.values()].sort((x, y) => (x.d < y.d ? -1 : 1))
|
||||
}
|
||||
|
||||
// The kept load per exercise. "The larger one wins" held while the app only ever raised it —
|
||||
// but an assistance machine progresses downwards, so there the smaller number is the newer,
|
||||
// harder setting and taking the larger would hand back the help the other device just dropped
|
||||
// (issue #232). `beatsWeight` knows which way round each exercise runs; the date breaks a tie
|
||||
// on an exercise where both sides moved in the same direction.
|
||||
function mergeExWeights(n = {}, o = {}) {
|
||||
const out = { ...(o || {}), ...(n || {}) }
|
||||
for (const k of Object.keys(o || {})) {
|
||||
if (n && n[k] && o[k] && (o[k].w || 0) > (n[k].w || 0)) out[k] = o[k]
|
||||
if (!(n && n[k] && o[k])) continue
|
||||
if (beatsWeight(k, o[k].w || 0, n[k].w || 0)) out[k] = o[k]
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
// can load: lb to the nearest 0.5, kg to the nearest 0.25 — enough that a value converted there
|
||||
// and back lands where it started for any plate-loadable number.
|
||||
import { isSideSet, syncSideAggregate } from './workout-model.js'
|
||||
import { workoutVolume } from './history.js'
|
||||
|
||||
const LB_PER_KG = 2.2046226218
|
||||
|
||||
@@ -13,6 +14,15 @@ export function convertWeight(value, from, to) {
|
||||
return Math.round(v / LB_PER_KG * 4) / 4
|
||||
}
|
||||
|
||||
// Body weight is not loaded on a bar: the weigh-in sheet steps and stores it at 0.1, so plate
|
||||
// rounding would move most weigh-ins on a kg → lb → kg round trip (78.6 → 173.5 → 78.75; QA C15).
|
||||
// A tenth in either unit is fine enough that kg → lb → kg comes home for every 0.1-kg value.
|
||||
export function convertBodyWeight(value, from, to) {
|
||||
if (from === to || value == null || value === '' || !Number.isFinite(Number(value))) return value
|
||||
const v = Number(value)
|
||||
return Math.round((to === 'lb' ? v * LB_PER_KG : v / LB_PER_KG) * 10) / 10
|
||||
}
|
||||
|
||||
const convSet = (set, from, to) => {
|
||||
if (!set || typeof set !== 'object') return set
|
||||
const out = { ...set }
|
||||
@@ -47,13 +57,24 @@ export function convertStateUnit(S, to) {
|
||||
const from = S.unit || 'kg'
|
||||
if (from === to) return S
|
||||
const c = v => convertWeight(v, from, to)
|
||||
const bw = v => convertBodyWeight(v, from, to)
|
||||
// A session carries its body weight of the day and a cached total volume; History rows, the
|
||||
// detail header, the month calendar and the heatmap tooltips read those rather than summing
|
||||
// sets, so they must move with the sets or show kg totals under an lb label (QA C11). The
|
||||
// volume is re-added from the converted sets, so it agrees with the set list to the number.
|
||||
const convSession = s => {
|
||||
const out = { ...s, entries: (s.entries || []).map(e => convEntry(e, from, to)) }
|
||||
if (out.bw != null) out.bw = bw(out.bw)
|
||||
if (Number.isFinite(out.vol)) out.vol = workoutVolume({ entries: out.entries.filter(e => Array.isArray(e?.sets)) })
|
||||
return out
|
||||
}
|
||||
const out = { ...S, unit: to }
|
||||
if (Array.isArray(S.bodyweight)) out.bodyweight = S.bodyweight.map(b => ({ ...b, w: c(b.w) }))
|
||||
if (S.targetW != null) out.targetW = c(S.targetW)
|
||||
if (Array.isArray(S.bodyweight)) out.bodyweight = S.bodyweight.map(b => ({ ...b, w: bw(b.w) }))
|
||||
if (S.targetW != null) out.targetW = bw(S.targetW)
|
||||
if (S.exWeights) out.exWeights = Object.fromEntries(Object.entries(S.exWeights).map(([k, v]) => [k, v && typeof v === 'object' ? { ...v, w: c(v.w) } : c(v)]))
|
||||
if (S.barWeights) out.barWeights = Object.fromEntries(Object.entries(S.barWeights).map(([k, v]) => [k, c(v)]))
|
||||
if (Array.isArray(S.routines)) out.routines = S.routines.map(r => ({ ...r, ex: (r.ex || []).map(cfg => convTarget(cfg, from, to)) }))
|
||||
if (Array.isArray(S.workouts)) out.workouts = S.workouts.map(w => ({ ...w, entries: (w.entries || []).map(e => convEntry(e, from, to)) }))
|
||||
if (S.active) out.active = { ...S.active, entries: (S.active.entries || []).map(e => convEntry(e, from, to)) }
|
||||
if (Array.isArray(S.workouts)) out.workouts = S.workouts.map(convSession)
|
||||
if (S.active) out.active = convSession(S.active)
|
||||
return out
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { convertWeight, convertStateUnit } from './units.js'
|
||||
import { workoutVolume } from './history.js'
|
||||
|
||||
describe('convertWeight', () => {
|
||||
it('rounds lb to a half and kg to a quarter', () => {
|
||||
@@ -32,8 +33,8 @@ describe('convertStateUnit', () => {
|
||||
it('converts every stored weight and keeps everything else', () => {
|
||||
const out = convertStateUnit(S, 'lb')
|
||||
expect(out.unit).toBe('lb')
|
||||
expect(out.targetW).toBe(176.5)
|
||||
expect(out.bodyweight[0]).toEqual({ d: '2026-01-01', w: 181.5, t: 1 })
|
||||
expect(out.targetW).toBe(176.4) // body weight keeps its 0.1, see below
|
||||
expect(out.bodyweight[0]).toEqual({ d: '2026-01-01', w: 181.7, t: 1 })
|
||||
expect(out.exWeights['0025'].w).toBe(176.5)
|
||||
expect(out.exWeights.legacy).toBe(220.5)
|
||||
expect(out.barWeights['0025']).toBe(44)
|
||||
@@ -49,4 +50,36 @@ describe('convertStateUnit', () => {
|
||||
it('is a no-op for the unit already in use', () => {
|
||||
expect(convertStateUnit(S, 'kg')).toBe(S)
|
||||
})
|
||||
// History rows, the detail header, the month calendar and the heatmap tooltips read the
|
||||
// cached `vol` and `bw` off the saved workout rather than summing sets, so a conversion that
|
||||
// skips them shows kg totals under an lb label (QA C11).
|
||||
it('converts each workout\'s cached volume and session body weight, and the active session\'s (QA C11)', () => {
|
||||
const drop = { id: '0025', sets: [{ w: 80, r: 5, done: true, type: 'dropset', drops: [{ w: 60, r: 5 }] }, { w: 40, r: 8, done: true, phase: 'warmup' }] }
|
||||
const state = { ...S,
|
||||
workouts: [{ id: 'w', vol: 700, bw: 82.4, entries: [drop] }, { id: 'x', entries: [] }],
|
||||
active: { ...S.active, bw: 82.4 } }
|
||||
const out = convertStateUnit(state, 'lb')
|
||||
// 176.5 × 5 plus the 132.5 × 5 drop, warm-up left out — what the converted set list adds up to.
|
||||
expect(out.workouts[0].vol).toBe(1545)
|
||||
expect(workoutVolume(out.workouts[0])).toBe(1545)
|
||||
expect(out.workouts[0].bw).toBe(181.7)
|
||||
expect(out.active.bw).toBe(181.7)
|
||||
// A workout that never had a cached volume does not grow one.
|
||||
expect(out.workouts[1]).not.toHaveProperty('vol')
|
||||
expect(state.workouts[0].vol).toBe(700) // the input is not mutated
|
||||
})
|
||||
// Body weight is weighed in and edited at 0.1, not loaded on a bar: rounding it to plate steps
|
||||
// moved 22 of 24 weigh-ins on a kg → lb → kg round trip (QA C15). The goal weight is one too.
|
||||
it('keeps body weight at 0.1 resolution and brings a kg → lb → kg round trip home (QA C15)', () => {
|
||||
const state = { unit: 'kg', targetW: 77, bodyweight: [78.6, 82.1, 82.2, 81.8, 81.4].map((w, i) => ({ d: `2026-01-0${i + 1}`, w, t: i })),
|
||||
workouts: [{ id: 'w', bw: 78.6, entries: [] }], active: { id: 'a', bw: 78.6, entries: [] } }
|
||||
const lb = convertStateUnit(state, 'lb')
|
||||
expect(lb.bodyweight.map(b => b.w)).toEqual([173.3, 181, 181.2, 180.3, 179.5])
|
||||
expect(lb.targetW).toBe(169.8)
|
||||
const back = convertStateUnit(lb, 'kg')
|
||||
expect(back.bodyweight.map(b => b.w)).toEqual([78.6, 82.1, 82.2, 81.8, 81.4])
|
||||
expect(back.targetW).toBe(77)
|
||||
expect(back.workouts[0].bw).toBe(78.6)
|
||||
expect(back.active.bw).toBe(78.6)
|
||||
})
|
||||
})
|
||||
@@ -37,11 +37,17 @@ export function keyboardOpen(win = window) {
|
||||
export function realign(win = window) {
|
||||
if (keyboardOpen(win)) return false
|
||||
if (viewportDisplacement(win) <= 1) return false
|
||||
// The keyboard is gone but a text field may still hold focus: on WebKit tapping a <button>
|
||||
// (the set's tick, the RIR cell) does not blur the input, and iOS only puts the viewports
|
||||
// back once focus has left. Nothing is being typed with the keyboard down, so let it go.
|
||||
const active = win.document.activeElement
|
||||
if (isText(active)) active.blur?.()
|
||||
// Never touch a page while a text field has focus — no blur, no scroll, no unpin (issue #242).
|
||||
// `keyboardOpen` cannot be trusted mid-animation: both sides of its subtraction move, because
|
||||
// the browser chrome collapses while the keyboard comes up. Measured on iOS 26.6 with the
|
||||
// keyboard animating in, `innerHeight` fell 684 → 374 while the visual viewport sat at 158,
|
||||
// so the difference dropped back under the threshold and the keyboard read as closed about
|
||||
// 100 ms after every tap. This used to blur the field there, which is why the login sheet's
|
||||
// name and invite-code fields threw the keyboard straight back out.
|
||||
// Nothing is lost by standing down: the correction still runs on `focusout`, which is when
|
||||
// iOS actually needs it, and the two cases the blur was written for let go of the field
|
||||
// themselves — Workout.jsx blurs when a set is ticked, Modals.jsx when a sheet opens.
|
||||
if (isText(win.document.activeElement)) return false
|
||||
if (bodyPinned(win)) return realignPinned(win)
|
||||
win.scrollTo(win.scrollX || 0, win.scrollY || 0)
|
||||
return true
|
||||
|
||||
@@ -43,20 +43,33 @@ describe('viewport guard', () => {
|
||||
expect(realign(fakeWindow({ offsetTop: 190, vvHeight: 480 }))).toBe(false) // keyboard still up
|
||||
})
|
||||
|
||||
it('lets go of a text field that kept focus after the keyboard closed, then realigns', () => {
|
||||
// WebKit: tapping the set's tick does not blur the weight field. With the keyboard down
|
||||
// and the page displaced, that focus is what keeps iOS from putting the viewports back.
|
||||
it('stands down while a text field has focus, however displaced the page looks (issue #242)', () => {
|
||||
// `keyboardOpen` is unreliable while the keyboard animates in — the browser chrome collapses
|
||||
// at the same time, so `innerHeight` falls with the visual viewport and the difference dips
|
||||
// back under the threshold. A displaced page plus a focused field is therefore "somebody is
|
||||
// typing", not "the keyboard has gone": it used to blur the field and throw the keyboard out.
|
||||
const active = { tagName: 'INPUT', blur: vi.fn() }
|
||||
const w = fakeWindow({ offsetTop: 190, active })
|
||||
expect(realign(w)).toBe(true)
|
||||
expect(active.blur).toHaveBeenCalledTimes(1)
|
||||
expect(w.scrollTo).toHaveBeenCalledWith(0, 0)
|
||||
expect(realign(w)).toBe(false)
|
||||
expect(active.blur).not.toHaveBeenCalled()
|
||||
expect(w.scrollTo).not.toHaveBeenCalled()
|
||||
// the same while a sheet has the body pinned: no unpin/repin under the keyboard either
|
||||
const pinned = fakeWindow({ offsetTop: 190, active: { tagName: 'TEXTAREA', blur: vi.fn() }, bodyStyle: { position: 'fixed', top: '-120px' } })
|
||||
expect(realign(pinned)).toBe(false)
|
||||
expect(pinned.scrollTo).not.toHaveBeenCalled()
|
||||
// an aligned page is left alone, focus included (a desktop browser mid-typing)
|
||||
const typing = { tagName: 'INPUT', blur: vi.fn() }
|
||||
expect(realign(fakeWindow({ active: typing }))).toBe(false)
|
||||
expect(typing.blur).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('still realigns a displaced page once focus has left the field', () => {
|
||||
// The correction that used to ride on the blur now happens on `focusout`, when iOS needs it.
|
||||
const w = fakeWindow({ offsetTop: 190, active: { tagName: 'BUTTON' } })
|
||||
expect(realign(w)).toBe(true)
|
||||
expect(w.scrollTo).toHaveBeenCalledWith(0, 0)
|
||||
})
|
||||
|
||||
it('unpins the body for one scroll when a sheet has it fixed, and pins it back where it was', () => {
|
||||
const bodyStyle = { position: 'fixed', top: '-240px' }
|
||||
const w = fakeWindow({ offsetTop: 190, scrollY: 0, bodyStyle })
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
// Issue #139: a per-side figure off kg plates lands on .25 and .75, and one decimal reported
|
||||
// those as .3 and .8. The setting adds precision that is already in the number — it changes
|
||||
// nothing about what is stored.
|
||||
import { describe, it, expect, afterEach } from 'vitest'
|
||||
import { fmtNum, setWeightDecimals, weightDecimals } from './format.js'
|
||||
|
||||
afterEach(() => setWeightDecimals(1))
|
||||
|
||||
describe('weight decimals', () => {
|
||||
it('rounds to one decimal by default, exactly as before', () => {
|
||||
expect(weightDecimals()).toBe(1)
|
||||
expect(fmtNum(62.75)).toBe('62.8')
|
||||
expect(fmtNum(20.25)).toBe('20.3')
|
||||
})
|
||||
|
||||
it('keeps the quarter when asked for two', () => {
|
||||
setWeightDecimals(2)
|
||||
expect(fmtNum(62.75)).toBe('62.75')
|
||||
expect(fmtNum(20.25)).toBe('20.25')
|
||||
})
|
||||
|
||||
it('never invents precision that is not there', () => {
|
||||
setWeightDecimals(2)
|
||||
expect(fmtNum(100)).toBe('100')
|
||||
expect(fmtNum(62.5)).toBe('62.5')
|
||||
expect(fmtNum(0)).toBe('0')
|
||||
})
|
||||
|
||||
it('ignores anything that is not 1 or 2', () => {
|
||||
setWeightDecimals(5); expect(weightDecimals()).toBe(1)
|
||||
setWeightDecimals(undefined); expect(weightDecimals()).toBe(1)
|
||||
setWeightDecimals(2); expect(weightDecimals()).toBe(2)
|
||||
})
|
||||
})
|
||||
@@ -148,18 +148,20 @@ export default {
|
||||
'This removes it from your history for good.': 'Das entfernt es endgültig aus deinem Verlauf.',
|
||||
'Workout deleted': 'Training gelöscht',
|
||||
'Delete workout': 'Training löschen',
|
||||
'Rename workout': 'Training umbenennen',
|
||||
'Workout title': 'Trainingstitel',
|
||||
'{0} done': '{0} geschafft',
|
||||
'Confirm the weight you worked with — your highest becomes the default next time.': 'Bestätige das Gewicht, mit dem du trainiert hast — dein höchstes wird beim nächsten Mal vorausgefüllt.',
|
||||
'Then finish the superset partner.': 'Dann den Supersatz-Partner abschliessen.',
|
||||
'Then finish the superset partner.': 'Dann den Supersatz-Partner abschließen.',
|
||||
'Previous best:': 'Bisheriger Bestwert:',
|
||||
'new record!': 'neuer Rekord!',
|
||||
'Save': 'Speichern',
|
||||
'Save & next exercise': 'Speichern & nächste Übung',
|
||||
'Just close': 'Nur schliessen',
|
||||
'Just close': 'Nur schließen',
|
||||
'Save weight': 'Gewicht speichern',
|
||||
'Tracked — next time starts at {0}': 'Gespeichert — nächstes Mal startest du bei {0}',
|
||||
"That's the whole workout!": 'Das war das ganze Training!',
|
||||
'Every exercise done — great work. Finish up, or keep going and add another exercise.': 'Alle Übungen geschafft — stark! Schliesse ab oder mach weiter und füge eine Übung hinzu.',
|
||||
'Every exercise done — great work. Finish up, or keep going and add another exercise.': 'Alle Übungen geschafft — stark! Schließe ab oder mach weiter und füge eine Übung hinzu.',
|
||||
'Continue workout': 'Weitertrainieren',
|
||||
'Keep going — tap “+ Add exercise” below': 'Weiter so — tippe unten auf „+ Übung hinzufügen“',
|
||||
'Workout complete!': 'Training abgeschlossen!',
|
||||
@@ -258,7 +260,7 @@ export default {
|
||||
'Exercise progress': 'Übungs-Fortschritt',
|
||||
'Top speed per workout': 'Top-Tempo pro Training',
|
||||
'Best set weight per workout': 'Bestes Satzgewicht pro Training',
|
||||
'Finish your first workout to see progress curves here.': 'Schliess dein erstes Training ab, um hier Fortschrittskurven zu sehen.',
|
||||
'Finish your first workout to see progress curves here.': 'Schließ dein erstes Training ab, um hier Fortschrittskurven zu sehen.',
|
||||
'Recent workouts': 'Letzte Trainings',
|
||||
'Less time': 'Weniger',
|
||||
'More time': 'Mehr',
|
||||
@@ -333,12 +335,18 @@ export default {
|
||||
'The screen stays on while a workout is running, so you don’t have to unlock your phone between sets.': 'Der Bildschirm bleibt an, solange ein Workout läuft — so musst du zwischen den Sätzen nicht entsperren.',
|
||||
'Weight unit': 'Gewichtseinheit',
|
||||
'Week starts on': 'Woche beginnt am',
|
||||
'Weight decimals': 'Nachkommastellen',
|
||||
'How precisely weights are shown.': 'Wie genau Gewichte angezeigt werden.',
|
||||
'0.5': '0,5',
|
||||
'0.25': '0,25',
|
||||
'Rest timer': 'Pausen-Timer',
|
||||
'Sounds': 'Töne',
|
||||
'Flash screen when timer ends': 'Bildschirm bei Timer-Ende blinken lassen',
|
||||
'Weigh in before workouts': 'Vor dem Training wiegen',
|
||||
'Asks for your body weight when a workout starts. Off starts the session straight away.': 'Fragt beim Start eines Trainings nach deinem Körpergewicht. Aus startet die Einheit direkt.',
|
||||
'No entries yet — log your weight to start the curve.': 'Noch keine Einträge — trag dein Gewicht ein, um die Kurve zu starten.',
|
||||
'Play sounds when the phone is on silent': 'Töne auch bei stummgeschaltetem Telefon abspielen',
|
||||
'Music playing on this phone stops during a workout and does not resume by itself.': 'Musik, die auf diesem Telefon läuft, stoppt während eines Trainings und setzt nicht von selbst wieder ein.',
|
||||
'Data': 'Daten',
|
||||
'Export backup (JSON)': 'Backup exportieren (JSON)',
|
||||
'Import backup': 'Backup importieren',
|
||||
@@ -406,12 +414,12 @@ export default {
|
||||
// --- data terms: targets & muscles ---
|
||||
'abductors': 'Abduktoren', 'abs': 'Bauch', 'adductors': 'Adduktoren', 'biceps': 'Bizeps',
|
||||
'calves': 'Waden', 'cardiovascular system': 'Herz-Kreislauf', 'delts': 'Schultern',
|
||||
'forearms': 'Unterarme', 'glutes': 'Gesäss', 'hamstrings': 'Beinbeuger', 'lats': 'Latissimus',
|
||||
'forearms': 'Unterarme', 'glutes': 'Gesäß', 'hamstrings': 'Beinbeuger', 'lats': 'Latissimus',
|
||||
'levator scapulae': 'Schulterblattheber', 'pectorals': 'Brustmuskeln', 'quads': 'Beinstrecker',
|
||||
'serratus anterior': 'Sägemuskel', 'spine': 'Wirbelsäule', 'traps': 'Trapezmuskel',
|
||||
'triceps': 'Trizeps', 'upper back': 'oberer Rücken',
|
||||
'abdominals': 'Bauchmuskeln', 'ankle stabilizers': 'Sprunggelenk-Stabilisatoren', 'ankles': 'Sprunggelenke',
|
||||
'brachialis': 'Armbeuger', 'core': 'Rumpf', 'deltoids': 'Deltamuskeln', 'feet': 'Füsse',
|
||||
'brachialis': 'Armbeuger', 'core': 'Rumpf', 'deltoids': 'Deltamuskeln', 'feet': 'Füße',
|
||||
'grip muscles': 'Griffkraft', 'groin': 'Leiste', 'hands': 'Hände', 'hip flexors': 'Hüftbeuger',
|
||||
'inner thighs': 'Innenschenkel', 'latissimus dorsi': 'Latissimus', 'lower abs': 'unterer Bauch',
|
||||
'lower back': 'unterer Rücken', 'obliques': 'seitliche Bauchmuskeln', 'quadriceps': 'Beinstrecker',
|
||||
@@ -444,7 +452,7 @@ export default {
|
||||
'Edit or delete this exercise': 'Übung bearbeiten oder löschen',
|
||||
'Remove from routine': 'Aus Routine entfernen',
|
||||
'Minimize': 'Verkleinern',
|
||||
'Expand': 'Vergrössern',
|
||||
'Expand': 'Vergrößern',
|
||||
'Exercise animations': 'Übungs-Animationen',
|
||||
'Workout view': 'Trainingsansicht',
|
||||
'Cards': 'Karten',
|
||||
@@ -453,7 +461,7 @@ export default {
|
||||
'Current': 'Aktuell',
|
||||
'Set current': 'Als aktuell markieren',
|
||||
'Move, swap and remove below act on the exercise marked {0}.': 'Verschieben, Tauschen und Entfernen unten wirken auf die als {0} markierte Übung.',
|
||||
'Full': 'Gross',
|
||||
'Full': 'Groß',
|
||||
'Small': 'Klein',
|
||||
'Hidden': 'Versteckt',
|
||||
'Invite code': 'Einladungscode',
|
||||
@@ -578,6 +586,7 @@ export default {
|
||||
'{0} exercises in the file aren’t in your library and were left out.': '{0} Übungen aus der Datei sind nicht in deiner Bibliothek und wurden weggelassen.',
|
||||
'Use this weekly schedule': 'Diesen Wochenplan verwenden',
|
||||
'Replaces your current Mon–Sun assignments.': 'Ersetzt deine aktuelle Mo–So-Belegung.',
|
||||
'Added {0} routine to your plan': '{0} Routine zu deinem Plan hinzugefügt',
|
||||
'Added {0} routines to your plan': '{0} Routinen zu deinem Plan hinzugefügt',
|
||||
'this isn’t an openGym plan file': 'das ist keine openGym-Plandatei',
|
||||
'Shared routine': 'Geteilte Routine',
|
||||
@@ -643,6 +652,10 @@ export default {
|
||||
'Same weight — aim for {0} reps this time.': 'Gleiches Gewicht — diesmal {0} Wiederholungen anpeilen.',
|
||||
'Last set hit {0} reps — twice the target, so take a double jump of {1} {2}.': 'Letzter Satz mit {0} Wiederholungen — doppelte Vorgabe, also ein doppelter Sprung von {1} {2}.',
|
||||
'Every rep last time — {0} {1} more.': 'Letztes Mal jede Wiederholung — {0} {1} mehr.',
|
||||
'Every rep last time — {0} {1} less help.': 'Letztes Mal jede Wiederholung — {0} {1} weniger Hilfe.',
|
||||
'Top of the rep range in every set — {0} {1} less help, back to {2} reps.': 'Oberes Ende des Wiederholungsbereichs in jedem Satz — {0} {1} weniger Hilfe, zurück auf {2} Wiederholungen.',
|
||||
'Missed reps — {0} {1} of help while you build back up.': 'Wiederholungen verfehlt — {0} {1} Hilfe, bis du dich wieder herangearbeitet hast.',
|
||||
'Stalled {0} sessions — back to {1} {2} of help and build up again.': '{0} Einheiten festgefahren — zurück auf {1} {2} Hilfe und neu aufbauen.',
|
||||
'Missed reps {0} sessions running — reset to {1} {2} and work back up.': '{0} Einheiten in Folge Wiederholungen verfehlt — zurück auf {1} {2} und wieder hocharbeiten.',
|
||||
'Missed reps — reset to {0} {1} and work back up.': 'Wiederholungen verfehlt — zurück auf {0} {1} und wieder hocharbeiten.',
|
||||
'Missed reps last time — same weight again ({0} of {1} to go).': 'Letztes Mal Wiederholungen verfehlt — dasselbe Gewicht noch einmal (noch {0} von {1}).',
|
||||
@@ -1151,6 +1164,9 @@ export default {
|
||||
'Bar ({0})': 'Stange ({0})',
|
||||
'Bar {0}': 'Stange {0}',
|
||||
'Default for this bar type.': 'Standard für diesen Stangentyp.',
|
||||
'No bar': 'Keine Stange',
|
||||
'The weight you log is all plates.': 'Das eingetragene Gewicht sind nur Scheiben.',
|
||||
'Plates are counted from 0 — turn this off for the default ({0}).': 'Scheiben werden ab 0 gerechnet — ausschalten fuer den Standard ({0}).',
|
||||
'Set to 0 to go back to the default ({0}).': 'Auf 0 stellen, um zum Standard ({0}) zurückzukehren.',
|
||||
'Applies to this exercise everywhere, not just this plan.': 'Gilt überall für diese Übung, nicht nur in diesem Plan.',
|
||||
'You still log the total weight — the bar only feeds the per-side plate math.': 'Eingetragen wird weiterhin das Gesamtgewicht — die Stange zählt nur für die Scheiben-Rechnung pro Seite.',
|
||||
|
||||
@@ -141,6 +141,8 @@ export default {
|
||||
'This removes it from your history for good.': 'Se elimina de tu historial para siempre.',
|
||||
'Workout deleted': 'Entrenamiento eliminado',
|
||||
'Delete workout': 'Eliminar entrenamiento',
|
||||
'Rename workout': 'Renombrar entrenamiento',
|
||||
'Workout title': 'Título del entrenamiento',
|
||||
'{0} done': '{0} hecho',
|
||||
'Confirm the weight you worked with — your highest becomes the default next time.': 'Confirma el peso con el que trabajaste — el más alto será el predeterminado la próxima vez.',
|
||||
'Then finish the superset partner.': 'Luego termina el otro ejercicio de la superserie.',
|
||||
@@ -318,12 +320,18 @@ export default {
|
||||
'The screen stays on while a workout is running, so you don’t have to unlock your phone between sets.': 'La pantalla se mantiene encendida mientras hay un entrenamiento en curso, así no tienes que desbloquear el móvil entre series.',
|
||||
'Weight unit': 'Unidad de peso',
|
||||
'Week starts on': 'La semana empieza el',
|
||||
'Weight decimals': 'Decimales del peso',
|
||||
'How precisely weights are shown.': 'Con qué precisión se muestran los pesos.',
|
||||
'0.5': '0,5',
|
||||
'0.25': '0,25',
|
||||
'Rest timer': 'Temporizador de descanso',
|
||||
'Sounds': 'Sonidos',
|
||||
'Flash screen when timer ends': 'Hacer parpadear la pantalla al finalizar el temporizador',
|
||||
'Weigh in before workouts': 'Pesarse antes de entrenar',
|
||||
'Asks for your body weight when a workout starts. Off starts the session straight away.': 'Pide tu peso corporal al empezar un entrenamiento. Desactivado, la sesión empieza directamente.',
|
||||
'No entries yet — log your weight to start the curve.': 'Sin registros aún — apunta tu peso para empezar la curva.',
|
||||
'Play sounds when the phone is on silent': 'Reproducir sonidos con el teléfono en silencio',
|
||||
'Music playing on this phone stops during a workout and does not resume by itself.': 'La música que suena en este teléfono se detiene durante un entrenamiento y no se reanuda por sí sola.',
|
||||
'Data': 'Datos',
|
||||
'Export backup (JSON)': 'Exportar copia (JSON)',
|
||||
'Import backup': 'Importar copia',
|
||||
@@ -559,6 +567,7 @@ export default {
|
||||
'{0} exercises in the file aren’t in your library and were left out.': '{0} ejercicios del archivo no están en tu biblioteca y se han omitido.',
|
||||
'Use this weekly schedule': 'Usar este horario semanal',
|
||||
'Replaces your current Mon–Sun assignments.': 'Reemplaza tu asignación actual de lun–dom.',
|
||||
'Added {0} routine to your plan': 'Se añadió {0} rutina a tu plan',
|
||||
'Added {0} routines to your plan': 'Se añadieron {0} rutinas a tu plan',
|
||||
'this isn’t an openGym plan file': 'esto no es un archivo de plan de openGym',
|
||||
'Shared routine': 'Rutina compartida',
|
||||
@@ -624,6 +633,10 @@ export default {
|
||||
'Same weight — aim for {0} reps this time.': 'Mismo peso: esta vez apunta a {0} repeticiones.',
|
||||
'Last set hit {0} reps — twice the target, so take a double jump of {1} {2}.': 'La última serie llegó a {0} repeticiones: el doble del objetivo, así que sube el doble, {1} {2}.',
|
||||
'Every rep last time — {0} {1} more.': 'La última vez, todas las repeticiones: {0} {1} más.',
|
||||
'Every rep last time — {0} {1} less help.': 'Todas las repeticiones la última vez — {0} {1} menos de ayuda.',
|
||||
'Top of the rep range in every set — {0} {1} less help, back to {2} reps.': 'Tope del rango de repeticiones en cada serie — {0} {1} menos de ayuda, vuelve a {2} repeticiones.',
|
||||
'Missed reps — {0} {1} of help while you build back up.': 'Repeticiones falladas — {0} {1} de ayuda mientras vuelves a subir.',
|
||||
'Stalled {0} sessions — back to {1} {2} of help and build up again.': '{0} sesiones estancado — vuelve a {1} {2} de ayuda y sube otra vez.',
|
||||
'Missed reps {0} sessions running — reset to {1} {2} and work back up.': '{0} sesiones seguidas fallando repeticiones: vuelve a {1} {2} y sube de nuevo.',
|
||||
'Missed reps — reset to {0} {1} and work back up.': 'Fallaste repeticiones: vuelve a {0} {1} y sube de nuevo.',
|
||||
'Missed reps last time — same weight again ({0} of {1} to go).': 'Fallaste repeticiones la última vez: el mismo peso otra vez (quedan {0} de {1}).',
|
||||
@@ -1131,6 +1144,9 @@ export default {
|
||||
'Bar ({0})': 'Barra ({0})',
|
||||
'Bar {0}': 'Barra {0}',
|
||||
'Default for this bar type.': 'Valor por defecto para este tipo de barra.',
|
||||
'No bar': 'Sin barra',
|
||||
'The weight you log is all plates.': 'El peso que registras son solo discos.',
|
||||
'Plates are counted from 0 — turn this off for the default ({0}).': 'Los discos se cuentan desde 0 — desactívalo para el valor por defecto ({0}).',
|
||||
'Set to 0 to go back to the default ({0}).': 'Pon 0 para volver al valor por defecto ({0}).',
|
||||
'Applies to this exercise everywhere, not just this plan.': 'Se aplica a este ejercicio en todas partes, no solo en este plan.',
|
||||
'You still log the total weight — the bar only feeds the per-side plate math.': 'Sigues registrando el peso total — la barra solo se usa para calcular los discos por lado.',
|
||||
|
||||
@@ -141,6 +141,8 @@ export default {
|
||||
'This removes it from your history for good.': 'Elle sera retirée de ton historique pour de bon.',
|
||||
'Workout deleted': 'Séance supprimée',
|
||||
'Delete workout': 'Supprimer la séance',
|
||||
'Rename workout': 'Renommer la séance',
|
||||
'Workout title': 'Titre de la séance',
|
||||
'{0} done': '{0} terminé',
|
||||
'Confirm the weight you worked with — your highest becomes the default next time.': 'Confirme le poids utilisé — le plus élevé devient la valeur par défaut la prochaine fois.',
|
||||
'Then finish the superset partner.': 'Puis termine le partenaire du superset.',
|
||||
@@ -318,12 +320,18 @@ export default {
|
||||
'The screen stays on while a workout is running, so you don’t have to unlock your phone between sets.': 'L’écran reste allumé tant qu’une séance est en cours, pas besoin de déverrouiller ton téléphone entre les séries.',
|
||||
'Weight unit': 'Unité de poids',
|
||||
'Week starts on': 'La semaine commence le',
|
||||
'Weight decimals': 'Décimales du poids',
|
||||
'How precisely weights are shown.': 'Avec quelle précision les poids sont affichés.',
|
||||
'0.5': '0,5',
|
||||
'0.25': '0,25',
|
||||
'Rest timer': 'Minuteur de repos',
|
||||
'Sounds': 'Sons',
|
||||
'Flash screen when timer ends': 'Faire clignoter l’écran à la fin du minuteur',
|
||||
'Weigh in before workouts': 'Se peser avant la séance',
|
||||
'Asks for your body weight when a workout starts. Off starts the session straight away.': 'Demande ton poids au début d’une séance. Désactivé, la séance démarre directement.',
|
||||
'No entries yet — log your weight to start the curve.': 'Aucune entrée — note ton poids pour démarrer la courbe.',
|
||||
'Play sounds when the phone is on silent': 'Jouer les sons même si le téléphone est en mode silencieux',
|
||||
'Music playing on this phone stops during a workout and does not resume by itself.': 'La musique en cours de lecture sur ce téléphone s’arrête pendant une séance et ne reprend pas toute seule.',
|
||||
'Data': 'Données',
|
||||
'Export backup (JSON)': 'Exporter une sauvegarde (JSON)',
|
||||
'Import backup': 'Importer une sauvegarde',
|
||||
@@ -559,6 +567,7 @@ export default {
|
||||
'{0} exercises in the file aren’t in your library and were left out.': '{0} exercices du fichier ne sont pas dans ta bibliothèque et ont été ignorés.',
|
||||
'Use this weekly schedule': 'Utiliser ce planning hebdomadaire',
|
||||
'Replaces your current Mon–Sun assignments.': 'Remplace ton attribution lun–dim actuelle.',
|
||||
'Added {0} routine to your plan': '{0} routine ajoutée à ton plan',
|
||||
'Added {0} routines to your plan': '{0} routines ajoutées à ton plan',
|
||||
'this isn’t an openGym plan file': 'ce n\'est pas un fichier de plan openGym',
|
||||
'Shared routine': 'Routine partagée',
|
||||
@@ -624,6 +633,10 @@ export default {
|
||||
'Same weight — aim for {0} reps this time.': 'Même poids — vise {0} répétitions cette fois.',
|
||||
'Last set hit {0} reps — twice the target, so take a double jump of {1} {2}.': 'Dernière série à {0} répétitions — le double de l’objectif, donc un saut double de {1} {2}.',
|
||||
'Every rep last time — {0} {1} more.': 'Toutes les répétitions la dernière fois — {0} {1} de plus.',
|
||||
'Every rep last time — {0} {1} less help.': 'Toutes les répétitions la dernière fois — {0} {1} d’aide en moins.',
|
||||
'Top of the rep range in every set — {0} {1} less help, back to {2} reps.': 'Haut de la fourchette de répétitions à chaque série — {0} {1} d’aide en moins, retour à {2} répétitions.',
|
||||
'Missed reps — {0} {1} of help while you build back up.': 'Répétitions manquées — {0} {1} d’aide le temps de remonter.',
|
||||
'Stalled {0} sessions — back to {1} {2} of help and build up again.': '{0} séances au point mort — retour à {1} {2} d’aide et on remonte.',
|
||||
'Missed reps {0} sessions running — reset to {1} {2} and work back up.': 'Répétitions manquées {0} séances de suite — retour à {1} {2} et on remonte.',
|
||||
'Missed reps — reset to {0} {1} and work back up.': 'Répétitions manquées — retour à {0} {1} et on remonte.',
|
||||
'Missed reps last time — same weight again ({0} of {1} to go).': 'Répétitions manquées la dernière fois — même poids à nouveau ({0} sur {1} restants).',
|
||||
@@ -1131,6 +1144,9 @@ export default {
|
||||
'Bar ({0})': 'Barre ({0})',
|
||||
'Bar {0}': 'Barre {0}',
|
||||
'Default for this bar type.': 'Valeur par défaut pour ce type de barre.',
|
||||
'No bar': 'Sans barre',
|
||||
'The weight you log is all plates.': 'Le poids que tu notes, ce sont les disques.',
|
||||
'Plates are counted from 0 — turn this off for the default ({0}).': 'Les disques sont comptés à partir de 0 — désactive pour la valeur par défaut ({0}).',
|
||||
'Set to 0 to go back to the default ({0}).': 'Mets 0 pour revenir à la valeur par défaut ({0}).',
|
||||
'Applies to this exercise everywhere, not just this plan.': 'S’applique à cet exercice partout, pas seulement dans ce plan.',
|
||||
'You still log the total weight — the bar only feeds the per-side plate math.': 'Tu enregistres toujours le poids total — la barre ne sert qu’au calcul des disques par côté.',
|
||||
|
||||
@@ -141,6 +141,8 @@ export default {
|
||||
'This removes it from your history for good.': 'यह आपके इतिहास से हमेशा के लिए हट जाएगा।',
|
||||
'Workout deleted': 'वर्कआउट हटाया गया',
|
||||
'Delete workout': 'वर्कआउट हटाएँ',
|
||||
'Rename workout': 'वर्कआउट का नाम बदलें',
|
||||
'Workout title': 'वर्कआउट का शीर्षक',
|
||||
'{0} done': '{0} पूरा',
|
||||
'Confirm the weight you worked with — your highest becomes the default next time.': 'जिस वज़न से काम किया उसकी पुष्टि करें — सबसे ज़्यादा वज़न अगली बार डिफ़ॉल्ट बन जाएगा।',
|
||||
'Then finish the superset partner.': 'फिर सुपरसेट का दूसरा व्यायाम पूरा करें।',
|
||||
@@ -318,12 +320,18 @@ export default {
|
||||
'The screen stays on while a workout is running, so you don’t have to unlock your phone between sets.': 'वर्कआउट चलने के दौरान स्क्रीन चालू रहती है, ताकि सेट के बीच फ़ोन अनलॉक न करना पड़े।',
|
||||
'Weight unit': 'वज़न की इकाई',
|
||||
'Week starts on': 'सप्ताह शुरू होता है',
|
||||
'Weight decimals': 'वज़न के दशमलव',
|
||||
'How precisely weights are shown.': 'वज़न कितनी सटीकता से दिखें।',
|
||||
'0.5': '0.5',
|
||||
'0.25': '0.25',
|
||||
'Rest timer': 'आराम टाइमर',
|
||||
'Sounds': 'ध्वनियाँ',
|
||||
'Flash screen when timer ends': 'टाइमर खत्म होने पर स्क्रीन फ्लैश करें',
|
||||
'Weigh in before workouts': 'वर्कआउट से पहले वज़न दर्ज करना',
|
||||
'Asks for your body weight when a workout starts. Off starts the session straight away.': 'वर्कआउट शुरू होते समय आपका वज़न पूछता है। बंद होने पर सेशन सीधे शुरू होता है।',
|
||||
'No entries yet — log your weight to start the curve.': 'अभी कोई एंट्री नहीं — ग्राफ़ शुरू करने के लिए वज़न दर्ज करें।',
|
||||
'Play sounds when the phone is on silent': 'फ़ोन साइलेंट पर हो तब भी आवाज़ें बजाएँ',
|
||||
'Music playing on this phone stops during a workout and does not resume by itself.': 'इस फ़ोन पर चल रहा संगीत वर्कआउट के दौरान रुक जाता है और अपने आप फिर से शुरू नहीं होता।',
|
||||
'Data': 'डेटा',
|
||||
'Export backup (JSON)': 'बैकअप निर्यात करें (JSON)',
|
||||
'Import backup': 'बैकअप आयात करें',
|
||||
@@ -559,6 +567,7 @@ export default {
|
||||
'{0} exercises in the file aren’t in your library and were left out.': 'फ़ाइल के {0} व्यायाम आपकी लाइब्रेरी में नहीं हैं और छोड़ दिए गए।',
|
||||
'Use this weekly schedule': 'यह साप्ताहिक कार्यक्रम इस्तेमाल करें',
|
||||
'Replaces your current Mon–Sun assignments.': 'आपके मौजूदा सोम–रवि निर्धारण को बदल देता है।',
|
||||
'Added {0} routine to your plan': 'आपके प्लान में {0} रूटीन जोड़ा गया',
|
||||
'Added {0} routines to your plan': 'आपके प्लान में {0} रूटीन जोड़े गए',
|
||||
'this isn’t an openGym plan file': 'यह openGym प्लान फ़ाइल नहीं है',
|
||||
'Shared routine': 'साझा किया गया रूटीन',
|
||||
@@ -624,6 +633,10 @@ export default {
|
||||
'Same weight — aim for {0} reps this time.': 'वही वज़न — इस बार {0} रेप्स का लक्ष्य रखें।',
|
||||
'Last set hit {0} reps — twice the target, so take a double jump of {1} {2}.': 'आख़िरी सेट में {0} रेप्स — लक्ष्य से दोगुने, इसलिए {1} {2} की दोगुनी छलांग।',
|
||||
'Every rep last time — {0} {1} more.': 'पिछली बार सारे रेप्स — {0} {1} ज़्यादा।',
|
||||
'Every rep last time — {0} {1} less help.': 'पिछली बार हर दोहराव — {0} {1} कम सहारा।',
|
||||
'Top of the rep range in every set — {0} {1} less help, back to {2} reps.': 'हर सेट में दोहराव सीमा के शीर्ष पर — {0} {1} कम सहारा, वापस {2} दोहराव पर।',
|
||||
'Missed reps — {0} {1} of help while you build back up.': 'दोहराव छूटे — जब तक दोबारा बनाओ तब तक {0} {1} सहारा।',
|
||||
'Stalled {0} sessions — back to {1} {2} of help and build up again.': '{0} सत्र से रुका हुआ — वापस {1} {2} सहारे पर और फिर से बढ़ाओ।',
|
||||
'Missed reps {0} sessions running — reset to {1} {2} and work back up.': 'लगातार {0} सेशन रेप्स चूके — {1} {2} पर लौटें और फिर से बढ़ाएँ।',
|
||||
'Missed reps — reset to {0} {1} and work back up.': 'रेप्स चूके — {0} {1} पर लौटें और फिर से बढ़ाएँ।',
|
||||
'Missed reps last time — same weight again ({0} of {1} to go).': 'पिछली बार रेप्स चूके — वही वज़न दोबारा ({1} में से {0} बाकी)।',
|
||||
@@ -1131,6 +1144,9 @@ export default {
|
||||
'Bar ({0})': 'बार ({0})',
|
||||
'Bar {0}': 'बार {0}',
|
||||
'Default for this bar type.': 'इस तरह की बार का डिफ़ॉल्ट मान।',
|
||||
'No bar': 'कोई बार नहीं',
|
||||
'The weight you log is all plates.': 'आप जो वज़न दर्ज करते हैं वह पूरा प्लेट है।',
|
||||
'Plates are counted from 0 — turn this off for the default ({0}).': 'प्लेट 0 से गिनी जाती हैं — डिफ़ॉल्ट ({0}) के लिए इसे बंद करें।',
|
||||
'Set to 0 to go back to the default ({0}).': 'डिफ़ॉल्ट ({0}) पर लौटने के लिए 0 सेट करें।',
|
||||
'Applies to this exercise everywhere, not just this plan.': 'यह इस एक्सरसाइज़ पर हर जगह लागू होता है, सिर्फ़ इसी प्लान पर नहीं।',
|
||||
'You still log the total weight — the bar only feeds the per-side plate math.': 'आप अब भी कुल वज़न ही दर्ज करते हैं — बार सिर्फ़ हर तरफ़ की प्लेट गिनती में काम आता है।',
|
||||
|
||||
@@ -140,6 +140,8 @@ export default {
|
||||
'This removes it from your history for good.': 'Ez véglegesen eltávolítja az előzményeidből.',
|
||||
'Workout deleted': 'Edzés törölve',
|
||||
'Delete workout': 'Edzés törlése',
|
||||
'Rename workout': 'Edzés átnevezése',
|
||||
'Workout title': 'Edzés címe',
|
||||
'{0} done': '{0} kész',
|
||||
'Confirm the weight you worked with — your highest becomes the default next time.': 'Erősítsd meg a súlyt, amivel dolgoztál — a legmagasabb lesz az alapértelmezett legközelebb.',
|
||||
'Then finish the superset partner.': 'Aztán fejezd be a szuperszett párját.',
|
||||
@@ -325,6 +327,10 @@ export default {
|
||||
'The screen stays on while a workout is running, so you don’t have to unlock your phone between sets.': 'A képernyő edzés közben bekapcsolva marad, így sorozatok között nem kell feloldanod a telefonod.',
|
||||
'Weight unit': 'Súlymértékegység',
|
||||
'Week starts on': 'A hét kezdőnapja',
|
||||
'Weight decimals': 'Súly tizedesjegyei',
|
||||
'How precisely weights are shown.': 'Milyen pontosan jelenjen meg a súly.',
|
||||
'0.5': '0,5',
|
||||
'0.25': '0,25',
|
||||
'Rest timer': 'Pihenő időzítő',
|
||||
'Sounds': 'Hangok',
|
||||
'Data': 'Adatok',
|
||||
@@ -540,6 +546,7 @@ export default {
|
||||
'{0} exercises in the file aren’t in your library and were left out.': '{0} gyakorlat a fájlban nincs a könyvtáradban, ezért kimaradt.',
|
||||
'Use this weekly schedule': 'Heti beosztás alkalmazása',
|
||||
'Replaces your current Mon–Sun assignments.': 'Lecseréli a jelenlegi H–V beosztásod.',
|
||||
'Added {0} routine to your plan': '{0} rutin hozzáadva a tervedhez',
|
||||
'Added {0} routines to your plan': '{0} rutin hozzáadva a tervedhez',
|
||||
'this isn’t an openGym plan file': 'ez nem egy openGym tervfájl',
|
||||
'Shared routine': 'Megosztott rutin',
|
||||
@@ -601,6 +608,10 @@ export default {
|
||||
'Same weight — aim for {0} reps this time.': 'Ugyanaz a súly — most {0} ismétlést célozz meg.',
|
||||
'Last set hit {0} reps — twice the target, so take a double jump of {1} {2}.': 'Az utolsó sorozat {0} ismétlést ért el — kétszerese a célnak, ezért dupla ugrás: {1} {2}.',
|
||||
'Every rep last time — {0} {1} more.': 'Legutóbb minden ismétlés meglett — {0} {1} plusz.',
|
||||
'Every rep last time — {0} {1} less help.': 'Múltkor minden ismétlés megvolt — {0} {1} kevesebb segítség.',
|
||||
'Top of the rep range in every set — {0} {1} less help, back to {2} reps.': 'Az ismétléstartomány teteje minden sorozatban — {0} {1} kevesebb segítség, vissza {2} ismétlésre.',
|
||||
'Missed reps — {0} {1} of help while you build back up.': 'Kimaradt ismétlések — {0} {1} segítség, amíg visszaépíted.',
|
||||
'Stalled {0} sessions — back to {1} {2} of help and build up again.': '{0} edzés óta megrekedt — vissza {1} {2} segítségre, és építsd fel újra.',
|
||||
'Missed reps {0} sessions running — reset to {1} {2} and work back up.': '{0} edzés óta hiányoznak ismétlések — vissza {1} {2}, és építsd fel újra.',
|
||||
'Missed reps — reset to {0} {1} and work back up.': 'Hiányoztak ismétlések — vissza {0} {1}, és építsd fel újra.',
|
||||
'Missed reps last time — same weight again ({0} of {1} to go).': 'Legutóbb hiányoztak ismétlések — ugyanaz a súly megint (még {0} van hátra {1}-ból).',
|
||||
@@ -748,6 +759,8 @@ export default {
|
||||
'Weigh in before workouts': 'Súlymérés edzés előtt',
|
||||
'Asks for your body weight when a workout starts. Off starts the session straight away.': 'Edzés indításakor rákérdez a testsúlyodra. Kikapcsolva az edzés azonnal indul.',
|
||||
'No entries yet — log your weight to start the curve.': 'Még nincs bejegyzés — rögzítsd a súlyodat a görbe elindításához.',
|
||||
'Play sounds when the phone is on silent': 'Hangok lejátszása akkor is, ha a telefon némítva van',
|
||||
'Music playing on this phone stops during a workout and does not resume by itself.': 'A telefonon szóló zene edzés közben leáll, és nem indul újra magától.',
|
||||
'Import from Hevy': 'Importálás a Hevyből',
|
||||
'Pull your history with a Hevy Pro API key': 'Előzmények letöltése Hevy Pro API-kulccsal',
|
||||
'Pull your history with a Hevy Pro API key. The key is only used for this import and is not saved.': 'Előzmények letöltése Hevy Pro API-kulccsal. A kulcs csak ehhez az importhoz kell, nem mentjük el.',
|
||||
@@ -796,6 +809,9 @@ export default {
|
||||
'Bar ({0})': 'Rúd ({0})',
|
||||
'Bar {0}': 'Rúd {0}',
|
||||
'Default for this bar type.': 'Alapérték ehhez a rúdtípushoz.',
|
||||
'No bar': 'Nincs rúd',
|
||||
'The weight you log is all plates.': 'A beírt súly csak a tárcsák.',
|
||||
'Plates are counted from 0 — turn this off for the default ({0}).': 'A tárcsák 0-tól számítanak — kapcsold ki az alapértékhez ({0}).',
|
||||
'Set to 0 to go back to the default ({0}).': 'Állítsd 0-ra az alapérték ({0}) visszaállításához.',
|
||||
'Applies to this exercise everywhere, not just this plan.': 'Mindenhol érvényes erre a gyakorlatra, nem csak ebben a tervben.',
|
||||
'You still log the total weight — the bar only feeds the per-side plate math.': 'Továbbra is a teljes súlyt rögzíted — a rúd csak az oldalankénti tárcsaszámításhoz kell.',
|
||||
|
||||
@@ -141,6 +141,8 @@ export default {
|
||||
'This removes it from your history for good.': 'Verrà rimosso per sempre dalla cronologia.',
|
||||
'Workout deleted': 'Allenamento eliminato',
|
||||
'Delete workout': 'Elimina allenamento',
|
||||
'Rename workout': 'Rinomina allenamento',
|
||||
'Workout title': 'Titolo dell’allenamento',
|
||||
'{0} done': '{0} fatto',
|
||||
'Confirm the weight you worked with — your highest becomes the default next time.': 'Conferma il peso usato — il più alto diventa il predefinito la prossima volta.',
|
||||
'Then finish the superset partner.': "Poi completa l'altro esercizio del superset.",
|
||||
@@ -318,12 +320,18 @@ export default {
|
||||
'The screen stays on while a workout is running, so you don’t have to unlock your phone between sets.': 'Lo schermo resta acceso mentre un allenamento è in corso, così non devi sbloccare il telefono tra una serie e l’altra.',
|
||||
'Weight unit': 'Unità di peso',
|
||||
'Week starts on': 'La settimana inizia il',
|
||||
'Weight decimals': 'Decimali del peso',
|
||||
'How precisely weights are shown.': 'Con quanta precisione vengono mostrati i pesi.',
|
||||
'0.5': '0,5',
|
||||
'0.25': '0,25',
|
||||
'Rest timer': 'Timer di riposo',
|
||||
'Sounds': 'Suoni',
|
||||
'Flash screen when timer ends': 'Fai lampeggiare lo schermo alla fine del timer',
|
||||
'Weigh in before workouts': 'Pesarsi prima dell’allenamento',
|
||||
'Asks for your body weight when a workout starts. Off starts the session straight away.': 'Chiede il tuo peso all’avvio di un allenamento. Disattivato, la sessione parte subito.',
|
||||
'No entries yet — log your weight to start the curve.': 'Nessun dato — registra il tuo peso per iniziare la curva.',
|
||||
'Play sounds when the phone is on silent': 'Riproduci i suoni anche con il telefono in silenzioso',
|
||||
'Music playing on this phone stops during a workout and does not resume by itself.': 'La musica in riproduzione su questo telefono si ferma durante un allenamento e non riprende da sola.',
|
||||
'Data': 'Dati',
|
||||
'Export backup (JSON)': 'Esporta backup (JSON)',
|
||||
'Import backup': 'Importa backup',
|
||||
@@ -559,6 +567,7 @@ export default {
|
||||
'{0} exercises in the file aren’t in your library and were left out.': '{0} esercizi del file non sono nella tua libreria e sono stati esclusi.',
|
||||
'Use this weekly schedule': 'Usa questo programma settimanale',
|
||||
'Replaces your current Mon–Sun assignments.': 'Sostituisce la tua assegnazione lun–dom attuale.',
|
||||
'Added {0} routine to your plan': 'Aggiunta {0} routine al tuo piano',
|
||||
'Added {0} routines to your plan': 'Aggiunte {0} routine al tuo piano',
|
||||
'this isn’t an openGym plan file': 'questo non è un file di piano openGym',
|
||||
'Shared routine': 'Routine condivisa',
|
||||
@@ -624,6 +633,10 @@ export default {
|
||||
'Same weight — aim for {0} reps this time.': 'Stesso peso: questa volta punta a {0} ripetizioni.',
|
||||
'Last set hit {0} reps — twice the target, so take a double jump of {1} {2}.': 'Ultima serie a {0} ripetizioni: il doppio dell’obiettivo, quindi salto doppio di {1} {2}.',
|
||||
'Every rep last time — {0} {1} more.': 'L’ultima volta tutte le ripetizioni: {0} {1} in più.',
|
||||
'Every rep last time — {0} {1} less help.': 'Tutte le ripetizioni l’ultima volta — {0} {1} di aiuto in meno.',
|
||||
'Top of the rep range in every set — {0} {1} less help, back to {2} reps.': 'Cima dell’intervallo di ripetizioni in ogni serie — {0} {1} di aiuto in meno, torna a {2} ripetizioni.',
|
||||
'Missed reps — {0} {1} of help while you build back up.': 'Ripetizioni mancate — {0} {1} di aiuto mentre risali.',
|
||||
'Stalled {0} sessions — back to {1} {2} of help and build up again.': 'Fermo da {0} sessioni — torna a {1} {2} di aiuto e risali.',
|
||||
'Missed reps {0} sessions running — reset to {1} {2} and work back up.': 'Ripetizioni mancate per {0} sessioni di fila: torna a {1} {2} e risali.',
|
||||
'Missed reps — reset to {0} {1} and work back up.': 'Ripetizioni mancate: torna a {0} {1} e risali.',
|
||||
'Missed reps last time — same weight again ({0} of {1} to go).': 'Ripetizioni mancate l’ultima volta: stesso peso ancora ({0} di {1} rimasti).',
|
||||
@@ -1131,6 +1144,9 @@ export default {
|
||||
'Bar ({0})': 'Bilanciere ({0})',
|
||||
'Bar {0}': 'Bilanciere {0}',
|
||||
'Default for this bar type.': 'Valore predefinito per questo tipo di bilanciere.',
|
||||
'No bar': 'Senza bilanciere',
|
||||
'The weight you log is all plates.': 'Il peso che registri sono solo i dischi.',
|
||||
'Plates are counted from 0 — turn this off for the default ({0}).': 'I dischi si contano da 0 — disattiva per il valore predefinito ({0}).',
|
||||
'Set to 0 to go back to the default ({0}).': 'Imposta 0 per tornare al valore predefinito ({0}).',
|
||||
'Applies to this exercise everywhere, not just this plan.': 'Vale per questo esercizio ovunque, non solo in questo piano.',
|
||||
'You still log the total weight — the bar only feeds the per-side plate math.': 'Registri comunque il peso totale — il bilanciere serve solo al calcolo dei dischi per lato.',
|
||||
|
||||
@@ -141,6 +141,8 @@ export default {
|
||||
'This removes it from your history for good.': '기록에서 영구히 삭제됩니다.',
|
||||
'Workout deleted': '운동 삭제됨',
|
||||
'Delete workout': '운동 삭제',
|
||||
'Rename workout': '운동 이름 변경',
|
||||
'Workout title': '운동 제목',
|
||||
'{0} done': '{0} 완료',
|
||||
'Confirm the weight you worked with — your highest becomes the default next time.': '사용한 무게를 확인하세요 — 최고 무게가 다음번 기본값이 됩니다.',
|
||||
'Then finish the superset partner.': '그다음 슈퍼세트 짝 운동을 마무리하세요.',
|
||||
@@ -318,12 +320,18 @@ export default {
|
||||
'The screen stays on while a workout is running, so you don’t have to unlock your phone between sets.': '운동이 진행되는 동안 화면이 켜져 있어 세트 사이에 잠금을 해제할 필요가 없습니다.',
|
||||
'Weight unit': '무게 단위',
|
||||
'Week starts on': '주 시작 요일',
|
||||
'Weight decimals': '무게 소수점',
|
||||
'How precisely weights are shown.': '무게를 얼마나 정밀하게 표시할지.',
|
||||
'0.5': '0.5',
|
||||
'0.25': '0.25',
|
||||
'Rest timer': '휴식 타이머',
|
||||
'Sounds': '소리',
|
||||
'Flash screen when timer ends': '타이머 종료 시 화면 깜박임',
|
||||
'Weigh in before workouts': '운동 전 체중 기록',
|
||||
'Asks for your body weight when a workout starts. Off starts the session straight away.': '운동을 시작할 때 체중을 물어봅니다. 끄면 세션이 바로 시작됩니다.',
|
||||
'No entries yet — log your weight to start the curve.': '아직 기록이 없어요 — 체중을 기록해 그래프를 시작하세요.',
|
||||
'Play sounds when the phone is on silent': '무음 모드에서도 소리 재생',
|
||||
'Music playing on this phone stops during a workout and does not resume by itself.': '운동 중에는 이 휴대폰에서 재생 중인 음악이 멈추며, 자동으로 다시 재생되지 않습니다.',
|
||||
'Data': '데이터',
|
||||
'Export backup (JSON)': '백업 내보내기 (JSON)',
|
||||
'Import backup': '백업 가져오기',
|
||||
@@ -559,6 +567,7 @@ export default {
|
||||
'{0} exercises in the file aren’t in your library and were left out.': '파일의 운동 {0}개가 라이브러리에 없어 제외했습니다.',
|
||||
'Use this weekly schedule': '이 주간 일정 사용',
|
||||
'Replaces your current Mon–Sun assignments.': '현재 월–일 배정을 대체합니다.',
|
||||
'Added {0} routine to your plan': '계획에 루틴 {0}개를 추가했습니다',
|
||||
'Added {0} routines to your plan': '계획에 루틴 {0}개를 추가했습니다',
|
||||
'this isn’t an openGym plan file': 'openGym 계획 파일이 아닙니다',
|
||||
'Shared routine': '공유된 루틴',
|
||||
@@ -624,6 +633,10 @@ export default {
|
||||
'Same weight — aim for {0} reps this time.': '같은 무게 — 이번엔 {0}회를 노려보세요.',
|
||||
'Last set hit {0} reps — twice the target, so take a double jump of {1} {2}.': '마지막 세트 {0}회 — 목표의 두 배라 {1} {2}만큼 두 배로 올립니다.',
|
||||
'Every rep last time — {0} {1} more.': '지난번 전 세트 완수 — {0} {1} 증가.',
|
||||
'Every rep last time — {0} {1} less help.': '지난번에 모든 반복 성공 — 보조 {0} {1} 줄이기.',
|
||||
'Top of the rep range in every set — {0} {1} less help, back to {2} reps.': '모든 세트에서 반복 범위 상단 — 보조 {0} {1} 줄이고 {2}회로 돌아가기.',
|
||||
'Missed reps — {0} {1} of help while you build back up.': '반복 실패 — 다시 올라올 때까지 보조 {0} {1}.',
|
||||
'Stalled {0} sessions — back to {1} {2} of help and build up again.': '{0}회 정체 — 보조 {1} {2}로 돌아가 다시 쌓기.',
|
||||
'Missed reps {0} sessions running — reset to {1} {2} and work back up.': '{0}회 연속으로 목표 횟수 미달 — {1} {2}로 되돌리고 다시 올라가세요.',
|
||||
'Missed reps — reset to {0} {1} and work back up.': '목표 횟수 미달 — {0} {1}로 되돌리고 다시 올라가세요.',
|
||||
'Missed reps last time — same weight again ({0} of {1} to go).': '지난번 목표 횟수 미달 — 같은 무게로 한 번 더 ({1}회 중 {0}회 남음).',
|
||||
@@ -1131,6 +1144,9 @@ export default {
|
||||
'Bar ({0})': '바 ({0})',
|
||||
'Bar {0}': '바 {0}',
|
||||
'Default for this bar type.': '이 바 종류의 기본값입니다.',
|
||||
'No bar': '바 없음',
|
||||
'The weight you log is all plates.': '기록하는 무게가 전부 원판입니다.',
|
||||
'Plates are counted from 0 — turn this off for the default ({0}).': '원판을 0부터 계산합니다 — 기본값({0})으로 돌리려면 끄세요.',
|
||||
'Set to 0 to go back to the default ({0}).': '0으로 두면 기본값({0})으로 돌아갑니다.',
|
||||
'Applies to this exercise everywhere, not just this plan.': '이 플랜만이 아니라 어디서든 이 운동에 적용됩니다.',
|
||||
'You still log the total weight — the bar only feeds the per-side plate math.': '기록은 여전히 총 무게입니다 — 바 무게는 한쪽에 끼울 원판 계산에만 쓰입니다.',
|
||||
|
||||
@@ -141,6 +141,8 @@ export default {
|
||||
'This removes it from your history for good.': 'To usunie go z historii na zawsze.',
|
||||
'Workout deleted': 'Trening usunięty',
|
||||
'Delete workout': 'Usuń trening',
|
||||
'Rename workout': 'Zmień nazwę treningu',
|
||||
'Workout title': 'Tytuł treningu',
|
||||
'{0} done': '{0} — gotowe',
|
||||
'Confirm the weight you worked with — your highest becomes the default next time.': 'Potwierdź ciężar, z którym pracowałeś — najwyższy będzie domyślny następnym razem.',
|
||||
'Then finish the superset partner.': 'Potem dokończ drugie ćwiczenie superserii.',
|
||||
@@ -318,12 +320,18 @@ export default {
|
||||
'The screen stays on while a workout is running, so you don’t have to unlock your phone between sets.': 'Ekran pozostaje włączony w trakcie treningu, więc nie musisz odblokowywać telefonu między seriami.',
|
||||
'Weight unit': 'Jednostka wagi',
|
||||
'Week starts on': 'Tydzień zaczyna się w',
|
||||
'Weight decimals': 'Miejsca dziesiętne ciężaru',
|
||||
'How precisely weights are shown.': 'Jak dokładnie pokazywać ciężary.',
|
||||
'0.5': '0,5',
|
||||
'0.25': '0,25',
|
||||
'Rest timer': 'Minutnik przerwy',
|
||||
'Sounds': 'Dźwięki',
|
||||
'Flash screen when timer ends': 'Migaj ekranem po zakończeniu minutnika',
|
||||
'Weigh in before workouts': 'Ważenie przed treningiem',
|
||||
'Asks for your body weight when a workout starts. Off starts the session straight away.': 'Pyta o Twoją masę ciała przy rozpoczęciu treningu. Wyłączone — sesja zaczyna się od razu.',
|
||||
'No entries yet — log your weight to start the curve.': 'Brak wpisów — zapisz wagę, aby zacząć krzywą.',
|
||||
'Play sounds when the phone is on silent': 'Odtwarzaj dźwięki także przy wyciszonym telefonie',
|
||||
'Music playing on this phone stops during a workout and does not resume by itself.': 'Muzyka odtwarzana na tym telefonie zatrzymuje się podczas treningu i nie wznawia się sama.',
|
||||
'Data': 'Dane',
|
||||
'Export backup (JSON)': 'Eksportuj kopię (JSON)',
|
||||
'Import backup': 'Importuj kopię',
|
||||
@@ -559,6 +567,7 @@ export default {
|
||||
'{0} exercises in the file aren’t in your library and were left out.': '{0} ćwiczeń z pliku nie ma w Twojej bibliotece i zostały pominięte.',
|
||||
'Use this weekly schedule': 'Użyj tego harmonogramu tygodnia',
|
||||
'Replaces your current Mon–Sun assignments.': 'Zastępuje Twój obecny przydział pon–niedz.',
|
||||
'Added {0} routine to your plan': 'Dodano {0} plan treningowy do Twojego planu',
|
||||
'Added {0} routines to your plan': 'Dodano {0} planów treningowych do Twojego planu',
|
||||
'this isn’t an openGym plan file': 'to nie jest plik planu openGym',
|
||||
'Shared routine': 'Udostępniony plan treningowy',
|
||||
@@ -624,6 +633,10 @@ export default {
|
||||
'Same weight — aim for {0} reps this time.': 'Ten sam ciężar — tym razem celuj w {0} powtórzeń.',
|
||||
'Last set hit {0} reps — twice the target, so take a double jump of {1} {2}.': 'Ostatnia seria to {0} powtórzeń — dwukrotność celu, więc podwójny skok o {1} {2}.',
|
||||
'Every rep last time — {0} {1} more.': 'Ostatnio wszystkie powtórzenia — {0} {1} więcej.',
|
||||
'Every rep last time — {0} {1} less help.': 'Ostatnio każde powtórzenie — {0} {1} mniej pomocy.',
|
||||
'Top of the rep range in every set — {0} {1} less help, back to {2} reps.': 'Górny zakres powtórzeń w każdej serii — {0} {1} mniej pomocy, wróć do {2} powtórzeń.',
|
||||
'Missed reps — {0} {1} of help while you build back up.': 'Brak powtórzeń — {0} {1} pomocy, aż wrócisz do formy.',
|
||||
'Stalled {0} sessions — back to {1} {2} of help and build up again.': 'Zastój od {0} sesji — wróć do {1} {2} pomocy i buduj od nowa.',
|
||||
'Missed reps {0} sessions running — reset to {1} {2} and work back up.': 'Nieudane powtórzenia w {0} sesjach z rzędu — wróć do {1} {2} i buduj od nowa.',
|
||||
'Missed reps — reset to {0} {1} and work back up.': 'Nieudane powtórzenia — wróć do {0} {1} i buduj od nowa.',
|
||||
'Missed reps last time — same weight again ({0} of {1} to go).': 'Ostatnio nieudane powtórzenia — ten sam ciężar jeszcze raz (zostało {0} z {1}).',
|
||||
@@ -1131,6 +1144,9 @@ export default {
|
||||
'Bar ({0})': 'Gryf ({0})',
|
||||
'Bar {0}': 'Gryf {0}',
|
||||
'Default for this bar type.': 'Wartość domyślna dla tego typu gryfu.',
|
||||
'No bar': 'Bez gryfu',
|
||||
'The weight you log is all plates.': 'Zapisany ciężar to same talerze.',
|
||||
'Plates are counted from 0 — turn this off for the default ({0}).': 'Talerze liczone od 0 — wyłącz, aby wrócić do domyślnego ({0}).',
|
||||
'Set to 0 to go back to the default ({0}).': 'Ustaw 0, aby wrócić do wartości domyślnej ({0}).',
|
||||
'Applies to this exercise everywhere, not just this plan.': 'Dotyczy tego ćwiczenia wszędzie, nie tylko w tym planie.',
|
||||
'You still log the total weight — the bar only feeds the per-side plate math.': 'Nadal zapisujesz ciężar całkowity — gryf służy tylko do wyliczenia talerzy na stronę.',
|
||||
|
||||
@@ -118,6 +118,8 @@ export const PT_BR_OVERRIDES = {
|
||||
'Weigh in before workouts': 'Pesar antes do treino',
|
||||
'Asks for your body weight when a workout starts. Off starts the session straight away.': 'Pede seu peso ao iniciar um treino. Desligado, a sessão começa na hora.',
|
||||
'No entries yet — log your weight to start the curve.': 'Ainda não há registros — informe seu peso para começar a curva.',
|
||||
'Play sounds when the phone is on silent': 'Tocar sons com o celular no silencioso',
|
||||
'Music playing on this phone stops during a workout and does not resume by itself.': 'A música que estiver tocando neste celular para durante o treino e não volta sozinha.',
|
||||
'Export backup (JSON)': 'Exportar backup (JSON)',
|
||||
'Import backup': 'Importar backup',
|
||||
'Reset everything?': 'Redefinir tudo?',
|
||||
@@ -208,6 +210,7 @@ export const PT_BR_OVERRIDES = {
|
||||
'{0} exercise in the file isn’t in your library and was left out.': '{0} exercício do arquivo não está na sua biblioteca e foi ignorado.',
|
||||
'{0} exercises in the file aren’t in your library and were left out.': '{0} exercícios do arquivo não estão na sua biblioteca e foram ignorados.',
|
||||
'Replaces your current Mon–Sun assignments.': 'Substitui os dias definidos de segunda a domingo.',
|
||||
'Added {0} routine to your plan': '{0} rotina adicionada ao seu plano',
|
||||
'Added {0} routines to your plan': '{0} rotinas adicionadas ao seu plano',
|
||||
'this isn’t an openGym plan file': 'este não é um arquivo de plano do openGym',
|
||||
'This screen could not be drawn. Your data is safe on this device.': 'Não foi possível exibir esta tela. Seus dados estão seguros neste dispositivo.',
|
||||
|
||||
@@ -141,6 +141,8 @@ export default {
|
||||
'This removes it from your history for good.': 'Isto remove-o do histórico para sempre.',
|
||||
'Workout deleted': 'Treino eliminado',
|
||||
'Delete workout': 'Eliminar treino',
|
||||
'Rename workout': 'Renomear treino',
|
||||
'Workout title': 'Título do treino',
|
||||
'{0} done': '{0} feito',
|
||||
'Confirm the weight you worked with — your highest becomes the default next time.': 'Confirma o peso com que trabalhaste — o mais alto fica predefinido na próxima vez.',
|
||||
'Then finish the superset partner.': 'Depois termina o par da supersérie.',
|
||||
@@ -318,12 +320,18 @@ export default {
|
||||
'The screen stays on while a workout is running, so you don’t have to unlock your phone between sets.': 'O ecrã fica ligado enquanto há um treino a decorrer, para não teres de desbloquear o telemóvel entre séries.',
|
||||
'Weight unit': 'Unidade de peso',
|
||||
'Week starts on': 'Início da semana',
|
||||
'Weight decimals': 'Casas decimais do peso',
|
||||
'How precisely weights are shown.': 'Com que precisão os pesos são mostrados.',
|
||||
'0.5': '0,5',
|
||||
'0.25': '0,25',
|
||||
'Rest timer': 'Temporizador de descanso',
|
||||
'Sounds': 'Sons',
|
||||
'Flash screen when timer ends': 'Piscar o ecrã quando o temporizador terminar',
|
||||
'Weigh in before workouts': 'Pesar antes do treino',
|
||||
'Asks for your body weight when a workout starts. Off starts the session straight away.': 'Pede o teu peso ao iniciar um treino. Desligado, a sessão começa de imediato.',
|
||||
'No entries yet — log your weight to start the curve.': 'Ainda sem registos — regista o teu peso para começar a curva.',
|
||||
'Play sounds when the phone is on silent': 'Reproduzir sons com o telemóvel em silêncio',
|
||||
'Music playing on this phone stops during a workout and does not resume by itself.': 'A música a tocar neste telemóvel para durante um treino e não retoma sozinha.',
|
||||
'Data': 'Dados',
|
||||
'Export backup (JSON)': 'Exportar cópia (JSON)',
|
||||
'Import backup': 'Importar cópia',
|
||||
@@ -559,6 +567,7 @@ export default {
|
||||
'{0} exercises in the file aren’t in your library and were left out.': '{0} exercícios do ficheiro não estão na tua biblioteca e foram ignorados.',
|
||||
'Use this weekly schedule': 'Usar este horário semanal',
|
||||
'Replaces your current Mon–Sun assignments.': 'Substitui a tua atribuição atual de seg–dom.',
|
||||
'Added {0} routine to your plan': 'Adicionada {0} rotina ao teu plano',
|
||||
'Added {0} routines to your plan': 'Adicionadas {0} rotinas ao teu plano',
|
||||
'this isn’t an openGym plan file': 'isto não é um ficheiro de plano openGym',
|
||||
'Shared routine': 'Rotina partilhada',
|
||||
@@ -624,6 +633,10 @@ export default {
|
||||
'Same weight — aim for {0} reps this time.': 'Mesmo peso — desta vez aponta a {0} repetições.',
|
||||
'Last set hit {0} reps — twice the target, so take a double jump of {1} {2}.': 'A última série chegou a {0} repetições — o dobro do objetivo, por isso um salto duplo de {1} {2}.',
|
||||
'Every rep last time — {0} {1} more.': 'Da última vez, todas as repetições — mais {0} {1}.',
|
||||
'Every rep last time — {0} {1} less help.': 'Todas as repetições da última vez — {0} {1} menos de ajuda.',
|
||||
'Top of the rep range in every set — {0} {1} less help, back to {2} reps.': 'Topo do intervalo de repetições em cada série — {0} {1} menos de ajuda, de volta a {2} repetições.',
|
||||
'Missed reps — {0} {1} of help while you build back up.': 'Repetições falhadas — {0} {1} de ajuda enquanto recuperas.',
|
||||
'Stalled {0} sessions — back to {1} {2} of help and build up again.': '{0} sessões estagnado — de volta a {1} {2} de ajuda e sobe outra vez.',
|
||||
'Missed reps {0} sessions running — reset to {1} {2} and work back up.': 'Repetições falhadas em {0} sessões seguidas — volta a {1} {2} e sobe outra vez.',
|
||||
'Missed reps — reset to {0} {1} and work back up.': 'Falhaste repetições — volta a {0} {1} e sobe outra vez.',
|
||||
'Missed reps last time — same weight again ({0} of {1} to go).': 'Falhaste repetições da última vez — o mesmo peso outra vez (faltam {0} de {1}).',
|
||||
@@ -1131,6 +1144,9 @@ export default {
|
||||
'Bar ({0})': 'Barra ({0})',
|
||||
'Bar {0}': 'Barra {0}',
|
||||
'Default for this bar type.': 'Predefinição para este tipo de barra.',
|
||||
'No bar': 'Sem barra',
|
||||
'The weight you log is all plates.': 'O peso que registas são só discos.',
|
||||
'Plates are counted from 0 — turn this off for the default ({0}).': 'Os discos contam a partir de 0 — desliga para o valor predefinido ({0}).',
|
||||
'Set to 0 to go back to the default ({0}).': 'Coloca 0 para voltar à predefinição ({0}).',
|
||||
'Applies to this exercise everywhere, not just this plan.': 'Aplica-se a este exercício em todo o lado, não só neste plano.',
|
||||
'You still log the total weight — the bar only feeds the per-side plate math.': 'Continuas a registar o peso total — a barra só conta para o cálculo dos discos por lado.',
|
||||
|
||||
@@ -141,6 +141,8 @@ export default {
|
||||
'This removes it from your history for good.': 'Она будет навсегда удалена из истории.',
|
||||
'Workout deleted': 'Тренировка удалена',
|
||||
'Delete workout': 'Удалить тренировку',
|
||||
'Rename workout': 'Переименовать тренировку',
|
||||
'Workout title': 'Название тренировки',
|
||||
'{0} done': '{0} — готово',
|
||||
'Confirm the weight you worked with — your highest becomes the default next time.': 'Подтверди рабочий вес — наибольший станет значением по умолчанию в следующий раз.',
|
||||
'Then finish the superset partner.': 'Затем доделай второе упражнение суперсета.',
|
||||
@@ -318,12 +320,18 @@ export default {
|
||||
'The screen stays on while a workout is running, so you don’t have to unlock your phone between sets.': 'Экран не гаснет, пока идёт тренировка, — не нужно разблокировать телефон между подходами.',
|
||||
'Weight unit': 'Единица веса',
|
||||
'Week starts on': 'Неделя начинается с',
|
||||
'Weight decimals': 'Знаки после запятой',
|
||||
'How precisely weights are shown.': 'Насколько точно показывать вес.',
|
||||
'0.5': '0,5',
|
||||
'0.25': '0,25',
|
||||
'Rest timer': 'Таймер отдыха',
|
||||
'Sounds': 'Звуки',
|
||||
'Flash screen when timer ends': 'Мигать экраном по окончании таймера',
|
||||
'Weigh in before workouts': 'Взвешивание перед тренировкой',
|
||||
'Asks for your body weight when a workout starts. Off starts the session straight away.': 'Спрашивает ваш вес при начале тренировки. Выключено — сессия начинается сразу.',
|
||||
'No entries yet — log your weight to start the curve.': 'Записей пока нет — внеси вес, чтобы начать кривую.',
|
||||
'Play sounds when the phone is on silent': 'Воспроизводить звуки при беззвучном режиме',
|
||||
'Music playing on this phone stops during a workout and does not resume by itself.': 'Музыка, играющая на этом телефоне, останавливается во время тренировки и сама не возобновляется.',
|
||||
'Data': 'Данные',
|
||||
'Export backup (JSON)': 'Экспорт резервной копии (JSON)',
|
||||
'Import backup': 'Импорт резервной копии',
|
||||
@@ -559,6 +567,7 @@ export default {
|
||||
'{0} exercises in the file aren’t in your library and were left out.': '{0} упражнений из файла отсутствуют в вашей библиотеке и были пропущены.',
|
||||
'Use this weekly schedule': 'Использовать это расписание недели',
|
||||
'Replaces your current Mon–Sun assignments.': 'Заменяет твоё текущее распределение пн–вс.',
|
||||
'Added {0} routine to your plan': 'В твой план добавлена {0} программа',
|
||||
'Added {0} routines to your plan': 'В твой план добавлено программ: {0}',
|
||||
'this isn’t an openGym plan file': 'это не файл плана openGym',
|
||||
'Shared routine': 'Общая программа',
|
||||
@@ -624,6 +633,10 @@ export default {
|
||||
'Same weight — aim for {0} reps this time.': 'Тот же вес — в этот раз целься на {0} повторений.',
|
||||
'Last set hit {0} reps — twice the target, so take a double jump of {1} {2}.': 'В последнем подходе {0} повторений — вдвое больше цели, поэтому двойной шаг {1} {2}.',
|
||||
'Every rep last time — {0} {1} more.': 'В прошлый раз все повторения — плюс {0} {1}.',
|
||||
'Every rep last time — {0} {1} less help.': 'В прошлый раз все повторения — помощи меньше на {0} {1}.',
|
||||
'Top of the rep range in every set — {0} {1} less help, back to {2} reps.': 'Верх диапазона повторений в каждом подходе — помощи меньше на {0} {1}, снова {2} повторений.',
|
||||
'Missed reps — {0} {1} of help while you build back up.': 'Повторения не добраны — {0} {1} помощи, пока восстанавливаешься.',
|
||||
'Stalled {0} sessions — back to {1} {2} of help and build up again.': 'Застой {0} тренировок — назад к {1} {2} помощи и набирать заново.',
|
||||
'Missed reps {0} sessions running — reset to {1} {2} and work back up.': 'Повторения не даются {0} тренировки подряд — вернись к {1} {2} и наращивай снова.',
|
||||
'Missed reps — reset to {0} {1} and work back up.': 'Повторения не дались — вернись к {0} {1} и наращивай снова.',
|
||||
'Missed reps last time — same weight again ({0} of {1} to go).': 'В прошлый раз повторения не дались — тот же вес ещё раз (осталось {0} из {1}).',
|
||||
@@ -1131,6 +1144,9 @@ export default {
|
||||
'Bar ({0})': 'Гриф ({0})',
|
||||
'Bar {0}': 'Гриф {0}',
|
||||
'Default for this bar type.': 'Значение по умолчанию для этого типа грифа.',
|
||||
'No bar': 'Без грифа',
|
||||
'The weight you log is all plates.': 'Записанный вес — это только блины.',
|
||||
'Plates are counted from 0 — turn this off for the default ({0}).': 'Блины считаются от 0 — выключи, чтобы вернуть значение по умолчанию ({0}).',
|
||||
'Set to 0 to go back to the default ({0}).': 'Поставь 0, чтобы вернуться к значению по умолчанию ({0}).',
|
||||
'Applies to this exercise everywhere, not just this plan.': 'Действует для этого упражнения везде, а не только в этом плане.',
|
||||
'You still log the total weight — the bar only feeds the per-side plate math.': 'Записывается по-прежнему общий вес — гриф нужен только для расчёта блинов на сторону.',
|
||||
|
||||
@@ -140,6 +140,8 @@ export default {
|
||||
'This removes it from your history for good.': 'จะลบออกจากประวัติอย่างถาวร',
|
||||
'Workout deleted': 'ลบการออกกำลังกายแล้ว',
|
||||
'Delete workout': 'ลบการออกกำลังกาย',
|
||||
'Rename workout': 'เปลี่ยนชื่อการออกกำลังกาย',
|
||||
'Workout title': 'ชื่อการออกกำลังกาย',
|
||||
'{0} done': 'เสร็จแล้ว {0}',
|
||||
'Confirm the weight you worked with — your highest becomes the default next time.': 'ยืนยันน้ำหนักที่ใช้ — น้ำหนักสูงสุดจะถูกตั้งเป็นค่าเริ่มต้นในครั้งถัดไป',
|
||||
'Then finish the superset partner.': 'จากนั้นทำท่าคู่ซูเปอร์เซ็ตให้เสร็จ',
|
||||
@@ -325,6 +327,10 @@ export default {
|
||||
'The screen stays on while a workout is running, so you don’t have to unlock your phone between sets.': 'จอจะไม่ปิดขณะออกกำลังกาย จะได้ไม่ต้องปลดล็อกโทรศัพท์ระหว่างเซ็ต',
|
||||
'Weight unit': 'หน่วยน้ำหนัก',
|
||||
'Week starts on': 'สัปดาห์เริ่มวัน',
|
||||
'Weight decimals': 'ทศนิยมของน้ำหนัก',
|
||||
'How precisely weights are shown.': 'แสดงน้ำหนักละเอียดแค่ไหน',
|
||||
'0.5': '0.5',
|
||||
'0.25': '0.25',
|
||||
'Rest timer': 'ตัวจับเวลาพัก',
|
||||
'Sounds': 'เสียง',
|
||||
'Data': 'ข้อมูล',
|
||||
@@ -540,6 +546,7 @@ export default {
|
||||
'{0} exercises in the file aren’t in your library and were left out.': 'มี {0} ท่าในไฟล์ที่ไม่มีในคลังของคุณ จึงถูกข้ามไป',
|
||||
'Use this weekly schedule': 'ใช้ตารางรายสัปดาห์นี้',
|
||||
'Replaces your current Mon–Sun assignments.': 'จะแทนที่ตารางจันทร์–อาทิตย์ปัจจุบันของคุณ',
|
||||
'Added {0} routine to your plan': 'เพิ่ม {0} รูทีนเข้าแผนของคุณแล้ว',
|
||||
'Added {0} routines to your plan': 'เพิ่ม {0} รูทีนเข้าแผนของคุณแล้ว',
|
||||
'this isn’t an openGym plan file': 'นี่ไม่ใช่ไฟล์แผนของ openGym',
|
||||
'Shared routine': 'รูทีนที่แชร์มา',
|
||||
@@ -601,6 +608,10 @@ export default {
|
||||
'Same weight — aim for {0} reps this time.': 'น้ำหนักเดิม — ตั้งเป้าที่ {0} ครั้งในรอบนี้',
|
||||
'Last set hit {0} reps — twice the target, so take a double jump of {1} {2}.': 'เซ็ตสุดท้ายทำได้ {0} ครั้ง — เกินเป้าสองเท่า จึงเพิ่มน้ำหนักแบบก้าวกระโดด {1} {2}',
|
||||
'Every rep last time — {0} {1} more.': 'ครั้งก่อนทำครบทุกครั้ง — เพิ่มอีก {0} {1}',
|
||||
'Every rep last time — {0} {1} less help.': 'ครั้งก่อนครบทุกครั้ง — ลดตัวช่วย {0} {1}',
|
||||
'Top of the rep range in every set — {0} {1} less help, back to {2} reps.': 'ถึงเพดานช่วงจำนวนครั้งทุกเซ็ต — ลดตัวช่วย {0} {1} แล้วกลับไปที่ {2} ครั้ง',
|
||||
'Missed reps — {0} {1} of help while you build back up.': 'ทำครบไม่ได้ — ใช้ตัวช่วย {0} {1} ระหว่างไต่กลับขึ้นมา',
|
||||
'Stalled {0} sessions — back to {1} {2} of help and build up again.': 'ตัน {0} ครั้ง — กลับไปใช้ตัวช่วย {1} {2} แล้วไต่ใหม่',
|
||||
'Missed reps {0} sessions running — reset to {1} {2} and work back up.': 'พลาดจำนวนครั้งติดต่อกัน {0} ครั้ง — รีเซ็ตกลับไปที่ {1} {2} แล้วค่อยไต่ขึ้นใหม่',
|
||||
'Missed reps — reset to {0} {1} and work back up.': 'พลาดจำนวนครั้ง — รีเซ็ตกลับไปที่ {0} {1} แล้วค่อยไต่ขึ้นใหม่',
|
||||
'Missed reps last time — same weight again ({0} of {1} to go).': 'ครั้งก่อนพลาดจำนวนครั้ง — น้ำหนักเดิมอีกครั้ง (เหลืออีก {0} จาก {1})',
|
||||
@@ -756,6 +767,8 @@ export default {
|
||||
'Weigh in before workouts': 'ชั่งน้ำหนักก่อนออกกำลังกาย',
|
||||
'Asks for your body weight when a workout starts. Off starts the session straight away.': 'ถามน้ำหนักตัวเมื่อเริ่มออกกำลังกาย ถ้าปิด เซสชันจะเริ่มทันที',
|
||||
'No entries yet — log your weight to start the curve.': 'ยังไม่มีข้อมูล — บันทึกน้ำหนักเพื่อเริ่มกราฟ',
|
||||
'Play sounds when the phone is on silent': 'เล่นเสียงแม้โทรศัพท์อยู่ในโหมดเงียบ',
|
||||
'Music playing on this phone stops during a workout and does not resume by itself.': 'เพลงที่เล่นอยู่บนโทรศัพท์นี้จะหยุดระหว่างการออกกำลังกาย และจะไม่เล่นต่อเอง',
|
||||
'Import from Hevy': 'นำเข้าจาก Hevy',
|
||||
'Pull your history with a Hevy Pro API key': 'ดึงประวัติด้วยคีย์ API ของ Hevy Pro',
|
||||
'Pull your history with a Hevy Pro API key. The key is only used for this import and is not saved.': 'ดึงประวัติด้วยคีย์ API ของ Hevy Pro คีย์ใช้สำหรับการนำเข้าครั้งนี้เท่านั้นและจะไม่ถูกบันทึก',
|
||||
@@ -804,6 +817,9 @@ export default {
|
||||
'Bar ({0})': 'บาร์ ({0})',
|
||||
'Bar {0}': 'บาร์ {0}',
|
||||
'Default for this bar type.': 'ค่าเริ่มต้นสำหรับบาร์ชนิดนี้',
|
||||
'No bar': 'ไม่มีบาร์',
|
||||
'The weight you log is all plates.': 'น้ำหนักที่บันทึกคือแผ่นทั้งหมด',
|
||||
'Plates are counted from 0 — turn this off for the default ({0}).': 'นับแผ่นจาก 0 — ปิดเพื่อกลับไปค่าเริ่มต้น ({0})',
|
||||
'Set to 0 to go back to the default ({0}).': 'ตั้งเป็น 0 เพื่อกลับไปใช้ค่าเริ่มต้น ({0})',
|
||||
'Applies to this exercise everywhere, not just this plan.': 'มีผลกับท่านี้ทุกที่ ไม่ใช่เฉพาะในแผนนี้',
|
||||
'You still log the total weight — the bar only feeds the per-side plate math.': 'คุณยังบันทึกน้ำหนักรวมเหมือนเดิม — บาร์ใช้สำหรับคำนวณแผ่นน้ำหนักต่อข้างเท่านั้น',
|
||||
|
||||
@@ -141,6 +141,8 @@ export default {
|
||||
'This removes it from your history for good.': 'Geçmişinden kalıcı olarak kaldırılır.',
|
||||
'Workout deleted': 'Antrenman silindi',
|
||||
'Delete workout': 'Antrenmanı sil',
|
||||
'Rename workout': 'Antrenmanı yeniden adlandır',
|
||||
'Workout title': 'Antrenman başlığı',
|
||||
'{0} done': '{0} tamamlandı',
|
||||
'Confirm the weight you worked with — your highest becomes the default next time.': 'Çalıştığın ağırlığı onayla — en yükseği bir dahaki sefer varsayılan olur.',
|
||||
'Then finish the superset partner.': 'Sonra süpersetin diğer egzersizini bitir.',
|
||||
@@ -318,12 +320,18 @@ export default {
|
||||
'The screen stays on while a workout is running, so you don’t have to unlock your phone between sets.': 'Antrenman sürerken ekran açık kalır, böylece setler arasında telefonunu açmak zorunda kalmazsın.',
|
||||
'Weight unit': 'Ağırlık birimi',
|
||||
'Week starts on': 'Hafta başlangıcı',
|
||||
'Weight decimals': 'Ağırlık ondalığı',
|
||||
'How precisely weights are shown.': 'Ağırlıklar ne kadar hassas gösterilsin.',
|
||||
'0.5': '0,5',
|
||||
'0.25': '0,25',
|
||||
'Rest timer': 'Dinlenme sayacı',
|
||||
'Sounds': 'Sesler',
|
||||
'Flash screen when timer ends': 'Zamanlayıcı bitince ekranı yanıp söndür',
|
||||
'Weigh in before workouts': 'Antrenman öncesi tartılma',
|
||||
'Asks for your body weight when a workout starts. Off starts the session straight away.': 'Antrenman başlarken kilonu sorar. Kapalıyken seans hemen başlar.',
|
||||
'No entries yet — log your weight to start the curve.': 'Henüz kayıt yok — eğriyi başlatmak için kilonu gir.',
|
||||
'Play sounds when the phone is on silent': 'Telefon sessizdeyken de sesleri çal',
|
||||
'Music playing on this phone stops during a workout and does not resume by itself.': 'Bu telefonda çalan müzik antrenman sırasında durur ve kendiliğinden devam etmez.',
|
||||
'Data': 'Veriler',
|
||||
'Export backup (JSON)': 'Yedeği dışa aktar (JSON)',
|
||||
'Import backup': 'Yedeği içe aktar',
|
||||
@@ -559,6 +567,7 @@ export default {
|
||||
'{0} exercises in the file aren’t in your library and were left out.': 'Dosyadaki {0} egzersiz kitaplığında yok ve atlandı.',
|
||||
'Use this weekly schedule': 'Bu hafta programını kullan',
|
||||
'Replaces your current Mon–Sun assignments.': 'Mevcut Pzt–Paz atamanı değiştirir.',
|
||||
'Added {0} routine to your plan': 'Planına {0} rutin eklendi',
|
||||
'Added {0} routines to your plan': 'Planına {0} rutin eklendi',
|
||||
'this isn’t an openGym plan file': 'bu bir openGym plan dosyası değil',
|
||||
'Shared routine': 'Paylaşılan rutin',
|
||||
@@ -624,6 +633,10 @@ export default {
|
||||
'Same weight — aim for {0} reps this time.': 'Aynı ağırlık — bu sefer {0} tekrarı hedefle.',
|
||||
'Last set hit {0} reps — twice the target, so take a double jump of {1} {2}.': 'Son set {0} tekrar — hedefin iki katı, bu yüzden {1} {2} çift artış.',
|
||||
'Every rep last time — {0} {1} more.': 'Geçen sefer bütün tekrarlar tamam — {0} {1} daha.',
|
||||
'Every rep last time — {0} {1} less help.': 'Geçen sefer her tekrar tamam — {0} {1} daha az destek.',
|
||||
'Top of the rep range in every set — {0} {1} less help, back to {2} reps.': 'Her sette tekrar aralığının üstü — {0} {1} daha az destek, {2} tekrara dön.',
|
||||
'Missed reps — {0} {1} of help while you build back up.': 'Tekrarlar eksik — toparlanana kadar {0} {1} destek.',
|
||||
'Stalled {0} sessions — back to {1} {2} of help and build up again.': '{0} antrenmandır takılı — {1} {2} desteğe dön ve yeniden çık.',
|
||||
'Missed reps {0} sessions running — reset to {1} {2} and work back up.': 'Üst üste {0} seans tekrarlar eksik — {1} {2} ağırlığa dön ve yeniden çık.',
|
||||
'Missed reps — reset to {0} {1} and work back up.': 'Tekrarlar eksik kaldı — {0} {1} ağırlığa dön ve yeniden çık.',
|
||||
'Missed reps last time — same weight again ({0} of {1} to go).': 'Geçen sefer tekrarlar eksikti — aynı ağırlık bir kez daha ({1} denemeden {0} kaldı).',
|
||||
@@ -1131,6 +1144,9 @@ export default {
|
||||
'Bar ({0})': 'Bar ({0})',
|
||||
'Bar {0}': 'Bar {0}',
|
||||
'Default for this bar type.': 'Bu bar türü için varsayılan.',
|
||||
'No bar': 'Bar yok',
|
||||
'The weight you log is all plates.': 'Girdiğin ağırlığın tamamı plaka.',
|
||||
'Plates are counted from 0 — turn this off for the default ({0}).': 'Plakalar 0’dan sayılır — varsayılana ({0}) dönmek için kapat.',
|
||||
'Set to 0 to go back to the default ({0}).': 'Varsayılana ({0}) dönmek için 0 yap.',
|
||||
'Applies to this exercise everywhere, not just this plan.': 'Yalnızca bu planda değil, bu egzersiz için her yerde geçerli.',
|
||||
'You still log the total weight — the bar only feeds the per-side plate math.': 'Yine de toplam ağırlığı kaydedersin — bar yalnızca taraf başına plaka hesabına girer.',
|
||||
|
||||
@@ -141,6 +141,8 @@ export default {
|
||||
'This removes it from your history for good.': '它将从历史中永久删除。',
|
||||
'Workout deleted': '训练已删除',
|
||||
'Delete workout': '删除训练',
|
||||
'Rename workout': '重命名训练',
|
||||
'Workout title': '训练标题',
|
||||
'{0} done': '{0} 完成',
|
||||
'Confirm the weight you worked with — your highest becomes the default next time.': '确认你使用的重量——最高值将成为下次的默认值。',
|
||||
'Then finish the superset partner.': '然后完成超级组的另一个动作。',
|
||||
@@ -318,12 +320,18 @@ export default {
|
||||
'The screen stays on while a workout is running, so you don’t have to unlock your phone between sets.': '训练进行时屏幕保持常亮,组间无需再解锁手机。',
|
||||
'Weight unit': '重量单位',
|
||||
'Week starts on': '一周开始于',
|
||||
'Weight decimals': '重量小数位',
|
||||
'How precisely weights are shown.': '重量显示的精确程度。',
|
||||
'0.5': '0.5',
|
||||
'0.25': '0.25',
|
||||
'Rest timer': '休息计时',
|
||||
'Sounds': '声音',
|
||||
'Flash screen when timer ends': '计时结束时闪烁屏幕',
|
||||
'Weigh in before workouts': '训练前称重',
|
||||
'Asks for your body weight when a workout starts. Off starts the session straight away.': '开始训练时询问体重。关闭后直接进入训练。',
|
||||
'No entries yet — log your weight to start the curve.': '还没有记录——记录体重以开始曲线。',
|
||||
'Play sounds when the phone is on silent': '手机静音时也播放提示音',
|
||||
'Music playing on this phone stops during a workout and does not resume by itself.': '锻炼期间,这部手机正在播放的音乐会停止,且不会自动恢复。',
|
||||
'Data': '数据',
|
||||
'Export backup (JSON)': '导出备份(JSON)',
|
||||
'Import backup': '导入备份',
|
||||
@@ -559,6 +567,7 @@ export default {
|
||||
'{0} exercises in the file aren’t in your library and were left out.': '文件中有 {0} 个动作不在你的动作库中,已略过。',
|
||||
'Use this weekly schedule': '使用此每周日程',
|
||||
'Replaces your current Mon–Sun assignments.': '替换你当前的周一至周日安排。',
|
||||
'Added {0} routine to your plan': '已向你的计划添加 {0} 个训练日',
|
||||
'Added {0} routines to your plan': '已向你的计划添加 {0} 个训练日',
|
||||
'this isn’t an openGym plan file': '这不是 openGym 计划文件',
|
||||
'Shared routine': '共享的训练日',
|
||||
@@ -624,6 +633,10 @@ export default {
|
||||
'Same weight — aim for {0} reps this time.': '同样的重量——这次目标 {0} 次。',
|
||||
'Last set hit {0} reps — twice the target, so take a double jump of {1} {2}.': '最后一组做了 {0} 次——是目标的两倍,因此加倍上调 {1} {2}。',
|
||||
'Every rep last time — {0} {1} more.': '上次全部完成——加 {0} {1}。',
|
||||
'Every rep last time — {0} {1} less help.': '上次每组都完成 — 辅助减少 {0} {1}。',
|
||||
'Top of the rep range in every set — {0} {1} less help, back to {2} reps.': '每组都达到次数上限 — 辅助减少 {0} {1},回到 {2} 次。',
|
||||
'Missed reps — {0} {1} of help while you build back up.': '次数未达标 — 辅助 {0} {1},慢慢练回来。',
|
||||
'Stalled {0} sessions — back to {1} {2} of help and build up again.': '已停滞 {0} 次 — 回到 {1} {2} 辅助,重新往上加。',
|
||||
'Missed reps {0} sessions running — reset to {1} {2} and work back up.': '连续 {0} 次未完成次数——回到 {1} {2} 重新往上做。',
|
||||
'Missed reps — reset to {0} {1} and work back up.': '次数未完成——回到 {0} {1} 重新往上做。',
|
||||
'Missed reps last time — same weight again ({0} of {1} to go).': '上次次数未完成——再用同样的重量(还剩 {0}/{1} 次)。',
|
||||
@@ -1131,6 +1144,9 @@ export default {
|
||||
'Bar ({0})': '杆 ({0})',
|
||||
'Bar {0}': '杆 {0}',
|
||||
'Default for this bar type.': '此类杠铃杆的默认值。',
|
||||
'No bar': '无杠铃杆',
|
||||
'The weight you log is all plates.': '你记录的重量全部是杠铃片。',
|
||||
'Plates are counted from 0 — turn this off for the default ({0}).': '杠铃片从 0 开始计算 — 关闭以使用默认值({0})。',
|
||||
'Set to 0 to go back to the default ({0}).': '设为 0 即恢复默认值({0})。',
|
||||
'Applies to this exercise everywhere, not just this plan.': '对这个动作处处生效,不只在此计划中。',
|
||||
'You still log the total weight — the bar only feeds the per-side plate math.': '记录的仍是总重量——杆重只用于每侧杠铃片的计算。',
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
// @vitest-environment happy-dom
|
||||
import React, { act } from 'react'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { resolve } from 'node:path'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import { useStore } from './store/useStore.js'
|
||||
@@ -22,6 +24,7 @@ function mountTopSheet() {
|
||||
return host
|
||||
}
|
||||
const button = (host, text) => [...host.querySelectorAll('button')].find(b => b.textContent.trim() === text)
|
||||
const cssSource = readFileSync(resolve(process.cwd(), 'src/index.css'), 'utf8')
|
||||
|
||||
describe('log a past workout', () => {
|
||||
beforeEach(() => {
|
||||
@@ -53,6 +56,26 @@ describe('log a past workout', () => {
|
||||
expect(useStore.getState().S.active).toBeNull()
|
||||
})
|
||||
|
||||
// The Date and Start-time rows are the only .lrow rows in the app that pair a title with a
|
||||
// fixed-width field and nothing that can give way. A pixel floor under the title column therefore
|
||||
// comes straight out of the field: 104px pushed the date input 23px off a 320px screen, calendar
|
||||
// picker and all, so there was no way to open the picker on a small phone. The floor has to be the
|
||||
// row's own longest word (min-width:auto), which these short titles barely ask for.
|
||||
it('gives the date and time fields a title column that can shrink', () => {
|
||||
logPastWorkoutSheet()
|
||||
const host = mountTopSheet()
|
||||
const fields = [...host.querySelectorAll('.lrow input.timef')]
|
||||
expect(fields.map(i => i.type)).toEqual(['date', 'time'])
|
||||
for (const field of fields) expect(field.closest('.lrow').querySelectorAll('.lrow-v')).toHaveLength(0)
|
||||
const rule = cssSource.match(/^\.lrow-m\{([^}]*)\}/m)
|
||||
expect(rule?.[1]).toContain('min-width:auto')
|
||||
expect(rule[1]).not.toMatch(/min-width:\s*[\d.]/)
|
||||
// and where even the longest word leaves no room for the field (Polish "Godzina rozpoczęcia"
|
||||
// at 320px), the field drops onto its own line rather than over the edge of the card.
|
||||
expect(cssSource).toContain('.lrow:has(.timef){flex-wrap:wrap}')
|
||||
expect(cssSource).toContain('.lrow>.timef{margin-left:auto}')
|
||||
})
|
||||
|
||||
it('starts a backfilled session straight away on a free day', () => {
|
||||
logPastWorkoutSheet()
|
||||
const host = mountTopSheet()
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
// @vitest-environment happy-dom
|
||||
// QA C10. Since the muscles of a custom exercise are stored in the map's order (83b2a14), the
|
||||
// one-word target `tg` was silently taken from the sorted list: a hip thrust with Traps as an
|
||||
// extra primary became a "Traps" exercise in the library, the picker and the Muscles view, and
|
||||
// tap order no longer let the user correct it. The target is the primary picked first; an edit
|
||||
// keeps the old target while it is still a primary.
|
||||
import React, { act } from 'react'
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import { EXIDX, registerCustom } from './lib/exercises.js'
|
||||
import { DEF, useStore } from './store/useStore.js'
|
||||
import { useUI } from './store/useUI.js'
|
||||
import { _setLangState } from './lib/i18n-core.js'
|
||||
import { bindUI } from './components/ui.jsx'
|
||||
import { customExSheet } from './sheets.jsx'
|
||||
|
||||
bindUI(useUI) // the multi-select rows open their sheet through the shared controls
|
||||
|
||||
const mounted = []
|
||||
const S = () => useStore.getState().S
|
||||
|
||||
// Renders whatever sheet is on top and returns its host element.
|
||||
function renderTop() {
|
||||
const sheet = useUI.getState().sheets.at(-1)
|
||||
const host = document.createElement('div')
|
||||
document.body.appendChild(host)
|
||||
const root = createRoot(host)
|
||||
mounted.push(root)
|
||||
act(() => root.render(sheet.render(() => useUI.getState().closeSheet(sheet.id))))
|
||||
return host
|
||||
}
|
||||
function type(el, value) {
|
||||
Object.getOwnPropertyDescriptor(el.constructor.prototype, 'value').set.call(el, value)
|
||||
el.dispatchEvent(new Event('input', { bubbles: true }))
|
||||
}
|
||||
const byText = (host, sel, text) => [...host.querySelectorAll(sel)].find(e => e.textContent.trim() === text)
|
||||
const click = (host, sel, text) => {
|
||||
const el = byText(host, sel, text)
|
||||
if (!el) throw new Error(`nothing with text "${text}"`)
|
||||
act(() => el.click())
|
||||
}
|
||||
// The form's multi-select rows open a nested sheet; tap the given labels there, in order, then Done.
|
||||
function pickMuscles(form, rowTitle, labels) {
|
||||
const row = [...form.querySelectorAll('.lrow')].find(e => e.textContent.includes(rowTitle))
|
||||
act(() => row.click())
|
||||
const sub = renderTop()
|
||||
for (const l of labels) click(sub, 'button', l)
|
||||
click(sub, 'button', 'Done')
|
||||
}
|
||||
const custom = (over = {}) => ({
|
||||
id: 'cqa1', n: 'QA Custom Thrust', bp: 'upper legs', eq: 'barbell', custom: true, desc: '',
|
||||
tg: 'gluteal', sm: ['forearm', 'hip-flexors'], primaries: ['gluteal'], secondaries: ['forearm', 'hip-flexors'],
|
||||
muscleGroups: ['gluteal', 'forearm', 'hip-flexors'], ...over,
|
||||
})
|
||||
function seed(ex) {
|
||||
useStore.setState(s => ({ S: { ...s.S, customEx: [ex] } }))
|
||||
registerCustom([ex])
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
globalThis.IS_REACT_ACT_ENVIRONMENT = true
|
||||
useUI.setState({ sheets: [], toastMsg: '' })
|
||||
useStore.setState({ S: structuredClone(DEF), user: null })
|
||||
registerCustom([])
|
||||
_setLangState('en', null, null, null)
|
||||
document.body.innerHTML = ''
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
act(() => { mounted.splice(0).forEach(root => root.unmount()) })
|
||||
_setLangState('en', null, null, null)
|
||||
registerCustom([])
|
||||
})
|
||||
|
||||
describe('custom exercise target (QA C10)', () => {
|
||||
it('is the primary tapped first, while the stored list keeps the map order', () => {
|
||||
customExSheet(null)
|
||||
const form = renderTop()
|
||||
act(() => type(form.querySelector('input.input'), 'QA Hip Thrust Pull'))
|
||||
click(form, '.chip', 'upper legs')
|
||||
click(form, '.chip', 'barbell')
|
||||
pickMuscles(form, 'Primary muscle groups', ['Hamstrings', 'Glutes', 'Traps'])
|
||||
click(form, 'button', 'Create exercise')
|
||||
const c = S().customEx.find(x => x.n === 'QA Hip Thrust Pull')
|
||||
expect(c.primaries).toEqual(['trapezius', 'gluteal', 'hamstring'])
|
||||
expect(c.tg).toBe('hamstring')
|
||||
expect(c.muscleGroups).toEqual(['trapezius', 'gluteal', 'hamstring'])
|
||||
})
|
||||
|
||||
it('survives an edit that adds a primary higher up the body', () => {
|
||||
const ex = custom({ tg: 'hamstring', primaries: ['gluteal', 'hamstring'], secondaries: [], sm: [], muscleGroups: ['gluteal', 'hamstring'] })
|
||||
seed(ex)
|
||||
customExSheet(EXIDX[ex.id])
|
||||
const form = renderTop()
|
||||
pickMuscles(form, 'Primary muscle groups', ['Traps'])
|
||||
click(form, 'button', 'Save')
|
||||
const c = S().customEx[0]
|
||||
expect(c.primaries).toEqual(['trapezius', 'gluteal', 'hamstring'])
|
||||
expect(c.tg).toBe('hamstring')
|
||||
})
|
||||
|
||||
it('moves to another primary only when the old target is dropped', () => {
|
||||
const ex = custom({ tg: 'hamstring', primaries: ['gluteal', 'hamstring'], secondaries: [], sm: [], muscleGroups: ['gluteal', 'hamstring'] })
|
||||
seed(ex)
|
||||
customExSheet(EXIDX[ex.id])
|
||||
const form = renderTop()
|
||||
pickMuscles(form, 'Primary muscle groups', ['Hamstrings']) // untick it
|
||||
click(form, 'button', 'Save')
|
||||
const c = S().customEx[0]
|
||||
expect(c.primaries).toEqual(['gluteal'])
|
||||
expect(c.tg).toBe('gluteal')
|
||||
})
|
||||
|
||||
// Dropping the target used to hand it to the head of the map-sorted list, which is where C10
|
||||
// started: an upper-legs exercise read "Traps · barbell" again the moment its target went away.
|
||||
it('hands a dropped target to the primary tapped in this sheet, not to the topmost muscle', () => {
|
||||
const ex = custom({ tg: 'hamstring', primaries: ['trapezius', 'gluteal', 'hamstring'], secondaries: ['forearm'], sm: ['forearm'],
|
||||
muscleGroups: ['trapezius', 'gluteal', 'hamstring', 'forearm'] })
|
||||
seed(ex)
|
||||
customExSheet(EXIDX[ex.id])
|
||||
const form = renderTop()
|
||||
pickMuscles(form, 'Primary muscle groups', ['Hamstrings', 'Quads']) // untick the target, tap another
|
||||
click(form, 'button', 'Save')
|
||||
const c = S().customEx[0]
|
||||
expect(c.primaries).toEqual(['trapezius', 'gluteal', 'quadriceps'])
|
||||
expect(c.tg).toBe('quadriceps')
|
||||
})
|
||||
|
||||
// Tapping the same chip twice leaves the selection as it was, so it says nothing about what the
|
||||
// user wants the target to be — the muscle actually added does.
|
||||
it('ignores a primary that was tapped on and off again', () => {
|
||||
const ex = custom({ tg: 'hamstring', primaries: ['trapezius', 'hamstring'], secondaries: [], sm: [], muscleGroups: ['trapezius', 'hamstring'] })
|
||||
seed(ex)
|
||||
customExSheet(EXIDX[ex.id])
|
||||
const form = renderTop()
|
||||
pickMuscles(form, 'Primary muscle groups', ['Hamstrings', 'Chest', 'Chest', 'Glutes'])
|
||||
click(form, 'button', 'Save')
|
||||
const c = S().customEx[0]
|
||||
expect(c.primaries).toEqual(['trapezius', 'gluteal'])
|
||||
expect(c.tg).toBe('gluteal')
|
||||
})
|
||||
})
|
||||
@@ -1,11 +1,11 @@
|
||||
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { useStore } from './store/useStore.js'
|
||||
import { useUI } from './store/useUI.js'
|
||||
import { EXDB, EXIDX, BODYPARTS, isCardio, isBodyweightEq, allExercises, equipmentOf, smOf, matchExercise, exOr } from './lib/exercises.js'
|
||||
import { EXDB, EXIDX, BODYPARTS, isCardio, isBodyweightEq, allExercises, equipmentOf, smOf, searchExercises, exOr, isAssisted, betterWeight, beatsWeight } from './lib/exercises.js'
|
||||
import { activeProfile, exAvailable, ALL_EQUIPMENT, newProfile } from './lib/equipment.js'
|
||||
import { fmtDate, fmtNum, capWords, fmtVol, fmtDur, durPart, todayISO, isoOf, uid, exCount, DAYN, DAYS, weekOrder, weekStartOf, weekDayOffset, MONTHS_LONG, ACCENTS } from './lib/format.js'
|
||||
import { fmtDate, fmtNum, capWords, fmtVol, fmtDur, durPart, todayISO, isoOf, uid, exCount, routineCount, DAYN, DAYS, weekOrder, weekStartOf, weekDayOffset, MONTHS_LONG, ACCENTS } from './lib/format.js'
|
||||
import { lastEntryFor, bestWeightFor, bestWeightForEntry, buildSets, effectiveRoutineIds, workoutVolume, setsDone, setsDoneActive, setUnitsTotal, lastBW, supersetUnits, unitOf, setLabel, defaultConfig, cleanupSg, modeOf, effortOf, EFFORT, capEffort, stepEffort, isBw, isPerSide, sideReps, workSetsDone, applyIntensifierPlan, MAX_PLANNED_WARMUPS, NOTE_MAX } from './lib/history.js'
|
||||
import { usesBar, barWeightFor, defaultBarWeight, hasBarOverride } from './lib/bar.js'
|
||||
import { usesBar, barWeightFor, defaultBarWeight, hasBarOverride, isNoBar } from './lib/bar.js'
|
||||
import { toScale, rirOf, EFFORT_PRESETS, effortColor } from './lib/effort.js'
|
||||
import { beep, vibrate } from './lib/sound.js'
|
||||
import { t, dateLocale, instrFor, exerciseNameFor, getLang, INSTR_LANGS } from './lib/i18n.js'
|
||||
@@ -19,7 +19,7 @@ import { Button, Slider, Switch, Segmented, SelectRow, Row, TextField, NumberFie
|
||||
import { glyphOf, GLYPH_GROUPS, DEFAULT_GLYPH } from './lib/glyphs.js'
|
||||
import BodyMap from './components/BodyMap.jsx'
|
||||
import MuscleExplorer from './components/MuscleExplorer.jsx'
|
||||
import { exerciseMuscleSnapshot, loadOfWorkouts, MUSCLES, MUSCLE_NAME, normalizeMuscleGroups, hasExplicitMuscleMetadata } from './lib/muscles.js'
|
||||
import { exerciseMuscleSnapshot, loadOfWorkouts, MUSCLES, MUSCLE_NAME, normalizeMuscleGroups, hasExplicitMuscleMetadata, inMuscleOrder } from './lib/muscles.js'
|
||||
import { parseImport, mergeImport } from './lib/import-csv.js'
|
||||
import { importHevyData, HevyApiError, HEVY_DEV_SETTINGS, mergeHevyRoutines } from './lib/import-hevy.js'
|
||||
import { buildPlanBundle, parsePlan, mergePlan, printPlan, planPrintHTML } from './lib/plan-share.js'
|
||||
@@ -162,7 +162,8 @@ export const starterPlanSheet = () => ui().openSheet(close => <StarterPlanChoose
|
||||
// Fixed range, not a moving window — a window that resizes itself mid-drag (the previous
|
||||
// attempt) makes the thumb's position unpredictable: every time it grows, everything already
|
||||
// placed on it shifts toward one side. A static range never has that problem, at the cost of
|
||||
// coarser precision per pixel — the +/- buttons cover exact values.
|
||||
// coarser precision per pixel — the +/- buttons, and typing straight into the read-out, cover
|
||||
// exact values.
|
||||
// The ceiling follows the profile's unit: 300 covers a body weight or a working weight in
|
||||
// kg, but as pounds it cut off at 136 kg — below plenty of people's body weight, and well
|
||||
// below an everyday squat.
|
||||
@@ -173,10 +174,16 @@ function WeightInput({ value, setValue, unit }) {
|
||||
const clamp = x => Math.max(W_LO, Math.min(W_HI, Math.round((x || 0) * 10) / 10))
|
||||
const sv = Math.max(W_LO, Math.min(W_HI, value))
|
||||
const onSlide = v => setValue(clamp(v))
|
||||
const onType = v => setValue(v)
|
||||
|
||||
return <>
|
||||
<div className="bwstep">
|
||||
<button className="bw-pm" onClick={() => onSlide(value - 0.1)} aria-label="minus 0.1"><Icon name="minus" /></button>
|
||||
<div className="bw-read">{fmtNum(value)}<span className="u"> {unit}</span></div>
|
||||
<label className="bw-read">
|
||||
<NumberField fit value={value} onChange={onType} aria-label={t('Weight ({0})', unit)} enterKeyHint="done"
|
||||
onKeyDown={e => { if (e.key === 'Enter') e.currentTarget.blur() }} />
|
||||
<span className="u"> {unit}</span>
|
||||
</label>
|
||||
<button className="bw-pm" onClick={() => onSlide(value + 0.1)} aria-label="plus 0.1"><Icon name="plus" /></button>
|
||||
</div>
|
||||
<div className="chips" style={{ justifyContent: 'center', margin: '8px 0' }}>
|
||||
@@ -576,17 +583,32 @@ function BarWeightEditor({ ex, extra }) {
|
||||
const st = useStore(s => s.S)
|
||||
const explicit = hasBarOverride(st, ex.id)
|
||||
const def = defaultBarWeight(ex.eq, st.unit)
|
||||
const noBar = isNoBar(st, ex.id)
|
||||
const setBar = v => update(s => {
|
||||
s.barWeights = s.barWeights || {}
|
||||
const n = Math.max(0, Math.round((v || 0) * 100) / 100)
|
||||
if (n > 0) s.barWeights[ex.id] = n; else delete s.barWeights[ex.id]
|
||||
})
|
||||
// "No bar" is a stored 0, which is a different thing from no entry at all: a counterbalanced
|
||||
// Smith carriage weighs nothing in your hands, so the plate math and the drop-set steps must
|
||||
// start from what you logged (issue #138). Clearing it goes back to the bar type's default.
|
||||
const setNoBar = on => update(s => {
|
||||
s.barWeights = s.barWeights || {}
|
||||
if (on) s.barWeights[ex.id] = 0; else delete s.barWeights[ex.id]
|
||||
})
|
||||
return <>
|
||||
<div className="row cfgrow" style={{ marginBottom: 6 }}>
|
||||
{!noBar && <div className="row cfgrow" style={{ marginBottom: 6 }}>
|
||||
<Stepper label={t('Bar ({0})', st.unit)} value={barWeightFor(st, ex) || 0} step={2.5} onChange={setBar} />
|
||||
</div>}
|
||||
<div className="list menu-list" style={{ marginBottom: 6 }}>
|
||||
<Row icon="barbell" title={t('No bar')} subtitle={t('The weight you log is all plates.')}>
|
||||
<Switch checked={noBar} onChange={setNoBar} />
|
||||
</Row>
|
||||
</div>
|
||||
<div className="small dim" style={{ marginBottom: 18 }}>
|
||||
{explicit ? t('Set to 0 to go back to the default ({0}).', fmtNum(def) + ' ' + st.unit) : t('Default for this bar type.')}
|
||||
{noBar ? t('Plates are counted from 0 — turn this off for the default ({0}).', fmtNum(def) + ' ' + st.unit)
|
||||
: explicit ? t('Set to 0 to go back to the default ({0}).', fmtNum(def) + ' ' + st.unit)
|
||||
: t('Default for this bar type.')}
|
||||
{extra ? ' ' + extra : ''}
|
||||
</div>
|
||||
</>
|
||||
@@ -670,7 +692,10 @@ function ExerciseDetail({ ex, close }) {
|
||||
<h4 className="sec">{t('Bar weight')}</h4>
|
||||
<BarWeightEditor ex={ex} extra={t('You still log the total weight — the bar only feeds the per-side plate math.')} />
|
||||
</>}
|
||||
{!isCardio(ex) && <OneRM ex={ex} />}
|
||||
{/* No one-rep max on an assistance machine: the load is the help you were given, so the
|
||||
calculator would answer "your 1RM is 23 kg" about a number that gets smaller as you get
|
||||
stronger (issue #232). Cardio has none for the same kind of reason. */}
|
||||
{!isCardio(ex) && !isAssisted(ex) && <OneRM ex={ex} />}
|
||||
{instrFor(ex).length > 0 &&<><h4 className="sec">{t('How to')}{!INSTR_LANGS.includes(getLang()) && <span className="dim" style={{ textTransform: 'none', letterSpacing: 0 }}> · {t('instructions in English')}</span>}</h4><ol className="steps-list">{instrFor(ex).map((s, i) => <li key={i}>{s}</li>)}</ol></>}
|
||||
</>
|
||||
}
|
||||
@@ -780,7 +805,15 @@ function CustomExForm({ existing, prefill, onDone, close }) {
|
||||
const norm = hasExplicitMuscleMetadata(existing || {}) ? normalizeMuscleGroups(existing || {}) : []
|
||||
return norm.slice(1)
|
||||
})
|
||||
const togglePrimary = value => setPrimaries(current => current.includes(value) ? current.filter(m => m !== value) : [...current, value])
|
||||
// Every primary chip this sheet saw a tap on, in that order. `primaries` alone cannot say what the
|
||||
// user reached for first: an existing exercise seeds it in the map's order, because that is how the
|
||||
// muscles are stored. The taps are the only record of the user's own order, and they decide the
|
||||
// target when the one the exercise had is un-ticked.
|
||||
const [primaryTaps, setPrimaryTaps] = useState([])
|
||||
const togglePrimary = value => {
|
||||
setPrimaryTaps(current => [...current, value])
|
||||
setPrimaries(current => current.includes(value) ? current.filter(m => m !== value) : [...current, value])
|
||||
}
|
||||
const toggleSecondary = value => setSecondaries(current => current.includes(value) ? current.filter(m => m !== value) : [...current, value])
|
||||
const save = () => {
|
||||
const name = n.trim()
|
||||
@@ -790,16 +823,25 @@ function CustomExForm({ existing, prefill, onDone, close }) {
|
||||
const dup = allExercises(S()).find(e => e.n.toLowerCase() === name.toLowerCase() && e.id !== (existing || {}).id)
|
||||
if (dup) { toast(t('“{0}” already exists', dup.n)); return }
|
||||
const d = desc.trim().slice(0, 1000)
|
||||
const prim = bp === 'cardio' ? ['cardiovascular system'] : [...primaries]
|
||||
const sm = secondaries.filter(m => !prim.includes(m))
|
||||
// Stored in the map's order, not the order the chips were tapped in — the tags on the exercise
|
||||
// used to shuffle with every edit.
|
||||
const prim = bp === 'cardio' ? ['cardiovascular system'] : inMuscleOrder(primaries)
|
||||
const sm = inMuscleOrder(secondaries.filter(m => !prim.includes(m)))
|
||||
const groups = [...prim, ...sm]
|
||||
// The one-word target (the library row, the picker, the Muscles view) is not the sorted list's
|
||||
// head — a hip thrust with Traps as an extra primary is not a Traps exercise. It is the primary
|
||||
// tapped first, and an edit keeps the exercise's target as long as that muscle is still a primary.
|
||||
// Once that muscle is gone the next answer is the first one tapped here that survived — a tap that
|
||||
// only turned a chip off says nothing and is skipped with it. The sorted list is the last resort,
|
||||
// for the user who drops the target and adds nothing in its place.
|
||||
const tg = (existing && prim.includes(existing.tg)) ? existing.tg : (primaryTaps.find(m => prim.includes(m)) || prim[0] || '')
|
||||
let id = existing && existing.id
|
||||
if (existing) update(s => { const c = (s.customEx || []).find(x => x.id === id); if (c) {
|
||||
c.n = name; c.bp = bp; c.desc = d; c.tg = prim[0] || ''; c.sm = sm; c.muscleGroups = groups; c.primaries = prim; c.secondaries = sm; c.eq = eq
|
||||
c.n = name; c.bp = bp; c.desc = d; c.tg = tg; c.sm = sm; c.muscleGroups = groups; c.primaries = prim; c.secondaries = sm; c.eq = eq
|
||||
} })
|
||||
else {
|
||||
id = 'c' + uid()
|
||||
update(s => { (s.customEx = s.customEx || []).push({ id, n: name, bp, desc: d, tg: prim[0] || '', sm, muscleGroups: groups, primaries: prim, secondaries: sm, eq, custom: true }) })
|
||||
update(s => { (s.customEx = s.customEx || []).push({ id, n: name, bp, desc: d, tg, sm, muscleGroups: groups, primaries: prim, secondaries: sm, eq, custom: true }) })
|
||||
}
|
||||
close()
|
||||
toast(existing ? t('Saved') : t('“{0}” created', name))
|
||||
@@ -885,7 +927,7 @@ function ExercisePicker({ onPick, close }) {
|
||||
const all = allExercises(st)
|
||||
const profile = activeProfile(st)
|
||||
const inScope = e => bp === '★' ? usage[e.id] : bp === '☆' ? isFav(st, e.id) : (!bp || e.bp === bp)
|
||||
let base = all.filter(e => inScope(e) && matchExercise(e, q))
|
||||
let base = searchExercises(all.filter(inScope), q)
|
||||
if (bp === '★') base = [...base].sort((a, b) => (usage[b.id] - usage[a.id]) || exerciseNameFor(a).localeCompare(exerciseNameFor(b)))
|
||||
const eqFiltered = (profile && !showAll) ? base.filter(e => exAvailable(st, e)) : base
|
||||
const eqOpts = equipmentOf(eqFiltered)
|
||||
@@ -940,7 +982,7 @@ function ExercisePicker({ onPick, close }) {
|
||||
<div className="grow"><div className="tt">{t('Create your own exercise')}</div><div className="ss">{t('name + body part, no animation')}</div></div><Icon name="plus" className="chev" />
|
||||
</div>}
|
||||
{f.slice(0, shown).map(e => <div key={e.id} className="item" {...tappable(() => onPick(e))}>
|
||||
<Thumb ex={e} /><div className="grow"><div className="tt capitalize">{isFav(st, e.id) && <Icon name="starFill" className="fav-star" />}{exerciseNameFor(e)}</div><div className="ss capitalize">{t(e.tg || e.bp)} · {t(e.eq)}</div></div>
|
||||
<Thumb ex={e} /><div className="grow"><div className="tt capitalize">{isFav(st, e.id) && <Icon name="starFill" className="fav-star" />}{exerciseNameFor(e)}</div><div className="ss capitalize">{t(MUSCLE_NAME[e.tg] || e.tg || e.bp)} · {t(e.eq)}</div></div>
|
||||
{/* Accent tag = already in a routine/log ("Chosen"); the yellow star by the name = favourite. */}
|
||||
{usage[e.id] && <span className="tag acc"><Icon name="starFill" /></span>}
|
||||
{/* A "+" glyph reads as "add this now" — it used to just open the same detail sheet as
|
||||
@@ -1107,7 +1149,9 @@ function ProgressionFields({ ex, mode, c, setC, routine, unit, perSide }) {
|
||||
...options.map(p => ({ value: p, label: t(POLICY_NAME[p]) }))]} />
|
||||
</div>
|
||||
<div className="small dim" style={{ marginBottom: active === 'off' ? 18 : 10 }}>{t(POLICY_DESC[active])}</div>
|
||||
{active !== 'off' && <div className="row cfgrow" style={{ marginBottom: 18 }}>
|
||||
{/* Double progression on a weighted exercise fills this row with four steppers; `cfgrow-4`
|
||||
lets it wrap into two pairs on phones, where four abreast left the inputs a few px wide. */}
|
||||
{active !== 'off' && <div className={'row cfgrow' + (active === 'double' && epleyEligible ? ' cfgrow-4' : '')} style={{ marginBottom: 18 }}>
|
||||
<Stepper label={mode === 'time' ? t('Step (seconds)') : t('Step ({0})', unit)} value={inc}
|
||||
step={mode === 'time' ? 5 : 1.25} decimal={mode !== 'time'} invalid={invalid} className={invalid ? 'invalid' : ''}
|
||||
onChange={v => setC(x => ({ ...x, inc: v }))} />
|
||||
@@ -1219,12 +1263,14 @@ function ExConfig({ ex, existing, onSave, onDelete, close, routine, initial }) {
|
||||
<Media ex={ex} />
|
||||
{/* The same tags the exercise detail sheet shows, secondaries included: choosing what goes
|
||||
into a plan is exactly when "what else does this hit" matters, and until now that was
|
||||
only visible from the Exercises tab, after the fact. */}
|
||||
only visible from the Exercises tab, after the fact. Custom exercises and the newer
|
||||
metadata name muscles by the map's ids ("forearm", "gluteal"), which only MUSCLE_NAME
|
||||
turns into a translatable label. */}
|
||||
<div className="row" style={{ gap: 6, flexWrap: 'wrap', margin: '10px 0 14px' }}>
|
||||
{cardio && <span className="tag acc"><Icon name="figureRun" />{t('Cardio')}</span>}
|
||||
<span className="tag">{t(ex.tg || ex.bp)}</span><span className="tag">{t(ex.eq)}</span>
|
||||
<span className="tag">{t(MUSCLE_NAME[ex.tg] || ex.tg || ex.bp)}</span><span className="tag">{t(ex.eq)}</span>
|
||||
{!cardio && (ex.secondaries?.length ? ex.secondaries : smOf(ex)).slice(0, 3)
|
||||
.map((s, i) => <span key={i} className="tag dim">{t(s)}</span>)}
|
||||
.map((s, i) => <span key={i} className="tag dim">{t(MUSCLE_NAME[s] || s)}</span>)}
|
||||
</div>
|
||||
{ex.desc && <div className="exnote">{ex.desc}</div>}
|
||||
{!cardio && <div style={{ marginBottom: 14 }}>
|
||||
@@ -1481,7 +1527,7 @@ function PlanTools({ close }) {
|
||||
const f = ev.target.files[0]; ev.target.value = ''; if (!f) return
|
||||
const rd = new FileReader()
|
||||
rd.onload = () => {
|
||||
try { const bundle = parsePlan(rd.result); close(); planImportSheet(bundle) }
|
||||
try { const bundle = parsePlan(rd.result, st.unit || 'kg'); close(); planImportSheet(bundle) }
|
||||
catch (e) { toast(t('Import failed: {0}', e.message)) }
|
||||
}
|
||||
rd.readAsText(f)
|
||||
@@ -1515,13 +1561,13 @@ function PlanImport({ bundle, close }) {
|
||||
const apply = () => {
|
||||
update(s => mergePlan(s, bundle, { schedule }))
|
||||
close()
|
||||
toast(t('Added {0} routines to your plan', bundle.routineCount))
|
||||
toast(t(bundle.routineCount === 1 ? 'Added {0} routine to your plan' : 'Added {0} routines to your plan', bundle.routineCount))
|
||||
nav('/plan')
|
||||
}
|
||||
return <>
|
||||
<h3>{bundle.name ? t('Import “{0}”', bundle.name) : t('Import this plan')}</h3>
|
||||
<div className="muted small" style={{ marginBottom: 14 }}>
|
||||
{t(bundle.routineCount === 1 ? '{0} routine' : '{0} routines', bundle.routineCount)}
|
||||
{routineCount(bundle.routineCount)}
|
||||
{' · ' + exCount(bundle.exerciseCount)}
|
||||
{bundle.scheduledDays > 0
|
||||
? ' · ' + t(bundle.scheduledDays === 1 ? 'scheduled on {0} day' : 'scheduled on {0} days', bundle.scheduledDays)
|
||||
@@ -1875,7 +1921,9 @@ function AddRoutineToSession({ close }) {
|
||||
if (!s.active) return
|
||||
s.active.entries.push(...entries)
|
||||
s.active.routineIds = [...[].concat(s.active.routineIds || []), r.id]
|
||||
s.active.name = deriveSessionName(s.active.routineIds.map(id => s.routines.find(x => x.id === id)?.name).filter(Boolean))
|
||||
if (!s.active.customName) {
|
||||
s.active.name = deriveSessionName(s.active.routineIds.map(id => s.routines.find(x => x.id === id)?.name).filter(Boolean))
|
||||
}
|
||||
})
|
||||
close()
|
||||
toast(t('{0} added — {1}', r.name, exCount(r.ex.length)))
|
||||
@@ -1912,9 +1960,13 @@ function TopWeight({ entryIdx, close }) {
|
||||
// to sit after every one of them.
|
||||
const entry = A ? A.entries[entryIdx] : null
|
||||
const ex = entry && EXIDX[entry.id]
|
||||
const maxSet = entry ? Math.max(0, ...entry.sets.filter(s => s.done && !isWarmupRow(s)).map(s => s.w || 0)) : 0
|
||||
const prevBest = entry ? Math.max((st.exWeights[entry.id] || {}).w || 0, bestWeightFor(st, entry.id)) : 0
|
||||
const [v, setV] = useState(entry ? (Math.max(maxSet, prevBest) || entry.target.weight || 0) : 0)
|
||||
// "Best" runs the other way on an assistance machine: the lightest setting is the record, and
|
||||
// a 0 means nothing logged rather than a new low (issue #232).
|
||||
const fold = (a, b) => (a > 0 && b > 0 ? betterWeight(entry.id, a, b) : Math.max(a, b))
|
||||
const doneW = entry ? entry.sets.filter(s => s.done && !isWarmupRow(s)).map(s => s.w || 0).filter(w => w > 0) : []
|
||||
const maxSet = entry && doneW.length ? doneW.reduce((a, b) => betterWeight(entry.id, a, b)) : 0
|
||||
const prevBest = entry ? fold((st.exWeights[entry.id] || {}).w || 0, bestWeightFor(st, entry.id)) : 0
|
||||
const [v, setV] = useState(entry ? (fold(maxSet, prevBest) || entry.target.weight || 0) : 0)
|
||||
useEffect(() => { if (!entry) close() }, [!entry])
|
||||
|
||||
const units = supersetUnits(A ? A.entries : [])
|
||||
@@ -1930,7 +1982,7 @@ function TopWeight({ entryIdx, close }) {
|
||||
update(s => {
|
||||
s.active.entries[entryIdx].topW = n
|
||||
const cur = s.exWeights[entry.id]
|
||||
s.exWeights[entry.id] = { w: Math.max(n, cur ? cur.w : 0), d: todayISO() }
|
||||
s.exWeights[entry.id] = { w: cur && cur.w > 0 && n > 0 ? betterWeight(entry.id, n, cur.w) : Math.max(n, cur ? cur.w : 0), d: todayISO() }
|
||||
})
|
||||
close()
|
||||
if (advance && unitDone) {
|
||||
@@ -2050,6 +2102,41 @@ function SessionNote({ close }) {
|
||||
}
|
||||
export const sessionNoteSheet = () => ui().openSheet(close => <SessionNote close={close} />)
|
||||
|
||||
function RenameWorkout({ close }) {
|
||||
const inputRef = useRef(null)
|
||||
const onFocus = useSheetKeyboard(inputRef)
|
||||
const st = useStore(s => s.S)
|
||||
const update = useStore(s => s.update)
|
||||
const A = st.active
|
||||
const [name, setName] = useState(A?.name || '')
|
||||
useEffect(() => { if (!A) close() }, [!A])
|
||||
if (!A) return null
|
||||
|
||||
const trimmed = name.trim().slice(0, 60)
|
||||
const canSave = trimmed.length > 0
|
||||
|
||||
const save = () => {
|
||||
if (!canSave) return
|
||||
update(s => {
|
||||
if (!s.active) return
|
||||
s.active.name = trimmed
|
||||
s.active.customName = true
|
||||
})
|
||||
close()
|
||||
}
|
||||
|
||||
return <>
|
||||
<h3>{t('Rename workout')}</h3>
|
||||
<input ref={inputRef} className="input" type="text" autoFocus maxLength={60} value={name}
|
||||
placeholder={t('Workout title')}
|
||||
onFocus={onFocus} onChange={e => setName(e.target.value)}
|
||||
onKeyDown={e => { if (e.key === 'Enter' && canSave) save() }} />
|
||||
<div style={{ height: 18 }} />
|
||||
<Button variant="primary" disabled={!canSave} onClick={save}>{t('Save')}</Button>
|
||||
</>
|
||||
}
|
||||
export const renameWorkoutSheet = () => ui().openSheet(close => <RenameWorkout close={close} />)
|
||||
|
||||
/* Drop-set drops and rest-pause bursts are edited inline on the set row itself (Workout.jsx) —
|
||||
no sheet, no timer. A planned exercise (see the "Intensifier" config below) arrives with them
|
||||
already computed via applyIntensifierPlan; an unplanned straight set can still grow one live
|
||||
@@ -2108,8 +2195,9 @@ function doFinishWorkout() {
|
||||
// A workout logged into the past cannot claim records against the history that came after
|
||||
// it, so a backfilled session reports none and leaves the confirmed weights alone.
|
||||
if (!past) A.entries.forEach(e => {
|
||||
const mx = Math.max(0, ...e.sets.filter(s => s.done && !isWarmupRow(s)).map(s => s.w))
|
||||
if (mx > 0 && mx > bestWeightFor(st, e.id)) prs.push(e.id)
|
||||
const loads = e.sets.filter(s => s.done && !isWarmupRow(s)).map(s => s.w).filter(w => w > 0)
|
||||
const mx = loads.length ? loads.reduce((a, b) => betterWeight(e.id, a, b)) : 0
|
||||
if (beatsWeight(e.id, mx, bestWeightFor(st, e.id))) prs.push(e.id)
|
||||
// A heavier estimate without a heavier top set is its own kind of progress —
|
||||
// same weight for more reps. Reported separately so it can't be read as a load PR.
|
||||
const rec = is1RMRecord(st, e.id, e)
|
||||
@@ -2127,7 +2215,7 @@ function doFinishWorkout() {
|
||||
} else {
|
||||
w.entries.forEach(e => {
|
||||
const mx = bestWeightForEntry(e)
|
||||
if (mx > 0) { const cur = s.exWeights[e.id]; if (!cur || mx > cur.w) s.exWeights[e.id] = { w: mx, d: w.d } }
|
||||
if (mx > 0 && beatsWeight(e.id, mx, (s.exWeights[e.id] || {}).w || 0)) s.exWeights[e.id] = { w: mx, d: w.d }
|
||||
})
|
||||
s.workouts.push(w)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
// @vitest-environment happy-dom
|
||||
// QA C9. Custom exercises and the newer exercise metadata name muscles by the map's ids. The
|
||||
// picker row, the routine config sheet and the Muscles rows printed those ids ("gluteal",
|
||||
// "forearm", "hip-flexors") where the detail sheet already said Glutes / Forearms / Hip flexors —
|
||||
// and in German "forearm" stayed English, because only the display names have translations.
|
||||
import React, { act } from 'react'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import { EXIDX, registerCustom } from './lib/exercises.js'
|
||||
import { DEF, useStore } from './store/useStore.js'
|
||||
import { useUI } from './store/useUI.js'
|
||||
import { _setLangState } from './lib/i18n-core.js'
|
||||
import de from './locales/de.js'
|
||||
import { exercisePicker, exConfigSheet } from './sheets.jsx'
|
||||
import MuscleExplorer from './components/MuscleExplorer.jsx'
|
||||
|
||||
const mounted = []
|
||||
const S = () => useStore.getState().S
|
||||
|
||||
// Renders whatever sheet is on top and returns its host element.
|
||||
function renderTop() {
|
||||
const sheet = useUI.getState().sheets.at(-1)
|
||||
const host = document.createElement('div')
|
||||
document.body.appendChild(host)
|
||||
const root = createRoot(host)
|
||||
mounted.push(root)
|
||||
act(() => root.render(sheet.render(() => useUI.getState().closeSheet(sheet.id))))
|
||||
return host
|
||||
}
|
||||
function render(node) {
|
||||
const host = document.createElement('div')
|
||||
document.body.appendChild(host)
|
||||
const root = createRoot(host)
|
||||
mounted.push(root)
|
||||
act(() => root.render(node))
|
||||
return host
|
||||
}
|
||||
function type(el, value) {
|
||||
Object.getOwnPropertyDescriptor(el.constructor.prototype, 'value').set.call(el, value)
|
||||
el.dispatchEvent(new Event('input', { bubbles: true }))
|
||||
}
|
||||
const rowFor = (host, name) => [...host.querySelectorAll('.item')].find(e => e.textContent.includes(name))
|
||||
const custom = (over = {}) => ({
|
||||
id: 'cqa1', n: 'QA Custom Thrust', bp: 'upper legs', eq: 'barbell', custom: true, desc: '',
|
||||
tg: 'gluteal', sm: ['forearm', 'hip-flexors'], primaries: ['gluteal'], secondaries: ['forearm', 'hip-flexors'],
|
||||
muscleGroups: ['gluteal', 'forearm', 'hip-flexors'], ...over,
|
||||
})
|
||||
function seed(ex) {
|
||||
useStore.setState(s => ({ S: { ...s.S, customEx: [ex] } }))
|
||||
registerCustom([ex])
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
globalThis.IS_REACT_ACT_ENVIRONMENT = true
|
||||
useUI.setState({ sheets: [], toastMsg: '' })
|
||||
useStore.setState({ S: structuredClone(DEF), user: null })
|
||||
registerCustom([])
|
||||
_setLangState('en', null, null, null)
|
||||
document.body.innerHTML = ''
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
act(() => { mounted.splice(0).forEach(root => root.unmount()) })
|
||||
_setLangState('en', null, null, null)
|
||||
registerCustom([])
|
||||
})
|
||||
|
||||
describe('muscle names in the rows and tags (QA C9)', () => {
|
||||
it('picker row shows the display name, not the map id', () => {
|
||||
seed(custom())
|
||||
exercisePicker(vi.fn())
|
||||
const host = renderTop()
|
||||
act(() => type(host.querySelector('input.input'), 'QA Custom'))
|
||||
expect(rowFor(host, 'QA Custom Thrust').querySelector('.ss').textContent).toBe('Glutes · barbell')
|
||||
})
|
||||
|
||||
it('config sheet tags read like the detail sheet, for a custom exercise and for power clean', () => {
|
||||
seed(custom())
|
||||
exConfigSheet(EXIDX.cqa1, null, vi.fn())
|
||||
const tags = h => [...h.querySelectorAll('.tag')].map(e => e.textContent.trim())
|
||||
expect(tags(renderTop())).toEqual(['Glutes', 'barbell', 'Forearms', 'Hip flexors'])
|
||||
// #207 Olympic lifts list their secondaries as map ids ('forearm', 'deltoids').
|
||||
exConfigSheet(EXIDX['0648'], null, vi.fn())
|
||||
expect(tags(renderTop())).toEqual(['hamstrings', 'barbell', 'Calves', 'Forearms', 'Shoulders'])
|
||||
})
|
||||
|
||||
it('translates them in German too — "forearm" was staying English', () => {
|
||||
_setLangState('de', de, null, null)
|
||||
seed(custom())
|
||||
exConfigSheet(EXIDX['0648'], null, vi.fn())
|
||||
const tags = [...renderTop().querySelectorAll('.tag')].map(e => e.textContent.trim())
|
||||
expect(tags).toEqual(['Beinbeuger', 'Langhantel', 'Waden', 'Unterarme', 'Schultern'])
|
||||
exercisePicker(vi.fn())
|
||||
const host = renderTop()
|
||||
act(() => type(host.querySelector('input.input'), 'QA Custom'))
|
||||
expect(rowFor(host, 'QA Custom Thrust').querySelector('.ss').textContent).toBe('Gesäß · Langhantel')
|
||||
})
|
||||
|
||||
// The dataset's cardio target "cardiovascular system" is both a map id and a translated key
|
||||
// of its own. Routing it through MUSCLE_NAME must not cost it its translation: the 29
|
||||
// built-in cardio exercises read "Herz-Kreislauf" in German, never "Cardiovascular system".
|
||||
it('keeps the cardio target translated (burpee, de)', () => {
|
||||
_setLangState('de', de, null, null)
|
||||
exercisePicker(vi.fn())
|
||||
const host = renderTop()
|
||||
act(() => type(host.querySelector('input.input'), 'burpee'))
|
||||
expect(rowFor(host, 'burpee').querySelector('.ss').textContent).toBe('Herz-Kreislauf · Körpergewicht')
|
||||
exConfigSheet(EXIDX['1160'], null, vi.fn())
|
||||
const tags = [...renderTop().querySelectorAll('.tag')].map(e => e.textContent.trim())
|
||||
expect(tags).toEqual(['Cardio', 'Herz-Kreislauf', 'Körpergewicht'])
|
||||
})
|
||||
|
||||
it('Muscles explorer row names the target the same way', () => {
|
||||
seed(custom())
|
||||
const host = render(<MuscleExplorer onDetail={vi.fn()} onPlan={vi.fn()} />)
|
||||
const chip = [...host.querySelectorAll('.chip[aria-pressed]')].find(e => e.textContent.startsWith('Glutes'))
|
||||
act(() => chip.click())
|
||||
act(() => type(host.querySelector('.search input'), 'QA Custom'))
|
||||
expect(rowFor(host, 'QA Custom Thrust').querySelector('.ss').textContent).toBe('Primary target · Glutes · barbell')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,56 @@
|
||||
// @vitest-environment happy-dom
|
||||
// Importing a one-routine plan file toasted "Added 1 routines to your plan" (QA copy): the
|
||||
// sheet's summary line already picked the singular, the toast after the merge did not.
|
||||
import React, { act } from 'react'
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import { useStore } from './store/useStore.js'
|
||||
import { useUI } from './store/useUI.js'
|
||||
import { planImportSheet } from './sheets.jsx'
|
||||
import { parsePlan } from './lib/plan-share.js'
|
||||
import { EXDB } from './lib/exercises.js'
|
||||
|
||||
const clone = v => JSON.parse(JSON.stringify(v))
|
||||
const ids = EXDB.filter(e => e.bp !== 'cardio').slice(0, 2).map(e => e.id)
|
||||
const mounted = []
|
||||
|
||||
function renderTop() {
|
||||
const sheet = useUI.getState().sheets.at(-1)
|
||||
const host = document.createElement('div')
|
||||
document.body.appendChild(host)
|
||||
const root = createRoot(host)
|
||||
mounted.push(root)
|
||||
act(() => root.render(sheet.render(() => useUI.getState().closeSheet(sheet.id))))
|
||||
return host
|
||||
}
|
||||
const buttonFor = (host, label) => [...host.querySelectorAll('button')].find(b => b.textContent === label)
|
||||
const bundleOf = routines => parsePlan({ opengym_plan: 1, unit: 'kg', week: {}, routines, customEx: [] }, 'kg')
|
||||
const routine = (id, name) => ({ id, name, emoji: null, ex: [{ id: ids[0], sets: 3, reps: 8, weight: 40 }] })
|
||||
|
||||
beforeEach(() => {
|
||||
globalThis.IS_REACT_ACT_ENVIRONMENT = true
|
||||
useUI.setState({ sheets: [], toastMsg: '' })
|
||||
document.body.innerHTML = ''
|
||||
const S = clone(useStore.getState().S)
|
||||
S.routines = []
|
||||
S.week = {}
|
||||
useStore.setState({ S, user: null })
|
||||
})
|
||||
afterEach(() => { act(() => { mounted.splice(0).forEach(r => r.unmount()) }) })
|
||||
|
||||
describe('Plan import sheet — the toast counts what it added', () => {
|
||||
it('says "1 routine" for a single routine', () => {
|
||||
planImportSheet(bundleOf([routine('a', 'Push')]))
|
||||
const host = renderTop()
|
||||
act(() => { buttonFor(host, 'Add to my plan').click() })
|
||||
expect(useStore.getState().S.routines).toHaveLength(1)
|
||||
expect(useUI.getState().toastMsg).toBe('Added 1 routine to your plan')
|
||||
})
|
||||
|
||||
it('keeps the plural for several', () => {
|
||||
planImportSheet(bundleOf([routine('a', 'Push'), routine('b', 'Pull')]))
|
||||
const host = renderTop()
|
||||
act(() => { buttonFor(host, 'Add to my plan').click() })
|
||||
expect(useUI.getState().toastMsg).toBe('Added 2 routines to your plan')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,55 @@
|
||||
// @vitest-environment happy-dom
|
||||
import React, { act } from 'react'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import { EXDB } from './lib/exercises.js'
|
||||
import { useStore } from './store/useStore.js'
|
||||
import { useUI } from './store/useUI.js'
|
||||
import { exConfigSheet } from './sheets.jsx'
|
||||
|
||||
// A weighted machine exercise: double progression adds the two rep steppers and the
|
||||
// Epley deload stepper, four in one row (QA C6).
|
||||
const ex = EXDB.find(e => e.id === '0009')
|
||||
const mounted = []
|
||||
|
||||
function renderConfig(cfg) {
|
||||
exConfigSheet(ex, { sets: 3, reps: 10, weight: 40, mode: 'reps', ...cfg }, vi.fn())
|
||||
const sheet = useUI.getState().sheets.at(-1)
|
||||
const host = document.createElement('div')
|
||||
document.body.appendChild(host)
|
||||
const root = createRoot(host)
|
||||
mounted.push(root)
|
||||
act(() => root.render(sheet.render(() => useUI.getState().closeSheet(sheet.id))))
|
||||
const row = [...host.querySelectorAll('.cfgrow')].find(r => r.querySelector('.stp-l')?.textContent.startsWith('Step'))
|
||||
return { host, row }
|
||||
}
|
||||
|
||||
describe('exercise configuration progression row', () => {
|
||||
beforeEach(() => {
|
||||
globalThis.IS_REACT_ACT_ENVIRONMENT = true
|
||||
useUI.setState({ sheets: [] })
|
||||
useStore.setState(s => ({ S: { ...s.S, unit: 'kg' } }))
|
||||
document.body.innerHTML = ''
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
act(() => { mounted.splice(0).forEach(root => root.unmount()) })
|
||||
})
|
||||
|
||||
it('marks the four-stepper double-progression row so it can wrap into pairs on phones', () => {
|
||||
const { row } = renderConfig({ prog: 'double' })
|
||||
expect(row.querySelectorAll('.stp-w')).toHaveLength(4)
|
||||
expect(row.classList.contains('cfgrow-4')).toBe(true)
|
||||
})
|
||||
|
||||
it('leaves the shorter rows alone', () => {
|
||||
// linear on a weighted exercise: Step + Deload, two steppers
|
||||
const linear = renderConfig({ prog: 'linear' })
|
||||
expect(linear.row.querySelectorAll('.stp-w')).toHaveLength(2)
|
||||
expect(linear.row.classList.contains('cfgrow-4')).toBe(false)
|
||||
// double on a body-weight exercise: no Epley deload, three steppers
|
||||
const bw = renderConfig({ prog: 'double', weight: 0, bodyweight: true })
|
||||
expect(bw.row.querySelectorAll('.stp-w')).toHaveLength(3)
|
||||
expect(bw.row.classList.contains('cfgrow-4')).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,100 @@
|
||||
// @vitest-environment happy-dom
|
||||
import React, { act } from 'react'
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import { useStore } from './store/useStore.js'
|
||||
import { useUI } from './store/useUI.js'
|
||||
import { bwSheet } from './sheets.jsx'
|
||||
|
||||
// The big weight read-out (body weight, goal, top weight after an exercise) used to be text:
|
||||
// the only ways to a number were the slider, ±0.1 and the ±0.5/±1 chips, so 72.3 → 85.7 was a
|
||||
// drag you then corrected tap by tap. It is a field now. These pin the two things that make
|
||||
// typing into it usable — a half-typed value is not clamped back at you, and the controls
|
||||
// around it carry on from what you typed — plus the ceiling: the slider stops at 300 kg, a
|
||||
// typed weight does not.
|
||||
const mounted = []
|
||||
|
||||
function type(el, value) {
|
||||
Object.getOwnPropertyDescriptor(el.constructor.prototype, 'value').set.call(el, value)
|
||||
el.dispatchEvent(new Event('input', { bubbles: true }))
|
||||
}
|
||||
|
||||
function renderBw() {
|
||||
bwSheet()
|
||||
const sheet = useUI.getState().sheets.at(-1)
|
||||
const host = document.createElement('div')
|
||||
document.body.appendChild(host)
|
||||
const root = createRoot(host)
|
||||
mounted.push(root)
|
||||
act(() => root.render(sheet.render(() => useUI.getState().closeSheet(sheet.id))))
|
||||
const input = host.querySelector('.bw-read input')
|
||||
const slider = host.querySelector('.sld')
|
||||
const button = label => [...host.querySelectorAll('button')].find(b => (b.getAttribute('aria-label') || b.textContent.trim()) === label)
|
||||
return { host, input, slider, button }
|
||||
}
|
||||
|
||||
describe('weight read-out is a typable field', () => {
|
||||
beforeEach(() => {
|
||||
globalThis.IS_REACT_ACT_ENVIRONMENT = true
|
||||
useUI.setState({ sheets: [] })
|
||||
useStore.setState(s => ({ S: { ...s.S, unit: 'kg', bodyweight: [] } }))
|
||||
document.body.innerHTML = ''
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
act(() => { mounted.splice(0).forEach(root => root.unmount()) })
|
||||
})
|
||||
|
||||
it('shows the current weight in a decimal field with the unit beside it', () => {
|
||||
const { input, host } = renderBw()
|
||||
expect(input).toBeTruthy()
|
||||
expect(input.value).toBe('70')
|
||||
expect(input.getAttribute('inputmode')).toBe('decimal')
|
||||
expect(input.getAttribute('aria-label')).toBe('Weight (kg)')
|
||||
expect(host.querySelector('.bw-read .u').textContent.trim()).toBe('kg')
|
||||
})
|
||||
|
||||
it('keeps a half-typed value on screen instead of clamping it, and moves the slider with it', () => {
|
||||
const { input, slider } = renderBw()
|
||||
act(() => type(input, ''))
|
||||
expect(input.value).toBe('')
|
||||
|
||||
act(() => type(input, '8'))
|
||||
expect(input.value).toBe('8')
|
||||
|
||||
act(() => type(input, '82,5'))
|
||||
expect(input.value).toBe('82.5')
|
||||
expect(slider.getAttribute('aria-valuenow')).toBe('82.5')
|
||||
})
|
||||
|
||||
it('steps on from the typed value and saves what ends up on screen', () => {
|
||||
const { input, button } = renderBw()
|
||||
act(() => type(input, '82.5'))
|
||||
act(() => button('plus 0.1').click())
|
||||
expect(input.value).toBe('82.6')
|
||||
|
||||
act(() => button('Save').click())
|
||||
const bw = useStore.getState().S.bodyweight
|
||||
expect(bw).toHaveLength(1)
|
||||
expect(bw[0].w).toBe(82.6)
|
||||
expect(useUI.getState().sheets).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('lets a typed weight sit past the slider ceiling rather than cutting it off', () => {
|
||||
const { input, slider, button } = renderBw()
|
||||
act(() => type(input, '320'))
|
||||
expect(input.value).toBe('320')
|
||||
expect(slider.getAttribute('aria-valuenow')).toBe('300')
|
||||
|
||||
act(() => button('Save').click())
|
||||
expect(useStore.getState().S.bodyweight[0].w).toBe(320)
|
||||
})
|
||||
|
||||
it('still refuses to save an empty field', () => {
|
||||
const { input, button } = renderBw()
|
||||
act(() => type(input, ''))
|
||||
act(() => button('Save').click())
|
||||
expect(useStore.getState().S.bodyweight).toHaveLength(0)
|
||||
expect(useUI.getState().sheets).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
@@ -21,7 +21,7 @@ const SYNC_KEY = 'gym_sync'
|
||||
const CHECK_MIN_MS = 3000 // rev checks closer together than this are the same event (focus + visibility)
|
||||
const POLL_MS = 30000 // while the app is open and signed in, ask the server for its revision this often
|
||||
export const DEF = {
|
||||
unit: 'kg', restSec: 90, restPauseSec: 15, sound: true, timerFlash: false, keepAwake: true, lang: 'en',
|
||||
unit: 'kg', restSec: 90, restPauseSec: 15, sound: true, soundOnSilent: false, timerFlash: false, keepAwake: true, lang: 'en',
|
||||
theme: 'dark', accent: 'lime', body: 'male', targetW: null,
|
||||
bodyweight: [], routines: [], week: {}, dayPlan: {},
|
||||
exWeights: {}, workouts: [], active: null, customEx: [], gifSize: 'full',
|
||||
@@ -55,6 +55,9 @@ export const DEF = {
|
||||
// every profile written before this setting existed keeps the week it has been looking at.
|
||||
// See lib/format.js: nothing reads this field directly, everything goes through the helpers.
|
||||
weekStart: 1,
|
||||
// Decimals on displayed weights: 1 by default, 2 for anyone loading quarter plates or
|
||||
// microplates (issue #139). Display only — nothing is stored or rounded differently.
|
||||
wdec: 1,
|
||||
// Per-exercise bar weight overrides, keyed by exercise id, in the profile unit (see
|
||||
// lib/bar.js). Personal equipment, so it syncs with the account but never travels in a
|
||||
// shared plan. Logged weights stay the total — this only feeds the plate math.
|
||||
|
||||
@@ -14,7 +14,6 @@ const pushRestTimer = sec => { if (useStore.getState().user) api('/api/push/rest
|
||||
const cancelPushRestTimer = () => { if (useStore.getState().user) api('/api/push/rest-timer/cancel', { method: 'POST', body: JSON.stringify({ deviceId: deviceId() }) }).catch(() => {}) }
|
||||
|
||||
const notificationsSupported = () => typeof window !== 'undefined' && 'Notification' in window
|
||||
let requestRestNotificationPermissionP = null
|
||||
|
||||
// Set the moment the tab goes hidden, never cleared here — timerTick/workTick read and
|
||||
// clear it themselves once they're running visible again. Lets a completion tick tell
|
||||
@@ -26,34 +25,28 @@ if (typeof document !== 'undefined') {
|
||||
document.addEventListener('visibilitychange', () => { if (document.hidden) pageHiddenAt = Date.now() })
|
||||
}
|
||||
|
||||
const requestRestNotificationPermission = async () => {
|
||||
if (!notificationsSupported()) return false
|
||||
if (Notification.permission === 'granted') return true
|
||||
if (Notification.permission === 'denied') return false
|
||||
if (!requestRestNotificationPermissionP) {
|
||||
requestRestNotificationPermissionP = Notification.requestPermission()
|
||||
.then(perm => perm === 'granted')
|
||||
.catch(() => false)
|
||||
.finally(() => {
|
||||
requestRestNotificationPermissionP = null
|
||||
})
|
||||
}
|
||||
return requestRestNotificationPermissionP
|
||||
// The Push switch in Settings is the one place notifications are turned on, and "on" means this
|
||||
// browser holds a push subscription. This local alert used to ignore it: every rest asked for the
|
||||
// permission by itself, and once granted — a page cannot hand a permission back — it fired with the
|
||||
// switch off (issue #239). Off is off now; the permission is only ever asked for by the switch.
|
||||
const restAlertsOn = async reg => {
|
||||
if (Notification.permission !== 'granted') return false
|
||||
try { return !!(await reg?.pushManager?.getSubscription?.()) } catch { return false }
|
||||
}
|
||||
|
||||
const maybeRestNotification = async () => {
|
||||
if (!notificationsSupported()) return
|
||||
if (!document.hidden && document.visibilityState !== 'hidden') return
|
||||
if (Notification.permission !== 'granted' && !(await requestRestNotificationPermission())) return
|
||||
try {
|
||||
const reg = await navigator.serviceWorker?.getRegistration?.()
|
||||
if (!(await restAlertsOn(reg))) return
|
||||
// Same tag as the server's push (api/push-messages.js): whichever lands second replaces the
|
||||
// first instead of stacking a second banner. No body — it only repeated the title.
|
||||
// Android Chrome forbids the Notification constructor (Illegal constructor) - the
|
||||
// service-worker registration path is the one that actually pops there.
|
||||
const reg = await navigator.serviceWorker?.getRegistration?.()
|
||||
if (reg?.showNotification) {
|
||||
reg.showNotification(t('Rest over — next set!'), { body: t('Rest over — next set!') })
|
||||
return
|
||||
}
|
||||
new Notification(t('Rest over — next set!'), { body: t('Rest over — next set!') })
|
||||
const opts = { tag: 'rest-timer', icon: 'icon-512.png' }
|
||||
if (reg?.showNotification) { reg.showNotification(t('Rest over — next set!'), opts); return }
|
||||
new Notification(t('Rest over — next set!'), opts)
|
||||
} catch {
|
||||
// Intentionally ignore: notification APIs vary by browser and policy in edge cases.
|
||||
}
|
||||
@@ -101,7 +94,6 @@ export const useUI = create((set, get) => ({
|
||||
if (!(sec > 0)) return
|
||||
const endsAt = Date.now() + sec * 1000
|
||||
set({ timer: { left: sec, total: sec, endsAt, forIdx } })
|
||||
requestRestNotificationPermission()
|
||||
pushRestTimer(sec)
|
||||
timerTick = () => {
|
||||
const tm = get().timer
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
// @vitest-environment happy-dom
|
||||
// Issue #239: the local "rest over" alert ignored the Push switch in Settings. Every rest asked
|
||||
// for the notification permission on its own, and once granted it fired with the switch off —
|
||||
// a page cannot give a permission back. "On" is this browser holding a push subscription.
|
||||
import { describe, expect, it, beforeEach, afterEach, vi } from 'vitest'
|
||||
import { useUI } from './useUI.js'
|
||||
import { useStore } from './useStore.js'
|
||||
|
||||
let showNotification, requestPermission, subscription, originalSettings
|
||||
const hide = hidden => {
|
||||
Object.defineProperty(document, 'hidden', { configurable: true, get: () => hidden })
|
||||
Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => hidden ? 'hidden' : 'visible' })
|
||||
document.dispatchEvent(new Event('visibilitychange'))
|
||||
}
|
||||
const runOut = async () => {
|
||||
useUI.getState().startRest(2)
|
||||
hide(true)
|
||||
await vi.advanceTimersByTimeAsync(3000)
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
originalSettings = useStore.getState().S
|
||||
useStore.setState({ S: { ...originalSettings, sound: false }, user: null })
|
||||
useUI.setState({ timer: null })
|
||||
showNotification = vi.fn()
|
||||
requestPermission = vi.fn(async () => 'granted')
|
||||
subscription = null
|
||||
globalThis.Notification = Object.assign(vi.fn(), { permission: 'granted', requestPermission })
|
||||
window.Notification = globalThis.Notification
|
||||
Object.defineProperty(navigator, 'serviceWorker', {
|
||||
configurable: true,
|
||||
value: { getRegistration: async () => ({ showNotification, pushManager: { getSubscription: async () => subscription } }) },
|
||||
})
|
||||
})
|
||||
afterEach(() => {
|
||||
useUI.getState().stopRest()
|
||||
hide(false)
|
||||
useStore.setState({ S: originalSettings })
|
||||
delete globalThis.Notification
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
describe('the local rest-over alert follows the Push switch', () => {
|
||||
it('stays silent with the switch off, even though the permission is granted', async () => {
|
||||
await runOut()
|
||||
expect(showNotification).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('fires once with the switch on, tagged like the server push, without repeating the title', async () => {
|
||||
subscription = { endpoint: 'https://push.example/x' }
|
||||
await runOut()
|
||||
expect(showNotification).toHaveBeenCalledTimes(1)
|
||||
const [title, opts] = showNotification.mock.calls[0]
|
||||
expect(title).toBe('Rest over — next set!')
|
||||
expect(opts.tag).toBe('rest-timer')
|
||||
expect(opts.body).toBeUndefined()
|
||||
})
|
||||
|
||||
it('never asks for the permission by itself — only the switch does', async () => {
|
||||
globalThis.Notification.permission = 'default'
|
||||
await runOut()
|
||||
expect(requestPermission).not.toHaveBeenCalled()
|
||||
expect(showNotification).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||