Merge merge request !20 (intensifiers, pairing, theme, security hardening)
Takes the nine commits as submitted, with three adjustments: - remote.test.js ran in the node environment while remote.js pulls in api.js, which reads navigator.userAgent at module scope — the file failed to import. Same @vitest-environment happy-dom pragma the api tests use. - Drops skills-lock.json. It pins a personal Claude Code skill chain to third-party GitHub repos by hash; that is contributor tooling, not a project artefact, and this project's GitHub access is gone. CLAUDE.md itself is kept — it is an accurate description of the repo. - Corrects two stale claims in that CLAUDE.md: the website deploys from .gitlab-ci.yml, not GitHub Pages, and the CI gate is GitLab, not Gitea Actions with a dormant GitHub copy. pt-BR: 23 of the 44 new pt strings are European (ficheiro, telemóvel, Definições, «guillemets», tu-forms), so they get Brazilian overrides rather than being inherited; fingerprint re-baselined.
This commit is contained in:
commit
7d2460c2c2
47 files changed
+2296
-109
No files matched your search
+20
-6
@@ -70,12 +70,26 @@ RP_NAME=openGym
|
||||
# AUDIT_IP=full # the whole address
|
||||
#
|
||||
# The address is read from CF-Connecting-IP, then the first entry of
|
||||
# X-Forwarded-For, then X-Real-IP. The web container sets the last two, so the
|
||||
# bundled stack is correct as-is. Cloudflare is first in that list on purpose: a
|
||||
# Cloudflare tunnel does not put the visitor in X-Forwarded-For at all, so that
|
||||
# header would otherwise record the tunnel itself and look perfectly plausible.
|
||||
# Whatever you run in front has to overwrite these headers rather than pass a
|
||||
# client-supplied one through — they are only as trustworthy as your proxy.
|
||||
# X-Forwarded-For, then X-Real-IP, and finally the connecting socket itself if
|
||||
# none of those is present.
|
||||
#
|
||||
# A forwarded-for header is only worth anything if whatever sits in front
|
||||
# OVERWRITES it instead of passing a client-supplied one through — otherwise a
|
||||
# caller simply states the address it would like logged. The web container now
|
||||
# overwrites X-Forwarded-For and X-Real-IP with the real peer, and DROPS
|
||||
# CF-Connecting-IP, so the bundled stack records an address nobody can choose.
|
||||
# (Before, X-Forwarded-For was appended to rather than replaced, and
|
||||
# CF-Connecting-IP was passed straight through — both were forgeable.)
|
||||
#
|
||||
# Cloudflare is first in that list on purpose: a Cloudflare tunnel does not put
|
||||
# the visitor in X-Forwarded-For at all, so that header would otherwise record
|
||||
# the tunnel itself and look perfectly plausible. If — and only if — Cloudflare
|
||||
# is genuinely in front of you, let its header through again:
|
||||
#
|
||||
# CF_CONNECTING_IP=$http_cf_connecting_ip
|
||||
#
|
||||
# That is safe there because Cloudflare sets the header itself, replacing
|
||||
# anything the client sent. Anywhere else, leave it unset.
|
||||
|
||||
# ── Session length (optional) ──────────────────────────────────────────────
|
||||
# How long a sign-in lasts, in days. Default 90 — long enough that people who
|
||||
|
||||
@@ -14,3 +14,5 @@ node_modules/
|
||||
*.log
|
||||
.DS_Store
|
||||
node_modules
|
||||
.claude/
|
||||
.agents/
|
||||
@@ -0,0 +1,136 @@
|
||||
# CLAUDE.md
|
||||
|
||||
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
||||
|
||||
## What this is
|
||||
|
||||
openGym is a self-hosted gym & body-weight tracker PWA. Two containers (`api` + `web`) plus a
|
||||
`./data` folder the user owns — no third-party account, no telemetry. Passkey (WebAuthn) login,
|
||||
installable as a home-screen app, optional Capacitor shells for standalone Android/iOS builds.
|
||||
License: AGPL-3.0-or-later.
|
||||
|
||||
## Project layout
|
||||
|
||||
```
|
||||
frontend/ React 19 + Vite app (src/views, src/components, src/store, src/lib). Builds to static files.
|
||||
android/ + ios/ are the Capacitor shells for the standalone mobile app (docs/MOBILE.md).
|
||||
api/ backend — server.js (Node, no framework), deps: @simplewebauthn/server, web-push.
|
||||
web/ multi-stage Dockerfile (builds frontend → nginx) + nginx.conf.template (serves app, proxies /api).
|
||||
mcp/ optional MCP server — read-only stdio bridge exposing a user's workouts/1RM/muscle
|
||||
balance to LLM clients (Claude Desktop, Cursor…). Not part of the Docker build; only
|
||||
runs when an LLM client spawns it.
|
||||
media/ exercise img/gif, gitignored, fetched at runtime by the `media` compose service.
|
||||
website/ static marketing site (plain HTML/CSS/JS), deployed separately by .gitlab-ci.yml.
|
||||
docs/ SELF_HOSTING.md, MOBILE.md.
|
||||
```
|
||||
|
||||
## Commands
|
||||
|
||||
```bash
|
||||
# Local stack (api + web + media, prebuilt or built from source)
|
||||
cp .env.example .env
|
||||
docker compose up -d --build
|
||||
|
||||
# Frontend dev server (hot reload), proxies /api to :3000
|
||||
cd frontend && npm install && npm run dev
|
||||
|
||||
# Frontend tests (training logic: progression, 1RM, session read-back)
|
||||
cd frontend && npm test # vitest run
|
||||
cd frontend && npm run test:watch
|
||||
npx vitest run src/lib/progression.test.js # single file
|
||||
npx vitest run -t "some test name" # single test by name
|
||||
|
||||
# MCP server tests
|
||||
cd mcp && npm test
|
||||
|
||||
# Production build
|
||||
cd frontend && npm run build
|
||||
cd frontend && npm run build:mobile # + cap sync, points media at the CDN dataset
|
||||
```
|
||||
|
||||
There is no linter/formatter configured (no ESLint/Prettier config in the repo) and no
|
||||
TypeScript — match the existing style by hand.
|
||||
|
||||
The CI gate is `.gitlab-ci.yml` on GitLab, the canonical remote (see README): it runs the
|
||||
`frontend/` tests on Node 22 — the same version as `web/Dockerfile` / `api/Dockerfile`
|
||||
(`node:22-alpine`) — and additionally builds and publishes the Docker images, packages the
|
||||
signed Android APK, and deploys the demo/docs site. The Gitea and GitHub workflow copies
|
||||
(`.gitea/workflows/`, `.github/workflows/`) are dormant mirrors; neither host runs them.
|
||||
|
||||
## Architecture
|
||||
|
||||
### Frontend (`frontend/src`)
|
||||
|
||||
- **`store/useStore.js`** — single Zustand store holding the entire client-side app state (`S`),
|
||||
persisted to `localStorage` (`gym_state_v1`) and debounce-pushed to the server when signed in
|
||||
(`pushState`, see `lib/api.js`). On the Capacitor mobile build it's also mirrored to a file via
|
||||
`lib/mobile.js` (`nativeSave`), since WebView storage can be evicted. `store/useUI.js` holds
|
||||
ephemeral UI state (modals, active sheet, etc.) separately from persisted data.
|
||||
- **`lib/`** — pure, framework-free helpers, each paired with a same-directory `*.test.js`. This
|
||||
is where the domain logic lives, most importantly:
|
||||
- `progression.js` — the progression-rule engine (linear, Greyskull LP, double progression,
|
||||
time-based). Rules implement a shared policy interface; adding a new one plugs in here.
|
||||
- `onerm.js` — estimated 1RM from logged sets.
|
||||
- `finish-workout.js` — reduces a completed session back into state (weights advance, PRs, etc).
|
||||
- `recovery.js` / `recovery-view.js` — fatigue/muscle-recovery model.
|
||||
- `workout-model.js`, `supersetFlow.js` — in-session workout state machine, incl. supersets.
|
||||
- `exercises.js` / `exercises-data.js` — the exercise library (1,324 built-ins + user-defined).
|
||||
- `api.js` — the only place that talks to the backend (`fetch` wrapper, session cookie flows).
|
||||
- CONTRIBUTING.md is explicit: **anything that decides what you lift next, or reads a logged
|
||||
session back, is a pure helper here with a unit test beside it** — not verifiable by
|
||||
clicking, and the progression engine has already had two bugs that only a test caught.
|
||||
- **`views/`** — one file per screen (Home, Workout, Plan, Library, Stats, History, Settings,
|
||||
Admin, Login, RoutineEdit), routed by `react-router-dom` from `App.jsx`.
|
||||
- **`components/`** — shared UI (charts, modals, timers); `instr/` holds per-language exercise
|
||||
instruction text; `locales/` is the i18n string catalogue (`lib/i18n.js` / `i18n-core.js`).
|
||||
- Mobile: `@capacitor/*` wraps the same web build into native shells under `frontend/android` and
|
||||
`frontend/ios` (see `docs/MOBILE.md`); `mobile.js` in `lib/` gates native-only behavior (file
|
||||
persistence, local notifications, wake lock) behind a `MOBILE` flag.
|
||||
|
||||
### API (`api/server.js`)
|
||||
|
||||
Single file, no framework, plain `node:http`. Requests are dispatched through a `routes` object
|
||||
keyed by `'METHOD /path'` (e.g. `routes['GET /api/health']`) matched against `req.method + ' ' +
|
||||
url.pathname` — add a new endpoint by adding a key here. State is two flat JSON files under
|
||||
`DATA_DIR` (`db.json`: users/credentials/subscriptions/invites; `state-<uid>.json`: per-user
|
||||
workout data), written with a write-temp-then-rename atomic pattern (`atomicWrite`). Auth is
|
||||
WebAuthn passkeys (`@simplewebauthn/server`) plus a signed session cookie (HMAC'd with a
|
||||
`DATA_DIR/secret` generated on first boot) — no JWT/session-store dependency. Optional pieces
|
||||
gated by env vars: `ADMIN_UIDS` (admin dashboard), `INVITE_ONLY` (signup needs a code),
|
||||
`ALLOW_GUEST` (client-only guest mode never hits the server at all), plus a rotating
|
||||
`data/audit.log` (JSONL) for sign-in/admin events. Web Push (`web-push`, VAPID keys
|
||||
auto-generated into `data/vapid.json`) drives rest-timer-over and day-reminder notifications.
|
||||
|
||||
### MCP server (`mcp/src`)
|
||||
|
||||
Read-only stdio MCP bridge (`@modelcontextprotocol/sdk`) that lets an LLM client read a single
|
||||
user's routines/workouts/body-weight/1RM/muscle-balance directly from the same `DATA_DIR` the API
|
||||
writes to — no network call, no extra container. `state.js` loads/derives the data, `tools.js`
|
||||
defines the exposed MCP tools (zod-validated schemas), `labels.js` maps internal keys to
|
||||
human-readable labels, `index.js` wires it together. See `mcp/README.md` for the client-config
|
||||
side (Claude Desktop / Cursor).
|
||||
|
||||
### Passkeys and self-hosting constraints
|
||||
|
||||
WebAuthn passkeys are bound to an exact hostname (`RP_ID`) and require HTTPS (localhost excepted)
|
||||
— this shapes a lot of the API and Settings code (`RP_ID`/`ORIGIN` env vars, guest-mode fallback
|
||||
when neither is available). Read `docs/SELF_HOSTING.md` before touching auth, session, or
|
||||
notification code; it documents the exact env-var contract (`RP_ID`, `ORIGIN`, `PORT`,
|
||||
`WEB_PORT`, `NGINX_PORT`, `BACKEND`, `SESSION_DAYS`, `ADMIN_UIDS`, `INVITE_ONLY`, `ALLOW_GUEST`,
|
||||
`AUDIT_*`, `VAPID_SUBJECT`) that real deployments depend on.
|
||||
|
||||
### Docker / deploy
|
||||
|
||||
`docker-compose.yml` has three services: `media` (one-shot exercise-asset downloader, gitignored
|
||||
output), `api`, `web` (multi-stage build of `frontend/` served by nginx, which also proxies
|
||||
`/api` → `api` and serves the shared media volume — single origin, required for passkeys).
|
||||
`web/nginx.conf.template` is rendered from env vars at container start (`NGINX_PORT`, `BACKEND`,
|
||||
`PORT`), so host/port remapping works against prebuilt images without a rebuild.
|
||||
|
||||
## Guidelines from CONTRIBUTING.md worth knowing before changing code
|
||||
|
||||
- **Dependency-light is a hard constraint, not a preference.** Frontend: React + Router + Zustand
|
||||
and nothing else. `api/`: two dependencies total. New dependencies are a hard sell either side.
|
||||
- Don't commit `media/` or `data/` (gitignored).
|
||||
- Training-logic changes (progression, 1RM, session read-back) need a unit test in `src/lib`
|
||||
beside the code, not just manual clicking-through.
|
||||
@@ -0,0 +1,188 @@
|
||||
# PROJECT_CONTEXT.md
|
||||
|
||||
Notes for whoever picks this up next. Not a spec — a map of what changed and why, kept next to
|
||||
the code it describes. See `CLAUDE.md` for the general architecture; this file only covers the
|
||||
drop-set / rest-pause work.
|
||||
|
||||
## What this adds
|
||||
|
||||
Two new set "shapes" on top of the existing straight/warm-up model:
|
||||
|
||||
- **Drop-set**: a main set followed by one or more weight drops, logged with no real rest.
|
||||
- **Rest-pause / myo-reps**: an activation set (a normal set near failure) followed by short
|
||||
bursts of extra reps, each preceded by a brief rest.
|
||||
|
||||
Both are **planned on the exercise**, in the same config sheet used by the routine editor and by
|
||||
"add exercise" mid-workout (`ExConfig` in `sheets.jsx`) — not decided live during the workout.
|
||||
Planning it stamps every set of that exercise and pre-fills the actual drop/burst rows with
|
||||
real, already-editable numbers the moment the session starts. A straight (unplanned) set can
|
||||
still grow a drop/burst live via "+ Drop"/"+ Burst" — that path never went away, it just isn't
|
||||
the primary one anymore.
|
||||
|
||||
## The set row (`frontend/src/lib/workout-model.js`)
|
||||
|
||||
There was never a `type` enum on a set row before this — only `phase` (`'work'` / `'warmup'`,
|
||||
with a legacy `warmup: true` boolean as fallback). This adds a **second, orthogonal**
|
||||
discriminator, `type`:
|
||||
|
||||
```js
|
||||
phase: 'work' | 'warmup' // existing axis — prep or the real session?
|
||||
type: 'straight' | 'dropset' | 'restpause' // new axis — what shape is this row? (default 'straight')
|
||||
```
|
||||
|
||||
A drop-set or rest-pause row is still exactly one entry in `entry.sets` — the extra work rides
|
||||
*inside* that row, the same trick `phase` already uses for warm-ups:
|
||||
|
||||
```js
|
||||
// dropset — main set + extra drops ON TOP of it (extraVolumeOf adds the drops back in for totals)
|
||||
{ type: 'dropset', w: 100, r: 5, done: true, drops: [{ w: 80, r: 5 }, { w: 64, r: 5 }] }
|
||||
|
||||
// restpause — the row's own r IS the total across every burst; clusters are a BREAKDOWN of that
|
||||
// same total, not extra on top of it (12 → [6, 3, 2, 1], and 6+3+2+1 == 12, always)
|
||||
{ type: 'restpause', w: 60, r: 12, done: true, clusters: [{ r: 6, restSec: 15 }, { r: 3, restSec: 15 }, { r: 2, restSec: 15 }, { r: 1, restSec: 15 }] }
|
||||
```
|
||||
|
||||
Those two extras genuinely mean different things, which trips people up (it tripped this
|
||||
implementation up first): a drop-set's `drops` are *additional* work beyond the main set — the
|
||||
main set stays a real, separate effort. A rest-pause row's `clusters` are the *decomposition* of
|
||||
its own `r` — there is no separate "first burst is the real one" distinction, `r` already speaks
|
||||
for the whole thing. Getting this backwards is exactly the bug this file's earlier revision had:
|
||||
`r` held only the split's biggest chunk, so the row displayed a random-looking fraction of what
|
||||
was configured instead of the number that was actually typed in.
|
||||
|
||||
Pure helpers in `workout-model.js`, mirroring the existing `phaseForSet`/`isWarmupRow` style:
|
||||
|
||||
- `setType(set)`, `isDropSet(set)`, `isRestPauseSet(set)` — read the discriminator.
|
||||
- `dropsOf(set)` / `clustersOf(set)` — the extras array, or `[]` for anything else.
|
||||
- `extraVolumeOf(set)` — weight×reps across a drop-set's `drops`, on top of the row's own w×r.
|
||||
**Zero for rest-pause** — see above, its `clusters` never add to this or they'd double-count.
|
||||
- `addDrop(set, drop)` / `addCluster(set, cluster)` — pure append, stamps `type`.
|
||||
- `removeDropAt(set, i)` / `removeClusterAt(set, i)` — pure remove by index; clearing the last
|
||||
one reverts the row to `'straight'`.
|
||||
- `setDropAt(set, i, patch)` / `setClusterAt(set, i, patch)` — pure in-place edit (the weight/reps
|
||||
steppers on an already-added drop/burst).
|
||||
- `nextDropWeight(prevWeight, pct)` — pct% lighter than `prevWeight`, rounded to the nearest .5.
|
||||
- `nextBurstReps(prevReps)` — roughly half of `prevReps`, floored at 1.
|
||||
- `splitBurstReps(total)` — splits a rest-pause **total** rep count into a descending,
|
||||
roughly-halving sequence of bursts that sums back to it (`12 → [6, 3, 2, 1]`). This is what a
|
||||
planned rest-pause exercise configures directly: you say how many total reps you want out of
|
||||
the whole rest-pause portion, not how many separate rests.
|
||||
|
||||
In `Workout.jsx`, `addBurstRow`/`removeCluster`/`setClusterField` all adjust the row's own `r` by
|
||||
the same delta as whatever they just did to `clusters`, so the invariant (`r` == sum of every
|
||||
`clustersOf` entry) survives live edits too, not just the initial plan — including the case of
|
||||
tapping "+ Burst" cold on a plain straight set, where the set's original reps become the seed a
|
||||
running total grows from rather than a separately-standing "main" effort. `addDrop`/`removeDrop`
|
||||
on a drop-set row do **not** do this — a drop-set's main set stays independent on purpose.
|
||||
|
||||
## Planning (`ExConfig` in `sheets.jsx`) → `cfg.intensifier`
|
||||
|
||||
The exercise config sheet (routine editor and mid-workout "add exercise" both use it) has an
|
||||
"Intensifier" picker: None / Drop-set / Rest-pause. Selecting one adds `intensifier` to the saved
|
||||
config:
|
||||
|
||||
```js
|
||||
// drop-set: every configured set becomes a drop-set — N drops, each pct% lighter than the one before
|
||||
{ intensifier: { type: 'dropset', count: 2, pct: 20 } }
|
||||
|
||||
// rest-pause: NOT applied per set. It replaces the exercise's whole set list with exactly two
|
||||
// rows regardless of the configured "Sets" (which the UI hides once this is selected, since it
|
||||
// no longer means anything) — a warm-up at the exercise's own "Reps" field, then one rest-pause
|
||||
// work set. Doing the full activation+bursts protocol several times over isn't how rest-pause is
|
||||
// actually trained, so this is a structural replacement, not a per-row stamp like drop-set.
|
||||
{ intensifier: { type: 'restpause', totalReps: 12, restSec: 15 } }
|
||||
```
|
||||
|
||||
`applyIntensifierPlan(sets, cfg)` (`history.js`) applies that. It must run **after**
|
||||
`applyPrescription`: a drop-set's chain of drops is a percentage of each row's own `w`, so it has
|
||||
to use the final prescribed weight, not the pre-progression one `buildSets` started from — same
|
||||
reasoning for where the two rest-pause rows get their weight from. Both call sites chain it last:
|
||||
|
||||
```js
|
||||
applyIntensifierPlan(applyPrescription(buildSets(st, cfg), plan), cfg) // beginWorkout, sheets.jsx
|
||||
applyIntensifierPlan(freestyle ? sets : applyPrescription(sets, plan), full) // add-exercise, Workout.jsx
|
||||
```
|
||||
|
||||
`buildSets` itself knows nothing about intensifiers — it only builds the plain rows (for
|
||||
rest-pause, `applyIntensifierPlan` discards all of them but the weight).
|
||||
|
||||
**Known open questions, deliberately left alone for now:**
|
||||
- The progression engine (`readSession`/`nextPrescription`) judges a rest-pause exercise's one
|
||||
non-warm-up row against `target.reps` — the exercise's plain "Reps" field (what the *warm-up*
|
||||
row uses), compared against the work row's `r`, which is now the rest-pause *total* and so is
|
||||
usually well above that goal. In practice this means a rest-pause exercise will almost always
|
||||
read as "hit the goal" and progress — not obviously wrong, but not a deliberately designed
|
||||
comparison either.
|
||||
- `onerm.js`'s `estimate1RM` refuses anything past `REP_CAP` (12 reps) as "work capacity, not
|
||||
strength" — a rest-pause row's `r` being the total means any rest-pause exercise with a total
|
||||
over 12 (most of them) never contributes a 1RM estimate or PR. Also not fixed — it falls out
|
||||
naturally from an existing, deliberate rule, not a new one, but worth knowing it applies here.
|
||||
|
||||
## Guided workout UI (`Workout.jsx`)
|
||||
|
||||
Every non-warm-up reps-mode row renders its drops/clusters as **editable sub-rows** right under
|
||||
it (`.subrow`, reusing the same stepper look as the main row, just smaller) — not read-only chips
|
||||
behind a sheet. A planned exercise arrives with these already filled in; nothing needs pressing
|
||||
for them to show up. `"+ Drop"`/`"+ Burst"` (hidden on whichever type doesn't apply to that row)
|
||||
just appends one more entry with the same suggested-next-value math
|
||||
(`nextDropWeight`/`nextBurstReps`), for a drop/burst beyond what was planned, or for turning an
|
||||
unplanned straight set into one on the spot.
|
||||
|
||||
There is deliberately **no countdown timer** for rest-pause bursts anymore (an earlier version of
|
||||
this had one, using the work-timer bar) — with the burst rows already pre-filled and editable,
|
||||
forcing a real-time countdown added friction without adding value; the short rest between bursts
|
||||
is self-timed.
|
||||
|
||||
**Testing gotcha, not a code bug:** `S.active` (the in-progress workout) and each routine's saved
|
||||
`intensifier` config both live in `localStorage` and are untouched by redeploying the container.
|
||||
Iterating on this feature while an old workout is still active, or without re-saving an
|
||||
already-configured exercise, replays stale pre-`totalReps` data. Discard the active workout and
|
||||
re-save the exercise's config after a schema change like this one.
|
||||
|
||||
## Settings (`useStore.js` DEF, `Settings.jsx`)
|
||||
|
||||
`S.restPauseSec` (default 15) is the fallback rest used when "+ Burst" is tapped on a set with no
|
||||
planned rest-pause of its own. It's a real user-editable default now — **Settings → During a
|
||||
workout → Rest-pause rest** — the same pattern as the existing `S.restSec` (long) rest timer.
|
||||
A planned exercise's own `intensifier.restSec` always overrides this.
|
||||
|
||||
## Why most of the app didn't need to change
|
||||
|
||||
1RM estimation (`onerm.js`) and the progression engine (`progression.js`) read a set row's own
|
||||
`w`/`r`/`sec` directly, never anything nested — so a drop-set's main set, or a rest-pause row's
|
||||
own total, is automatically the only thing they see; `drops`/`clusters` never had to be taught to
|
||||
either of them. What *did* need a one-line hook, because they sum across a session rather than
|
||||
reading one row:
|
||||
|
||||
- `workoutVolume` (`history.js`) — adds `extraVolumeOf(s)` on top of `w×r` per row. Drop-set
|
||||
drops count; rest-pause clusters don't (see above — they're already inside the row's own `r`).
|
||||
- `setTonnage` (`recovery.js`) — same split: `extraTonnage(...)` prices a drop-set's drops with
|
||||
the same intensity-weighted formula (`load × reps × min(1, load/1RM)^1.5`) as the main set, and
|
||||
is a no-op for rest-pause for the same double-counting reason.
|
||||
- `applyPrescription` (`progression.js`) — when a policy grows the set count (bodyweight double
|
||||
progression, issue #33), the newly appended row keeps the seed's `type` (that's the exercise's
|
||||
plan) but never its already-logged `drops`/`clusters` (that's specific work the new row never
|
||||
actually did).
|
||||
|
||||
`muscles.js`'s `loadOf` ("effective sets" for the muscle-balance map) is untouched on purpose: a
|
||||
drop-set/rest-pause row still counts as one set there, same as today — that model was never
|
||||
weight-based to begin with.
|
||||
|
||||
## Persistence
|
||||
|
||||
No backend or schema change was needed. `api/server.js` writes `state-<uid>.json` verbatim with
|
||||
no set-shape validation beyond "is an object". The MCP server (`mcp/src`) re-imports the same
|
||||
`workoutVolume`/`onerm.js`/`muscles.js` helpers from `frontend/src/lib` rather than duplicating
|
||||
them, so its reported volume/1RM figures pick up the fix automatically too.
|
||||
|
||||
## i18n
|
||||
|
||||
All new strings are translated in `locales/es.js` (the other ten locales fall back to English via
|
||||
`t()`, which is safe but not localized — nobody's asked for those yet).
|
||||
|
||||
## Out of scope for this pass
|
||||
|
||||
- Import from other apps (FitNotes/Strong/Hevy) — no equivalent concept there yet.
|
||||
- Planning which *specific* sets of an exercise get the intensifier — it's all-or-nothing per
|
||||
exercise (every set), which is what was asked for; a "last set only" option would need a
|
||||
per-row opt-out on top of this.
|
||||
+57
-24
@@ -65,9 +65,12 @@ in the thread; there's no objection, and no request to sit on it indefinitely.
|
||||
- **Missing rate limiting**, brute force, or "I sent 100k requests and it got slow". The app
|
||||
has no rate limiting at all and doesn't pretend to; that belongs in the reverse proxy you put
|
||||
in front of it. Genuine amplification (one small request causing unbounded work) *is* in scope.
|
||||
- **Missing security headers** (CSP, HSTS, X-Frame-Options) — `web/nginx.conf` sets none; TLS
|
||||
and headers are the reverse proxy's job. A concrete attack that headers would have stopped is
|
||||
still worth reporting.
|
||||
- **Missing security headers.** `web/nginx.conf.template` sets `X-Frame-Options: DENY`,
|
||||
`Content-Security-Policy: frame-ancestors 'none'`, `X-Content-Type-Options: nosniff` and
|
||||
`Referrer-Policy: same-origin`. It deliberately does **not** set HSTS or a full CSP: TLS is the
|
||||
reverse proxy's job, and a script/style policy tight enough to be worth having needs testing
|
||||
against the built app rather than being asserted here. A concrete attack that a header would
|
||||
have stopped is still worth reporting.
|
||||
- Instances served over plain `http://` on a LAN IP. Unsupported: passkeys don't work there and
|
||||
the session cookie isn't marked `Secure`.
|
||||
- Scanner output with no working exploit, and `npm audit` findings in build-time
|
||||
@@ -84,22 +87,37 @@ Read this before hosting openGym for anyone other than yourself.
|
||||
- **Passkeys only.** No passwords, no email addresses, no reset flow. Registration and login are
|
||||
verified server-side by `@simplewebauthn/server` against `expectedOrigin: ORIGIN` and
|
||||
`expectedRPID: RP_ID`, and the authenticator's signature counter is stored and updated on every
|
||||
login (`api/server.js:382-432`, `api/server.js:443-492`).
|
||||
- **Sessions are a signed cookie.** `gymsid` carries `<uid>:<expiry>:<version>` plus an
|
||||
HMAC-SHA256 tag over it, compared in constant time (`api/server.js:153-166`). The key is 32
|
||||
login (`api/server.js:561-620`, `api/server.js:622-675`).
|
||||
- **Sessions are a signed cookie.** It carries `<uid>:<expiry>:<version>` plus an
|
||||
HMAC-SHA256 tag over it, compared in constant time (`api/server.js:230-243`). The key is 32
|
||||
random bytes generated on first run and written to `./data/secret` with mode `0600`
|
||||
(`api/server.js:39-41`). The cookie is `HttpOnly` and `SameSite=Lax`, and gets `Secure` **only
|
||||
when `ORIGIN` starts with `https:`** (`api/server.js:34`, `api/server.js:205-208`).
|
||||
(`api/server.js:40-43`). The cookie is `HttpOnly` and `SameSite=Lax`, and gets `Secure` **only
|
||||
when `ORIGIN` starts with `https:`** (`api/server.js:36`, `api/server.js:316-322`). On an https
|
||||
instance it is named `__Host-gymsid`: the prefix makes the *browser* enforce that the cookie is
|
||||
host-only, which is what stops a sibling subdomain from planting a second session cookie on the
|
||||
shared parent domain and having it shadow the real one. Over plain `http://localhost` the
|
||||
prefix is not allowed, so the old name `gymsid` stays; both are accepted on the way in, so
|
||||
upgrading signs nobody out. If one name ever arrives twice with different values, both are
|
||||
refused rather than guessing which is the real session (`api/server.js:261`).
|
||||
- **Any user can end every session they have.** `POST /api/logout/all` increments that account's
|
||||
session version, and every authenticated request checks the version in the cookie against the
|
||||
one on the user record (`api/server.js:172`, `api/server.js:192-193`), so every cookie ever
|
||||
one on the user record (`api/server.js:249`, `api/server.js:302-303`), so every cookie ever
|
||||
issued for the account — on every device, including a copy someone walked off with — stops
|
||||
verifying at once. Passkeys are untouched; signing back in works immediately.
|
||||
- **Data is isolated per user by the session's uid.** `GET`/`PUT /api/data` only ever touch
|
||||
`state-<uid>.json` for the caller (`api/server.js:517-534`); no route lets a normal user name
|
||||
`state-<uid>.json` for the caller (`api/server.js:727-748`); no route lets a normal user name
|
||||
another user.
|
||||
- **Disabling an account takes effect immediately.** Every authenticated request and every login
|
||||
is rejected for a disabled user (`api/server.js:189`, `api/server.js:488`).
|
||||
is rejected for a disabled user (`api/server.js:299`, `api/server.js:667`).
|
||||
- **Push endpoints cannot be aimed at your network.** A subscription's `endpoint` is a URL the
|
||||
server connects out to and it comes from whoever is signed in, so `/api/push/*` would otherwise
|
||||
be a request-forgery lever from inside the Docker network. It must be `https:`, and the
|
||||
connection is refused at socket level if the host resolves to a loopback, private, link-local
|
||||
(including cloud metadata) or CGNAT address — enforced in the agent's DNS lookup, not in a
|
||||
prior pass, so there is no rebinding window (`api/server.js:86-119`). Sends have a 10 s timeout
|
||||
(a stalling endpoint used to hang the request handler indefinitely), run at most 6 at a time,
|
||||
and each account is capped at 20 subscriptions, so one small request cannot become an unbounded
|
||||
burst of outbound connections (`api/server.js:84`).
|
||||
- **There is an activity log.** Sign-ins, sign-outs, failed and refused attempts, and every admin
|
||||
action are appended to `./data/audit.log`, one JSON object per line, and shown in the admin
|
||||
dashboard. It is on by default (`AUDIT_LOG=0` disables it) and capped at `AUDIT_MAX` events /
|
||||
@@ -118,22 +136,31 @@ Read this before hosting openGym for anyone other than yourself.
|
||||
before an archive of `./data` goes somewhere you don't run.
|
||||
- **Admins can read everything.** A user listed in `ADMIN_UIDS` (or flagged `admin: true` in
|
||||
`db.json`) gets every user's full history and body weight, can disable accounts, and can create
|
||||
or revoke invite codes (`api/server.js:600-722`). Off by default — a fresh instance has no admin.
|
||||
or revoke invite codes (`api/server.js:825-947`). Off by default — a fresh instance has no admin.
|
||||
- **Sessions can't be revoked one device at a time.** Revocation is per *account*, not per
|
||||
session: `POST /api/logout/all` kills all of them at once and there is no device list to pick
|
||||
from. `POST /api/logout` on its own only clears the cookie in that one browser
|
||||
(`api/server.js:498-502`) — a copy taken beforehand keeps working. Sessions last **90 days** by
|
||||
default, settable with `SESSION_DAYS` (`api/server.js:31`); each cookie carries the lifetime it
|
||||
(`api/server.js:677-681`) — a copy taken beforehand keeps working. Sessions last **90 days** by
|
||||
default, settable with `SESSION_DAYS` (`api/server.js:33`); each cookie carries the lifetime it
|
||||
was issued with, so changing the setting doesn't reach cookies that are already out. Deleting
|
||||
`./data/secret` and restarting still works as the instance-wide reset, and disabling an account
|
||||
still locks out one user completely.
|
||||
- **CSRF protection is `SameSite=Lax` and nothing else.** There are no CSRF tokens.
|
||||
- **CSRF protection is `SameSite=Lax` plus an origin check, not tokens.** There are no CSRF
|
||||
tokens. `SameSite=Lax` alone was not enough: it keeps the cookie off a cross-*site* request but
|
||||
a sibling subdomain (`gym.example.com` vs anything else under `example.com` — one domain, one
|
||||
reverse proxy, several apps, i.e. the usual self-hosting layout) is the *same* site and does
|
||||
get the cookie. So every state-changing request that a browser sent must also be
|
||||
`Sec-Fetch-Site: same-origin`, or carry an `Origin` equal to `ORIGIN` where that header is
|
||||
missing (`api/server.js:344`). Requests authenticated with a Bearer token skip the check —
|
||||
a browser never attaches one by itself, so there is no ambient authority to borrow — as do the
|
||||
register/login/pair handshakes, which carry their own credential in the body and act on no
|
||||
existing session (`api/server.js:338`).
|
||||
- **User verification is preferred, not required.** Both handshakes pass
|
||||
`requireUserVerification: false` (`api/server.js:396`, `api/server.js:465`), so a passkey
|
||||
`requireUserVerification: false` (`api/server.js:575`, `api/server.js:644`), so a passkey
|
||||
released without a biometric or PIN is still accepted. In practice: unlocked device ≈ account
|
||||
access.
|
||||
- **One passkey per profile, and no recovery.** Every successful registration creates a *new*
|
||||
profile (`api/server.js:421-430`); there is no route to attach a second passkey to an existing
|
||||
profile (`api/server.js:600-609`); there is no route to attach a second passkey to an existing
|
||||
one, and no email or reset path. Lose the passkey and that profile is unreachable — only direct
|
||||
surgery on `./data` gets it back.
|
||||
- **Disabling someone isn't a ban.** They can still register a fresh profile with a new passkey
|
||||
@@ -146,17 +173,23 @@ Read this before hosting openGym for anyone other than yourself.
|
||||
in the clear.
|
||||
- **No rate limiting anywhere.** Nothing throttles logins, registrations or writes, and
|
||||
`POST /api/register/options` still answers whether an invite code is valid
|
||||
(`api/server.js:360`), so an invite-only instance on the open internet should have a rate limit
|
||||
in front of it. New invite codes are 16 hex characters — 64 bits (`api/server.js:668`) — which
|
||||
(`api/server.js:544`), so an invite-only instance on the open internet should have a rate limit
|
||||
in front of it. New invite codes are 16 hex characters — 64 bits (`api/server.js:891`) — which
|
||||
makes guessing one impractical even unthrottled; codes generated by earlier versions are 8
|
||||
characters / 32 bits and still work, so revoke and reissue any that are still unused. The only
|
||||
hard limit
|
||||
in the app is a 5 MB request body (`api/server.js:32`).
|
||||
in the app is a 5 MB request body (`api/server.js:34`).
|
||||
- **The activity log is not an audit archive, and it records less than you might assume.** No IP
|
||||
address unless you set `AUDIT_IP` (`net` truncates to a /24 or /48; the default is `off`, and
|
||||
when it is on the address is taken from `CF-Connecting-IP`, `X-Forwarded-For` or `X-Real-IP` and
|
||||
is therefore only as trustworthy as the proxy in front of you), never
|
||||
the browser's user-agent, and never the passkey id behind a failed sign-in — that id is a stable
|
||||
address unless you set `AUDIT_IP` (`net` truncates to a /24 or /48; the default is `off`). When it is on, the
|
||||
address comes from `CF-Connecting-IP`, `X-Forwarded-For`, `X-Real-IP` or, failing all three,
|
||||
the connecting socket — so it is only as trustworthy as whatever sits in front, which has to
|
||||
*overwrite* those headers rather than pass a client-supplied one through. The bundled web
|
||||
container now does: it replaces `X-Forwarded-For`/`X-Real-IP` with the real peer and drops
|
||||
`CF-Connecting-IP` unless you set `CF_CONNECTING_IP=$http_cf_connecting_ip`, which is correct
|
||||
only with Cloudflare genuinely in front. Before that it appended to `X-Forwarded-For` and
|
||||
passed `CF-Connecting-IP` straight through, and the API reads the first entry — so any caller
|
||||
could choose the address recorded against it. Never the browser's user-agent,
|
||||
and never the passkey id behind a failed sign-in — that id is a stable
|
||||
handle for one device, and storing it would let an admin follow an unknown device from attempt
|
||||
to attempt. So a failed sign-in from a passkey this instance doesn't know is recorded as a time
|
||||
and nothing else. Retention is a cap, not an archive: old events are dropped, not exported. Any
|
||||
|
||||
+259
-20
@@ -4,6 +4,8 @@ import http from 'node:http';
|
||||
import crypto from 'node:crypto';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import https from 'node:https';
|
||||
import dns from 'node:dns';
|
||||
import {
|
||||
generateRegistrationOptions, verifyRegistrationResponse,
|
||||
generateAuthenticationOptions, verifyAuthenticationResponse
|
||||
@@ -66,25 +68,100 @@ catch { vapid = webpush.generateVAPIDKeys(); fs.writeFileSync(vapidFile, JSON.st
|
||||
const VAPID_SUBJECT = process.env.VAPID_SUBJECT || (SECURE ? ORIGIN : 'mailto:admin@localhost');
|
||||
webpush.setVapidDetails(VAPID_SUBJECT, vapid.publicKey, vapid.privateKey);
|
||||
|
||||
/* A push subscription's `endpoint` is a URL this server connects out to, chosen by whoever is
|
||||
signed in — so without a check /api/push/* is a request-forgery lever, and the api container
|
||||
sits on the same Docker network as the rest of the self-hoster's stack. Three limits below:
|
||||
|
||||
1. PUSH_AGENT rejects any connection to a private/loopback/link-local address at the moment
|
||||
the socket is opened. Validating the URL alone would leave a DNS-rebinding window — the
|
||||
name is resolved a second time inside web-push — so the check has to live in the lookup
|
||||
the request itself uses, not in a prior pass.
|
||||
2. PUSH_TIMEOUT_MS: an endpoint that accepts TCP and then stalls used to hang the request
|
||||
handler that awaited it, indefinitely. web-push sets no timeout of its own.
|
||||
3. PUSH_CONCURRENCY: one small request must not turn into an unbounded burst of outbound
|
||||
connections (with MAX_SUBS_PER_USER below, that is the other half of the same problem). */
|
||||
const PUSH_TIMEOUT_MS = 10000;
|
||||
const PUSH_CONCURRENCY = 6;
|
||||
const MAX_SUBS_PER_USER = 20;
|
||||
|
||||
function isPrivateAddr(ip) {
|
||||
const v = String(ip).toLowerCase();
|
||||
const m4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(v);
|
||||
if (m4) {
|
||||
const a = +m4[1], b = +m4[2];
|
||||
if (a === 0 || a === 10 || a === 127) return true; // this-network, private, loopback
|
||||
if (a === 169 && b === 254) return true; // link-local (cloud metadata)
|
||||
if (a === 172 && b >= 16 && b <= 31) return true; // private
|
||||
if (a === 192 && b === 168) return true; // private
|
||||
if (a === 192 && b === 0) return true; // 192.0.0.0/24, 192.0.2.0/24
|
||||
if (a === 100 && b >= 64 && b <= 127) return true; // CGNAT
|
||||
if (a >= 224) return true; // multicast + reserved
|
||||
return false;
|
||||
}
|
||||
const m6 = /^::ffff:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/.exec(v);
|
||||
if (m6) return isPrivateAddr(m6[1]); // IPv4-mapped IPv6
|
||||
if (v === '::' || v === '::1') return true; // unspecified, loopback
|
||||
if (/^fe[89ab]/.test(v)) return true; // link-local
|
||||
if (/^f[cd]/.test(v)) return true; // unique local
|
||||
return false;
|
||||
}
|
||||
|
||||
// Same shape as dns.lookup, so https.Agent can use it directly.
|
||||
function guardedLookup(hostname, options, cb) {
|
||||
dns.lookup(hostname, options, (err, address, family) => {
|
||||
if (err) return cb(err);
|
||||
const list = Array.isArray(address) ? address : [{ address, family }];
|
||||
if (list.some(a => isPrivateAddr(a.address))) {
|
||||
return cb(Object.assign(new Error('refusing to connect to a private address: ' + hostname), { code: 'EPUSHBLOCKED' }));
|
||||
}
|
||||
cb(null, address, family);
|
||||
});
|
||||
}
|
||||
const PUSH_AGENT = new https.Agent({ lookup: guardedLookup, keepAlive: false });
|
||||
|
||||
// Cheap pre-check so a bad endpoint is refused at subscribe time with a useful message, rather
|
||||
// than silently never delivering. PUSH_AGENT is what actually enforces the address rule.
|
||||
function pushEndpointError(raw) {
|
||||
let u;
|
||||
try { u = new URL(String(raw || '')); } catch { return 'endpoint is not a valid URL'; }
|
||||
if (u.protocol !== 'https:') return 'endpoint must be an https:// URL';
|
||||
if (u.username || u.password) return 'endpoint must not carry credentials';
|
||||
// A literal address can be judged right here, which turns the common case into a clear error
|
||||
// at subscribe time instead of a delivery that quietly never happens. Hostnames are left to
|
||||
// PUSH_AGENT, which is the check that actually has to hold.
|
||||
const host = u.hostname.replace(/^\[|\]$/g, '');
|
||||
if (/^[0-9.]+$/.test(host) || host.includes(':')) {
|
||||
if (isPrivateAddr(host)) return 'endpoint must not point at a private address';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
async function sendPush(userId, payload) {
|
||||
const subs = db.subs.filter(s => s.userId === userId);
|
||||
if (!subs.length) return;
|
||||
const body = JSON.stringify(payload);
|
||||
let dirty = false;
|
||||
await Promise.all(subs.map(async sub => {
|
||||
// urgency 'high' is the one lever we have over delivery speed — iOS/Android throttle
|
||||
// low-urgency background push more aggressively under battery-saving modes. TTL is left
|
||||
// at the library default (long) so a briefly-offline device still gets it once reconnected,
|
||||
// rather than risking it being dropped for the sake of shaving off latency that TTL doesn't
|
||||
// actually control anyway.
|
||||
try { await webpush.sendNotification({ endpoint: sub.endpoint, keys: sub.keys }, body, { urgency: 'high' }); }
|
||||
catch (e) {
|
||||
console.error('push send failed', userId, e.statusCode, e.body || e.message);
|
||||
if (e.statusCode === 404 || e.statusCode === 410) {
|
||||
db.subs = db.subs.filter(s => s.endpoint !== sub.endpoint); dirty = true;
|
||||
let next = 0;
|
||||
const worker = async () => {
|
||||
while (next < subs.length) {
|
||||
const sub = subs[next++];
|
||||
// urgency 'high' is the one lever we have over delivery speed — iOS/Android throttle
|
||||
// low-urgency background push more aggressively under battery-saving modes. TTL is left
|
||||
// at the library default (long) so a briefly-offline device still gets it once reconnected,
|
||||
// rather than risking it being dropped for the sake of shaving off latency that TTL doesn't
|
||||
// actually control anyway.
|
||||
try {
|
||||
await webpush.sendNotification({ endpoint: sub.endpoint, keys: sub.keys }, body,
|
||||
{ urgency: 'high', timeout: PUSH_TIMEOUT_MS, agent: PUSH_AGENT });
|
||||
} catch (e) {
|
||||
console.error('push send failed', userId, e.statusCode, e.body || e.message);
|
||||
if (e.statusCode === 404 || e.statusCode === 410) {
|
||||
db.subs = db.subs.filter(s => s.endpoint !== sub.endpoint); dirty = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}));
|
||||
};
|
||||
await Promise.all(Array.from({ length: Math.min(PUSH_CONCURRENCY, subs.length) }, worker));
|
||||
if (dirty) saveDb();
|
||||
}
|
||||
|
||||
@@ -171,11 +248,44 @@ function makeSession(user) {
|
||||
const exp = Date.now() + SESSION_DAYS * 86400000;
|
||||
return sign(user.id + ':' + exp + ':' + sessionVersion(user));
|
||||
}
|
||||
// With the __Host- prefix the *browser* guarantees the cookie is host-only (no Domain attribute
|
||||
// is even allowed) — which is what stops a sibling subdomain, e.g. anything-else.example.com
|
||||
// against gym.example.com, from planting a second session cookie for the shared parent domain
|
||||
// and having it shadow the real one. The prefix also requires Secure, so it only works on an
|
||||
// https ORIGIN; over plain http://localhost the old name stays, and localhost has no sibling
|
||||
// subdomains to worry about. Both names are accepted on the way in, so upgrading an instance
|
||||
// does not sign anybody out — they move onto the prefixed cookie at their next sign-in.
|
||||
const COOKIE = SECURE ? '__Host-gymsid' : 'gymsid';
|
||||
const LEGACY_COOKIE = 'gymsid';
|
||||
// Every value for a given name, in the order the browser sent them. Not an object: reducing
|
||||
// duplicates to one entry silently picks a winner, and picking the *last* one handed a shadowing
|
||||
// cookie the session outright.
|
||||
function cookieValues(req, name) {
|
||||
const out = [];
|
||||
for (const c of (req.headers.cookie || '').split(';')) {
|
||||
const i = c.indexOf('=');
|
||||
if (i < 0) continue;
|
||||
if (c.slice(0, i).trim() === name) out.push(c.slice(i + 1).trim());
|
||||
}
|
||||
return out;
|
||||
}
|
||||
function cookieToken(req) {
|
||||
for (const name of (COOKIE === LEGACY_COOKIE ? [COOKIE] : [COOKIE, LEGACY_COOKIE])) {
|
||||
const vals = cookieValues(req, name);
|
||||
if (!vals.length) continue;
|
||||
// Two different values under one name is not something a browser does on its own — it means
|
||||
// somebody else got to set one. There is no safe way to guess which is the real session, so
|
||||
// refuse both: a signed-out user signs back in, a shadowing attempt gets nothing.
|
||||
if (vals.some(v => v !== vals[0])) return null;
|
||||
return vals[0];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
function readSession(req) {
|
||||
const cookies = Object.fromEntries((req.headers.cookie || '').split(';').map(c => {
|
||||
const i = c.indexOf('='); return i < 0 ? ['', ''] : [c.slice(0, i).trim(), c.slice(i + 1).trim()];
|
||||
}));
|
||||
const tok = cookies.gymsid;
|
||||
// The paired mobile app has no cookie jar shared with the API's origin, so it carries the same
|
||||
// signed token in an Authorization header instead — same payload, same verification below.
|
||||
const auth = req.headers.authorization || '';
|
||||
const tok = cookieToken(req) || (auth.startsWith('Bearer ') ? auth.slice(7).trim() : null);
|
||||
if (!tok) return null;
|
||||
const payload = verifySig(tok);
|
||||
if (!payload) return null;
|
||||
@@ -199,10 +309,56 @@ function requireAdmin(req, res) {
|
||||
if (!isAdmin(user)) { audit(req, 'admin.denied', { ok: false, user }); json(res, 403, { error: 'forbidden' }); return null; }
|
||||
return user;
|
||||
}
|
||||
const expireCookie = name => `${name}=; Path=/; Max-Age=0; HttpOnly;${SECURE} SameSite=Lax`;
|
||||
function sessionCookie(user) {
|
||||
return `gymsid=${makeSession(user)}; Path=/; Max-Age=${SESSION_DAYS * 86400}; HttpOnly;${SECURE} SameSite=Lax`;
|
||||
const fresh = `${COOKIE}=${makeSession(user)}; Path=/; Max-Age=${SESSION_DAYS * 86400}; HttpOnly;${SECURE} SameSite=Lax`;
|
||||
// Signing in also retires any pre-upgrade cookie, so nobody is left carrying an unprefixed one
|
||||
// (or a shadowing copy of it) alongside the new session.
|
||||
return COOKIE === LEGACY_COOKIE ? [fresh] : [fresh, expireCookie(LEGACY_COOKIE)];
|
||||
}
|
||||
const clearCookie = COOKIE === LEGACY_COOKIE
|
||||
? [expireCookie(LEGACY_COOKIE)]
|
||||
: [expireCookie(COOKIE), expireCookie(LEGACY_COOKIE)];
|
||||
|
||||
/* ---------- CSRF ---------- */
|
||||
// SameSite=Lax keeps the session cookie off a genuinely cross-*site* request. It does not keep it
|
||||
// off a *sibling subdomain*: gym.example.com and anything-else.example.com are the same site, and
|
||||
// that is the ordinary self-hosting layout — one domain, one reverse proxy, several apps. Nothing
|
||||
// else in a request was being checked either; readBody() JSON.parse's the body whatever the
|
||||
// Content-Type claims, so a hostile page could reach the state-changing routes with a form-style
|
||||
// POST that needs no CORS preflight at all.
|
||||
//
|
||||
// So a state-changing request that came from a browser has to come from ORIGIN. The exemptions
|
||||
// below are not holes: each of those routes carries its own credential in the body (a WebAuthn
|
||||
// challenge id, a one-shot pairing code), none of them acts on the caller's existing session, and
|
||||
// they have to keep working from the mobile WebView, whose origin is never ORIGIN.
|
||||
const CSRF_EXEMPT = new Set([
|
||||
'POST /api/register/options', 'POST /api/register/verify',
|
||||
'POST /api/login/options', 'POST /api/login/verify',
|
||||
'POST /api/pair/redeem'
|
||||
]);
|
||||
const originsMatch = (a, b) => a.replace(/\/+$/, '') === b.replace(/\/+$/, '');
|
||||
function csrfOk(req, key) {
|
||||
if (req.method === 'GET' || req.method === 'HEAD' || req.method === 'OPTIONS') return true;
|
||||
if (CSRF_EXEMPT.has(key)) return true;
|
||||
// The paired mobile app authenticates with a Bearer token. A browser never attaches one on its
|
||||
// own, so there is no ambient authority for a hostile page to borrow and no origin to check.
|
||||
if ((req.headers.authorization || '').startsWith('Bearer ')) return true;
|
||||
// Sec-Fetch-Site is set by the browser itself and no page can forge it, and it states exactly
|
||||
// the property wanted here — more precisely than comparing origins can. 'same-origin' is the
|
||||
// app talking to its own backend; a hostile page reports 'cross-site'; a sibling subdomain,
|
||||
// the case SameSite=Lax misses entirely, reports 'same-site'. It is also what keeps the Vite
|
||||
// dev server working, where the page is on another port and its Origin is legitimately not
|
||||
// ORIGIN. Absent on older Safari and on proxies that strip it, hence the fallback below.
|
||||
const site = req.headers['sec-fetch-site'];
|
||||
if (site) return site === 'same-origin' || site === 'none';
|
||||
const origin = req.headers.origin;
|
||||
// No Origin header at all means no browser sent this — curl, a script, a monitoring check.
|
||||
// Browsers put an Origin on every state-changing request and a page cannot suppress it, so the
|
||||
// forgery this exists to stop always carries one.
|
||||
if (!origin) return true;
|
||||
return originsMatch(origin, ORIGIN);
|
||||
}
|
||||
const clearCookie = `gymsid=; Path=/; Max-Age=0; HttpOnly;${SECURE} SameSite=Lax`;
|
||||
|
||||
/* ---------- challenge store (in-memory, 5 min TTL) ---------- */
|
||||
const challenges = new Map(); // cid -> {challenge, name?, uid?, exp}
|
||||
@@ -219,6 +375,21 @@ function takeChallenge(cid) {
|
||||
}
|
||||
setInterval(() => { for (const [k, v] of challenges) if (v.exp < Date.now()) challenges.delete(k); }, 60000).unref();
|
||||
|
||||
// ---------- device pairing (mobile app "connect to my server", no WebAuthn ceremony) ----------
|
||||
// A passkey ceremony can't run inside the app's WebView (its origin never matches RP_ID), so the
|
||||
// app authenticates by redeeming a short code minted from an already signed-in browser tab —
|
||||
// same 5-min-TTL/one-shot shape as the WebAuthn challenge store above.
|
||||
const pairings = new Map(); // code -> {uid, exp}
|
||||
const PAIR_CODE_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; // no 0/O/1/I — read off a screen
|
||||
function makePairCode() {
|
||||
let code;
|
||||
do {
|
||||
code = Array.from(crypto.randomBytes(8)).map(b => PAIR_CODE_ALPHABET[b % PAIR_CODE_ALPHABET.length]).join('');
|
||||
} while (pairings.has(code));
|
||||
return code;
|
||||
}
|
||||
setInterval(() => { for (const [k, v] of pairings) if (v.exp < Date.now()) pairings.delete(k); }, 60000).unref();
|
||||
|
||||
/* ---------- helpers ---------- */
|
||||
function json(res, code, obj, extraHeaders) {
|
||||
const body = JSON.stringify(obj);
|
||||
@@ -287,7 +458,10 @@ function clientIp(req) {
|
||||
if (AUDIT_IP === 'off') return null;
|
||||
const raw = String(req.headers['cf-connecting-ip'] || '').trim()
|
||||
|| String(req.headers['x-forwarded-for'] || '').split(',')[0].trim()
|
||||
|| String(req.headers['x-real-ip'] || '').trim();
|
||||
|| String(req.headers['x-real-ip'] || '').trim()
|
||||
// Nothing in front at all: the socket peer is the client, and it cannot be forged. Behind
|
||||
// the bundled web container a header always wins before this is reached.
|
||||
|| String(req.socket?.remoteAddress || '').replace(/^::ffff:/, '').trim();
|
||||
const ip = raw.replace(/^\[|\]$/g, '').slice(0, 45);
|
||||
if (!/^[0-9a-fA-F:.]{3,45}$/.test(ip)) return null; // never store a header verbatim
|
||||
if (AUDIT_IP === 'full') return ip;
|
||||
@@ -516,6 +690,37 @@ const routes = {
|
||||
json(res, 200, { ok: true }, { 'Set-Cookie': clearCookie });
|
||||
},
|
||||
|
||||
// Mobile app pairing: called from an already signed-in browser tab (Settings → "Pair the
|
||||
// mobile app") to mint a short code the phone can redeem below.
|
||||
'POST /api/pair/create': async (req, res) => {
|
||||
const user = readSession(req);
|
||||
if (!user) return json(res, 401, { error: 'not signed in' });
|
||||
const code = makePairCode();
|
||||
pairings.set(code, { uid: user.id, exp: Date.now() + 5 * 60000 });
|
||||
audit(req, 'auth.pair.create', { user });
|
||||
json(res, 200, { code });
|
||||
},
|
||||
|
||||
// Called from the mobile app itself with the code shown in the browser. No session required —
|
||||
// the code IS the credential, one-shot and 5-minute-lived like a WebAuthn challenge.
|
||||
'POST /api/pair/redeem': async (req, res) => {
|
||||
const body = await readBody(req);
|
||||
const code = String(body.code || '').trim().toUpperCase();
|
||||
const p = pairings.get(code);
|
||||
if (p) pairings.delete(code);
|
||||
if (!p || p.exp < Date.now()) {
|
||||
audit(req, 'auth.pair.fail', { ok: false, msg: 'code-invalid' });
|
||||
return json(res, 400, { error: 'invalid or expired code' });
|
||||
}
|
||||
const user = db.users.find(u => u.id === p.uid);
|
||||
if (!user || user.disabled) {
|
||||
audit(req, 'auth.pair.fail', { ok: false, uid: p.uid, msg: 'user-unavailable' });
|
||||
return json(res, 400, { error: 'invalid or expired code' });
|
||||
}
|
||||
audit(req, 'auth.pair.ok', { user });
|
||||
json(res, 200, { token: makeSession(user), user: { id: user.id, name: user.name, admin: isAdmin(user) } });
|
||||
},
|
||||
|
||||
'GET /api/data': async (req, res) => {
|
||||
const user = readSession(req);
|
||||
if (!user) return json(res, 401, { error: 'not signed in' });
|
||||
@@ -543,8 +748,21 @@ const routes = {
|
||||
const body = await readBody(req);
|
||||
const sub = body.subscription;
|
||||
if (!sub?.endpoint || !sub?.keys?.p256dh || !sub?.keys?.auth) return json(res, 400, { error: 'invalid subscription' });
|
||||
const bad = pushEndpointError(sub.endpoint);
|
||||
if (bad) return json(res, 400, { error: bad });
|
||||
// Only the two keys the push protocol needs are kept: `sub` is caller-supplied and would
|
||||
// otherwise put arbitrary fields into db.json, which every admin route reads back out.
|
||||
const keys = { p256dh: String(sub.keys.p256dh), auth: String(sub.keys.auth) };
|
||||
db.subs = db.subs.filter(s => s.endpoint !== sub.endpoint);
|
||||
db.subs.push({ userId: user.id, endpoint: sub.endpoint, keys: sub.keys, created: new Date().toISOString() });
|
||||
// A browser holds one subscription per device, so this cap is far above real use. Without
|
||||
// it a single account could pile up endpoints without limit — every one of them a target
|
||||
// sendPush() would then contact, and a whole rewrite of db.json per addition.
|
||||
const mine = db.subs.filter(s => s.userId === user.id);
|
||||
if (mine.length >= MAX_SUBS_PER_USER) {
|
||||
const drop = new Set(mine.slice(0, mine.length - MAX_SUBS_PER_USER + 1).map(s => s.endpoint));
|
||||
db.subs = db.subs.filter(s => !drop.has(s.endpoint));
|
||||
}
|
||||
db.subs.push({ userId: user.id, endpoint: sub.endpoint, keys, created: new Date().toISOString() });
|
||||
saveDb();
|
||||
json(res, 200, { ok: true });
|
||||
},
|
||||
@@ -725,10 +943,31 @@ const routes = {
|
||||
};
|
||||
|
||||
http.createServer(async (req, res) => {
|
||||
// Same-origin (the deployed nginx-proxied web app) never triggers CORS, so this only matters
|
||||
// for the paired mobile app calling in from its own WebView origin. It carries no cookie
|
||||
// (auth is the Authorization header instead), so Allow-Credentials is deliberately never set —
|
||||
// reflecting the origin here can't expose the cookie session to anyone.
|
||||
const origin = req.headers.origin;
|
||||
if (origin) { res.setHeader('Access-Control-Allow-Origin', origin); res.setHeader('Vary', 'Origin'); }
|
||||
if (req.method === 'OPTIONS') {
|
||||
res.writeHead(204, {
|
||||
'Access-Control-Allow-Methods': 'GET,POST,PUT,DELETE,OPTIONS',
|
||||
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
|
||||
'Access-Control-Max-Age': '86400'
|
||||
});
|
||||
return res.end();
|
||||
}
|
||||
const url = new URL(req.url, 'http://x');
|
||||
const key = req.method + ' ' + url.pathname;
|
||||
const handler = routes[key];
|
||||
if (!handler) return json(res, 404, { error: 'not found' });
|
||||
if (!csrfOk(req, key)) {
|
||||
// Logged, not audited: this is reachable without a session, and an audit entry per attempt
|
||||
// would let anyone fill the log. An operator who has genuinely mis-set ORIGIN needs to see
|
||||
// the mismatch, and the container log is where they will look.
|
||||
console.warn('refused cross-origin', key, 'origin=' + req.headers.origin, 'expected=' + ORIGIN);
|
||||
return json(res, 403, { error: 'cross-origin request refused' });
|
||||
}
|
||||
try { await handler(req, res); }
|
||||
catch (e) {
|
||||
console.error(key, e);
|
||||
|
||||
@@ -69,6 +69,9 @@ services:
|
||||
- NGINX_PORT=${NGINX_PORT:-80}
|
||||
- BACKEND=${BACKEND:-api}
|
||||
- PORT=${PORT:-3000}
|
||||
# Empty drops the CF-Connecting-IP header, so a direct client cannot forge the address
|
||||
# the activity log records. Cloudflare users set CF_CONNECTING_IP=$$http_cf_connecting_ip.
|
||||
- CF_CONNECTING_IP=${CF_CONNECTING_IP:-}
|
||||
volumes:
|
||||
- ./media/img:/usr/share/nginx/html/img:ro
|
||||
- ./media/gif:/usr/share/nginx/html/gif:ro
|
||||
+29
-5
@@ -10,11 +10,35 @@ openGym ships in two flavors from the same codebase:
|
||||
| Reminders | Web Push from your server | native local notifications, no server involved |
|
||||
| Exercise media | served by your server (`img/`, `gif/`) | loaded from the jsDelivr CDN |
|
||||
|
||||
The mobile flavor never talks to a backend: no sign-in screen, no sync, no telemetry.
|
||||
State is mirrored from `localStorage` into `opengym-state.json` in the app's private data
|
||||
directory on every change (iOS is allowed to evict WebView storage under pressure — the
|
||||
file mirror is the durable copy and is restored on launch). Backups go out through the
|
||||
OS share sheet instead of a browser download.
|
||||
The mobile flavor never talks to a backend by default: no sign-in screen, no sync, no
|
||||
telemetry. State is mirrored from `localStorage` into `opengym-state.json` in the app's
|
||||
private data directory on every change (iOS is allowed to evict WebView storage under
|
||||
pressure — the file mirror is the durable copy and is restored on launch). Backups go out
|
||||
through the OS share sheet instead of a browser download.
|
||||
|
||||
### Connecting the app to your own server
|
||||
|
||||
On first launch the app asks how you want to use it. Alongside the fully local mode above,
|
||||
you can instead **connect it to a self-hosted openGym server** — your data then lives there,
|
||||
synced the same way the browser PWA does, instead of only on the phone. This is a mode of the
|
||||
same app, not a different build or download.
|
||||
|
||||
Passkeys can't be used for this: the app's WebView runs at its own origin, which never
|
||||
matches the real hostname WebAuthn needs. Instead you *pair* the device from a browser
|
||||
that's already signed in: Settings → **"Pair the mobile app"** shows a one-time code (valid
|
||||
5 minutes); enter your server's address and that code in the app (same first-launch screen,
|
||||
or Settings → **"Connect to my server"** later) to finish. Notes:
|
||||
|
||||
- Requires network access every time the app is used — there's no offline file mirror once
|
||||
connected, same as the browser PWA.
|
||||
- Use an HTTPS address if at all possible: the connection carries a bearer token instead of
|
||||
a cookie, and that token would otherwise cross the network in plain text.
|
||||
- "Sign out everywhere" (Settings → Account, in the browser) revokes a paired app's access
|
||||
too — it's the same signed session token either way, just delivered over a header instead
|
||||
of a cookie. See `/api/pair/create` and `/api/pair/redeem` in `api/server.js` for the
|
||||
exchange itself.
|
||||
- Settings → "Disconnect" syncs one last time, then drops the device cleanly back to local
|
||||
mode.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
|
||||
@@ -42,6 +42,21 @@ passkey prompt won't appear. To use openGym from your phone you need a real HTTP
|
||||
|
||||
(You can still open it over LAN in **guest mode**, which stores data only in that browser.)
|
||||
|
||||
The standalone mobile app (`docs/MOBILE.md`) sidesteps this entirely for its "connect to my
|
||||
server" mode: instead of a passkey ceremony (impossible from inside its WebView, which never
|
||||
runs at your real hostname), it pairs by redeeming a short one-time code — minted from
|
||||
Settings → "Pair the mobile app" in an already signed-in browser tab — for a bearer token
|
||||
sent as an `Authorization` header rather than a cookie. Two consequences worth knowing if
|
||||
you're poking at the API directly:
|
||||
|
||||
- `POST /api/pair/create` (needs a session) and `POST /api/pair/redeem` (doesn't) implement
|
||||
this — see `api/server.js`. The returned token is the exact same signed value a cookie
|
||||
carries, so "sign out everywhere" invalidates it too.
|
||||
- The server reflects `Access-Control-Allow-Origin` for any request that sends an `Origin`
|
||||
header, so the app's own WebView origin can call the API cross-origin. It never sends
|
||||
`Access-Control-Allow-Credentials`, so this doesn't let a browser read your cookie session
|
||||
from another origin — only bearer-token requests benefit from it.
|
||||
|
||||
## 3. Expose it over HTTPS on your own domain
|
||||
|
||||
Put openGym behind something that terminates TLS for a hostname you control, then point it at
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "opengym-frontend",
|
||||
"version": "1.2.7",
|
||||
"version": "1.2.9",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "opengym-frontend",
|
||||
"version": "1.2.7",
|
||||
"version": "1.2.9",
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"dependencies": {
|
||||
"@capacitor/app": "^7.1.2",
|
||||
|
||||
+19
-2
@@ -16,6 +16,7 @@ import Modals from './components/Modals.jsx'
|
||||
import Toast from './components/Toast.jsx'
|
||||
import RestTimer from './components/RestTimer.jsx'
|
||||
import Login from './views/Login.jsx'
|
||||
import MobileOnboarding from './views/MobileOnboarding.jsx'
|
||||
import Home from './views/Home.jsx'
|
||||
import Plan from './views/Plan.jsx'
|
||||
import RoutineEdit from './views/RoutineEdit.jsx'
|
||||
@@ -28,9 +29,14 @@ import Admin from './views/Admin.jsx'
|
||||
|
||||
bindUI(useUI) // lets the shared controls open sheets without importing the store at module scope
|
||||
|
||||
// theme === 'system' follows the OS/browser preference instead of a fixed choice.
|
||||
const resolveTheme = theme => theme === 'light' || theme === 'dark'
|
||||
? theme
|
||||
: (window.matchMedia?.('(prefers-color-scheme: dark)').matches ? 'dark' : 'light')
|
||||
|
||||
function applyPrefs(theme, accent) {
|
||||
const de = document.documentElement
|
||||
de.dataset.theme = theme === 'light' ? 'light' : 'dark'
|
||||
de.dataset.theme = resolveTheme(theme)
|
||||
de.dataset.accent = ACCENTS[accent] ? accent : 'lime'
|
||||
const meta = document.querySelector('meta[name="theme-color"]')
|
||||
if (meta) meta.content = de.dataset.theme === 'light' ? '#f2f2f7' : '#000000'
|
||||
@@ -41,9 +47,20 @@ function Shell() {
|
||||
const loc = useLocation()
|
||||
const { S, user, ready } = useStore()
|
||||
const isGuest = useStore(s => s.isGuest())
|
||||
const needsMobileOnboarding = useStore(s => s.needsMobileOnboarding)
|
||||
const langV = useLang() // re-renders the whole shell when the language (pack) changes
|
||||
useEffect(() => { setNav(navigate) }, [navigate])
|
||||
useEffect(() => { applyPrefs(S.theme, S.accent) }, [S.theme, S.accent])
|
||||
// 'system' needs to react live if the OS theme flips while the app is open, not just on
|
||||
// the next mount — a fixed 'dark'/'light' choice never re-fires this since matchMedia
|
||||
// isn't consulted for those.
|
||||
useEffect(() => {
|
||||
if (S.theme !== 'system' || !window.matchMedia) return
|
||||
const mql = window.matchMedia('(prefers-color-scheme: dark)')
|
||||
const onChange = () => applyPrefs(S.theme, S.accent)
|
||||
mql.addEventListener('change', onChange)
|
||||
return () => mql.removeEventListener('change', onChange)
|
||||
}, [S.theme, S.accent])
|
||||
useEffect(() => { setLang(S.lang || 'en') }, [S.lang])
|
||||
useEffect(() => { document.documentElement.lang = S.lang || 'en' }, [langV, S.lang])
|
||||
// every tab/route change starts at the top of the page
|
||||
@@ -66,7 +83,7 @@ function Shell() {
|
||||
re-mounts the boundary, so the tab bar is always a way out */}
|
||||
<div id="app" className="vfade" key={loc.pathname}>
|
||||
<ErrorBoundary>
|
||||
{!authed ? <Login /> : (
|
||||
{!authed ? <Login /> : needsMobileOnboarding ? <MobileOnboarding /> : (
|
||||
<Routes>
|
||||
<Route path="/home" element={<Home />} />
|
||||
<Route path="/plan" element={<Plan />} />
|
||||
|
||||
@@ -585,6 +585,18 @@ h4.sec{
|
||||
.setrow.eff3 .stp .num{font-size:14px}
|
||||
.setrow.done .n{background:var(--acc);color:var(--on-acc)}
|
||||
.setrow.done{opacity:.45}
|
||||
/* drop-set drops / rest-pause bursts riding on a work row, editable like the row itself
|
||||
(issue: drop-sets & rest-pause) */
|
||||
.subrow{display:flex;align-items:center;gap:6px;padding:3px 0 3px 32px}
|
||||
.subrow .subn{font-size:11px;color:var(--label-3);flex:none;width:46px}
|
||||
.subrow .stp.mini{flex:1;min-width:0}
|
||||
.subrow .stp.mini button{width:26px;height:30px}
|
||||
.subrow .stp.mini .num{font-size:13px}
|
||||
.subrow .iconbtn{width:26px;height:26px;font-size:11px;flex:none}
|
||||
.setextra{display:flex;flex-wrap:wrap;gap:6px;margin:2px 0 8px 32px}
|
||||
.setextra .chip.add{display:inline-flex;align-items:center;gap:4px;color:var(--acc)}
|
||||
.setextra .chip.add svg{width:13px;height:13px}
|
||||
.setextra .chip.add:disabled{opacity:.35}
|
||||
/* why the next target is what it is (issue #17) */
|
||||
.progline{
|
||||
display:flex;align-items:flex-start;gap:7px;margin:6px 0 2px;
|
||||
|
||||
+20
-1
@@ -9,8 +9,27 @@ export const VAULT = IS_APPLE ? 'iCloud Keychain' : IS_ANDROID ? 'Google Passwor
|
||||
// only after the user chooses a passkey action and surface any genuine browser error there.
|
||||
export const webauthnOK = () => typeof window.PublicKeyCredential !== 'undefined'
|
||||
|
||||
// The paired mobile app (lib/remote.js) is the only caller of these — everywhere else stays on
|
||||
// same-origin cookies, so remoteBase/remoteToken stay empty and api() behaves exactly as before.
|
||||
let remoteBase = ''
|
||||
let remoteToken = null
|
||||
export function setRemoteAuth(base, token) { remoteBase = base || ''; remoteToken = token || null }
|
||||
|
||||
export async function api(path, opts) {
|
||||
const r = await fetch(path, Object.assign({ headers: { 'Content-Type': 'application/json' } }, opts))
|
||||
const headers = Object.assign({ 'Content-Type': 'application/json' }, opts && opts.headers)
|
||||
if (remoteToken) headers.Authorization = 'Bearer ' + remoteToken
|
||||
const r = await fetch(remoteBase + path, Object.assign({}, opts, { headers }))
|
||||
const data = await r.json().catch(() => ({}))
|
||||
if (!r.ok) { const e = new Error(data.error || ('HTTP ' + r.status)); e.status = r.status; throw e }
|
||||
return data
|
||||
}
|
||||
|
||||
// Bootstraps the connection itself: the base isn't configured yet (that's what this call decides),
|
||||
// so it talks straight to the server the user typed in, no Authorization header.
|
||||
export async function pairRedeem(serverBase, code) {
|
||||
const r = await fetch(serverBase + '/api/pair/redeem', {
|
||||
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ code })
|
||||
})
|
||||
const data = await r.json().catch(() => ({}))
|
||||
if (!r.ok) { const e = new Error(data.error || ('HTTP ' + r.status)); e.status = r.status; throw e }
|
||||
return data
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Pure helpers over the state object S (ported 1:1 from the vanilla app).
|
||||
import { todayISO, isoOf, weekKey, fmtNum } from './format.js'
|
||||
import { isCardio, isBodyweightEq } from './exercises.js'
|
||||
import { phaseForSet, modeForSet, modeForEntry, isWarmupRow, normalizeMode } from './workout-model.js'
|
||||
import { phaseForSet, modeForSet, modeForEntry, isWarmupRow, normalizeMode, extraVolumeOf, nextDropWeight, splitBurstReps } from './workout-model.js'
|
||||
const objectOf = value => value && typeof value === 'object' && !Array.isArray(value) ? value : {}
|
||||
// Completed-state-independent work rows whose authoritative mode matches the requested mode.
|
||||
const workRowsForMode = (entry = {}, mode = 'reps') => {
|
||||
@@ -286,11 +286,51 @@ export function buildSets(S, cfg, options = {}) {
|
||||
}
|
||||
return sets
|
||||
}
|
||||
|
||||
/**
|
||||
* Stamp every work row with the exercise's planned intensifier and pre-fill its drops/clusters,
|
||||
* already computed and editable — the plan designs the set, not a button pressed mid-workout.
|
||||
*
|
||||
* Must run AFTER applyPrescription: a drop-set's chain of drops is a percentage of each row's
|
||||
* own `w`, so it has to be computed from the final prescribed weight, not the pre-progression
|
||||
* one buildSets started from — otherwise a bumped working weight would leave stale, cheaper
|
||||
* drops sitting underneath it.
|
||||
*/
|
||||
export function applyIntensifierPlan(sets, cfg) {
|
||||
const kind = cfg && cfg.intensifier && cfg.intensifier.type
|
||||
if (kind !== 'dropset' && kind !== 'restpause') return sets
|
||||
if (kind === 'dropset') {
|
||||
const count = Math.max(1, Math.round(cfg.intensifier.count) || 1)
|
||||
const pct = cfg.intensifier.pct
|
||||
return sets.map(s => {
|
||||
if (isWarmupRow(s)) return s
|
||||
const drops = []
|
||||
let w = s.w || 0
|
||||
for (let k = 0; k < count; k++) { w = nextDropWeight(w, pct); drops.push({ w, r: s.r }) }
|
||||
return { ...s, type: 'dropset', drops }
|
||||
})
|
||||
}
|
||||
// Rest-pause trains as exactly two sets, not one per configured `sets` count: a warm-up at
|
||||
// the exercise's own configured reps, then a single rest-pause work set. Doing the full
|
||||
// activation+bursts protocol several times over isn't how rest-pause is actually trained, so
|
||||
// planning it replaces whatever buildSets built rather than stamping each of those rows.
|
||||
// The work row's own reps are the total — not "the total minus what the bursts carry" — and
|
||||
// the bursts are the full breakdown of that same total, down to the last one. See
|
||||
// extraVolumeOf/setTonnage: a rest-pause row's `clusters` are read-only display of how `r`
|
||||
// breaks down, not extra volume on top of it, precisely so this doesn't double-count.
|
||||
const restSec = Math.max(5, cfg.intensifier.restSec || 15)
|
||||
const totalReps = Math.max(1, Math.round(cfg.intensifier.totalReps) || 1)
|
||||
const w = (sets.find(s => !isWarmupRow(s)) || sets[0] || {}).w || 0
|
||||
const warmup = { w, r: Math.max(1, Math.round(cfg.reps) || 1), done: false, phase: 'warmup' }
|
||||
const work = { w, r: totalReps, done: false, type: 'restpause', clusters: splitBurstReps(totalReps).map(r => ({ r, restSec })) }
|
||||
return [warmup, work]
|
||||
}
|
||||
export function workoutVolume(w) {
|
||||
let v = 0
|
||||
// No special case for unilateral work: a per-side set logs its total, so both sides are
|
||||
// already in the rep count that arrives here.
|
||||
w.entries.forEach(e => e.sets.forEach(s => { if (s.done) v += (s.w || 0) * (s.r || 0) }))
|
||||
// already in the rep count that arrives here. Drop-set drops and rest-pause bursts add their
|
||||
// own weight x reps on top of the row's main/activation set (see extraVolumeOf).
|
||||
w.entries.forEach(e => e.sets.forEach(s => { if (s.done) v += (s.w || 0) * (s.r || 0) + extraVolumeOf(s) }))
|
||||
return v
|
||||
}
|
||||
export function setsDone(w) {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { modeOf, isTimed, fmtSec, setLabel, defaultConfig, buildSets, freestyleConfig, exLine, workoutVolume, bestWeightFor, bestWeightForEntry, effortOf, stepEffort, capEffort, isBw, isPerSide, sideReps, repStep, cascadeWeight, insertWarmupRow, removeRowAt, workSetsDone, pairAdjacent, unpairSuperset, supersetUnits } from './history.js'
|
||||
import { modeOf, isTimed, fmtSec, setLabel, defaultConfig, buildSets, freestyleConfig, exLine, workoutVolume, bestWeightFor, bestWeightForEntry, effortOf, stepEffort, capEffort, isBw, isPerSide, sideReps, repStep, cascadeWeight, insertWarmupRow, removeRowAt, workSetsDone, pairAdjacent, unpairSuperset, supersetUnits, applyIntensifierPlan } from './history.js'
|
||||
import { EXDB } from './exercises.js'
|
||||
|
||||
// Real ids out of the shipped catalogue, so the body-part fallback is exercised for real.
|
||||
@@ -456,6 +456,55 @@ describe('buildSets', () => {
|
||||
expect(buildSets(S, { id: LIFT, sets: 2, reps: 8, weight: 50 }, { preferLast: true }))
|
||||
.toEqual([{ w: 60, r: 10, done: false }, { w: 62.5, r: 8, done: false }])
|
||||
})
|
||||
|
||||
})
|
||||
|
||||
describe('applyIntensifierPlan', () => {
|
||||
it('pre-fills every work row with a chain of drops, each pct% lighter than the one before', () => {
|
||||
const sets = [{ w: 100, r: 8, done: false }, { w: 100, r: 8, done: false }]
|
||||
const out = applyIntensifierPlan(sets, { intensifier: { type: 'dropset', count: 2, pct: 20 } })
|
||||
expect(out).toEqual([
|
||||
{ w: 100, r: 8, done: false, type: 'dropset', drops: [{ w: 80, r: 8 }, { w: 64, r: 8 }] },
|
||||
{ w: 100, r: 8, done: false, type: 'dropset', drops: [{ w: 80, r: 8 }, { w: 64, r: 8 }] },
|
||||
])
|
||||
})
|
||||
|
||||
it('collapses rest-pause to exactly two rows regardless of how many sets were configured: a warm-up at the exercise\'s own reps, then one work set whose own reps ARE the total', () => {
|
||||
const sets = [{ w: 60, r: 8, done: false }, { w: 60, r: 8, done: false }, { w: 60, r: 8, done: false }]
|
||||
const out = applyIntensifierPlan(sets, { reps: 8, intensifier: { type: 'restpause', totalReps: 12, restSec: 15 } })
|
||||
expect(out).toEqual([
|
||||
{ w: 60, r: 8, done: false, phase: 'warmup' },
|
||||
{ w: 60, r: 12, done: false, type: 'restpause', clusters: [{ r: 6, restSec: 15 }, { r: 3, restSec: 15 }, { r: 2, restSec: 15 }, { r: 1, restSec: 15 }] },
|
||||
])
|
||||
// the full breakdown always sums back to the row's own r — no reps missing, none double-counted
|
||||
expect(out[1].clusters.reduce((sum, c) => sum + c.r, 0)).toBe(out[1].r)
|
||||
})
|
||||
|
||||
it('the warm-up reps come from the exercise\'s own configured reps, not the rest-pause total', () => {
|
||||
const sets = [{ w: 60, r: 8, done: false }]
|
||||
const out = applyIntensifierPlan(sets, { reps: 5, intensifier: { type: 'restpause', totalReps: 20, restSec: 15 } })
|
||||
expect(out[0]).toEqual({ w: 60, r: 5, done: false, phase: 'warmup' })
|
||||
})
|
||||
|
||||
it('carries the prescribed weight from the built sets onto both new rows', () => {
|
||||
const sets = [{ w: 82.5, r: 8, done: false }]
|
||||
const out = applyIntensifierPlan(sets, { reps: 8, intensifier: { type: 'restpause', totalReps: 4, restSec: 15 } })
|
||||
expect(out[0].w).toBe(82.5)
|
||||
expect(out[1].w).toBe(82.5)
|
||||
})
|
||||
|
||||
it('never touches a warm-up row', () => {
|
||||
const sets = [{ w: 20, r: 8, done: false, phase: 'warmup' }, { w: 100, r: 8, done: false }]
|
||||
const out = applyIntensifierPlan(sets, { intensifier: { type: 'dropset', count: 1, pct: 20 } })
|
||||
expect(out[0]).toEqual({ w: 20, r: 8, done: false, phase: 'warmup' })
|
||||
expect(out[1].type).toBe('dropset')
|
||||
})
|
||||
|
||||
it('leaves sets untouched with no intensifier configured', () => {
|
||||
const sets = [{ w: 100, r: 8, done: false }]
|
||||
expect(applyIntensifierPlan(sets, {})).toBe(sets)
|
||||
expect(applyIntensifierPlan(sets, { intensifier: { type: 'nonsense' } })).toBe(sets)
|
||||
})
|
||||
})
|
||||
|
||||
describe('workoutVolume', () => {
|
||||
@@ -473,6 +522,21 @@ describe('workoutVolume', () => {
|
||||
expect(workoutVolume(w)).toBe(320)
|
||||
})
|
||||
|
||||
it('adds drop-set drops on top of the row\'s main set', () => {
|
||||
const dropRow = { type: 'dropset', w: 100, r: 5, done: true, drops: [{ w: 80, r: 5 }, { w: 60, r: 5 }] }
|
||||
expect(workoutVolume({ entries: [{ id: LIFT, sets: [dropRow] }] })).toBe(100 * 5 + 80 * 5 + 60 * 5)
|
||||
})
|
||||
|
||||
it('counts a rest-pause row once — its own r is already the total across every burst', () => {
|
||||
const burstRow = { type: 'restpause', w: 60, r: 20, done: true, clusters: [{ r: 10, restSec: 15 }, { r: 5, restSec: 15 }, { r: 3, restSec: 15 }, { r: 1, restSec: 15 }, { r: 1, restSec: 15 }] }
|
||||
expect(workoutVolume({ entries: [{ id: LIFT, sets: [burstRow] }] })).toBe(60 * 20)
|
||||
})
|
||||
|
||||
it('ignores drops/bursts on a row that was never checked off', () => {
|
||||
const dropRow = { type: 'dropset', w: 100, r: 5, done: false, drops: [{ w: 80, r: 5 }] }
|
||||
expect(workoutVolume({ entries: [{ id: LIFT, sets: [dropRow] }] })).toBe(0)
|
||||
})
|
||||
|
||||
it('leaves an unloaded bodyweight set at zero volume rather than inventing a number', () => {
|
||||
const w = { entries: [{ id: BW, target: { bodyweight: true }, sets: [{ w: 0, r: 20, done: true }] }] }
|
||||
expect(workoutVolume(w)).toBe(0)
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
// Like the demo build, MOBILE is replaced at build time, so all of this folds away in
|
||||
// web bundles; the Capacitor plugins are only ever imported behind it.
|
||||
import { t } from './i18n-core.js'
|
||||
import { todayISO } from './format.js'
|
||||
|
||||
export const MOBILE = import.meta.env.VITE_MOBILE === '1'
|
||||
|
||||
@@ -30,6 +31,27 @@ export async function nativeSave(state) {
|
||||
} catch (e) { /* keep the localStorage copy */ }
|
||||
}
|
||||
|
||||
// "Connect to my server" mode (lib/remote.js): which of local-only / a paired remote account this
|
||||
// device chose, kept in its own file — never inside opengym-state.json, since that file's content
|
||||
// is exactly what pushState() PUTs to a server, and a device's own connection secret must never
|
||||
// travel as if it were training data.
|
||||
const REMOTE_FILE = 'opengym-remote.json'
|
||||
|
||||
export async function loadRemoteFile() {
|
||||
try {
|
||||
const { Filesystem, Directory, Encoding } = await import('@capacitor/filesystem')
|
||||
const r = await Filesystem.readFile({ path: REMOTE_FILE, directory: Directory.Data, encoding: Encoding.UTF8 })
|
||||
return JSON.parse(r.data)
|
||||
} catch (e) { return null } // never decided yet
|
||||
}
|
||||
|
||||
export async function saveRemoteFile(data) {
|
||||
try {
|
||||
const { Filesystem, Directory, Encoding } = await import('@capacitor/filesystem')
|
||||
await Filesystem.writeFile({ path: REMOTE_FILE, directory: Directory.Data, data: JSON.stringify(data), encoding: Encoding.UTF8 })
|
||||
} catch (e) { /* worst case: onboarding asks again next launch */ }
|
||||
}
|
||||
|
||||
// (Re)schedule the workout-day reminder: one repeating notification per weekday that has a
|
||||
// routine in the weekly plan. Cheap enough to run after any state change — the plan or the
|
||||
// reminder time may just have been edited. `interactive` gates the OS permission prompt to
|
||||
@@ -66,3 +88,20 @@ export async function shareExport(json, filename) {
|
||||
const w = await Filesystem.writeFile({ path: filename, directory: Directory.Cache, data: json, encoding: Encoding.UTF8 })
|
||||
await Share.share({ title: filename, url: w.uri })
|
||||
}
|
||||
|
||||
// "Auto-backup on changes" (Settings): a dated snapshot dropped into the Documents folder —
|
||||
// visible in Files (iOS) / a file manager (Android), unlike the private mirror nativeSave keeps
|
||||
// — so whatever the user points at that folder (a sync app, a manual copy) always has something
|
||||
// recent. One file per day; later triggers the same day just overwrite it.
|
||||
export async function writeAutoBackup(state) {
|
||||
try {
|
||||
const { Filesystem, Directory, Encoding } = await import('@capacitor/filesystem')
|
||||
await Filesystem.writeFile({
|
||||
path: `opengym-backup-${todayISO()}.json`,
|
||||
directory: Directory.Documents,
|
||||
data: JSON.stringify(state),
|
||||
encoding: Encoding.UTF8,
|
||||
recursive: true,
|
||||
})
|
||||
} catch (e) { /* best effort — the private mirror in Directory.Data still has the data */ }
|
||||
}
|
||||
@@ -148,6 +148,32 @@ describe('is1RMRecord', () => {
|
||||
})
|
||||
|
||||
|
||||
describe('drop-sets, rest-pause sets and 1RM', () => {
|
||||
it('estimates only from the main/activation weight×reps, ignoring lighter drops', () => {
|
||||
const entry = { id: 'x', sets: [
|
||||
{ type: 'dropset', w: 100, r: 5, done: true, drops: [{ w: 80, r: 5 }, { w: 60, r: 5 }] },
|
||||
] }
|
||||
expect(bestSetOf(entry)).toEqual(bestSetOf({ id: 'x', sets: [{ w: 100, r: 5, done: true }] }))
|
||||
})
|
||||
|
||||
it('estimates only from the row\'s own w/r, ignoring rest-pause bursts', () => {
|
||||
const entry = { id: 'x', sets: [
|
||||
{ type: 'restpause', w: 60, r: 8, done: true, clusters: [{ r: 4, restSec: 15 }, { r: 3, restSec: 15 }] },
|
||||
] }
|
||||
expect(bestSetOf(entry)).toEqual(bestSetOf({ id: 'x', sets: [{ w: 60, r: 8, done: true }] }))
|
||||
})
|
||||
|
||||
it('refuses to estimate a planned rest-pause row once its total reps exceed REP_CAP, same as any other high-rep set', () => {
|
||||
// A planned rest-pause row's own r is the total across every burst (see
|
||||
// applyIntensifierPlan/history.js), so it commonly lands above REP_CAP — the row is real
|
||||
// work, but "estimate a max from 20 broken-up reps" is exactly the fantasy REP_CAP refuses.
|
||||
const entry = { id: 'x', sets: [
|
||||
{ type: 'restpause', w: 60, r: 20, done: true, clusters: [{ r: 10, restSec: 15 }, { r: 5, restSec: 15 }, { r: 3, restSec: 15 }, { r: 1, restSec: 15 }, { r: 1, restSec: 15 }] },
|
||||
] }
|
||||
expect(bestSetOf(entry)).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('warm-up sets and 1RM', () => {
|
||||
const ENTRY = { id: 'warm-test', sets: [
|
||||
{ w: 20, r: 8, done: true, warmup: true },
|
||||
|
||||
@@ -272,7 +272,12 @@ export function applyPrescription(sets, p) {
|
||||
// would both invent work and never terminate the loop. Leave the entry untouched.
|
||||
if (!workRows.length) return out
|
||||
const seed = workRows[workRows.length - 1]
|
||||
while (out.filter(s => !isWarmupRow(s)).length < p.sets) out.push({ ...seed, done: false })
|
||||
// A freshly appended row hasn't been performed, so it never inherits a seed's already-
|
||||
// logged drops/clusters — that would invent extra work the row never actually did. Its
|
||||
// `type` is kept: that's the exercise's plan (every set is a drop-set/rest-pause), not
|
||||
// something this particular row logged.
|
||||
const { drops, clusters, ...plainSeed } = seed
|
||||
while (out.filter(s => !isWarmupRow(s)).length < p.sets) out.push({ ...plainSeed, done: false })
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -523,3 +523,34 @@ describe('applyPrescription never touches warm-up rows (round 3)', () => {
|
||||
expect(out).toEqual(sets) // no work row to seed growth from - nothing grows, no loop
|
||||
})
|
||||
})
|
||||
|
||||
describe('drop-sets and rest-pause sets in progression', () => {
|
||||
it('readSession judges a drop-set row on its own main weight/reps, ignoring the drops', () => {
|
||||
const withDrops = readSession({ id: LIFT, target: { sets: 1, reps: 5 }, sets: [
|
||||
{ type: 'dropset', w: 60, r: 5, done: true, drops: [{ w: 40, r: 8 }, { w: 20, r: 10 }] },
|
||||
] })
|
||||
const plain = readSession({ id: LIFT, target: { sets: 1, reps: 5 }, sets: [{ w: 60, r: 5, done: true }] })
|
||||
expect(withDrops).toEqual(plain)
|
||||
})
|
||||
|
||||
it('readSession judges a rest-pause row on its activation weight/reps, ignoring the bursts', () => {
|
||||
const withBursts = readSession({ id: LIFT, target: { sets: 1, reps: 8 }, sets: [
|
||||
{ type: 'restpause', w: 60, r: 8, done: true, clusters: [{ r: 4, restSec: 15 }, { r: 3, restSec: 15 }] },
|
||||
] })
|
||||
const plain = readSession({ id: LIFT, target: { sets: 1, reps: 8 }, sets: [{ w: 60, r: 8, done: true }] })
|
||||
expect(withBursts).toEqual(plain)
|
||||
})
|
||||
|
||||
it('applyPrescription still rewrites a drop-set/rest-pause row\'s own weight, leaving its drops/clusters untouched', () => {
|
||||
const sets = [{ type: 'dropset', w: 60, r: 5, done: false, drops: [{ w: 40, r: 8 }] }]
|
||||
const out = applyPrescription(sets, { kind: 'up', weight: 62.5 })
|
||||
expect(out[0]).toEqual({ type: 'dropset', w: 62.5, r: 5, done: false, drops: [{ w: 40, r: 8 }] })
|
||||
})
|
||||
|
||||
it('a newly grown row keeps the seed\'s planned type but not its already-logged drops/clusters', () => {
|
||||
const sets = [{ type: 'dropset', w: 0, r: 10, done: false, drops: [{ w: 0, r: 12 }] }]
|
||||
const out = applyPrescription(sets, { kind: 'up', weight: 0, reps: 10, sets: 2 })
|
||||
expect(out).toHaveLength(2)
|
||||
expect(out[1]).toEqual({ type: 'dropset', w: 0, r: 10, done: false })
|
||||
})
|
||||
})
|
||||
@@ -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(260)
|
||||
expect(inherited).toHaveLength(416)
|
||||
expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(283)
|
||||
expect(inherited).toHaveLength(437)
|
||||
// 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('4c32711daa44d6d35d775efd5324036d351b2d6c61d06c734e813b7096f8f704')
|
||||
expect(fingerprint, 'pt-PT inheritance changed; review the inherited pt-BR wording').toBe('70fd93bc049da76bc578701a82ecde33b1521ddae37a403076ad48b9694cc4e3')
|
||||
})
|
||||
|
||||
test('does not leak European Portuguese UI terms', () => {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { EXIDX } from './exercises.js'
|
||||
import { MUSCLES, musclesOf } from './muscles.js'
|
||||
import { isWarmupRow } from './workout-model.js'
|
||||
import { isWarmupRow, dropsOf } from './workout-model.js'
|
||||
|
||||
// A "normal" hard session for one muscle, in primary-set equivalents. The saturation curve
|
||||
// 1 - exp(-stimulus / REF) maps any session size onto [0,1) so volume raises the starting
|
||||
@@ -172,6 +172,25 @@ function session1RMs(workout, opts = {}) {
|
||||
return best
|
||||
}
|
||||
|
||||
// Extra tonnage from a drop-set's drops, weighted the same way as the row's own main set — a
|
||||
// drop taken near failure counts the same as any other hard rep for fatigue purposes, it just
|
||||
// carries its own (usually lighter) load.
|
||||
//
|
||||
// A rest-pause row's `clusters` are NOT extra here: the row's own `r` already is the total reps
|
||||
// across every burst (see applyIntensifierPlan/history.js), so the main tonnage term below
|
||||
// already covers it — adding clusters on top would double-count the same reps.
|
||||
function extraTonnage(ex, entry, set, workout, oneRm, opts = {}) {
|
||||
const drops = dropsOf(set)
|
||||
if (!drops.length) return 0
|
||||
const isBwEx = bodyweightConfigured(ex, entry, set, workout, opts)
|
||||
const weigh = (load, reps) => {
|
||||
if (!(load > 0) || !(reps > 0)) return 0
|
||||
const raw = load * reps
|
||||
return isBwEx || !(oneRm > 0) ? raw : raw * Math.min(1, load / oneRm) ** 1.5
|
||||
}
|
||||
return drops.reduce((sum, d) => sum + weigh(loadKgFor(ex, entry, d, workout, opts), Number(d?.r) || 0), 0)
|
||||
}
|
||||
|
||||
// Intensity-weighted tonnage for one completed set: load x reps x (load / exercise 1RM)^1.5.
|
||||
// The exponent saturates the "hard set" effect - a set at 90% of your 1RM counts ~0.81 of its
|
||||
// raw tonnage, one at 50% only ~0.35. Cardio, timed holds, and sets whose exercise has no
|
||||
@@ -186,13 +205,14 @@ function setTonnage(ex, entry, set, workout, oneRm, opts = {}) {
|
||||
const reps = set?.r || 1
|
||||
const load = loadKgFor(ex, entry, set, workout, opts)
|
||||
const raw = load * reps
|
||||
const extra = extraTonnage(ex, entry, set, workout, oneRm, opts)
|
||||
// A bodyweight target is already an external-load-normalised total (body mass + any added
|
||||
// load). It has no meaningful barbell-style 1RM intensity ratio in the legacy data model, so
|
||||
// retain the monotonic total-load stimulus instead of letting a newly created low 1RM shrink
|
||||
// a weighted bodyweight set below the unloaded version.
|
||||
if (bodyweightConfigured(ex, entry, set, workout, opts)) return raw
|
||||
if (!(oneRm > 0) || !(load > 0)) return raw
|
||||
return raw * Math.min(1, load / oneRm) ** 1.5
|
||||
if (bodyweightConfigured(ex, entry, set, workout, opts)) return raw + extra
|
||||
if (!(oneRm > 0) || !(load > 0)) return raw + extra
|
||||
return raw * Math.min(1, load / oneRm) ** 1.5 + extra
|
||||
}
|
||||
|
||||
// One session's per-muscle stimulus, calculated only from that session. A completed zero-load
|
||||
|
||||
@@ -403,6 +403,47 @@ describe('warm-up flag in strength and fatigue', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('drop-set drops add fatigue tonnage on top of the main set', () => {
|
||||
// Same within-session Epley baseline setTonnage derives from the row's own w/r (8 reps,
|
||||
// under REP_CAP), so a drop is weighted against the same 1RM as the main set.
|
||||
const oneRm = 80 * (1 + 8 / 30)
|
||||
|
||||
it('a drop-set drop adds its own intensity-weighted tonnage', () => {
|
||||
const dropRow = { done: true, type: 'dropset', w: 80, r: 8, drops: [{ w: 60, r: 6 }] }
|
||||
const dropTonnage = 60 * 6 * Math.min(1, 60 / oneRm) ** 1.5
|
||||
const expected = expectedFatigue([{ stimulus: V + dropTonnage }])
|
||||
|
||||
expect(fatigueOf([workoutAt(SINGLE.id, NOW, [dropRow])], NOW)[SINGLE_SLUG]).toBeCloseTo(expected, 8)
|
||||
// strictly more than the plain 80x8 set alone — the drop is real extra work
|
||||
expect(fatigueOf([workoutAt(SINGLE.id, NOW, [dropRow])], NOW)[SINGLE_SLUG])
|
||||
.toBeGreaterThan(fatigueOf([doneWorkoutAt(SINGLE.id, NOW)], NOW)[SINGLE_SLUG])
|
||||
})
|
||||
|
||||
it('leaves fatigue unchanged for a straight set with no drops', () => {
|
||||
const plain = { done: true, w: 80, r: 8 }
|
||||
expect(fatigueOf([workoutAt(SINGLE.id, NOW, [plain])], NOW)[SINGLE_SLUG])
|
||||
.toBeCloseTo(expectedFatigue([{ stimulus: V }]), 8)
|
||||
})
|
||||
})
|
||||
|
||||
describe('a rest-pause row\'s clusters add no extra fatigue tonnage', () => {
|
||||
// Its own r is already the total across every burst (see applyIntensifierPlan/history.js),
|
||||
// so setTonnage's main w x r term already covers all of it — clusters are a breakdown only.
|
||||
it('matches a plain set of the same w/r exactly, regardless of how the clusters break it down', () => {
|
||||
const burstRow = { done: true, type: 'restpause', w: 80, r: 8, clusters: [{ r: 4, restSec: 15 }] }
|
||||
const plainRow = { done: true, w: 80, r: 8 }
|
||||
expect(fatigueOf([workoutAt(SINGLE.id, NOW, [burstRow])], NOW)[SINGLE_SLUG])
|
||||
.toBeCloseTo(fatigueOf([workoutAt(SINGLE.id, NOW, [plainRow])], NOW)[SINGLE_SLUG], 10)
|
||||
})
|
||||
|
||||
it('holds for a realistic planned total too — a full descending split adds nothing beyond the row\'s own r', () => {
|
||||
const burstRow = { done: true, type: 'restpause', w: 80, r: 20, clusters: [{ r: 10, restSec: 15 }, { r: 5, restSec: 15 }, { r: 3, restSec: 15 }, { r: 1, restSec: 15 }, { r: 1, restSec: 15 }] }
|
||||
const plainRow = { done: true, w: 80, r: 20 }
|
||||
expect(fatigueOf([workoutAt(SINGLE.id, NOW, [burstRow])], NOW)[SINGLE_SLUG])
|
||||
.toBeCloseTo(fatigueOf([workoutAt(SINGLE.id, NOW, [plainRow])], NOW)[SINGLE_SLUG], 10)
|
||||
})
|
||||
})
|
||||
|
||||
describe('canonical loads and configured bodyweight', () => {
|
||||
const loaded = EXDB.find(ex => {
|
||||
const weights = musclesOf(ex)
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
// Mobile build only: "connect to my server" mode (see mobile.js's header comment for why the
|
||||
// mobile flavor has no backend at all by default). This is the alternative — pairing the app to
|
||||
// an already self-hosted openGym server instead of keeping data device-local.
|
||||
//
|
||||
// Passkeys can't be used from inside the app's own WebView (its origin never matches the
|
||||
// server's RP_ID), so auth here is a short one-time code redeemed from an already signed-in
|
||||
// browser tab (Settings → "Pair the mobile app") for a bearer token — see api/server.js's
|
||||
// /api/pair/create + /api/pair/redeem.
|
||||
import { pairRedeem, setRemoteAuth } from './api.js'
|
||||
import { loadRemoteFile, saveRemoteFile } from './mobile.js'
|
||||
|
||||
// Accepts what someone actually types: bare host, no scheme, trailing slash, stray whitespace.
|
||||
// Defaults to https:// (self-hosting docs already push for HTTPS; the one exception, localhost,
|
||||
// still parses fine without a scheme). Returns null for anything that isn't a usable URL at all.
|
||||
export function normalizeServerUrl(raw) {
|
||||
const s = String(raw || '').trim()
|
||||
if (!s) return null
|
||||
const withScheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(s) ? s : 'https://' + s
|
||||
try {
|
||||
const u = new URL(withScheme)
|
||||
if (!u.hostname) return null
|
||||
return u.origin
|
||||
} catch (e) { return null }
|
||||
}
|
||||
|
||||
export async function loadRemote() {
|
||||
return loadRemoteFile()
|
||||
}
|
||||
|
||||
export async function chooseLocal() {
|
||||
await saveRemoteFile({ mode: 'local' })
|
||||
}
|
||||
|
||||
export async function forgetRemote() {
|
||||
await saveRemoteFile({ mode: 'local' })
|
||||
setRemoteAuth('', null)
|
||||
}
|
||||
|
||||
// Redeems the pairing code, wires api.js at the resolved base, and persists the connection so
|
||||
// boot() can restore it on the next launch.
|
||||
export async function connect(rawUrl, code) {
|
||||
const base = normalizeServerUrl(rawUrl)
|
||||
if (!base) throw new Error('Enter a valid server address')
|
||||
const { token, user } = await pairRedeem(base, String(code || '').trim())
|
||||
setRemoteAuth(base, token)
|
||||
await saveRemoteFile({ mode: 'remote', base, token, user })
|
||||
return user
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { normalizeServerUrl } from './remote.js'
|
||||
|
||||
// The pairing flow lives or dies on this being forgiving about what someone types on a phone
|
||||
// keyboard, while still refusing input that can't possibly be a server address.
|
||||
describe('normalizeServerUrl', () => {
|
||||
it('accepts a bare host and adds https://', () => {
|
||||
expect(normalizeServerUrl('gym.example.com')).toBe('https://gym.example.com')
|
||||
})
|
||||
|
||||
it('keeps an explicit scheme, including http for LAN testing', () => {
|
||||
expect(normalizeServerUrl('http://192.168.1.20:8080')).toBe('http://192.168.1.20:8080')
|
||||
expect(normalizeServerUrl('https://gym.example.com')).toBe('https://gym.example.com')
|
||||
})
|
||||
|
||||
it('trims whitespace and a trailing path/slash down to the origin', () => {
|
||||
expect(normalizeServerUrl(' gym.example.com/ ')).toBe('https://gym.example.com')
|
||||
expect(normalizeServerUrl('https://gym.example.com/some/path')).toBe('https://gym.example.com')
|
||||
})
|
||||
|
||||
it('rejects empty or unusable input', () => {
|
||||
for (const v of ['', ' ', null, undefined, 'not a url at all!!']) {
|
||||
expect(normalizeServerUrl(v)).toBe(null)
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -22,6 +22,112 @@ export function isWarmupRow(set) {
|
||||
return phaseForSet(set) === 'warmup'
|
||||
}
|
||||
|
||||
// A row's shape beyond warm-up/work: 'straight' (default), 'dropset' (a main set followed by
|
||||
// weight drops logged with no rest) or 'restpause' (an activation set followed by short-rest
|
||||
// bursts). Both extras ride on the row itself — same card, not a new set in the array — the
|
||||
// same trick `phase` uses for warm-ups, so the rest of the app can keep reading a row's own
|
||||
// `w`/`r` and stay correct without knowing this field exists.
|
||||
export function setType(set) {
|
||||
const source = objectOf(set)
|
||||
return source.type === 'dropset' || source.type === 'restpause' ? source.type : 'straight'
|
||||
}
|
||||
export const isDropSet = set => setType(set) === 'dropset'
|
||||
export const isRestPauseSet = set => setType(set) === 'restpause'
|
||||
|
||||
/** A drop-set's weight drops, oldest first; empty for anything else. */
|
||||
export function dropsOf(set) {
|
||||
const source = objectOf(set)
|
||||
return isDropSet(source) && Array.isArray(source.drops) ? source.drops : []
|
||||
}
|
||||
|
||||
/** A rest-pause set's short-rest bursts, oldest first; empty for anything else. */
|
||||
export function clustersOf(set) {
|
||||
const source = objectOf(set)
|
||||
return isRestPauseSet(source) && Array.isArray(source.clusters) ? source.clusters : []
|
||||
}
|
||||
|
||||
/**
|
||||
* Weight x reps from a drop-set's drops, on top of its own main set. The 1RM estimate and the
|
||||
* progression engine deliberately read only a row's own `w`/`r` (the heaviest effort), so this
|
||||
* is the one place a drop-set's extra volume gets added back in for totals.
|
||||
*
|
||||
* A rest-pause row is different: its own `r` IS the total (every burst's reps included), and
|
||||
* `clusters` is only how that total breaks down — not extra volume on top of it. Adding
|
||||
* `clustersOf(set)` here as well would double-count the same reps twice.
|
||||
*/
|
||||
export function extraVolumeOf(set) {
|
||||
const drops = dropsOf(set)
|
||||
return drops.reduce((v, d) => v + (Number(d?.w) || 0) * (Number(d?.r) || 0), 0)
|
||||
}
|
||||
|
||||
/** Append a weight drop to a row, marking it a drop-set. */
|
||||
export function addDrop(set, drop) {
|
||||
const prev = Array.isArray(objectOf(set).drops) ? objectOf(set).drops : []
|
||||
return { ...objectOf(set), type: 'dropset', drops: [...prev, { w: Number(drop?.w) || 0, r: Number(drop?.r) || 0 }] }
|
||||
}
|
||||
|
||||
/** Append a short-rest burst to a row, marking it a rest-pause set. */
|
||||
export function addCluster(set, cluster) {
|
||||
const prev = Array.isArray(objectOf(set).clusters) ? objectOf(set).clusters : []
|
||||
return { ...objectOf(set), type: 'restpause', clusters: [...prev, { r: Number(cluster?.r) || 0, restSec: Number(cluster?.restSec) || 0 }] }
|
||||
}
|
||||
|
||||
/** Remove one drop by index. Clearing the last one reverts the row to a straight set. */
|
||||
export function removeDropAt(set, i) {
|
||||
const drops = (objectOf(set).drops || []).filter((_, idx) => idx !== i)
|
||||
return drops.length ? { ...objectOf(set), drops } : { ...objectOf(set), type: 'straight', drops }
|
||||
}
|
||||
|
||||
/** Remove one burst by index. Clearing the last one reverts the row to a straight set. */
|
||||
export function removeClusterAt(set, i) {
|
||||
const clusters = (objectOf(set).clusters || []).filter((_, idx) => idx !== i)
|
||||
return clusters.length ? { ...objectOf(set), clusters } : { ...objectOf(set), type: 'straight', clusters }
|
||||
}
|
||||
|
||||
/** Patch one drop's fields in place (weight/reps steppers edit an existing drop). */
|
||||
export function setDropAt(set, i, patch) {
|
||||
const drops = (objectOf(set).drops || []).slice()
|
||||
if (!drops[i]) return set
|
||||
drops[i] = { ...drops[i], ...patch }
|
||||
return { ...objectOf(set), drops }
|
||||
}
|
||||
|
||||
/** Patch one burst's fields in place (a reps stepper edits an existing burst). */
|
||||
export function setClusterAt(set, i, patch) {
|
||||
const clusters = (objectOf(set).clusters || []).slice()
|
||||
if (!clusters[i]) return set
|
||||
clusters[i] = { ...clusters[i], ...patch }
|
||||
return { ...objectOf(set), clusters }
|
||||
}
|
||||
|
||||
/** Suggested weight for the next drop: pct% lighter than the previous weight, rounded to .5. */
|
||||
export function nextDropWeight(prevWeight, pct = 20) {
|
||||
const p = Math.min(90, Math.max(1, Number(pct) || 20))
|
||||
return Math.round(Math.max(0, (Number(prevWeight) || 0) * (1 - p / 100)) * 2) / 2
|
||||
}
|
||||
|
||||
/** Suggested reps for the next rest-pause burst: roughly half the previous rep count. */
|
||||
export function nextBurstReps(prevReps) {
|
||||
return Math.max(1, Math.round((Number(prevReps) || 0) / 2))
|
||||
}
|
||||
|
||||
/**
|
||||
* Split a rest-pause total (the extra reps you want past the activation set) into a descending,
|
||||
* roughly-halving sequence of bursts that adds back up to it — e.g. 12 -> [6, 3, 2, 1]. This is
|
||||
* what a planned rest-pause exercise configures directly, rather than a burst count picked by
|
||||
* hand: you say how many reps you want out of the whole rest-pause portion, not how many rests.
|
||||
*/
|
||||
export function splitBurstReps(total) {
|
||||
const bursts = []
|
||||
let remaining = Math.max(0, Math.round(Number(total) || 0))
|
||||
while (remaining > 0) {
|
||||
const burst = Math.min(remaining, nextBurstReps(remaining))
|
||||
bursts.push(burst)
|
||||
remaining -= burst
|
||||
}
|
||||
return bursts
|
||||
}
|
||||
|
||||
export function normalizeMode(value, fallback = 'reps') {
|
||||
const token = typeof value === 'string' ? value.trim().toLowerCase() : ''
|
||||
if (MODES.includes(token)) return token
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import {
|
||||
phaseForSet, isWarmupRow, modeForSet, modeForEntry,
|
||||
setType, isDropSet, isRestPauseSet, dropsOf, clustersOf, extraVolumeOf,
|
||||
addDrop, addCluster, removeDropAt, removeClusterAt, setDropAt, setClusterAt,
|
||||
nextDropWeight, nextBurstReps, splitBurstReps,
|
||||
} from './workout-model.js'
|
||||
|
||||
describe('phaseForSet / isWarmupRow', () => {
|
||||
it('reads both the explicit phase and the legacy boolean', () => {
|
||||
expect(isWarmupRow({ phase: 'warmup' })).toBe(true)
|
||||
expect(isWarmupRow({ warmup: true })).toBe(true)
|
||||
expect(isWarmupRow({ phase: 'work' })).toBe(false)
|
||||
expect(isWarmupRow({})).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('setType / isDropSet / isRestPauseSet', () => {
|
||||
it('defaults to straight for anything without a recognised type', () => {
|
||||
expect(setType({})).toBe('straight')
|
||||
expect(setType({ type: 'nonsense' })).toBe('straight')
|
||||
expect(setType(null)).toBe('straight')
|
||||
expect(isDropSet({})).toBe(false)
|
||||
expect(isRestPauseSet({})).toBe(false)
|
||||
})
|
||||
|
||||
it('recognises drop-set and rest-pause rows', () => {
|
||||
expect(setType({ type: 'dropset' })).toBe('dropset')
|
||||
expect(isDropSet({ type: 'dropset' })).toBe(true)
|
||||
expect(setType({ type: 'restpause' })).toBe('restpause')
|
||||
expect(isRestPauseSet({ type: 'restpause' })).toBe(true)
|
||||
})
|
||||
|
||||
it('is a separate axis from warm-up — a row is not both at once by construction, but phase never leaks into type', () => {
|
||||
expect(setType({ phase: 'warmup', type: 'dropset' })).toBe('dropset')
|
||||
expect(isWarmupRow({ phase: 'warmup', type: 'dropset' })).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('dropsOf / clustersOf', () => {
|
||||
it('only return rows for their own type', () => {
|
||||
const drop = { type: 'dropset', drops: [{ w: 80, r: 5 }] }
|
||||
const burst = { type: 'restpause', clusters: [{ r: 4, restSec: 15 }] }
|
||||
expect(dropsOf(drop)).toEqual([{ w: 80, r: 5 }])
|
||||
expect(clustersOf(drop)).toEqual([])
|
||||
expect(clustersOf(burst)).toEqual([{ r: 4, restSec: 15 }])
|
||||
expect(dropsOf(burst)).toEqual([])
|
||||
})
|
||||
|
||||
it('is defensive about missing/malformed arrays', () => {
|
||||
expect(dropsOf({ type: 'dropset' })).toEqual([])
|
||||
expect(dropsOf({ type: 'dropset', drops: 'nope' })).toEqual([])
|
||||
expect(clustersOf(null)).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('extraVolumeOf', () => {
|
||||
it('sums weight x reps across a drop-set\'s own drops', () => {
|
||||
const set = { type: 'dropset', w: 100, r: 5, drops: [{ w: 80, r: 5 }, { w: 60, r: 6 }] }
|
||||
expect(extraVolumeOf(set)).toBe(80 * 5 + 60 * 6)
|
||||
})
|
||||
|
||||
it('is zero for rest-pause — its own r is already the total across every burst, so clusters are a breakdown, not extra volume', () => {
|
||||
const set = { type: 'restpause', w: 60, r: 20, clusters: [{ r: 10, restSec: 15 }, { r: 5, restSec: 15 }, { r: 3, restSec: 15 }, { r: 1, restSec: 15 }, { r: 1, restSec: 15 } ] }
|
||||
expect(extraVolumeOf(set)).toBe(0)
|
||||
})
|
||||
|
||||
it('is zero for a straight or warm-up set', () => {
|
||||
expect(extraVolumeOf({ w: 100, r: 5 })).toBe(0)
|
||||
expect(extraVolumeOf({ phase: 'warmup', w: 20, r: 8 })).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('addDrop / addCluster', () => {
|
||||
it('appends a drop and stamps the row as a drop-set', () => {
|
||||
const set = { w: 100, r: 5, done: true }
|
||||
const next = addDrop(set, { w: 80, r: 5 })
|
||||
expect(next.type).toBe('dropset')
|
||||
expect(next.drops).toEqual([{ w: 80, r: 5 }])
|
||||
expect(set.drops).toBeUndefined() // pure — the original row is untouched
|
||||
expect(addDrop(next, { w: 60, r: 4 }).drops).toEqual([{ w: 80, r: 5 }, { w: 60, r: 4 }])
|
||||
})
|
||||
|
||||
it('appends a burst and stamps the row as a rest-pause set', () => {
|
||||
const set = { w: 60, r: 8, done: true }
|
||||
const next = addCluster(set, { r: 4, restSec: 15 })
|
||||
expect(next.type).toBe('restpause')
|
||||
expect(next.clusters).toEqual([{ r: 4, restSec: 15 }])
|
||||
})
|
||||
})
|
||||
|
||||
describe('removeDropAt / removeClusterAt', () => {
|
||||
it('removes one entry by index, leaving the rest in place', () => {
|
||||
const set = { type: 'dropset', w: 100, r: 5, drops: [{ w: 80, r: 5 }, { w: 60, r: 5 }] }
|
||||
expect(removeDropAt(set, 0).drops).toEqual([{ w: 60, r: 5 }])
|
||||
})
|
||||
|
||||
it('removes one burst by index', () => {
|
||||
const set = { type: 'restpause', w: 60, r: 8, clusters: [{ r: 4, restSec: 15 }, { r: 3, restSec: 15 }] }
|
||||
expect(removeClusterAt(set, 1).clusters).toEqual([{ r: 4, restSec: 15 }])
|
||||
})
|
||||
|
||||
it('reverts the row to a straight set once its last drop/burst is removed', () => {
|
||||
const drop = { type: 'dropset', w: 100, r: 5, drops: [{ w: 80, r: 5 }] }
|
||||
expect(removeDropAt(drop, 0)).toEqual({ type: 'straight', w: 100, r: 5, drops: [] })
|
||||
expect(isDropSet(removeDropAt(drop, 0))).toBe(false)
|
||||
|
||||
const burst = { type: 'restpause', w: 60, r: 8, clusters: [{ r: 4, restSec: 15 }] }
|
||||
expect(removeClusterAt(burst, 0)).toEqual({ type: 'straight', w: 60, r: 8, clusters: [] })
|
||||
expect(isRestPauseSet(removeClusterAt(burst, 0))).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('setDropAt / setClusterAt', () => {
|
||||
it('patches one drop\'s fields, leaving the others untouched', () => {
|
||||
const set = { type: 'dropset', w: 100, r: 5, drops: [{ w: 80, r: 5 }, { w: 60, r: 5 }] }
|
||||
expect(setDropAt(set, 0, { w: 82.5 }).drops).toEqual([{ w: 82.5, r: 5 }, { w: 60, r: 5 }])
|
||||
expect(setDropAt(set, 1, { r: 6 }).drops).toEqual([{ w: 80, r: 5 }, { w: 60, r: 6 }])
|
||||
})
|
||||
|
||||
it('patches one burst\'s reps', () => {
|
||||
const set = { type: 'restpause', w: 60, r: 8, clusters: [{ r: 4, restSec: 15 }] }
|
||||
expect(setClusterAt(set, 0, { r: 5 }).clusters).toEqual([{ r: 5, restSec: 15 }])
|
||||
})
|
||||
|
||||
it('is a no-op for an index that does not exist', () => {
|
||||
const set = { type: 'dropset', w: 100, r: 5, drops: [{ w: 80, r: 5 }] }
|
||||
expect(setDropAt(set, 3, { w: 1 })).toBe(set)
|
||||
})
|
||||
})
|
||||
|
||||
describe('nextDropWeight / nextBurstReps', () => {
|
||||
it('drops by the given percentage, rounded to the nearest .5', () => {
|
||||
expect(nextDropWeight(100, 20)).toBe(80)
|
||||
expect(nextDropWeight(80, 20)).toBe(64)
|
||||
expect(nextDropWeight(61, 10)).toBe(55)
|
||||
})
|
||||
|
||||
it('defaults to 20% and never goes negative', () => {
|
||||
expect(nextDropWeight(100)).toBe(80)
|
||||
expect(nextDropWeight(0, 20)).toBe(0)
|
||||
})
|
||||
|
||||
it('roughly halves the previous rep count, floored at 1', () => {
|
||||
expect(nextBurstReps(8)).toBe(4)
|
||||
expect(nextBurstReps(1)).toBe(1)
|
||||
expect(nextBurstReps(0)).toBe(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('splitBurstReps', () => {
|
||||
it('splits a total into a descending, roughly-halving sequence that adds back up to it', () => {
|
||||
expect(splitBurstReps(12)).toEqual([6, 3, 2, 1])
|
||||
expect(splitBurstReps(6)).toEqual([3, 2, 1])
|
||||
expect(splitBurstReps(1)).toEqual([1])
|
||||
})
|
||||
|
||||
it('every split sums exactly to the requested total', () => {
|
||||
for (const total of [1, 2, 3, 5, 7, 10, 15, 20, 33]) {
|
||||
expect(splitBurstReps(total).reduce((a, b) => a + b, 0)).toBe(total)
|
||||
}
|
||||
})
|
||||
|
||||
it('is empty for zero or invalid input', () => {
|
||||
expect(splitBurstReps(0)).toEqual([])
|
||||
expect(splitBurstReps(-5)).toEqual([])
|
||||
expect(splitBurstReps(undefined)).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('modeForSet / modeForEntry stay reps-mode for drop-sets and rest-pause sets', () => {
|
||||
it('infers reps mode from the row\'s own r field regardless of type', () => {
|
||||
expect(modeForSet({ type: 'dropset', w: 100, r: 5 })).toBe('reps')
|
||||
expect(modeForSet({ type: 'restpause', w: 60, r: 8 })).toBe('reps')
|
||||
})
|
||||
|
||||
it('an entry mixing straight and drop-set rows still reads as one reps-mode entry', () => {
|
||||
const entry = { sets: [{ w: 100, r: 5 }, { type: 'dropset', w: 100, r: 5, drops: [{ w: 80, r: 5 }] }] }
|
||||
expect(modeForEntry(entry)).toBe('reps')
|
||||
})
|
||||
})
|
||||
@@ -170,6 +170,24 @@ export default {
|
||||
'Warm-up': 'Aufwärmen',
|
||||
'Add warm-up set': 'Aufwärmsatz hinzufügen',
|
||||
'Add set': 'Satz hinzufügen',
|
||||
'+ Drop': '+ Dropsatz',
|
||||
'+ Burst': '+ Burst',
|
||||
'Drop {0}': 'Dropsatz {0}',
|
||||
'Burst {0}': 'Burst {0}',
|
||||
'Remove drop': 'Dropsatz entfernen',
|
||||
'Remove burst': 'Burst entfernen',
|
||||
'Rest (s)': 'Pause (s)',
|
||||
'Drop-set / rest-pause': 'Dropsatz / Rest-Pause',
|
||||
'Intensifier': 'Intensivierungstechnik',
|
||||
'None': 'Keine',
|
||||
'Drop-set': 'Dropsatz',
|
||||
'Rest-pause': 'Rest-Pause',
|
||||
'Drops': 'Dropsätze',
|
||||
'Weight drop (%)': 'Gewichtsreduktion (%)',
|
||||
'Rest-pause reps': 'Rest-Pause-Wiederholungen',
|
||||
'Rest-pause rest': 'Rest-Pause-Pause',
|
||||
'Every set becomes a drop-set: after the main set, {0} drop(s) with no rest, each about {1}% lighter.': 'Jeder Satz wird zum Dropsatz: nach dem Hauptsatz {0} weitere Stufe(n) ohne Pause, jede etwa {1}% leichter.',
|
||||
'Every set becomes rest-pause: {0} reps to start, then {1} more split into short bursts, {2}s rest before each, roughly halving each time.': 'Jeder Satz wird zu Rest-Pause: {0} Wiederholungen zu Beginn, dann {1} weitere in kurzen Bursts, mit {2}s Pause davor, dabei jedes Mal etwa halbiert.',
|
||||
'Cardio logged': 'Cardio eingetragen',
|
||||
'Discard workout?': 'Training verwerfen?',
|
||||
'The sets you logged in this session will be lost.': 'Die in dieser Einheit eingetragenen Sätze gehen verloren.',
|
||||
@@ -271,6 +289,7 @@ export default {
|
||||
'Theme': 'Design',
|
||||
'Dark': 'Dunkel',
|
||||
'Light': 'Hell',
|
||||
'System': 'System',
|
||||
'Accent color': 'Akzentfarbe',
|
||||
'General': 'Allgemein',
|
||||
'During a workout': 'Während des Trainings',
|
||||
@@ -283,6 +302,8 @@ export default {
|
||||
'Data': 'Daten',
|
||||
'Export backup (JSON)': 'Backup exportieren (JSON)',
|
||||
'Import backup': 'Backup importieren',
|
||||
'Auto-backup on changes': 'Automatische Sicherung bei Änderungen',
|
||||
'Saves a dated copy to the Documents folder after finishing a workout or editing a routine — point a sync app at it, or copy it out by hand.': 'Speichert nach jedem beendeten Training oder jeder bearbeiteten Routine eine datierte Kopie im Ordner „Dokumente" — richte eine Sync-App darauf aus oder kopiere die Datei von Hand.',
|
||||
'Reset everything?': 'Alles zurücksetzen?',
|
||||
'Reset everything': 'Alles zurücksetzen',
|
||||
'Deletes your plan, workouts and body weight on this device. This cannot be undone.': 'Löscht Plan, Trainings und Körpergewicht auf diesem Gerät. Das kann nicht rückgängig gemacht werden.',
|
||||
@@ -622,5 +643,30 @@ export default {
|
||||
// --- muscle groups ---
|
||||
'Primary muscle groups': 'Primäre Muskelgruppen',
|
||||
'Additional muscle groups': 'Zusätzliche Muskelgruppen',
|
||||
'No explicit muscle group': 'Keine explizite Muskelgruppe'
|
||||
'No explicit muscle group': 'Keine explizite Muskelgruppe',
|
||||
|
||||
// "Connect to my server" (mobile app pairing)
|
||||
'Your server': 'Dein Server',
|
||||
'Synced with your openGym server.': 'Mit deinem openGym-Server synchronisiert.',
|
||||
'Disconnect': 'Trennen',
|
||||
'Disconnect from your server?': 'Verbindung zum Server trennen?',
|
||||
'Your data is synced to your server first, then this device switches back to local-only.': 'Deine Daten werden zuerst mit deinem Server synchronisiert, dann wechselt dieses Gerät zurück in den lokalen Modus.',
|
||||
'Disconnected — back to local-only': 'Verbindung getrennt — zurück im lokalen Modus',
|
||||
'Connect to my server': 'Mit meinem Server verbinden',
|
||||
'Sync this device to your own self-hosted openGym instead.': 'Dieses Gerät stattdessen mit deinem eigenen self-hosted openGym synchronisieren.',
|
||||
'Pair the mobile app': 'Mobile App koppeln',
|
||||
'Connect the openGym app on your phone to this account.': 'Verbinde die openGym-App auf deinem Handy mit diesem Konto.',
|
||||
'Could not generate a code': 'Code konnte nicht erstellt werden',
|
||||
'On the openGym app, choose “Connect to my server”, then enter this address and the code below. It expires in 5 minutes.': 'Wähle in der openGym-App „Mit meinem Server verbinden“, gib dann diese Adresse und den Code unten ein. Er läuft in 5 Minuten ab.',
|
||||
'Enter your server address and the code': 'Serveradresse und Code eingeben',
|
||||
'Connected': 'Verbunden',
|
||||
'Could not connect': 'Verbindung fehlgeschlagen',
|
||||
'Open Settings → “Pair the mobile app” on the openGym site you’re already signed into, then enter its address and the code shown there.': 'Öffne auf der openGym-Seite, bei der du bereits angemeldet bist, Einstellungen → „Mobile App koppeln“, und gib dann deren Adresse und den dort angezeigten Code ein.',
|
||||
'Server address (e.g. gym.example.com)': 'Serveradresse (z. B. gym.example.com)',
|
||||
'Pairing code': 'Kopplungscode',
|
||||
'Connecting…': 'Verbinde …',
|
||||
'Connect': 'Verbinden',
|
||||
'How do you want to use openGym?': 'Wie möchtest du openGym nutzen?',
|
||||
'Use on this device': 'Auf diesem Gerät nutzen',
|
||||
'Local keeps everything on this phone. Connecting syncs to your own openGym server instead — you can switch later in Settings.': 'Lokal behält alles auf diesem Handy. Verbinden synchronisiert stattdessen mit deinem eigenen openGym-Server — du kannst das später in den Einstellungen ändern.'
|
||||
}
|
||||
@@ -163,6 +163,24 @@ export default {
|
||||
'Warm-up': 'Calentamiento',
|
||||
'Add warm-up set': 'Añadir serie de calentamiento',
|
||||
'Add set': 'Añadir serie',
|
||||
'+ Drop': '+ Bajada',
|
||||
'+ Burst': '+ Ráfaga',
|
||||
'Drop {0}': 'Bajada {0}',
|
||||
'Burst {0}': 'Ráfaga {0}',
|
||||
'Remove drop': 'Quitar bajada',
|
||||
'Remove burst': 'Quitar ráfaga',
|
||||
'Rest (s)': 'Descanso (s)',
|
||||
'Drop-set / rest-pause': 'Series descendentes / rest-pause',
|
||||
'Intensifier': 'Intensificador',
|
||||
'None': 'Ninguno',
|
||||
'Drop-set': 'Serie descendente',
|
||||
'Rest-pause': 'Rest-pause',
|
||||
'Drops': 'Bajadas',
|
||||
'Weight drop (%)': 'Bajada de peso (%)',
|
||||
'Rest-pause reps': 'Repeticiones rest-pause',
|
||||
'Rest-pause rest': 'Descanso rest-pause',
|
||||
'Every set becomes a drop-set: after the main set, {0} drop(s) with no rest, each about {1}% lighter.': 'Cada serie se convierte en una serie descendente: tras la serie principal, {0} bajada(s) sin descanso, cada una un {1}% más ligera aprox.',
|
||||
'Every set becomes rest-pause: {0} reps to start, then {1} more split into short bursts, {2}s rest before each, roughly halving each time.': 'Cada serie se convierte en rest-pause: {0} reps para empezar, y {1} más repartidas en ráfagas cortas, con {2}s de descanso antes de cada una, bajando aprox. a la mitad cada vez.',
|
||||
'Cardio logged': 'Cardio registrado',
|
||||
'Discard workout?': '¿Descartar entrenamiento?',
|
||||
'The sets you logged in this session will be lost.': 'Las series registradas en esta sesión se perderán.',
|
||||
@@ -257,6 +275,7 @@ export default {
|
||||
'Theme': 'Tema',
|
||||
'Dark': 'Oscuro',
|
||||
'Light': 'Claro',
|
||||
'System': 'Sistema',
|
||||
'Accent color': 'Color de acento',
|
||||
'General': 'General',
|
||||
'During a workout': 'Durante el entrenamiento',
|
||||
@@ -269,6 +288,8 @@ export default {
|
||||
'Data': 'Datos',
|
||||
'Export backup (JSON)': 'Exportar copia (JSON)',
|
||||
'Import backup': 'Importar copia',
|
||||
'Auto-backup on changes': 'Copia automática al modificar',
|
||||
'Saves a dated copy to the Documents folder after finishing a workout or editing a routine — point a sync app at it, or copy it out by hand.': 'Guarda una copia fechada en la carpeta Documentos al terminar un entrenamiento o editar una rutina — apunta una app de sincronización a esa carpeta, o copia el archivo a mano.',
|
||||
'Reset everything?': '¿Restablecer todo?',
|
||||
'Reset everything': 'Restablecer todo',
|
||||
'Deletes your plan, workouts and body weight on this device. This cannot be undone.': 'Elimina tu plan, entrenamientos y peso corporal en este dispositivo. No se puede deshacer.',
|
||||
@@ -605,5 +626,30 @@ export default {
|
||||
// --- muscle groups ---
|
||||
'Primary muscle groups': 'Grupos musculares primarios',
|
||||
'Additional muscle groups': 'Grupos musculares adicionales',
|
||||
'No explicit muscle group': 'Sin grupo muscular explícito'
|
||||
'No explicit muscle group': 'Sin grupo muscular explícito',
|
||||
|
||||
// "Connect to my server" (mobile app pairing)
|
||||
'Your server': 'Tu servidor',
|
||||
'Synced with your openGym server.': 'Sincronizado con tu servidor de openGym.',
|
||||
'Disconnect': 'Desconectar',
|
||||
'Disconnect from your server?': '¿Desconectar de tu servidor?',
|
||||
'Your data is synced to your server first, then this device switches back to local-only.': 'Tus datos se sincronizan primero con tu servidor, y luego este dispositivo vuelve a modo local.',
|
||||
'Disconnected — back to local-only': 'Desconectado — de vuelta a modo local',
|
||||
'Connect to my server': 'Conectar a mi servidor',
|
||||
'Sync this device to your own self-hosted openGym instead.': 'Sincroniza este dispositivo con tu propio openGym self-hosted.',
|
||||
'Pair the mobile app': 'Emparejar la app móvil',
|
||||
'Connect the openGym app on your phone to this account.': 'Conecta la app de openGym en tu móvil a esta cuenta.',
|
||||
'Could not generate a code': 'No se pudo generar un código',
|
||||
'On the openGym app, choose “Connect to my server”, then enter this address and the code below. It expires in 5 minutes.': 'En la app de openGym, elige «Conectar a mi servidor», luego introduce esta dirección y el código de abajo. Caduca en 5 minutos.',
|
||||
'Enter your server address and the code': 'Introduce la dirección de tu servidor y el código',
|
||||
'Connected': 'Conectado',
|
||||
'Could not connect': 'No se pudo conectar',
|
||||
'Open Settings → “Pair the mobile app” on the openGym site you’re already signed into, then enter its address and the code shown there.': 'En Ajustes → «Emparejar la app móvil» del sitio de openGym en el que ya has iniciado sesión, luego introduce su dirección y el código que aparece ahí.',
|
||||
'Server address (e.g. gym.example.com)': 'Dirección del servidor (p. ej. gym.example.com)',
|
||||
'Pairing code': 'Código de emparejamiento',
|
||||
'Connecting…': 'Conectando…',
|
||||
'Connect': 'Conectar',
|
||||
'How do you want to use openGym?': '¿Cómo quieres usar openGym?',
|
||||
'Use on this device': 'Usar en este dispositivo',
|
||||
'Local keeps everything on this phone. Connecting syncs to your own openGym server instead — you can switch later in Settings.': 'Local mantiene todo en este teléfono. Conectar sincroniza con tu propio servidor de openGym — puedes cambiarlo luego en Ajustes.'
|
||||
}
|
||||
@@ -163,6 +163,24 @@ export default {
|
||||
'Warm-up': 'Échauffement',
|
||||
'Add warm-up set': 'Ajouter une série d’échauffement',
|
||||
'Add set': 'Ajouter une série',
|
||||
'+ Drop': '+ Drop set',
|
||||
'+ Burst': '+ Rafale',
|
||||
'Drop {0}': 'Drop set {0}',
|
||||
'Burst {0}': 'Rafale {0}',
|
||||
'Remove drop': 'Retirer le drop set',
|
||||
'Remove burst': 'Retirer la rafale',
|
||||
'Rest (s)': 'Repos (s)',
|
||||
'Drop-set / rest-pause': 'Drop-set / rest-pause',
|
||||
'Intensifier': 'Intensificateur',
|
||||
'None': 'Aucun',
|
||||
'Drop-set': 'Drop-set',
|
||||
'Rest-pause': 'Rest-pause',
|
||||
'Drops': 'Drop sets',
|
||||
'Weight drop (%)': 'Baisse de poids (%)',
|
||||
'Rest-pause reps': 'Répétitions rest-pause',
|
||||
'Rest-pause rest': 'Repos rest-pause',
|
||||
'Every set becomes a drop-set: after the main set, {0} drop(s) with no rest, each about {1}% lighter.': 'Chaque série devient un drop-set : après la série principale, {0} baisse(s) sans repos, chacune environ {1}% plus légère.',
|
||||
'Every set becomes rest-pause: {0} reps to start, then {1} more split into short bursts, {2}s rest before each, roughly halving each time.': 'Chaque série devient rest-pause : {0} répétitions pour commencer, puis {1} de plus réparties en courtes rafales, avec {2}s de repos avant chacune, en diminuant environ de moitié à chaque fois.',
|
||||
'Cardio logged': 'Cardio noté',
|
||||
'Discard workout?': 'Abandonner la séance ?',
|
||||
'The sets you logged in this session will be lost.': 'Les séries notées dans cette session seront perdues.',
|
||||
@@ -257,6 +275,7 @@ export default {
|
||||
'Theme': 'Thème',
|
||||
'Dark': 'Sombre',
|
||||
'Light': 'Clair',
|
||||
'System': 'Système',
|
||||
'Accent color': "Couleur d'accent",
|
||||
'General': 'Général',
|
||||
'During a workout': 'Pendant la séance',
|
||||
@@ -269,6 +288,8 @@ export default {
|
||||
'Data': 'Données',
|
||||
'Export backup (JSON)': 'Exporter une sauvegarde (JSON)',
|
||||
'Import backup': 'Importer une sauvegarde',
|
||||
'Auto-backup on changes': 'Sauvegarde automatique',
|
||||
'Saves a dated copy to the Documents folder after finishing a workout or editing a routine — point a sync app at it, or copy it out by hand.': 'Enregistre une copie datée dans le dossier Documents après chaque entraînement terminé ou modification de routine — pointez une appli de synchronisation dessus, ou copiez le fichier à la main.',
|
||||
'Reset everything?': 'Tout réinitialiser ?',
|
||||
'Reset everything': 'Tout réinitialiser',
|
||||
'Deletes your plan, workouts and body weight on this device. This cannot be undone.': 'Supprime ton plan, tes séances et ton poids corporel sur cet appareil. Irréversible.',
|
||||
@@ -605,5 +626,30 @@ export default {
|
||||
// --- muscle groups ---
|
||||
'Primary muscle groups': 'Groupes musculaires principaux',
|
||||
'Additional muscle groups': 'Groupes musculaires supplémentaires',
|
||||
'No explicit muscle group': 'Aucun groupe musculaire explicite'
|
||||
'No explicit muscle group': 'Aucun groupe musculaire explicite',
|
||||
|
||||
// "Connect to my server" (mobile app pairing)
|
||||
'Your server': 'Votre serveur',
|
||||
'Synced with your openGym server.': 'Synchronisé avec votre serveur openGym.',
|
||||
'Disconnect': 'Déconnecter',
|
||||
'Disconnect from your server?': 'Se déconnecter de votre serveur ?',
|
||||
'Your data is synced to your server first, then this device switches back to local-only.': "Vos données sont d'abord synchronisées avec votre serveur, puis cet appareil repasse en mode local.",
|
||||
'Disconnected — back to local-only': 'Déconnecté — retour en mode local',
|
||||
'Connect to my server': 'Se connecter à mon serveur',
|
||||
'Sync this device to your own self-hosted openGym instead.': 'Synchronise plutôt cet appareil avec votre propre openGym self-hosted.',
|
||||
'Pair the mobile app': "Associer l'application mobile",
|
||||
'Connect the openGym app on your phone to this account.': "Associez l'application openGym de votre téléphone à ce compte.",
|
||||
'Could not generate a code': 'Impossible de générer un code',
|
||||
'On the openGym app, choose “Connect to my server”, then enter this address and the code below. It expires in 5 minutes.': "Dans l'application openGym, choisissez « Se connecter à mon serveur », puis saisissez cette adresse et le code ci-dessous. Il expire dans 5 minutes.",
|
||||
'Enter your server address and the code': "Saisissez l'adresse de votre serveur et le code",
|
||||
'Connected': 'Connecté',
|
||||
'Could not connect': 'Connexion impossible',
|
||||
'Open Settings → “Pair the mobile app” on the openGym site you’re already signed into, then enter its address and the code shown there.': "Dans Réglages → « Associer l'application mobile » sur le site openGym où vous êtes déjà connecté, saisissez ensuite son adresse et le code qui s'y affiche.",
|
||||
'Server address (e.g. gym.example.com)': 'Adresse du serveur (ex. gym.example.com)',
|
||||
'Pairing code': "Code d'association",
|
||||
'Connecting…': 'Connexion…',
|
||||
'Connect': 'Connecter',
|
||||
'How do you want to use openGym?': 'Comment voulez-vous utiliser openGym ?',
|
||||
'Use on this device': 'Utiliser sur cet appareil',
|
||||
'Local keeps everything on this phone. Connecting syncs to your own openGym server instead — you can switch later in Settings.': 'Local garde tout sur ce téléphone. Se connecter synchronise plutôt avec votre propre serveur openGym — vous pourrez changer cela plus tard dans Réglages.'
|
||||
}
|
||||
@@ -163,6 +163,24 @@ export default {
|
||||
'Warm-up': 'वार्म-अप',
|
||||
'Add warm-up set': 'वार्म-अप सेट जोड़ें',
|
||||
'Add set': 'सेट जोड़ें',
|
||||
'+ Drop': '+ ड्रॉप सेट',
|
||||
'+ Burst': '+ बर्स्ट',
|
||||
'Drop {0}': 'ड्रॉप सेट {0}',
|
||||
'Burst {0}': 'बर्स्ट {0}',
|
||||
'Remove drop': 'ड्रॉप सेट हटाएं',
|
||||
'Remove burst': 'बर्स्ट हटाएं',
|
||||
'Rest (s)': 'आराम (सेकंड)',
|
||||
'Drop-set / rest-pause': 'ड्रॉप सेट / रेस्ट-पॉज़',
|
||||
'Intensifier': 'इंटेंसिफायर',
|
||||
'None': 'कोई नहीं',
|
||||
'Drop-set': 'ड्रॉप सेट',
|
||||
'Rest-pause': 'रेस्ट-पॉज़',
|
||||
'Drops': 'ड्रॉप्स',
|
||||
'Weight drop (%)': 'वज़न में कमी (%)',
|
||||
'Rest-pause reps': 'रेस्ट-पॉज़ रेप्स',
|
||||
'Rest-pause rest': 'रेस्ट-पॉज़ आराम',
|
||||
'Every set becomes a drop-set: after the main set, {0} drop(s) with no rest, each about {1}% lighter.': 'हर सेट ड्रॉप सेट बन जाता है: मुख्य सेट के बाद बिना आराम के {0} ड्रॉप, हर एक लगभग {1}% हल्का।',
|
||||
'Every set becomes rest-pause: {0} reps to start, then {1} more split into short bursts, {2}s rest before each, roughly halving each time.': 'हर सेट रेस्ट-पॉज़ बन जाता है: शुरुआत में {0} रेप्स, फिर छोटे बर्स्ट में बंटे {1} और, हर एक से पहले {2} सेकंड आराम, हर बार लगभग आधा होते हुए।',
|
||||
'Cardio logged': 'कार्डियो दर्ज हुआ',
|
||||
'Discard workout?': 'वर्कआउट छोड़ें?',
|
||||
'The sets you logged in this session will be lost.': 'इस सत्र में दर्ज किए सेट खो जाएँगे।',
|
||||
@@ -257,6 +275,7 @@ export default {
|
||||
'Theme': 'थीम',
|
||||
'Dark': 'डार्क',
|
||||
'Light': 'लाइट',
|
||||
'System': 'सिस्टम',
|
||||
'Accent color': 'एक्सेंट रंग',
|
||||
'General': 'सामान्य',
|
||||
'During a workout': 'वर्कआउट के दौरान',
|
||||
@@ -269,6 +288,8 @@ export default {
|
||||
'Data': 'डेटा',
|
||||
'Export backup (JSON)': 'बैकअप निर्यात करें (JSON)',
|
||||
'Import backup': 'बैकअप आयात करें',
|
||||
'Auto-backup on changes': 'बदलाव पर ऑटो-बैकअप',
|
||||
'Saves a dated copy to the Documents folder after finishing a workout or editing a routine — point a sync app at it, or copy it out by hand.': 'वर्कआउट खत्म करने या रूटीन एडिट करने के बाद Documents फ़ोल्डर में तारीख़ वाली कॉपी सेव करता है — उस फ़ोल्डर पर कोई सिंक ऐप लगाएं, या फ़ाइल को हाथ से कॉपी करें।',
|
||||
'Reset everything?': 'सब कुछ रीसेट करें?',
|
||||
'Reset everything': 'सब कुछ रीसेट करें',
|
||||
'Deletes your plan, workouts and body weight on this device. This cannot be undone.': 'इस डिवाइस पर आपकी योजना, वर्कआउट और वज़न हट जाएँगे। इसे पूर्ववत नहीं किया जा सकता।',
|
||||
@@ -605,5 +626,30 @@ export default {
|
||||
// --- muscle groups ---
|
||||
'Primary muscle groups': 'प्राथमिक मांसपेशी समूह',
|
||||
'Additional muscle groups': 'अतिरिक्त मांसपेशी समूह',
|
||||
'No explicit muscle group': 'कोई स्पष्ट मांसपेशी समूह नहीं'
|
||||
'No explicit muscle group': 'कोई स्पष्ट मांसपेशी समूह नहीं',
|
||||
|
||||
// "Connect to my server" (mobile app pairing)
|
||||
'Your server': 'आपका सर्वर',
|
||||
'Synced with your openGym server.': 'आपके openGym सर्वर के साथ सिंक हो गया।',
|
||||
'Disconnect': 'डिस्कनेक्ट करें',
|
||||
'Disconnect from your server?': 'क्या सर्वर से डिस्कनेक्ट करें?',
|
||||
'Your data is synced to your server first, then this device switches back to local-only.': 'आपका डेटा पहले आपके सर्वर से सिंक होगा, फिर यह डिवाइस लोकल मोड में वापस चला जाएगा।',
|
||||
'Disconnected — back to local-only': 'डिस्कनेक्ट हो गया — वापस लोकल मोड में',
|
||||
'Connect to my server': 'मेरे सर्वर से कनेक्ट करें',
|
||||
'Sync this device to your own self-hosted openGym instead.': 'इसके बजाय इस डिवाइस को अपने खुद के सेल्फ़-होस्टेड openGym से सिंक करें।',
|
||||
'Pair the mobile app': 'मोबाइल ऐप पेयर करें',
|
||||
'Connect the openGym app on your phone to this account.': 'अपने फ़ोन पर openGym ऐप को इस अकाउंट से जोड़ें।',
|
||||
'Could not generate a code': 'कोड जनरेट नहीं हो सका',
|
||||
'On the openGym app, choose “Connect to my server”, then enter this address and the code below. It expires in 5 minutes.': 'openGym ऐप में "मेरे सर्वर से कनेक्ट करें" चुनें, फिर यह पता और नीचे दिया कोड डालें। यह 5 मिनट में समाप्त हो जाता है।',
|
||||
'Enter your server address and the code': 'अपने सर्वर का पता और कोड डालें',
|
||||
'Connected': 'कनेक्ट हो गया',
|
||||
'Could not connect': 'कनेक्ट नहीं हो सका',
|
||||
'Open Settings → “Pair the mobile app” on the openGym site you’re already signed into, then enter its address and the code shown there.': 'जिस openGym साइट में आप पहले से साइन इन हैं, वहाँ सेटिंग्स → "मोबाइल ऐप पेयर करें" खोलें, फिर उसका पता और वहाँ दिखा कोड डालें।',
|
||||
'Server address (e.g. gym.example.com)': 'सर्वर का पता (जैसे gym.example.com)',
|
||||
'Pairing code': 'पेयरिंग कोड',
|
||||
'Connecting…': 'कनेक्ट हो रहा है…',
|
||||
'Connect': 'कनेक्ट करें',
|
||||
'How do you want to use openGym?': 'आप openGym का उपयोग कैसे करना चाहते हैं?',
|
||||
'Use on this device': 'इस डिवाइस पर उपयोग करें',
|
||||
'Local keeps everything on this phone. Connecting syncs to your own openGym server instead — you can switch later in Settings.': 'लोकल सब कुछ इसी फ़ोन पर रखता है। कनेक्ट करने पर इसके बजाय आपके अपने openGym सर्वर से सिंक होता है — इसे बाद में सेटिंग्स में बदला जा सकता है।'
|
||||
}
|
||||
@@ -163,6 +163,24 @@ export default {
|
||||
'Warm-up': 'Riscaldamento',
|
||||
'Add warm-up set': 'Aggiungi serie di riscaldamento',
|
||||
'Add set': 'Aggiungi serie',
|
||||
'+ Drop': '+ Drop set',
|
||||
'+ Burst': '+ Burst',
|
||||
'Drop {0}': 'Drop set {0}',
|
||||
'Burst {0}': 'Burst {0}',
|
||||
'Remove drop': 'Rimuovi drop set',
|
||||
'Remove burst': 'Rimuovi burst',
|
||||
'Rest (s)': 'Recupero (s)',
|
||||
'Drop-set / rest-pause': 'Drop-set / rest-pause',
|
||||
'Intensifier': 'Intensificatore',
|
||||
'None': 'Nessuno',
|
||||
'Drop-set': 'Drop-set',
|
||||
'Rest-pause': 'Rest-pause',
|
||||
'Drops': 'Drop set',
|
||||
'Weight drop (%)': 'Riduzione peso (%)',
|
||||
'Rest-pause reps': 'Ripetizioni rest-pause',
|
||||
'Rest-pause rest': 'Recupero rest-pause',
|
||||
'Every set becomes a drop-set: after the main set, {0} drop(s) with no rest, each about {1}% lighter.': 'Ogni serie diventa un drop-set: dopo la serie principale, {0} riduzione/i senza recupero, ciascuna circa il {1}% più leggera.',
|
||||
'Every set becomes rest-pause: {0} reps to start, then {1} more split into short bursts, {2}s rest before each, roughly halving each time.': 'Ogni serie diventa rest-pause: {0} ripetizioni iniziali, poi altre {1} suddivise in brevi burst, con {2}s di recupero prima di ciascuno, dimezzando circa ogni volta.',
|
||||
'Cardio logged': 'Cardio registrato',
|
||||
'Discard workout?': 'Scartare allenamento?',
|
||||
'The sets you logged in this session will be lost.': 'Le serie registrate in questa sessione andranno perse.',
|
||||
@@ -257,6 +275,7 @@ export default {
|
||||
'Theme': 'Tema',
|
||||
'Dark': 'Scuro',
|
||||
'Light': 'Chiaro',
|
||||
'System': 'Sistema',
|
||||
'Accent color': 'Colore accento',
|
||||
'General': 'Generale',
|
||||
'During a workout': 'Durante l’allenamento',
|
||||
@@ -269,6 +288,8 @@ export default {
|
||||
'Data': 'Dati',
|
||||
'Export backup (JSON)': 'Esporta backup (JSON)',
|
||||
'Import backup': 'Importa backup',
|
||||
'Auto-backup on changes': 'Backup automatico alle modifiche',
|
||||
'Saves a dated copy to the Documents folder after finishing a workout or editing a routine — point a sync app at it, or copy it out by hand.': "Salva una copia datata nella cartella Documenti dopo aver terminato un allenamento o modificato una routine — punta un'app di sincronizzazione lì, oppure copia il file a mano.",
|
||||
'Reset everything?': 'Azzerare tutto?',
|
||||
'Reset everything': 'Azzera tutto',
|
||||
'Deletes your plan, workouts and body weight on this device. This cannot be undone.': 'Elimina piano, allenamenti e peso corporeo su questo dispositivo. Irreversibile.',
|
||||
@@ -605,5 +626,30 @@ export default {
|
||||
// --- muscle groups ---
|
||||
'Primary muscle groups': 'Gruppi muscolari primari',
|
||||
'Additional muscle groups': 'Gruppi muscolari aggiuntivi',
|
||||
'No explicit muscle group': 'Nessun gruppo muscolare esplicito'
|
||||
'No explicit muscle group': 'Nessun gruppo muscolare esplicito',
|
||||
|
||||
// "Connect to my server" (mobile app pairing)
|
||||
'Your server': 'Il tuo server',
|
||||
'Synced with your openGym server.': 'Sincronizzato con il tuo server openGym.',
|
||||
'Disconnect': 'Disconnetti',
|
||||
'Disconnect from your server?': 'Disconnettersi dal server?',
|
||||
'Your data is synced to your server first, then this device switches back to local-only.': 'I tuoi dati vengono prima sincronizzati con il tuo server, poi questo dispositivo torna alla modalità locale.',
|
||||
'Disconnected — back to local-only': 'Disconnesso — tornato alla modalità locale',
|
||||
'Connect to my server': 'Connettiti al mio server',
|
||||
'Sync this device to your own self-hosted openGym instead.': 'Sincronizza invece questo dispositivo con il tuo openGym self-hosted.',
|
||||
'Pair the mobile app': "Abbina l'app mobile",
|
||||
'Connect the openGym app on your phone to this account.': "Collega l'app openGym sul tuo telefono a questo account.",
|
||||
'Could not generate a code': 'Impossibile generare un codice',
|
||||
'On the openGym app, choose “Connect to my server”, then enter this address and the code below. It expires in 5 minutes.': "Nell'app openGym scegli «Connettiti al mio server», poi inserisci questo indirizzo e il codice qui sotto. Scade tra 5 minuti.",
|
||||
'Enter your server address and the code': "Inserisci l'indirizzo del tuo server e il codice",
|
||||
'Connected': 'Connesso',
|
||||
'Could not connect': 'Connessione non riuscita',
|
||||
'Open Settings → “Pair the mobile app” on the openGym site you’re already signed into, then enter its address and the code shown there.': "In Impostazioni → «Abbina l'app mobile» sul sito openGym in cui hai già effettuato l'accesso, poi inserisci il suo indirizzo e il codice mostrato lì.",
|
||||
'Server address (e.g. gym.example.com)': 'Indirizzo del server (es. gym.example.com)',
|
||||
'Pairing code': 'Codice di abbinamento',
|
||||
'Connecting…': 'Connessione…',
|
||||
'Connect': 'Connetti',
|
||||
'How do you want to use openGym?': 'Come vuoi usare openGym?',
|
||||
'Use on this device': 'Usa su questo dispositivo',
|
||||
'Local keeps everything on this phone. Connecting syncs to your own openGym server instead — you can switch later in Settings.': 'Locale mantiene tutto su questo telefono. Connettersi sincronizza invece con il tuo server openGym — potrai cambiarlo più tardi nelle Impostazioni.'
|
||||
}
|
||||
@@ -163,6 +163,24 @@ export default {
|
||||
'Warm-up': '워밍업',
|
||||
'Add warm-up set': '워밍업 세트 추가',
|
||||
'Add set': '세트 추가',
|
||||
'+ Drop': '+ 드롭세트',
|
||||
'+ Burst': '+ 버스트',
|
||||
'Drop {0}': '드롭세트 {0}',
|
||||
'Burst {0}': '버스트 {0}',
|
||||
'Remove drop': '드롭세트 제거',
|
||||
'Remove burst': '버스트 제거',
|
||||
'Rest (s)': '휴식(초)',
|
||||
'Drop-set / rest-pause': '드롭세트 / 레스트포즈',
|
||||
'Intensifier': '강도 기법',
|
||||
'None': '없음',
|
||||
'Drop-set': '드롭세트',
|
||||
'Rest-pause': '레스트포즈',
|
||||
'Drops': '드롭 횟수',
|
||||
'Weight drop (%)': '중량 감소(%)',
|
||||
'Rest-pause reps': '레스트포즈 반복 수',
|
||||
'Rest-pause rest': '레스트포즈 휴식',
|
||||
'Every set becomes a drop-set: after the main set, {0} drop(s) with no rest, each about {1}% lighter.': '모든 세트가 드롭세트가 됩니다: 메인 세트 후 휴식 없이 {0}회 드롭, 매번 약 {1}%씩 가벼워집니다.',
|
||||
'Every set becomes rest-pause: {0} reps to start, then {1} more split into short bursts, {2}s rest before each, roughly halving each time.': '모든 세트가 레스트포즈가 됩니다: 처음 {0}회를 하고, 짧은 버스트로 나눠 {1}회를 더 하며, 매번 전에 {2}초씩 쉬고 매번 대략 절반으로 줄어듭니다.',
|
||||
'Cardio logged': '유산소 기록됨',
|
||||
'Discard workout?': '운동을 버릴까요?',
|
||||
'The sets you logged in this session will be lost.': '이 세션에서 기록한 세트가 사라집니다.',
|
||||
@@ -257,6 +275,7 @@ export default {
|
||||
'Theme': '테마',
|
||||
'Dark': '다크',
|
||||
'Light': '라이트',
|
||||
'System': '시스템',
|
||||
'Accent color': '강조 색상',
|
||||
'General': '일반',
|
||||
'During a workout': '운동 중',
|
||||
@@ -269,6 +288,8 @@ export default {
|
||||
'Data': '데이터',
|
||||
'Export backup (JSON)': '백업 내보내기 (JSON)',
|
||||
'Import backup': '백업 가져오기',
|
||||
'Auto-backup on changes': '변경 시 자동 백업',
|
||||
'Saves a dated copy to the Documents folder after finishing a workout or editing a routine — point a sync app at it, or copy it out by hand.': '운동을 마치거나 루틴을 수정한 뒤 날짜가 적힌 사본을 문서 폴더에 저장합니다 — 동기화 앱이 그 폴더를 보게 하거나 파일을 직접 복사하세요.',
|
||||
'Reset everything?': '전부 초기화할까요?',
|
||||
'Reset everything': '전부 초기화',
|
||||
'Deletes your plan, workouts and body weight on this device. This cannot be undone.': '이 기기의 계획, 운동, 체중을 삭제합니다. 되돌릴 수 없어요.',
|
||||
@@ -605,5 +626,30 @@ export default {
|
||||
// --- muscle groups ---
|
||||
'Primary muscle groups': '주요 근육 그룹',
|
||||
'Additional muscle groups': '추가 근육군',
|
||||
'No explicit muscle group': '명시적 근육군 없음'
|
||||
'No explicit muscle group': '명시적 근육군 없음',
|
||||
|
||||
// "Connect to my server" (mobile app pairing)
|
||||
'Your server': '내 서버',
|
||||
'Synced with your openGym server.': 'openGym 서버와 동기화됨',
|
||||
'Disconnect': '연결 해제',
|
||||
'Disconnect from your server?': '서버와 연결을 해제할까요?',
|
||||
'Your data is synced to your server first, then this device switches back to local-only.': '데이터가 먼저 서버와 동기화된 후, 이 기기는 로컬 모드로 돌아갑니다.',
|
||||
'Disconnected — back to local-only': '연결 해제됨 — 로컬 모드로 전환',
|
||||
'Connect to my server': '내 서버에 연결',
|
||||
'Sync this device to your own self-hosted openGym instead.': '대신 이 기기를 직접 호스팅하는 openGym 서버와 동기화합니다.',
|
||||
'Pair the mobile app': '모바일 앱 페어링',
|
||||
'Connect the openGym app on your phone to this account.': '휴대폰의 openGym 앱을 이 계정에 연결하세요.',
|
||||
'Could not generate a code': '코드를 생성하지 못했습니다',
|
||||
'On the openGym app, choose “Connect to my server”, then enter this address and the code below. It expires in 5 minutes.': 'openGym 앱에서 "내 서버에 연결"을 선택한 다음, 이 주소와 아래 코드를 입력하세요. 5분 후 만료됩니다.',
|
||||
'Enter your server address and the code': '서버 주소와 코드를 입력하세요',
|
||||
'Connected': '연결됨',
|
||||
'Could not connect': '연결하지 못했습니다',
|
||||
'Open Settings → “Pair the mobile app” on the openGym site you’re already signed into, then enter its address and the code shown there.': '이미 로그인된 openGym 사이트에서 설정 → "모바일 앱 페어링"을 열고, 주소와 거기에 표시된 코드를 입력하세요.',
|
||||
'Server address (e.g. gym.example.com)': '서버 주소 (예: gym.example.com)',
|
||||
'Pairing code': '페어링 코드',
|
||||
'Connecting…': '연결 중…',
|
||||
'Connect': '연결',
|
||||
'How do you want to use openGym?': 'openGym을 어떻게 사용하시겠어요?',
|
||||
'Use on this device': '이 기기에서 사용',
|
||||
'Local keeps everything on this phone. Connecting syncs to your own openGym server instead — you can switch later in Settings.': '로컬 모드는 모든 것을 이 휴대폰에 보관합니다. 연결하면 대신 자신의 openGym 서버와 동기화됩니다 — 나중에 설정에서 변경할 수 있습니다.'
|
||||
}
|
||||
@@ -163,6 +163,24 @@ export default {
|
||||
'Warm-up': 'Rozgrzewka',
|
||||
'Add warm-up set': 'Dodaj serię rozgrzewkową',
|
||||
'Add set': 'Dodaj serię',
|
||||
'+ Drop': '+ Seria zniżkująca',
|
||||
'+ Burst': '+ Seria rest-pause',
|
||||
'Drop {0}': 'Seria zniżkująca {0}',
|
||||
'Burst {0}': 'Seria rest-pause {0}',
|
||||
'Remove drop': 'Usuń serię zniżkującą',
|
||||
'Remove burst': 'Usuń serię rest-pause',
|
||||
'Rest (s)': 'Odpoczynek (s)',
|
||||
'Drop-set / rest-pause': 'Seria zniżkująca / rest-pause',
|
||||
'Intensifier': 'Technika intensyfikująca',
|
||||
'None': 'Brak',
|
||||
'Drop-set': 'Seria zniżkująca',
|
||||
'Rest-pause': 'Rest-pause',
|
||||
'Drops': 'Serie zniżkujące',
|
||||
'Weight drop (%)': 'Redukcja ciężaru (%)',
|
||||
'Rest-pause reps': 'Powtórzenia rest-pause',
|
||||
'Rest-pause rest': 'Odpoczynek rest-pause',
|
||||
'Every set becomes a drop-set: after the main set, {0} drop(s) with no rest, each about {1}% lighter.': 'Każda seria staje się serią zniżkującą: po serii głównej {0} redukcja(e) bez odpoczynku, każda lżejsza o ok. {1}%.',
|
||||
'Every set becomes rest-pause: {0} reps to start, then {1} more split into short bursts, {2}s rest before each, roughly halving each time.': 'Każda seria staje się rest-pause: {0} powtórzeń na start, potem kolejne {1} podzielone na krótkie serie, z {2}s odpoczynku przed każdą, zmniejszając się za każdym razem o połowę.',
|
||||
'Cardio logged': 'Cardio zapisane',
|
||||
'Discard workout?': 'Odrzucić trening?',
|
||||
'The sets you logged in this session will be lost.': 'Serie zapisane w tej sesji zostaną utracone.',
|
||||
@@ -257,6 +275,7 @@ export default {
|
||||
'Theme': 'Motyw',
|
||||
'Dark': 'Ciemny',
|
||||
'Light': 'Jasny',
|
||||
'System': 'System',
|
||||
'Accent color': 'Kolor akcentu',
|
||||
'General': 'Ogólne',
|
||||
'During a workout': 'Podczas treningu',
|
||||
@@ -269,6 +288,8 @@ export default {
|
||||
'Data': 'Dane',
|
||||
'Export backup (JSON)': 'Eksportuj kopię (JSON)',
|
||||
'Import backup': 'Importuj kopię',
|
||||
'Auto-backup on changes': 'Automatyczna kopia przy zmianach',
|
||||
'Saves a dated copy to the Documents folder after finishing a workout or editing a routine — point a sync app at it, or copy it out by hand.': 'Zapisuje datowaną kopię w folderze Dokumenty po zakończeniu treningu lub edycji rutyny — wskaż na ten folder aplikację synchronizującą albo skopiuj plik ręcznie.',
|
||||
'Reset everything?': 'Zresetować wszystko?',
|
||||
'Reset everything': 'Zresetuj wszystko',
|
||||
'Deletes your plan, workouts and body weight on this device. This cannot be undone.': 'Usuwa plan, treningi i masę ciała na tym urządzeniu. Nie można tego cofnąć.',
|
||||
@@ -605,5 +626,30 @@ export default {
|
||||
// --- muscle groups ---
|
||||
'Primary muscle groups': 'Podstawowe grupy mięśniowe',
|
||||
'Additional muscle groups': 'Dodatkowe grupy mięśniowe',
|
||||
'No explicit muscle group': 'Brak jawnej grupy mięśniowej'
|
||||
'No explicit muscle group': 'Brak jawnej grupy mięśniowej',
|
||||
|
||||
// "Connect to my server" (mobile app pairing)
|
||||
'Your server': 'Twój serwer',
|
||||
'Synced with your openGym server.': 'Zsynchronizowano z Twoim serwerem openGym.',
|
||||
'Disconnect': 'Rozłącz',
|
||||
'Disconnect from your server?': 'Rozłączyć z serwerem?',
|
||||
'Your data is synced to your server first, then this device switches back to local-only.': 'Twoje dane zostaną najpierw zsynchronizowane z serwerem, a następnie to urządzenie wróci do trybu lokalnego.',
|
||||
'Disconnected — back to local-only': 'Rozłączono — z powrotem w trybie lokalnym',
|
||||
'Connect to my server': 'Połącz z moim serwerem',
|
||||
'Sync this device to your own self-hosted openGym instead.': 'Zsynchronizuj to urządzenie z własnym, samodzielnie hostowanym openGym.',
|
||||
'Pair the mobile app': 'Sparuj aplikację mobilną',
|
||||
'Connect the openGym app on your phone to this account.': 'Połącz aplikację openGym na telefonie z tym kontem.',
|
||||
'Could not generate a code': 'Nie udało się wygenerować kodu',
|
||||
'On the openGym app, choose “Connect to my server”, then enter this address and the code below. It expires in 5 minutes.': 'W aplikacji openGym wybierz „Połącz z moim serwerem”, a potem wpisz ten adres i poniższy kod. Wygasa po 5 minutach.',
|
||||
'Enter your server address and the code': 'Wpisz adres swojego serwera i kod',
|
||||
'Connected': 'Połączono',
|
||||
'Could not connect': 'Nie udało się połączyć',
|
||||
'Open Settings → “Pair the mobile app” on the openGym site you’re already signed into, then enter its address and the code shown there.': 'W Ustawieniach → „Sparuj aplikację mobilną” na stronie openGym, na której jesteś już zalogowany, wpisz jej adres i wyświetlony tam kod.',
|
||||
'Server address (e.g. gym.example.com)': 'Adres serwera (np. gym.example.com)',
|
||||
'Pairing code': 'Kod parowania',
|
||||
'Connecting…': 'Łączenie…',
|
||||
'Connect': 'Połącz',
|
||||
'How do you want to use openGym?': 'Jak chcesz korzystać z openGym?',
|
||||
'Use on this device': 'Użyj na tym urządzeniu',
|
||||
'Local keeps everything on this phone. Connecting syncs to your own openGym server instead — you can switch later in Settings.': 'Tryb lokalny zachowuje wszystko na tym telefonie. Połączenie synchronizuje zamiast tego z Twoim własnym serwerem openGym — możesz to później zmienić w Ustawieniach.'
|
||||
}
|
||||
@@ -267,7 +267,32 @@ export const PT_BR_OVERRIDES = {
|
||||
'Add equipment profile': 'Adicionar perfil de equipamentos',
|
||||
'Delete profile?': 'Excluir perfil?',
|
||||
'"{0}" and its equipment list will be removed.': '“{0}” e sua lista de equipamentos serão removidos.',
|
||||
'Filters the exercise library and picker, and flags routine exercises that need something you don’t have in the active profile.': 'Filtra a biblioteca de exercícios e o seletor, e sinaliza os exercícios das rotinas que precisam de algo que você não tem no perfil ativo.'
|
||||
'Filters the exercise library and picker, and flags routine exercises that need something you don’t have in the active profile.': 'Filtra a biblioteca de exercícios e o seletor, e sinaliza os exercícios das rotinas que precisam de algo que você não tem no perfil ativo.',
|
||||
|
||||
// --- drop-sets, auto-backup and server pairing ---
|
||||
'Auto-backup on changes': 'Backup automático ao alterar',
|
||||
'Saves a dated copy to the Documents folder after finishing a workout or editing a routine — point a sync app at it, or copy it out by hand.': 'Salva uma cópia datada na pasta Documentos depois de terminar um treino ou editar uma rotina — aponte um aplicativo de sincronização para ela, ou copie o arquivo na mão.',
|
||||
'Your server': 'Seu servidor',
|
||||
'Synced with your openGym server.': 'Sincronizado com o seu servidor openGym.',
|
||||
'Disconnect': 'Desconectar',
|
||||
'Disconnect from your server?': 'Desconectar do seu servidor?',
|
||||
'Your data is synced to your server first, then this device switches back to local-only.': 'Seus dados são sincronizados com o seu servidor primeiro, depois este dispositivo volta ao modo somente local.',
|
||||
'Disconnected — back to local-only': 'Desconectado — de volta ao modo somente local',
|
||||
'Connect to my server': 'Conectar ao meu servidor',
|
||||
'Sync this device to your own self-hosted openGym instead.': 'Sincronize este dispositivo com o seu próprio openGym auto-hospedado.',
|
||||
'Pair the mobile app': 'Parear o aplicativo',
|
||||
'Connect the openGym app on your phone to this account.': 'Conecte o aplicativo openGym do seu celular a esta conta.',
|
||||
'On the openGym app, choose “Connect to my server”, then enter this address and the code below. It expires in 5 minutes.': 'No aplicativo openGym, escolha “Conectar ao meu servidor”, depois digite este endereço e o código abaixo. Ele expira em 5 minutos.',
|
||||
'Enter your server address and the code': 'Digite o endereço do seu servidor e o código',
|
||||
'Connected': 'Conectado',
|
||||
'Could not connect': 'Não foi possível conectar',
|
||||
'Open Settings → “Pair the mobile app” on the openGym site you’re already signed into, then enter its address and the code shown there.': 'No site openGym em que você já está conectado, abra Configurações → “Parear o aplicativo”, depois digite o endereço e o código mostrado lá.',
|
||||
'Connecting…': 'Conectando…',
|
||||
'Connect': 'Conectar',
|
||||
'How do you want to use openGym?': 'Como você quer usar o openGym?',
|
||||
'Local keeps everything on this phone. Connecting syncs to your own openGym server instead — you can switch later in Settings.': 'Local mantém tudo neste celular. Conectar sincroniza com o seu próprio servidor openGym — você pode mudar depois em Configurações.',
|
||||
'Every set becomes a drop-set: after the main set, {0} drop(s) with no rest, each about {1}% lighter.': 'Cada série vira uma série decrescente: depois da série principal, {0} queda(s) sem descanso, cada uma cerca de {1}% mais leve.',
|
||||
'Every set becomes rest-pause: {0} reps to start, then {1} more split into short bursts, {2}s rest before each, roughly halving each time.': 'Cada série vira rest-pause: {0} repetições para começar, depois mais {1} divididas em rajadas curtas, com {2}s de descanso antes de cada uma, caindo cerca de metade a cada vez.'
|
||||
}
|
||||
|
||||
export default { ...pt, ...PT_BR_OVERRIDES }
|
||||
@@ -163,6 +163,24 @@ export default {
|
||||
'Warm-up': 'Aquecimento',
|
||||
'Add warm-up set': 'Adicionar série de aquecimento',
|
||||
'Add set': 'Adicionar série',
|
||||
'+ Drop': '+ Queda',
|
||||
'+ Burst': '+ Rajada',
|
||||
'Drop {0}': 'Queda {0}',
|
||||
'Burst {0}': 'Rajada {0}',
|
||||
'Remove drop': 'Remover queda',
|
||||
'Remove burst': 'Remover rajada',
|
||||
'Rest (s)': 'Descanso (s)',
|
||||
'Drop-set / rest-pause': 'Séries decrescentes / rest-pause',
|
||||
'Intensifier': 'Intensificador',
|
||||
'None': 'Nenhum',
|
||||
'Drop-set': 'Série decrescente',
|
||||
'Rest-pause': 'Rest-pause',
|
||||
'Drops': 'Quedas',
|
||||
'Weight drop (%)': 'Queda de peso (%)',
|
||||
'Rest-pause reps': 'Repetições rest-pause',
|
||||
'Rest-pause rest': 'Descanso rest-pause',
|
||||
'Every set becomes a drop-set: after the main set, {0} drop(s) with no rest, each about {1}% lighter.': 'Cada série torna-se uma série decrescente: depois da série principal, {0} queda(s) sem descanso, cada uma cerca de {1}% mais leve.',
|
||||
'Every set becomes rest-pause: {0} reps to start, then {1} more split into short bursts, {2}s rest before each, roughly halving each time.': 'Cada série torna-se rest-pause: {0} repetições para começar, depois mais {1} divididas em rajadas curtas, com {2}s de descanso antes de cada uma, reduzindo cerca de metade a cada vez.',
|
||||
'Cardio logged': 'Cardio registado',
|
||||
'Discard workout?': 'Descartar treino?',
|
||||
'The sets you logged in this session will be lost.': 'As séries registadas nesta sessão vão perder-se.',
|
||||
@@ -257,6 +275,7 @@ export default {
|
||||
'Theme': 'Tema',
|
||||
'Dark': 'Escuro',
|
||||
'Light': 'Claro',
|
||||
'System': 'Sistema',
|
||||
'Accent color': 'Cor de destaque',
|
||||
'General': 'Geral',
|
||||
'During a workout': 'Durante o treino',
|
||||
@@ -269,6 +288,8 @@ export default {
|
||||
'Data': 'Dados',
|
||||
'Export backup (JSON)': 'Exportar cópia (JSON)',
|
||||
'Import backup': 'Importar cópia',
|
||||
'Auto-backup on changes': 'Cópia automática ao alterar',
|
||||
'Saves a dated copy to the Documents folder after finishing a workout or editing a routine — point a sync app at it, or copy it out by hand.': 'Guarda uma cópia datada na pasta Documentos após terminar um treino ou editar uma rotina — aponta uma app de sincronização para lá, ou copia o ficheiro à mão.',
|
||||
'Reset everything?': 'Repor tudo?',
|
||||
'Reset everything': 'Repor tudo',
|
||||
'Deletes your plan, workouts and body weight on this device. This cannot be undone.': 'Elimina o teu plano, treinos e peso corporal neste dispositivo. Não pode ser anulado.',
|
||||
@@ -605,5 +626,30 @@ export default {
|
||||
// --- muscle groups ---
|
||||
'Primary muscle groups': 'Grupos musculares primários',
|
||||
'Additional muscle groups': 'Grupos musculares adicionais',
|
||||
'No explicit muscle group': 'Nenhum grupo muscular explícito'
|
||||
'No explicit muscle group': 'Nenhum grupo muscular explícito',
|
||||
|
||||
// "Connect to my server" (mobile app pairing)
|
||||
'Your server': 'O teu servidor',
|
||||
'Synced with your openGym server.': 'Sincronizado com o teu servidor openGym.',
|
||||
'Disconnect': 'Desligar',
|
||||
'Disconnect from your server?': 'Desligar do teu servidor?',
|
||||
'Your data is synced to your server first, then this device switches back to local-only.': 'Os teus dados são primeiro sincronizados com o teu servidor, depois este dispositivo volta ao modo local.',
|
||||
'Disconnected — back to local-only': 'Desligado — de volta ao modo local',
|
||||
'Connect to my server': 'Ligar ao meu servidor',
|
||||
'Sync this device to your own self-hosted openGym instead.': 'Sincroniza este dispositivo com o teu próprio openGym self-hosted.',
|
||||
'Pair the mobile app': 'Emparelhar a app móvel',
|
||||
'Connect the openGym app on your phone to this account.': 'Liga a app openGym no teu telemóvel a esta conta.',
|
||||
'Could not generate a code': 'Não foi possível gerar um código',
|
||||
'On the openGym app, choose “Connect to my server”, then enter this address and the code below. It expires in 5 minutes.': 'Na app openGym, escolhe «Ligar ao meu servidor», depois introduz este endereço e o código abaixo. Expira em 5 minutos.',
|
||||
'Enter your server address and the code': 'Introduz o endereço do teu servidor e o código',
|
||||
'Connected': 'Ligado',
|
||||
'Could not connect': 'Não foi possível ligar',
|
||||
'Open Settings → “Pair the mobile app” on the openGym site you’re already signed into, then enter its address and the code shown there.': 'Em Definições → «Emparelhar a app móvel» no site openGym em que já tens sessão iniciada, introduz depois o endereço e o código apresentado aí.',
|
||||
'Server address (e.g. gym.example.com)': 'Endereço do servidor (ex. gym.example.com)',
|
||||
'Pairing code': 'Código de emparelhamento',
|
||||
'Connecting…': 'A ligar…',
|
||||
'Connect': 'Ligar',
|
||||
'How do you want to use openGym?': 'Como queres usar o openGym?',
|
||||
'Use on this device': 'Usar neste dispositivo',
|
||||
'Local keeps everything on this phone. Connecting syncs to your own openGym server instead — you can switch later in Settings.': 'Local mantém tudo neste telemóvel. Ligar sincroniza antes com o teu próprio servidor openGym — podes mudar mais tarde em Definições.'
|
||||
}
|
||||
@@ -163,6 +163,24 @@ export default {
|
||||
'Warm-up': 'Разминка',
|
||||
'Add warm-up set': 'Добавить разминочный подход',
|
||||
'Add set': 'Добавить подход',
|
||||
'+ Drop': '+ Дроп-сет',
|
||||
'+ Burst': '+ Серия рест-пауз',
|
||||
'Drop {0}': 'Дроп-сет {0}',
|
||||
'Burst {0}': 'Серия {0}',
|
||||
'Remove drop': 'Убрать дроп-сет',
|
||||
'Remove burst': 'Убрать серию',
|
||||
'Rest (s)': 'Отдых (с)',
|
||||
'Drop-set / rest-pause': 'Дроп-сет / рест-пауза',
|
||||
'Intensifier': 'Интенсификатор',
|
||||
'None': 'Нет',
|
||||
'Drop-set': 'Дроп-сет',
|
||||
'Rest-pause': 'Рест-пауза',
|
||||
'Drops': 'Дроп-сеты',
|
||||
'Weight drop (%)': 'Снижение веса (%)',
|
||||
'Rest-pause reps': 'Повторения рест-паузы',
|
||||
'Rest-pause rest': 'Отдых рест-паузы',
|
||||
'Every set becomes a drop-set: after the main set, {0} drop(s) with no rest, each about {1}% lighter.': 'Каждый подход становится дроп-сетом: после основного подхода {0} снижение(й) без отдыха, каждое примерно на {1}% легче.',
|
||||
'Every set becomes rest-pause: {0} reps to start, then {1} more split into short bursts, {2}s rest before each, roughly halving each time.': 'Каждый подход становится рест-паузой: сначала {0} повторений, затем ещё {1}, разбитых на короткие серии, с {2} с отдыха перед каждой, каждый раз примерно вдвое меньше.',
|
||||
'Cardio logged': 'Кардио записано',
|
||||
'Discard workout?': 'Отменить тренировку?',
|
||||
'The sets you logged in this session will be lost.': 'Подходы, записанные в этой сессии, будут потеряны.',
|
||||
@@ -257,6 +275,7 @@ export default {
|
||||
'Theme': 'Тема',
|
||||
'Dark': 'Тёмная',
|
||||
'Light': 'Светлая',
|
||||
'System': 'Системная',
|
||||
'Accent color': 'Акцентный цвет',
|
||||
'General': 'Основное',
|
||||
'During a workout': 'Во время тренировки',
|
||||
@@ -269,6 +288,8 @@ export default {
|
||||
'Data': 'Данные',
|
||||
'Export backup (JSON)': 'Экспорт резервной копии (JSON)',
|
||||
'Import backup': 'Импорт резервной копии',
|
||||
'Auto-backup on changes': 'Автосохранение копии при изменениях',
|
||||
'Saves a dated copy to the Documents folder after finishing a workout or editing a routine — point a sync app at it, or copy it out by hand.': 'Сохраняет копию с датой в папку «Документы» после завершения тренировки или редактирования программы — направьте туда приложение синхронизации или скопируйте файл вручную.',
|
||||
'Reset everything?': 'Сбросить всё?',
|
||||
'Reset everything': 'Сбросить всё',
|
||||
'Deletes your plan, workouts and body weight on this device. This cannot be undone.': 'Удаляет план, тренировки и вес тела на этом устройстве. Отменить нельзя.',
|
||||
@@ -605,5 +626,30 @@ export default {
|
||||
// --- muscle groups ---
|
||||
'Primary muscle groups': 'Основные группы мышц',
|
||||
'Additional muscle groups': 'Дополнительные мышечные группы',
|
||||
'No explicit muscle group': 'Без явной мышечной группы'
|
||||
'No explicit muscle group': 'Без явной мышечной группы',
|
||||
|
||||
// "Connect to my server" (mobile app pairing)
|
||||
'Your server': 'Ваш сервер',
|
||||
'Synced with your openGym server.': 'Синхронизировано с вашим сервером openGym.',
|
||||
'Disconnect': 'Отключить',
|
||||
'Disconnect from your server?': 'Отключиться от сервера?',
|
||||
'Your data is synced to your server first, then this device switches back to local-only.': 'Сначала данные синхронизируются с сервером, затем это устройство вернётся в локальный режим.',
|
||||
'Disconnected — back to local-only': 'Отключено — снова локальный режим',
|
||||
'Connect to my server': 'Подключиться к моему серверу',
|
||||
'Sync this device to your own self-hosted openGym instead.': 'Синхронизировать это устройство с вашим собственным self-hosted openGym.',
|
||||
'Pair the mobile app': 'Сопряжение мобильного приложения',
|
||||
'Connect the openGym app on your phone to this account.': 'Подключите приложение openGym на телефоне к этому аккаунту.',
|
||||
'Could not generate a code': 'Не удалось создать код',
|
||||
'On the openGym app, choose “Connect to my server”, then enter this address and the code below. It expires in 5 minutes.': 'В приложении openGym выберите «Подключиться к моему серверу», затем введите этот адрес и код ниже. Он действителен 5 минут.',
|
||||
'Enter your server address and the code': 'Введите адрес вашего сервера и код',
|
||||
'Connected': 'Подключено',
|
||||
'Could not connect': 'Не удалось подключиться',
|
||||
'Open Settings → “Pair the mobile app” on the openGym site you’re already signed into, then enter its address and the code shown there.': 'В Настройках → «Сопряжение мобильного приложения» на сайте openGym, где вы уже вошли, введите его адрес и показанный там код.',
|
||||
'Server address (e.g. gym.example.com)': 'Адрес сервера (например, gym.example.com)',
|
||||
'Pairing code': 'Код сопряжения',
|
||||
'Connecting…': 'Подключение…',
|
||||
'Connect': 'Подключить',
|
||||
'How do you want to use openGym?': 'Как вы хотите использовать openGym?',
|
||||
'Use on this device': 'Использовать на этом устройстве',
|
||||
'Local keeps everything on this phone. Connecting syncs to your own openGym server instead — you can switch later in Settings.': 'Локальный режим хранит всё на этом телефоне. Подключение вместо этого синхронизирует данные с вашим сервером openGym — вы сможете изменить это позже в Настройках.'
|
||||
}
|
||||
@@ -163,6 +163,24 @@ export default {
|
||||
'Warm-up': 'Isınma',
|
||||
'Add warm-up set': 'Isınma seti ekle',
|
||||
'Add set': 'Set ekle',
|
||||
'+ Drop': '+ Düşüş seti',
|
||||
'+ Burst': '+ Patlama',
|
||||
'Drop {0}': 'Düşüş seti {0}',
|
||||
'Burst {0}': 'Patlama {0}',
|
||||
'Remove drop': 'Düşüş setini kaldır',
|
||||
'Remove burst': 'Patlamayı kaldır',
|
||||
'Rest (s)': 'Dinlenme (sn)',
|
||||
'Drop-set / rest-pause': 'Düşüş seti / rest-pause',
|
||||
'Intensifier': 'Yoğunlaştırıcı',
|
||||
'None': 'Yok',
|
||||
'Drop-set': 'Düşüş seti',
|
||||
'Rest-pause': 'Rest-pause',
|
||||
'Drops': 'Düşüşler',
|
||||
'Weight drop (%)': 'Ağırlık düşüşü (%)',
|
||||
'Rest-pause reps': 'Rest-pause tekrarları',
|
||||
'Rest-pause rest': 'Rest-pause dinlenmesi',
|
||||
'Every set becomes a drop-set: after the main set, {0} drop(s) with no rest, each about {1}% lighter.': 'Her set düşüş setine dönüşür: ana setten sonra dinlenmeden {0} düşüş, her biri yaklaşık %{1} daha hafif.',
|
||||
'Every set becomes rest-pause: {0} reps to start, then {1} more split into short bursts, {2}s rest before each, roughly halving each time.': 'Her set rest-pause olur: başlangıçta {0} tekrar, ardından kısa patlamalara bölünmüş {1} tekrar daha, her birinden önce {2} sn dinlenme, her seferinde yaklaşık yarıya inerek.',
|
||||
'Cardio logged': 'Kardiyo kaydedildi',
|
||||
'Discard workout?': 'Antrenman iptal edilsin mi?',
|
||||
'The sets you logged in this session will be lost.': 'Bu oturumda kaydettiğin setler kaybolacak.',
|
||||
@@ -257,6 +275,7 @@ export default {
|
||||
'Theme': 'Tema',
|
||||
'Dark': 'Koyu',
|
||||
'Light': 'Açık',
|
||||
'System': 'Sistem',
|
||||
'Accent color': 'Vurgu rengi',
|
||||
'General': 'Genel',
|
||||
'During a workout': 'Antrenman sırasında',
|
||||
@@ -269,6 +288,8 @@ export default {
|
||||
'Data': 'Veriler',
|
||||
'Export backup (JSON)': 'Yedeği dışa aktar (JSON)',
|
||||
'Import backup': 'Yedeği içe aktar',
|
||||
'Auto-backup on changes': 'Değişikliklerde otomatik yedek',
|
||||
'Saves a dated copy to the Documents folder after finishing a workout or editing a routine — point a sync app at it, or copy it out by hand.': 'Bir antrenmanı bitirdikten veya bir rutini düzenledikten sonra Belgeler klasörüne tarihli bir kopya kaydeder — bir senkronizasyon uygulamasını o klasöre yönlendir ya da dosyayı elle kopyala.',
|
||||
'Reset everything?': 'Her şey sıfırlansın mı?',
|
||||
'Reset everything': 'Her şeyi sıfırla',
|
||||
'Deletes your plan, workouts and body weight on this device. This cannot be undone.': 'Bu cihazdaki planını, antrenmanlarını ve vücut ağırlığını siler. Geri alınamaz.',
|
||||
@@ -605,5 +626,30 @@ export default {
|
||||
// --- muscle groups ---
|
||||
'Primary muscle groups': 'Birincil kas grupları',
|
||||
'Additional muscle groups': 'Ek kas grupları',
|
||||
'No explicit muscle group': 'Açık kas grubu yok'
|
||||
'No explicit muscle group': 'Açık kas grubu yok',
|
||||
|
||||
// "Connect to my server" (mobile app pairing)
|
||||
'Your server': 'Sunucun',
|
||||
'Synced with your openGym server.': 'openGym sunucunla senkronize edildi.',
|
||||
'Disconnect': 'Bağlantıyı kes',
|
||||
'Disconnect from your server?': 'Sunucuyla bağlantı kesilsin mi?',
|
||||
'Your data is synced to your server first, then this device switches back to local-only.': 'Verilerin önce sunucunla senkronize edilir, ardından bu cihaz yerel moda geri döner.',
|
||||
'Disconnected — back to local-only': 'Bağlantı kesildi — yerel moda dönüldü',
|
||||
'Connect to my server': 'Sunucuma bağlan',
|
||||
'Sync this device to your own self-hosted openGym instead.': "Bu cihazı bunun yerine kendi self-hosted openGym'inle senkronize et.",
|
||||
'Pair the mobile app': 'Mobil uygulamayı eşleştir',
|
||||
'Connect the openGym app on your phone to this account.': 'Telefonundaki openGym uygulamasını bu hesaba bağla.',
|
||||
'Could not generate a code': 'Kod oluşturulamadı',
|
||||
'On the openGym app, choose “Connect to my server”, then enter this address and the code below. It expires in 5 minutes.': 'openGym uygulamasında “Sunucuma bağlan”ı seç, ardından bu adresi ve aşağıdaki kodu gir. 5 dakika içinde sona erer.',
|
||||
'Enter your server address and the code': 'Sunucu adresini ve kodu gir',
|
||||
'Connected': 'Bağlandı',
|
||||
'Could not connect': 'Bağlanılamadı',
|
||||
'Open Settings → “Pair the mobile app” on the openGym site you’re already signed into, then enter its address and the code shown there.': 'Zaten oturum açtığın openGym sitesinde Ayarlar → “Mobil uygulamayı eşleştir”i aç, ardından adresini ve orada gösterilen kodu gir.',
|
||||
'Server address (e.g. gym.example.com)': 'Sunucu adresi (ör. gym.example.com)',
|
||||
'Pairing code': 'Eşleştirme kodu',
|
||||
'Connecting…': 'Bağlanıyor…',
|
||||
'Connect': 'Bağlan',
|
||||
'How do you want to use openGym?': "openGym'i nasıl kullanmak istersin?",
|
||||
'Use on this device': 'Bu cihazda kullan',
|
||||
'Local keeps everything on this phone. Connecting syncs to your own openGym server instead — you can switch later in Settings.': "Yerel, her şeyi bu telefonda tutar. Bağlanmak ise bunun yerine kendi openGym sunucunla senkronize eder — bunu daha sonra Ayarlar'dan değiştirebilirsin."
|
||||
}
|
||||
@@ -163,6 +163,24 @@ export default {
|
||||
'Warm-up': '热身',
|
||||
'Add warm-up set': '添加热身组',
|
||||
'Add set': '加一组',
|
||||
'+ Drop': '+ 递减组',
|
||||
'+ Burst': '+ 爆发组',
|
||||
'Drop {0}': '递减组 {0}',
|
||||
'Burst {0}': '爆发组 {0}',
|
||||
'Remove drop': '移除递减组',
|
||||
'Remove burst': '移除爆发组',
|
||||
'Rest (s)': '休息(秒)',
|
||||
'Drop-set / rest-pause': '递减组 / 歇息暂停组',
|
||||
'Intensifier': '强化技巧',
|
||||
'None': '无',
|
||||
'Drop-set': '递减组',
|
||||
'Rest-pause': '歇息暂停组',
|
||||
'Drops': '递减次数',
|
||||
'Weight drop (%)': '减重幅度(%)',
|
||||
'Rest-pause reps': '歇息暂停次数',
|
||||
'Rest-pause rest': '歇息暂停休息',
|
||||
'Every set becomes a drop-set: after the main set, {0} drop(s) with no rest, each about {1}% lighter.': '每组都变成递减组:主组之后,无休息完成 {0} 次递减,每次约减轻 {1}%。',
|
||||
'Every set becomes rest-pause: {0} reps to start, then {1} more split into short bursts, {2}s rest before each, roughly halving each time.': '每组都变成歇息暂停组:先做 {0} 次,再分成几个短爆发共 {1} 次,每次前休息 {2} 秒,每次数量大约减半。',
|
||||
'Cardio logged': '有氧已记录',
|
||||
'Discard workout?': '放弃训练?',
|
||||
'The sets you logged in this session will be lost.': '本次记录的组数将丢失。',
|
||||
@@ -257,6 +275,7 @@ export default {
|
||||
'Theme': '主题',
|
||||
'Dark': '深色',
|
||||
'Light': '浅色',
|
||||
'System': '跟随系统',
|
||||
'Accent color': '强调色',
|
||||
'General': '通用',
|
||||
'During a workout': '训练期间',
|
||||
@@ -269,6 +288,8 @@ export default {
|
||||
'Data': '数据',
|
||||
'Export backup (JSON)': '导出备份(JSON)',
|
||||
'Import backup': '导入备份',
|
||||
'Auto-backup on changes': '变更时自动备份',
|
||||
'Saves a dated copy to the Documents folder after finishing a workout or editing a routine — point a sync app at it, or copy it out by hand.': '完成训练或编辑计划后,会在「文档」文件夹中保存一份带日期的副本——可以让同步应用指向该文件夹,或手动复制出来。',
|
||||
'Reset everything?': '重置所有内容?',
|
||||
'Reset everything': '重置所有内容',
|
||||
'Deletes your plan, workouts and body weight on this device. This cannot be undone.': '删除本设备上的计划、训练和体重。无法撤销。',
|
||||
@@ -605,5 +626,30 @@ export default {
|
||||
// --- muscle groups ---
|
||||
'Primary muscle groups': '主要肌群',
|
||||
'Additional muscle groups': '其他肌群',
|
||||
'No explicit muscle group': '无明确肌群'
|
||||
'No explicit muscle group': '无明确肌群',
|
||||
|
||||
// "Connect to my server" (mobile app pairing)
|
||||
'Your server': '你的服务器',
|
||||
'Synced with your openGym server.': '已与你的 openGym 服务器同步。',
|
||||
'Disconnect': '断开连接',
|
||||
'Disconnect from your server?': '要断开与服务器的连接吗?',
|
||||
'Your data is synced to your server first, then this device switches back to local-only.': '你的数据会先同步到服务器,然后此设备将切换回本地模式。',
|
||||
'Disconnected — back to local-only': '已断开连接——已切换回本地模式',
|
||||
'Connect to my server': '连接到我的服务器',
|
||||
'Sync this device to your own self-hosted openGym instead.': '改为将此设备与你自己的自托管 openGym 同步。',
|
||||
'Pair the mobile app': '配对手机应用',
|
||||
'Connect the openGym app on your phone to this account.': '将手机上的 openGym 应用连接到此账户。',
|
||||
'Could not generate a code': '无法生成配对码',
|
||||
'On the openGym app, choose “Connect to my server”, then enter this address and the code below. It expires in 5 minutes.': '在 openGym 应用中选择“连接到我的服务器”,然后输入此地址和下面的配对码。5 分钟后失效。',
|
||||
'Enter your server address and the code': '输入你的服务器地址和配对码',
|
||||
'Connected': '已连接',
|
||||
'Could not connect': '无法连接',
|
||||
'Open Settings → “Pair the mobile app” on the openGym site you’re already signed into, then enter its address and the code shown there.': '在你已登录的 openGym 网站上,打开设置 →“配对手机应用”,然后输入其地址和那里显示的配对码。',
|
||||
'Server address (e.g. gym.example.com)': '服务器地址(例如 gym.example.com)',
|
||||
'Pairing code': '配对码',
|
||||
'Connecting…': '连接中…',
|
||||
'Connect': '连接',
|
||||
'How do you want to use openGym?': '你想如何使用 openGym?',
|
||||
'Use on this device': '在此设备上使用',
|
||||
'Local keeps everything on this phone. Connecting syncs to your own openGym server instead — you can switch later in Settings.': '本地模式会把所有内容保留在这部手机上。连接则会改为与你自己的 openGym 服务器同步——之后可以在设置中更改。'
|
||||
}
|
||||
+56
-3
@@ -4,7 +4,7 @@ import { useUI } from './store/useUI.js'
|
||||
import { EXDB, EXIDX, BODYPARTS, isCardio, isBodyweightEq, allExercises, equipmentOf, smOf, matchExercise } from './lib/exercises.js'
|
||||
import { activeProfile, exAvailable, ALL_EQUIPMENT, newProfile } from './lib/equipment.js'
|
||||
import { fmtDate, fmtNum, fmtVol, fmtDur, durPart, todayISO, uid, exCount, DAYN, MONTHS_LONG, ACCENTS } from './lib/format.js'
|
||||
import { lastEntryFor, bestWeightFor, buildSets, effectiveRoutineId, workoutVolume, setsDone, setsDoneActive, lastBW, supersetUnits, unitOf, setLabel, defaultConfig, cleanupSg, modeOf, effortOf, isBw, isPerSide, sideReps, workSetsDone } from './lib/history.js'
|
||||
import { lastEntryFor, bestWeightFor, buildSets, effectiveRoutineId, workoutVolume, setsDone, setsDoneActive, lastBW, supersetUnits, unitOf, setLabel, defaultConfig, cleanupSg, modeOf, effortOf, isBw, isPerSide, sideReps, workSetsDone, applyIntensifierPlan } from './lib/history.js'
|
||||
import { beep, vibrate } from './lib/sound.js'
|
||||
import { t, instrFor, exerciseNameFor, getLang, INSTR_LANGS } from './lib/i18n.js'
|
||||
import { nav } from './lib/nav.js'
|
||||
@@ -613,6 +613,9 @@ function ExConfig({ ex, existing, onSave, onDelete, close, routine, initial }) {
|
||||
if (policyFor({ ...c, id: ex.id }, routine, 'reps') === 'double') out.repsMin = Math.min(reps, Math.max(1, Math.round(c.repsMin) || Math.max(1, reps - 2)))
|
||||
// A ceiling below the working reps would tell you to add a set on day one.
|
||||
if (bw && !(out.weight > 0) && c.repsMax > 0) out.repsMax = Math.max(reps, Math.round(c.repsMax))
|
||||
// Every set in this exercise becomes a drop-set/rest-pause (buildSets stamps the rows) —
|
||||
// decided here, in the plan, not re-decided live each time you train it.
|
||||
if (c.intensifier && c.intensifier.type) out.intensifier = c.intensifier
|
||||
onSave(out)
|
||||
}
|
||||
}
|
||||
@@ -638,13 +641,19 @@ function ExConfig({ ex, existing, onSave, onDelete, close, routine, initial }) {
|
||||
<Stepper label={t('Seconds')} value={c.sec} step={5} decimal={false} onChange={v => setC(x => ({ ...x, sec: v }))} />
|
||||
<Stepper label={t('Weight ({0})', st.unit)} value={c.weight} step={2.5} onChange={v => setC(x => ({ ...x, weight: v }))} />
|
||||
</> : <>
|
||||
<Stepper label={t('Sets')} value={c.sets} step={1} decimal={false} onChange={v => setC(x => ({ ...x, sets: v }))} />
|
||||
{/* Rest-pause always trains as exactly two rows — a warm-up at this rep count, then one
|
||||
rest-pause work set — so "Sets" has nothing left to mean and only invites a mismatch. */}
|
||||
{c.intensifier?.type !== 'restpause' &&
|
||||
<Stepper label={t('Sets')} value={c.sets} step={1} decimal={false} onChange={v => setC(x => ({ ...x, sets: v }))} />}
|
||||
<Stepper label={t('Reps')} value={c.reps} step={perSide ? 2 : 1} decimal={false} onChange={v => setC(x => ({ ...x, reps: v }))} />
|
||||
{/* On bodyweight work the weight stepper is the click #32 is about, so it is not here
|
||||
until there is a belt to describe — see the added-weight row below. */}
|
||||
{!bw && <Stepper label={t('Weight ({0})', st.unit)} value={c.weight} step={2.5} onChange={v => setC(x => ({ ...x, weight: v }))} />}
|
||||
</>}
|
||||
</div>
|
||||
{c.intensifier?.type === 'restpause' && <div className="small dim" style={{ marginTop: -10, marginBottom: 18 }}>
|
||||
{t('Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.')}
|
||||
</div>}
|
||||
{mode === 'time' && !bw && <div className="small dim" style={{ marginBottom: 18 }}>
|
||||
{t('A timer runs while you hold the set. Leave the weight at 0 for bodyweight holds.')}
|
||||
</div>}
|
||||
@@ -683,6 +692,43 @@ function ExConfig({ ex, existing, onSave, onDelete, close, routine, initial }) {
|
||||
? t('Reps climb to {0}, then a set is added and the reps start over. At {1} sets it asks you to add weight instead.', c.repsMax, MAX_BW_SETS)
|
||||
: t('Reps climb by one whenever every set was clean. Set a ceiling to add sets instead of reps forever.')}
|
||||
</div>}
|
||||
{mode === 'reps' && <>
|
||||
<h4 className="sec">{t('Drop-set / rest-pause')}</h4>
|
||||
<div className="sect-b" style={{ marginBottom: 8 }}>
|
||||
<SelectRow title={t('Intensifier')} sheetTitle={t('Intensifier')} value={c.intensifier?.type || ''}
|
||||
onChange={v => setC(x => ({
|
||||
...x,
|
||||
intensifier: !v ? undefined : v === 'dropset'
|
||||
? { type: 'dropset', count: x.intensifier?.count || 1, pct: x.intensifier?.pct || 20 }
|
||||
// The activation set's own reps are whatever "Reps" above already says — a
|
||||
// rest-pause plan only adds two new numbers: the total extra reps wanted past
|
||||
// it, and the rest between the bursts that total gets split into.
|
||||
: { type: 'restpause', totalReps: x.intensifier?.totalReps || x.reps || 8, restSec: x.intensifier?.restSec || st.restPauseSec || 15 },
|
||||
}))}
|
||||
options={[
|
||||
{ value: '', label: t('None') },
|
||||
{ value: 'dropset', label: t('Drop-set') },
|
||||
{ value: 'restpause', label: t('Rest-pause') },
|
||||
]} />
|
||||
</div>
|
||||
{c.intensifier?.type === 'dropset' && <div className="row cfgrow" style={{ marginBottom: 8 }}>
|
||||
<Stepper label={t('Drops')} value={c.intensifier.count} step={1} decimal={false}
|
||||
onChange={v => setC(x => ({ ...x, intensifier: { ...x.intensifier, count: Math.max(1, v) } }))} />
|
||||
<Stepper label={t('Weight drop (%)')} value={c.intensifier.pct} step={5} decimal={false}
|
||||
onChange={v => setC(x => ({ ...x, intensifier: { ...x.intensifier, pct: Math.max(5, v) } }))} />
|
||||
</div>}
|
||||
{c.intensifier?.type === 'restpause' && <div className="row cfgrow" style={{ marginBottom: 8 }}>
|
||||
<Stepper label={t('Rest-pause reps')} value={c.intensifier.totalReps} step={1} decimal={false}
|
||||
onChange={v => setC(x => ({ ...x, intensifier: { ...x.intensifier, totalReps: Math.max(1, v) } }))} />
|
||||
<Stepper label={t('Rest (s)')} value={c.intensifier.restSec} step={5} decimal={false}
|
||||
onChange={v => setC(x => ({ ...x, intensifier: { ...x.intensifier, restSec: Math.max(5, v) } }))} />
|
||||
</div>}
|
||||
{c.intensifier?.type && <div className="small dim" style={{ marginTop: -2, marginBottom: 18 }}>
|
||||
{c.intensifier.type === 'dropset'
|
||||
? t('Every set becomes a drop-set: after the main set, {0} drop(s) with no rest, each about {1}% lighter.', c.intensifier.count, c.intensifier.pct)
|
||||
: t('Every set becomes rest-pause: {0} reps to start, then {1} more split into short bursts, {2}s rest before each, roughly halving each time.', c.reps || 0, c.intensifier.totalReps, c.intensifier.restSec)}
|
||||
</div>}
|
||||
</>}
|
||||
<ProgressionFields ex={ex} mode={mode} c={c} setC={setC} routine={routine} unit={st.unit} />
|
||||
<textarea className="input" rows={3} maxLength={500} style={{ marginBottom: 18 }}
|
||||
placeholder={t('Note (optional) — loading cues, "bar only then +1 plate/side each set", anything worth remembering here')}
|
||||
@@ -927,7 +973,8 @@ export function beginWorkout(routineId, bw) {
|
||||
// kept on the entry purely so the workout can explain the number it chose.
|
||||
const entries = (r ? r.ex : []).map(cfg => {
|
||||
const plan = nextPrescription(st, cfg, r)
|
||||
return { id: cfg.id, sg: cfg.sg, target: { ...cfg }, plan, sets: applyPrescription(buildSets(st, cfg), plan) }
|
||||
const sets = applyIntensifierPlan(applyPrescription(buildSets(st, cfg), plan), cfg)
|
||||
return { id: cfg.id, sg: cfg.sg, target: { ...cfg }, plan, sets }
|
||||
})
|
||||
update(s => {
|
||||
s.active = { id: uid(), d: todayISO(), start: Date.now(), routineId, name: r ? r.name : t('Freestyle'), bw: bw || null, cur: 0, entries }
|
||||
@@ -985,6 +1032,11 @@ function TopWeight({ entryIdx, close }) {
|
||||
}
|
||||
export const topWeightSheet = entryIdx => ui().openSheet(close => <TopWeight entryIdx={entryIdx} 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
|
||||
by tapping "+ Drop"/"+ Burst", which appends with the same suggested-next-value math. */
|
||||
|
||||
// Shown when the last exercise's last set is checked — finish, or keep going.
|
||||
function WorkoutComplete({ close }) {
|
||||
return <div style={{ textAlign: 'center', padding: '8px 0' }}>
|
||||
@@ -1056,6 +1108,7 @@ function doFinishWorkout() {
|
||||
s.workouts.push(w)
|
||||
s.active = null
|
||||
})
|
||||
useStore.getState().autoBackupNow()
|
||||
useUI.getState().stopRest()
|
||||
beep(snd(), 880, 0.15); beep(snd(), 1100, 0.15, 0.18); beep(snd(), 1320, 0.3, 0.36)
|
||||
ui().openSheet(close => <FinishSummary w={w} prs={prs} e1prs={e1prs} close={close} />, { kind: 'center', locked: true })
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
import { create } from 'zustand'
|
||||
import { api } from '../lib/api.js'
|
||||
import { api, setRemoteAuth } from '../lib/api.js'
|
||||
import { localTZ } from '../lib/format.js'
|
||||
import { registerCustom } from '../lib/exercises.js'
|
||||
import { DEMO, DEMO_SEEDED } from '../lib/demo.js'
|
||||
import { guestAllowed } from '../lib/guest.js'
|
||||
import { MOBILE, nativeLoad, nativeSave, syncReminder } from '../lib/mobile.js'
|
||||
import { MOBILE, nativeLoad, nativeSave, syncReminder, writeAutoBackup } from '../lib/mobile.js'
|
||||
import { loadRemote, chooseLocal, forgetRemote, connect } from '../lib/remote.js'
|
||||
|
||||
const KEY = 'gym_state_v1'
|
||||
export const DEF = {
|
||||
unit: 'kg', restSec: 90, sound: true, keepAwake: true, lang: 'en',
|
||||
unit: 'kg', restSec: 90, restPauseSec: 15, sound: true, keepAwake: true, lang: 'en',
|
||||
theme: 'dark', accent: 'lime', body: 'male', targetW: null,
|
||||
bodyweight: [], routines: [], week: {}, dayPlan: {},
|
||||
exWeights: {}, workouts: [], active: null, customEx: [], gifSize: 'full',
|
||||
@@ -16,7 +17,7 @@ export const DEF = {
|
||||
// that a profile which never chose (loaded state is overlaid on DEF, on every path: local,
|
||||
// server pull, backup import) still falls back to the `showRir` boolean this replaced and
|
||||
// keeps the column it had. See effortOf.
|
||||
reminder: { on: false, time: '08:00', tz: null }, effort: null,
|
||||
reminder: { on: false, time: '08:00', tz: null }, effort: null, autoBackup: false,
|
||||
// Equipment profiles (issue: filter Library/picker/routines by what you actually own —
|
||||
// e.g. "Home" vs "Gym" — building on the session-only equipment filter from issue #6).
|
||||
equipProfiles: [], activeEquipId: null, equipFilterOn: false,
|
||||
@@ -87,6 +88,7 @@ export const useStore = create((set, get) => {
|
||||
S: (() => { const s = loadState(); registerCustom(s.customEx); return s })(),
|
||||
user: (() => { try { return JSON.parse(localStorage.getItem('gym_user')) || null } catch { return null } })(),
|
||||
ready: false,
|
||||
needsMobileOnboarding: false, // mobile build only — set true by boot() on a genuine first launch
|
||||
|
||||
// Mutate a draft of S via producer fn, then persist + schedule sync.
|
||||
update(mut, push = true) {
|
||||
@@ -96,6 +98,14 @@ export const useStore = create((set, get) => {
|
||||
},
|
||||
replaceState(S, push = false) { persist(clone(S), push) },
|
||||
|
||||
// Fires after the moments where losing local data would actually hurt — a workout just
|
||||
// logged, a routine just edited — not on every keystroke. No-op off mobile or with the
|
||||
// setting off; the private file mirror (nativePersist, above) already covers every change.
|
||||
autoBackupNow() {
|
||||
const S = get().S
|
||||
if (MOBILE && S.autoBackup) writeAutoBackup(S)
|
||||
},
|
||||
|
||||
isGuest: () => localStorage.getItem('gym_guest') === '1',
|
||||
setGuest(v) { if (v) localStorage.setItem('gym_guest', '1'); else localStorage.removeItem('gym_guest'); set({}) },
|
||||
|
||||
@@ -140,6 +150,31 @@ export const useStore = create((set, get) => {
|
||||
clearLocalSession()
|
||||
},
|
||||
|
||||
// Mobile-only ("connect to my server" onboarding, see App.jsx's needsMobileOnboarding).
|
||||
// Picking local — even before there's any data — persists the choice so onboarding never
|
||||
// asks again.
|
||||
async chooseLocalMode() {
|
||||
await chooseLocal()
|
||||
set({ needsMobileOnboarding: false })
|
||||
},
|
||||
// Redeems the pairing code shown in the browser (Settings → "Pair the mobile app") and
|
||||
// switches this device over to that account, same as signing in on the web does.
|
||||
async connectToServer(url, code) {
|
||||
const user = await connect(url, code) // throws on a bad URL/expired code — caller shows it
|
||||
get().setUser(user)
|
||||
await get().pullState()
|
||||
syncReminder(get().S)
|
||||
set({ needsMobileOnboarding: false })
|
||||
},
|
||||
// Leaves remote mode and drops cleanly back to local-only, without losing whatever was last
|
||||
// synced (signOut() already pushes before it clears).
|
||||
async disconnectServer() {
|
||||
await get().signOut()
|
||||
await forgetRemote()
|
||||
get().setGuest(true)
|
||||
set({ ready: true })
|
||||
},
|
||||
|
||||
// "Sign out everywhere": the server bumps this profile's session version, which kills every
|
||||
// session it has on any device — this browser included, so the app has to end up exactly
|
||||
// where a normal signOut leaves it. Unlike signOut the request is NOT swallowed: if it fails
|
||||
@@ -161,9 +196,26 @@ export const useStore = create((set, get) => {
|
||||
|
||||
// Boot: ask the server who we are, then pull.
|
||||
async boot() {
|
||||
// Mobile build: no backend either — restore from the file mirror (the durable copy;
|
||||
// localStorage may have been evicted since the last run) and go straight in.
|
||||
// Mobile build: no backend by default — restore from the file mirror (the durable copy;
|
||||
// localStorage may have been evicted since the last run) and go straight in. Unless this
|
||||
// device was paired to a server ("connect to my server" mode, lib/remote.js), in which
|
||||
// case it behaves exactly like the signed-in web flow below, straight from here.
|
||||
if (MOBILE) {
|
||||
const remote = await loadRemote()
|
||||
if (remote?.mode === 'remote') {
|
||||
setRemoteAuth(remote.base, remote.token)
|
||||
try {
|
||||
const me = await api('/api/me') // also catches a token revoked elsewhere (sign out everywhere)
|
||||
get().setUser(me.user)
|
||||
await get().pullState()
|
||||
} catch (e) {
|
||||
if (e.status === 401) { await forgetRemote(); get().setGuest(true) }
|
||||
else get().setUser(remote.user) // offline — keep going from the last-synced local copy
|
||||
}
|
||||
syncReminder(get().S)
|
||||
set({ ready: true })
|
||||
return
|
||||
}
|
||||
const saved = await nativeLoad()
|
||||
const S = get().S
|
||||
if (saved && (!hasData(S) || (saved._ts || 0) >= (S._ts || 0))) {
|
||||
@@ -173,7 +225,10 @@ export const useStore = create((set, get) => {
|
||||
}
|
||||
get().setGuest(true)
|
||||
syncReminder(get().S)
|
||||
set({ ready: true })
|
||||
// Only a genuinely first launch — nothing chosen yet and nothing to lose either — offers
|
||||
// the choice. Picking local (even with no data yet) persists that choice below and this
|
||||
// never asks again.
|
||||
set({ ready: true, needsMobileOnboarding: !remote && !hasData(get().S) })
|
||||
return
|
||||
}
|
||||
// Demo build (GitHub Pages): no backend at all — seed once, stay in guest mode.
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
// Mobile build only, first launch: the choice useStore.boot() couldn't make on its own — keep
|
||||
// everything on this device, or connect to a self-hosted openGym server instead. See
|
||||
// lib/remote.js for the pairing flow this hands off to.
|
||||
import { useState, useRef, useEffect } from 'react'
|
||||
import { useStore } from '../store/useStore.js'
|
||||
import { useUI } from '../store/useUI.js'
|
||||
import { t } from '../lib/i18n.js'
|
||||
import Icon from '../components/Icon.jsx'
|
||||
import { Button } from '../components/ui.jsx'
|
||||
|
||||
export function ConnectSheet({ close }) {
|
||||
const { connectToServer } = useStore()
|
||||
const [url, setUrl] = useState('')
|
||||
const [code, setCode] = useState('')
|
||||
const [busy, setBusy] = useState(false)
|
||||
const ref = useRef(null)
|
||||
useEffect(() => { setTimeout(() => ref.current?.focus(), 250) }, [])
|
||||
const go = async () => {
|
||||
if (!url.trim() || !code.trim()) { useUI.getState().toast(t('Enter your server address and the code')); return }
|
||||
setBusy(true)
|
||||
try { await connectToServer(url.trim(), code.trim()); close(); useUI.getState().toast(t('Connected')) }
|
||||
catch (e) { useUI.getState().toast(e.message || t('Could not connect')) }
|
||||
finally { setBusy(false) }
|
||||
}
|
||||
return <>
|
||||
<h3>{t('Connect to my server')}</h3>
|
||||
<div className="muted small" style={{ marginBottom: 14 }}>
|
||||
{t('Open Settings → “Pair the mobile app” on the openGym site you’re already signed into, then enter its address and the code shown there.')}
|
||||
</div>
|
||||
<input ref={ref} className="input" placeholder={t('Server address (e.g. gym.example.com)')} value={url}
|
||||
onChange={e => setUrl(e.target.value)} autoCapitalize="none" autoCorrect="off" inputMode="url" />
|
||||
<div style={{ height: 10 }} />
|
||||
<input className="input" placeholder={t('Pairing code')} maxLength={8} value={code}
|
||||
onChange={e => setCode(e.target.value.toUpperCase())} style={{ letterSpacing: '.14em', fontWeight: 600, textAlign: 'center' }} />
|
||||
<div style={{ height: 12 }} />
|
||||
<Button variant="primary" onClick={go} disabled={busy}>{busy ? t('Connecting…') : t('Connect')}</Button>
|
||||
</>
|
||||
}
|
||||
|
||||
export default function MobileOnboarding() {
|
||||
const { chooseLocalMode } = useStore()
|
||||
const head = <>
|
||||
<div style={{ fontSize: 54, display: 'flex', justifyContent: 'center', color: 'var(--acc)' }}><Icon name="dumbbell" /></div>
|
||||
<h1 style={{ fontSize: 34, fontWeight: 700, letterSpacing: '-.028em', margin: '10px 0 4px' }}>openGym</h1>
|
||||
</>
|
||||
const wrap = { display: 'flex', flexDirection: 'column', justifyContent: 'center', minHeight: '78vh', textAlign: 'center' }
|
||||
return (
|
||||
<div className="narrow" style={wrap}>
|
||||
{head}
|
||||
<div className="muted" style={{ marginBottom: 34 }}>{t('How do you want to use openGym?')}</div>
|
||||
<Button variant="primary" icon="lock" onClick={() => chooseLocalMode()}>{t('Use on this device')}</Button>
|
||||
<div style={{ height: 10 }} />
|
||||
<Button icon="rocket" onClick={() => useUI.getState().openSheet(close => <ConnectSheet close={close} />)}>{t('Connect to my server')}</Button>
|
||||
<div className="dim small" style={{ marginTop: 26, lineHeight: 1.5 }}>
|
||||
{t('Local keeps everything on this phone. Connecting syncs to your own openGym server instead — you can switch later in Settings.')}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -22,6 +22,10 @@ export default function RoutineEdit() {
|
||||
const update = useStore(s => s.update)
|
||||
const r = S.routines.find(x => x.id === id)
|
||||
useEffect(() => { if (!r) nav('/plan') }, [!!r])
|
||||
// Editing here has no explicit "save" — every field change persists immediately. A single
|
||||
// auto-backup on the way out (not per keystroke) covers the whole editing session, deletion
|
||||
// included: this still unmounts after the delete button navigates away.
|
||||
useEffect(() => () => useStore.getState().autoBackupNow(), [])
|
||||
if (!r) return null
|
||||
|
||||
const edit = fn => update(s => { fn(s.routines.find(x => x.id === id).ex) })
|
||||
|
||||
@@ -10,6 +10,7 @@ import { wakeLockSupported } from '../lib/wakelock.js'
|
||||
import { t, LANGS, INSTR_LANGS } from '../lib/i18n.js'
|
||||
import { DEMO, REPO } from '../lib/demo.js'
|
||||
import { MOBILE, shareExport, syncReminder } from '../lib/mobile.js'
|
||||
import { ConnectSheet } from './MobileOnboarding.jsx'
|
||||
import { loadStarterPlan, confirmSheet, importFromApp, equipmentProfileSheet } from '../sheets.jsx'
|
||||
import Icon from '../components/Icon.jsx'
|
||||
import { Section, Row, SelectRow, Switch, Segmented, Button, TextField } from '../components/ui.jsx'
|
||||
@@ -18,7 +19,7 @@ export default function Settings() {
|
||||
const nav = useNavigate()
|
||||
const S = useStore(s => s.S)
|
||||
const user = useStore(s => s.user)
|
||||
const { update, replaceState, setUser, pullState, pushState, signOut, signOutAll, resetDemo } = useStore()
|
||||
const { update, replaceState, setUser, pullState, pushState, signOut, signOutAll, resetDemo, disconnectServer } = useStore()
|
||||
const toast = useUI(s => s.toast)
|
||||
const fileRef = useRef(null)
|
||||
const importRef = useRef(null)
|
||||
@@ -73,12 +74,21 @@ export default function Settings() {
|
||||
</div>
|
||||
|
||||
{/* ---------- account (demo and mobile builds have nothing to sign in to) ---------- */}
|
||||
<Section title={MOBILE ? t('Your data') : DEMO ? t('Demo') : t('Account')}>
|
||||
{MOBILE ? <>
|
||||
<Section title={MOBILE ? (user ? t('Your server') : t('Your data')) : DEMO ? t('Demo') : t('Account')}>
|
||||
{MOBILE ? (user ? <>
|
||||
<Row icon="personCircle" iconTint="var(--grey)" title={user.name} subtitle={t('Synced with your openGym server.')} />
|
||||
{user.admin && <Row icon="wrench" iconTint="var(--indigo)" title={t('Admin dashboard')} accessory="chevron" onClick={() => nav('/admin')} />}
|
||||
<Row icon="signOut" iconTint="var(--red)" title={t('Disconnect')} danger onClick={() => confirmSheet({
|
||||
title: t('Disconnect from your server?'),
|
||||
message: t('Your data is synced to your server first, then this device switches back to local-only.'),
|
||||
confirmText: t('Disconnect'), danger: true,
|
||||
onConfirm: async () => { await disconnectServer(); nav('/home'); toast(t('Disconnected — back to local-only')) },
|
||||
})} />
|
||||
</> : <>
|
||||
<Row icon="lock" iconTint="var(--acc)" title={t('All data stays on this phone')} subtitle={t('No account, no cloud — back it up anytime with Export below.')} />
|
||||
<Row icon="rocket" iconTint="var(--indigo)" title={t('Self-host openGym')} subtitle={t('Passkey sign-in, sync across your devices, your own data.')} accessory="chevron"
|
||||
onClick={() => window.open(REPO, '_blank', 'noopener')} />
|
||||
</> : DEMO ? <>
|
||||
<Row icon="link" iconTint="var(--indigo)" title={t('Connect to my server')} subtitle={t('Sync this device to your own self-hosted openGym instead.')} accessory="chevron"
|
||||
onClick={() => useUI.getState().openSheet(close => <ConnectSheet close={close} />)} />
|
||||
</>) : DEMO ? <>
|
||||
<Row icon="sparkles" iconTint="var(--acc)" title={t('You’re in the demo')} subtitle={t('Example data, stored only in this browser — change anything you like.')} />
|
||||
<Row icon="reset" iconTint="var(--blue)" title={t('Reset demo data')} accessory="chevron"
|
||||
onClick={() => confirmSheet({ title: t('Reset demo data?'), message: t('Puts the example plan, workouts and weigh-ins back the way they started.'), confirmText: t('Reset'), onConfirm: () => { resetDemo(); nav('/home'); toast(t('Demo data reset')) } })} />
|
||||
@@ -87,6 +97,8 @@ export default function Settings() {
|
||||
</> : user ? <>
|
||||
<Row icon="personCircle" iconTint="var(--grey)" title={user.name} subtitle={t('Signed in with passkey — data syncs to this profile.')} />
|
||||
{user.admin && <Row icon="wrench" iconTint="var(--indigo)" title={t('Admin dashboard')} accessory="chevron" onClick={() => nav('/admin')} />}
|
||||
<Row icon="link" iconTint="var(--blue)" title={t('Pair the mobile app')} subtitle={t('Connect the openGym app on your phone to this account.')} accessory="chevron"
|
||||
onClick={() => useUI.getState().openSheet(close => <PairSheet close={close} />)} />
|
||||
<Row icon="signOut" iconTint="var(--red)" title={t('Sign out')} danger onClick={() => confirmSheet({ title: t('Sign out?'), message: t('Your data is synced to your profile first, then cleared from this device.'), confirmText: t('Sign out'), danger: true, onConfirm: () => { signOut(); nav('/home') } })} />
|
||||
<Row icon="shield" iconTint="var(--red)" title={t('Sign out everywhere')} subtitle={t('Ends this profile’s sessions on all your devices.')} danger onClick={signOutEverywhere} />
|
||||
</> : webauthnOK() ? <>
|
||||
@@ -120,6 +132,12 @@ export default function Settings() {
|
||||
<SelectRow icon="timer" iconTint="var(--orange)" title={t('Rest timer')}
|
||||
value={S.restSec} onChange={v => update(s => { s.restSec = v })}
|
||||
options={[60, 90, 120, 150, 180].map(v => ({ value: v, label: v + 's' }))} />
|
||||
{/* Default for a rest-pause burst added live on a plain set — a planned exercise's own
|
||||
"Rest (s)" (in its Intensifier config) overrides this, same as the main rest timer
|
||||
is the fallback whenever an exercise has no progression rule of its own. */}
|
||||
<SelectRow icon="bolt" iconTint="var(--acc)" title={t('Rest-pause rest')}
|
||||
value={S.restPauseSec} onChange={v => update(s => { s.restPauseSec = v })}
|
||||
options={[10, 15, 20, 30].map(v => ({ value: v, label: v + 's' }))} />
|
||||
{(wakeOK || !MOBILE) && (
|
||||
<Row icon="sun" iconTint="var(--yellow)" title={t('Keep screen awake')}
|
||||
subtitle={wakeOK ? null : t('Not supported in this browser.')}>
|
||||
@@ -150,8 +168,12 @@ export default function Settings() {
|
||||
<Row icon="moon" iconTint="var(--indigo)" title={t('Theme')}>
|
||||
<Segmented
|
||||
className="seg-inline"
|
||||
options={[{ value: 'dark', icon: 'moon', label: t('Dark') }, { value: 'light', icon: 'sun', label: t('Light') }]}
|
||||
value={S.theme === 'light' ? 'light' : 'dark'}
|
||||
options={[
|
||||
{ value: 'dark', icon: 'moon', label: t('Dark') },
|
||||
{ value: 'light', icon: 'sun', label: t('Light') },
|
||||
{ value: 'system', icon: 'gear', label: t('System') },
|
||||
]}
|
||||
value={S.theme || 'dark'}
|
||||
onChange={v => update(s => { s.theme = v })}
|
||||
/>
|
||||
</Row>
|
||||
@@ -183,6 +205,10 @@ export default function Settings() {
|
||||
accessory="chevron" onClick={() => importRef.current.click()} />
|
||||
<Row icon="upload" iconTint="var(--blue)" title={t('Import backup')} accessory="chevron" onClick={() => fileRef.current.click()} />
|
||||
<Row icon="download" iconTint="var(--blue)" title={t('Export backup (JSON)')} accessory="chevron" onClick={doExport} />
|
||||
{MOBILE && <Row icon="history" iconTint="var(--blue)" title={t('Auto-backup on changes')}
|
||||
subtitle={t('Saves a dated copy to the Documents folder after finishing a workout or editing a routine — point a sync app at it, or copy it out by hand.')}>
|
||||
<Switch checked={!!S.autoBackup} onChange={v => update(s => { s.autoBackup = v })} />
|
||||
</Row>}
|
||||
<Row icon="trash" iconTint="var(--red)" title={t('Reset everything')} danger onClick={() => confirmSheet({ title: t('Reset everything?'), message: t('Deletes your plan, workouts and body weight on this device. This cannot be undone.'), confirmText: t('Delete everything'), danger: true, onConfirm: () => { replaceState(JSON.parse(JSON.stringify(DEF)), true); nav('/home'); toast(t('All data reset')) } })} />
|
||||
</Section>
|
||||
<input ref={fileRef} type="file" accept=".json,application/json" style={{ display: 'none' }} onChange={doImport} />
|
||||
@@ -362,6 +388,28 @@ function EquipmentCard({ S, update }) {
|
||||
</Section>
|
||||
}
|
||||
|
||||
// Lets the mobile app's "connect to my server" mode (lib/remote.js) authenticate without a
|
||||
// WebAuthn ceremony of its own — the code is minted here, from an already signed-in session,
|
||||
// and redeemed by the app for a bearer token. See /api/pair/create in api/server.js.
|
||||
function PairSheet({ close }) {
|
||||
const [code, setCode] = useState(null)
|
||||
const [err, setErr] = useState(null)
|
||||
useEffect(() => { api('/api/pair/create', { method: 'POST', body: '{}' }).then(r => setCode(r.code)).catch(e => setErr(e.message || t('Could not generate a code'))) }, [])
|
||||
return <>
|
||||
<h3>{t('Pair the mobile app')}</h3>
|
||||
<div className="muted small" style={{ marginBottom: 14 }}>
|
||||
{t('On the openGym app, choose “Connect to my server”, then enter this address and the code below. It expires in 5 minutes.')}
|
||||
</div>
|
||||
{err ? <div className="dim small">{err}</div> : (
|
||||
<div className="card" style={{ textAlign: 'center', fontSize: 30, fontWeight: 700, letterSpacing: '.16em', padding: '18px 0' }}>
|
||||
{code || '········'}
|
||||
</div>
|
||||
)}
|
||||
<div style={{ height: 12 }} />
|
||||
<Button onClick={close}>{t('Done')}</Button>
|
||||
</>
|
||||
}
|
||||
|
||||
// The same registration as the sign-in screen's, reached from Settings instead. It asks for
|
||||
// the invite code on the same terms: an invite-only instance rejects a registration without
|
||||
// one, so a form that cannot collect it is a form that cannot succeed.
|
||||
|
||||
@@ -3,7 +3,7 @@ import { useNavigate } from 'react-router-dom'
|
||||
import { useStore } from '../store/useStore.js'
|
||||
import { useUI } from '../store/useUI.js'
|
||||
import { exOr } from '../lib/exercises.js'
|
||||
import { effectiveRoutine, lastEntryFor, bestWeightFor, buildSets, freestyleConfig, defaultConfig, setsDoneActive, supersetUnits, unitOf, setLabel, modeOf, isBw, isPerSide, sideReps, repStep, EFFORT, effortOf, stepEffort, capEffort, cascadeWeight, insertWarmupRow, removeRowAt, pairAdjacent, unpairSuperset, cleanupSg } from '../lib/history.js'
|
||||
import { effectiveRoutine, lastEntryFor, bestWeightFor, buildSets, freestyleConfig, defaultConfig, setsDoneActive, supersetUnits, unitOf, setLabel, modeOf, isBw, isPerSide, sideReps, repStep, EFFORT, effortOf, stepEffort, capEffort, cascadeWeight, insertWarmupRow, removeRowAt, pairAdjacent, unpairSuperset, cleanupSg, applyIntensifierPlan } from '../lib/history.js'
|
||||
import { fmtNum, fmtDate, todayISO, exCount, DAYN } from '../lib/format.js'
|
||||
import { beep, vibrate } from '../lib/sound.js'
|
||||
import { t, exerciseNameFor } from '../lib/i18n.js'
|
||||
@@ -15,7 +15,7 @@ import Icon from '../components/Icon.jsx'
|
||||
import { Button, Check, NumberField } from '../components/ui.jsx'
|
||||
import { nextPrescription, applyPrescription } from '../lib/progression.js'
|
||||
import { glyphOf } from '../lib/glyphs.js'
|
||||
import { isWarmupRow } from '../lib/workout-model.js'
|
||||
import { isWarmupRow, isDropSet, isRestPauseSet, dropsOf, clustersOf, addDrop, addCluster, removeDropAt, removeClusterAt, setDropAt, setClusterAt, nextDropWeight, nextBurstReps } from '../lib/workout-model.js'
|
||||
|
||||
/* ---------- start chooser (no active workout) ---------- */
|
||||
function StartChooser() {
|
||||
@@ -58,8 +58,39 @@ function Elapsed({ start }) {
|
||||
/* ---------- one exercise block (reps: weight×reps · time: a held duration · cardio: duration+speed) ---------- */
|
||||
function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemoveSet, onAddWarmup, onRemoveSetAt, onStartTimed, onPairPrev, onPairNext }) {
|
||||
const S = useStore(s => s.S)
|
||||
const update = useStore(s => s.update)
|
||||
const working = useUI(s => s.work)
|
||||
const entry = S.active.entries[entryIdx]
|
||||
// Drops/bursts mutate the row in place — same card, not a new set with its own long rest.
|
||||
// A planned exercise (see the exercise's "Intensifier" config) arrives with these already
|
||||
// filled in by applyIntensifierPlan; these only add/edit/remove entries live from here on.
|
||||
const mutSet = (i, fn) => update(s => { const row = s.active.entries[entryIdx].sets[i]; s.active.entries[entryIdx].sets[i] = fn(row) }, true)
|
||||
const addDropRow = i => mutSet(i, row => {
|
||||
const drops = dropsOf(row)
|
||||
const base = drops.length ? drops[drops.length - 1].w : (row.w || 0)
|
||||
const pct = entry.target?.intensifier?.type === 'dropset' ? entry.target.intensifier.pct : undefined
|
||||
return addDrop(row, { w: nextDropWeight(base, pct), r: row.r })
|
||||
})
|
||||
// A rest-pause row's own reps are always the total across every burst (see
|
||||
// applyIntensifierPlan/history.js) — clusters are the breakdown of that total, not extra on
|
||||
// top of it — so adding, removing or editing one keeps `r` in step by the same delta.
|
||||
const addBurstRow = i => mutSet(i, row => {
|
||||
const clusters = clustersOf(row)
|
||||
const base = clusters.length ? clusters[clusters.length - 1].r : (row.r || 0)
|
||||
const restSec = entry.target?.intensifier?.type === 'restpause' ? entry.target.intensifier.restSec : (S.restPauseSec || 15)
|
||||
const added = nextBurstReps(base)
|
||||
return { ...addCluster(row, { r: added, restSec }), r: (row.r || 0) + added }
|
||||
})
|
||||
const removeDrop = (i, di) => mutSet(i, row => removeDropAt(row, di))
|
||||
const removeCluster = (i, ci) => mutSet(i, row => {
|
||||
const removed = clustersOf(row)[ci]?.r || 0
|
||||
return { ...removeClusterAt(row, ci), r: Math.max(0, (row.r || 0) - removed) }
|
||||
})
|
||||
const setDropField = (i, di, field, v) => mutSet(i, row => setDropAt(row, di, { [field]: v }))
|
||||
const setClusterField = (i, ci, v) => mutSet(i, row => {
|
||||
const delta = (Number(v) || 0) - (clustersOf(row)[ci]?.r || 0)
|
||||
return { ...setClusterAt(row, ci, { r: v }), r: Math.max(0, (row.r || 0) + delta) }
|
||||
})
|
||||
const ex = exOr(entry.id)
|
||||
const mode = modeOf({ ...(entry.target || {}), id: entry.id })
|
||||
const cardio = mode === 'cardio'
|
||||
@@ -110,6 +141,15 @@ function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemov
|
||||
<button aria-label="Increase" onClick={() => bump(s, i, col, 1)}><Icon name="plus" /></button>
|
||||
</div>
|
||||
)
|
||||
// A smaller stepper for a drop's weight/reps or a burst's reps — editing what the plan (or a
|
||||
// live "+ Drop"/"+ Burst" tap) already put on the row, not typing into a fresh field.
|
||||
const miniStepper = (value, step, dec, onChange) => (
|
||||
<div className="stp mini">
|
||||
<button aria-label="Decrease" onClick={() => onChange(Math.max(0, Math.round(((value || 0) - step) * 100) / 100))}><Icon name="minus" /></button>
|
||||
<span className="val"><NumberField decimal={dec} value={value ?? ''} onChange={onChange} /></span>
|
||||
<button aria-label="Increase" onClick={() => onChange(Math.max(0, Math.round(((value || 0) + step) * 100) / 100))}><Icon name="plus" /></button>
|
||||
</div>
|
||||
)
|
||||
return <>
|
||||
<Media ex={ex} key={entry.id} compact={compact} minimizable />
|
||||
<div className="row between" style={{ marginBottom: 6 }}>
|
||||
@@ -160,6 +200,31 @@ function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemov
|
||||
disabled={entry.sets.length <= 1} onClick={() => onRemoveSetAt(i)}><Icon name="xmark" /></button>}
|
||||
<Check checked={s.done} onChange={() => onToggle(i)} />
|
||||
</div>
|
||||
{/* Drop-sets and rest-pause bursts extend this same row — no long rest, no new set.
|
||||
A planned exercise arrives with these already filled in (applyIntensifierPlan);
|
||||
every value here is just as editable as the main row's own weight/reps. */}
|
||||
{!warm && mode === 'reps' && <>
|
||||
{dropsOf(s).map((d, di) => (
|
||||
<div className="subrow" key={'d' + di}>
|
||||
<span className="subn">{t('Drop {0}', di + 1)}</span>
|
||||
{miniStepper(d.w, 2.5, true, v => setDropField(i, di, 'w', v))}
|
||||
{miniStepper(d.r, 1, false, v => setDropField(i, di, 'r', v))}
|
||||
<button className="iconbtn" aria-label={t('Remove drop')} onClick={() => removeDrop(i, di)}><Icon name="xmark" /></button>
|
||||
</div>
|
||||
))}
|
||||
{clustersOf(s).map((c, ci) => (
|
||||
<div className="subrow" key={'c' + ci}>
|
||||
<span className="subn">{t('Burst {0}', ci + 1)}</span>
|
||||
{miniStepper(c.r, 1, false, v => setClusterField(i, ci, v))}
|
||||
<span className="dim small">{c.restSec}s</span>
|
||||
<button className="iconbtn" aria-label={t('Remove burst')} onClick={() => removeCluster(i, ci)}><Icon name="xmark" /></button>
|
||||
</div>
|
||||
))}
|
||||
<div className="setextra">
|
||||
{!isRestPauseSet(s) && <button className="chip add" onClick={() => addDropRow(i)}><Icon name="arrowDown" />{t('+ Drop')}</button>}
|
||||
{!isDropSet(s) && <button className="chip add" onClick={() => addBurstRow(i)}><Icon name="bolt" />{t('+ Burst')}</button>}
|
||||
</div>
|
||||
</>}
|
||||
</div>
|
||||
})}
|
||||
<div style={{ height: 8 }} />
|
||||
@@ -429,7 +494,8 @@ function ActiveWorkout() {
|
||||
const full = { ...cfg, id: ex.id }
|
||||
const plan = freestyle ? null : nextPrescription(s, full, s.routines.find(r => r.id === s.active.routineId))
|
||||
const sets = buildSets(s, full, freestyle ? { preferLast: true } : undefined)
|
||||
s.active.entries.push({ id: ex.id, target: { ...cfg }, plan, sets: freestyle ? sets : applyPrescription(sets, plan) })
|
||||
const progressed = freestyle ? sets : applyPrescription(sets, plan)
|
||||
s.active.entries.push({ id: ex.id, target: { ...cfg }, plan, sets: applyIntensifierPlan(progressed, full) })
|
||||
s.active.cur = s.active.entries.length - 1
|
||||
}), null, routine, seed)
|
||||
})} icon="plus">{t('Add exercise')}</Button>
|
||||
|
||||
@@ -2,6 +2,12 @@ import { defineConfig } from 'vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
|
||||
const backend = process.env.API_TARGET || 'http://127.0.0.1:3000'
|
||||
// The API refuses a state-changing request that a browser sent from anywhere other than its own
|
||||
// ORIGIN (the CSRF guard in api/server.js). The dev server is on a different port, so the page's
|
||||
// real Origin is not ORIGIN — modern browsers get through on Sec-Fetch-Site: same-origin, and
|
||||
// presenting the expected Origin here covers the ones that don't send it. Match your .env if you
|
||||
// changed ORIGIN: API_ORIGIN=https://gym.example.com npm run dev
|
||||
const apiOrigin = process.env.API_ORIGIN || 'http://localhost:8080'
|
||||
const media = process.env.MEDIA_TARGET || 'http://127.0.0.1:8888'
|
||||
|
||||
// Optional web analytics (Umami). Injected only when BOTH vars are set at build time,
|
||||
@@ -27,7 +33,7 @@ export default defineConfig({
|
||||
base: './',
|
||||
server: {
|
||||
proxy: {
|
||||
'/api': { target: backend, changeOrigin: true },
|
||||
'/api': { target: backend, changeOrigin: true, headers: { Origin: apiOrigin } },
|
||||
'/img': { target: media, changeOrigin: true },
|
||||
'/gif': { target: media, changeOrigin: true }
|
||||
}
|
||||
|
||||
@@ -38,6 +38,11 @@ COPY --from=build /app/dist /usr/share/nginx/html
|
||||
ENV NGINX_PORT=80
|
||||
ENV BACKEND=api
|
||||
ENV PORT=3000
|
||||
# Empty = the CF-Connecting-IP header is dropped before it reaches the API, so it cannot be
|
||||
# forged by a direct client. Set to $http_cf_connecting_ip only when Cloudflare is really in
|
||||
# front. Defined here too, not just in compose, so the template always renders for anyone
|
||||
# running the prebuilt image from their own compose file.
|
||||
ENV CF_CONNECTING_IP=""
|
||||
|
||||
# Probe the port nginx was actually told to listen on (NGINX_PORT is configurable, so a
|
||||
# hardcoded http://localhost/ breaks on any instance that changed it), and address it as
|
||||
|
||||
+33
-3
@@ -5,14 +5,36 @@ server {
|
||||
root /usr/share/nginx/html;
|
||||
index index.html;
|
||||
|
||||
# API → backend container
|
||||
location /api/ {
|
||||
# Sent on every response below. NOTE: an `add_header` inside a location replaces the whole
|
||||
# inherited set rather than adding to it, so the two locations further down that set their
|
||||
# own Cache-Control have to repeat these three. Deliberately not a full Content-Security-
|
||||
# Policy: only frame-ancestors, which no part of the app depends on. TLS, HSTS and any
|
||||
# stricter policy stay the reverse proxy's job (see SECURITY.md).
|
||||
add_header X-Frame-Options "DENY" always;
|
||||
add_header X-Content-Type-Options "nosniff" always;
|
||||
add_header Referrer-Policy "same-origin" always;
|
||||
add_header Content-Security-Policy "frame-ancestors 'none'" always;
|
||||
|
||||
# API → backend container.
|
||||
# `^~` so this prefix beats the regex locations below: without it a request for a path such
|
||||
# as /api/anything.json would be matched by the \.(js|css|json|html)$ block instead and be
|
||||
# looked for on disk rather than proxied.
|
||||
location ^~ /api/ {
|
||||
proxy_pass http://${BACKEND}:${PORT};
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
# $remote_addr, NOT $proxy_add_x_forwarded_for: the latter APPENDS to whatever the client
|
||||
# sent, and the API reads the first entry — so a client could put any address it liked in
|
||||
# front of its own and choose what the activity log recorded about it. Overwriting is what
|
||||
# makes the header mean anything.
|
||||
proxy_set_header X-Forwarded-For $remote_addr;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
# Same reasoning, and the API trusts this one FIRST. Empty by default, which drops the
|
||||
# header entirely, so a direct client cannot forge it. Cloudflare users set
|
||||
# CF_CONNECTING_IP=$http_cf_connecting_ip to let the real one through — correct only when
|
||||
# Cloudflare is genuinely in front, because that is what overwrites a client-supplied one.
|
||||
proxy_set_header CF-Connecting-IP "${CF_CONNECTING_IP}";
|
||||
}
|
||||
|
||||
# SPA fallback
|
||||
@@ -23,12 +45,20 @@ server {
|
||||
# App shell: always revalidate so updates show up immediately
|
||||
location ~* \.(js|css|json|html)$ {
|
||||
add_header Cache-Control "no-cache, must-revalidate";
|
||||
add_header X-Frame-Options "DENY" always;
|
||||
add_header X-Content-Type-Options "nosniff" always;
|
||||
add_header Referrer-Policy "same-origin" always;
|
||||
add_header Content-Security-Policy "frame-ancestors 'none'" always;
|
||||
}
|
||||
|
||||
# Exercise images/GIFs never change → cache hard
|
||||
location ~* \.(png|jpg|jpeg|gif|ico|svg|woff|woff2|webp|avif)$ {
|
||||
expires 30d;
|
||||
add_header Cache-Control "public, max-age=2592000, immutable";
|
||||
add_header X-Frame-Options "DENY" always;
|
||||
add_header X-Content-Type-Options "nosniff" always;
|
||||
add_header Referrer-Policy "same-origin" always;
|
||||
add_header Content-Security-Policy "frame-ancestors 'none'" always;
|
||||
}
|
||||
|
||||
gzip on;
|
||||
|
||||
Reference in new issue
Block a user