Compare commits

...
60 Commits
Author SHA1 Message Date
Duarte Santos cf46301e06 v1.3.2 2026-09-05 14:18:56 +02:00
Duarte Santos 9eccb5a5c3 Merge mrbatch-0904: 17 Community-MRs plus Tester-Fixes fuer v1.3.2 2026-09-05 14:17:21 +02:00
Duarte Santos aba3280069 Merge !99: Coach: the create schema requires a routine id and a week 2026-09-05 13:31:50 +02:00
Duarte Santos c78bc6763f web: nginx loest den api-Container pro Request auf (502 nach api-Recreate, #16); renovate.json ohne _comment/_managers (#37)
nginx pinnte die IP von `api` beim Start; wird nur der api-Container neu erzeugt, laeuft jeder
/api-Aufruf auf 502, bis auch web neu startet. `resolver 127.0.0.11 valid=10s` plus proxy_pass
ueber eine Variable laesst nginx den Namen pro Request neu aufloesen.

Renovate lehnte die Konfiguration wegen der Pseudo-Schluessel `_comment` und `_managers` ab
("Invalid configuration option") und hatte die MRs eingestellt; beide Texte stehen jetzt im
offiziellen `description`-Feld.
2026-09-05 13:31:43 +02:00
Konstantinos Thermos 6730549845 Coach: cap the plan arrays in the schema, not only in the prompt
create.md asks for "1-7 routines, each 3-12 exercises" and validate.js slices at MAX_ROUTINES /
MAX_EX_PER_ROUTINE, but the schema the endpoint decodes against had no bound at all. A model that
starts repeating itself never reaches the validator: qwen2.5:3b walks the library id by id, three
sets of eight apiece, until it exhausts the 16k output limit — twelve minutes for an answer that
arrives truncated, which the adapter turns into "the answer was cut off at the output limit" and a
job that would already have hit COACH_JOB_TIMEOUT_MS.

maxItems on the two arrays states the caps that already exist, where the decoder can enforce them.
2026-09-04 18:58:23 +03:00
Konstantinos Thermos dafc80f1d6 Coach: the create schema requires a routine id and a week
CREATE_SCHEMA is handed to OpenAI-compatible endpoints as a grammar to decode against, and it
left both `routines[].id` and `week` optional. Small local models take that offer: llama3.2:3b
and qwen2.5:3b both answer with routines that carry no id, and a week naming what they wrote
into `name` instead. Nothing in the week then resolves, validate.js reports "the week schedules
0 days but 3 were asked for", the repair round produces the same answer again, and the job ends
as `unusable` — "The Coach answered with something the app couldn't use."

Requiring the two fields the week resolves through is enough. With them in the schema,
llama3.2:3b produces a plan that passes validatePlan on the first attempt, against the payload
that failed twice before. The validator is untouched; this only stops the grammar from offering
an answer it can never accept.
2026-09-04 18:46:39 +03:00
Duarte Santos 0cbd32c0f5 mrbatch: Listenmodus beendet den Workout nicht mehr zu frueh, Progression-Sheet speichert trotz Store-Clone, Progression-aus auch bei Swap/Sheet, Stepper snappt nur auf dem Raster, exWeights erst beim Abschluss
Aus dem Subagenten-Test der Workout-MRs:
- !96 x !92: toggle() beurteilte die Einheit des Markers statt die des angetippten Satzes; im
  Listenmodus kam "That's the whole workout!" nach einem Satz einer anderen Uebung.
- !77: Identitaetsvergleich scheitert an jedem Store-Clone (auch der Stangengewicht-Stepper im
  Sheet selbst) -> Vergleich auf Workout-Id, Listenlaenge und Uebung am Index.
- !71: useTarget bei Progression 'aus' auch fuer swapActiveWorkoutExercise und das
  Progression-Sheet im Workout.
- !84: stepWeight snappt nur, wenn der Wert schon auf dem Schrittraster liegt (62.5 +5 -> 67.5,
  nicht 70; 61.3 +1.25 -> 62.5 wie die Progression).
- !92: exWeights werden nur noch beim Abschluss geschrieben (doFinishWorkout), nicht beim
  Abhaken - ein korrigierter Tippfehler oder ein verworfener Workout wird nie zum "Best".
2026-09-04 17:16:49 +02:00
Duarte Santos 80cccdd2e0 mrbatch (!87): Muskel-Explorer folgt dem Geraete-Profil wie Library/Picker, Zurueck-Pfeil links, Satz nicht doppelt, Library-Tab bleibt markiert 2026-09-04 17:13:47 +02:00
Duarte Santos 6e9f5e7b9c mrbatch: preview_session baut die Session ueber session-start.js (Progression aus, Deload-Routinen, Warm-up-Schritt), meldet auch Zeit/Cardio-Overrides; Rest-Toast auch nach verstecktem Ablauf 2026-09-04 17:11:24 +02:00
Duarte Santos 0f021aa06d mrbatch: pt-BR-Guard nachgezogen, Sheet-Mock kennt starterPlanSheet, Listenmodus folgt !92 (kein Auto-Weiterspringen) 2026-09-04 16:57:42 +02:00
Duarte Santos f767d007a5 Merge !90: MCP: preview_session — what a routine will actually open with
# Conflicts:
#	mcp/README.md
2026-09-04 16:54:53 +02:00
Duarte Santos dfc63543ea Merge !94: feat: add Upper/Lower, Full Body and 5×5 starter plans
# Conflicts:
#	frontend/src/lib/pt-br-locale.test.js
2026-09-04 16:54:38 +02:00
Duarte Santos 194aa15f0e Merge !87: feat: add muscle exercise explorer
# Conflicts:
#	frontend/src/lib/pt-br-locale.test.js
2026-09-04 16:54:38 +02:00
Duarte Santos dab232a591 Merge !96: feat(workout): add configurable list view for active workouts
# Conflicts:
#	frontend/src/views/Workout.jsx
2026-09-04 16:54:38 +02:00
Duarte Santos d8130443a9 Merge !72: Exercise picker: the "+" adds now instead of opening the detail sheet
# Conflicts:
#	frontend/src/views/RoutineEdit.jsx
2026-09-04 16:54:08 +02:00
Duarte Santos 4bca5336d1 Merge !85: feat: add copy routine button to RoutineEdit view
# Conflicts:
#	frontend/src/lib/pt-br-locale.test.js
2026-09-04 16:53:52 +02:00
Duarte Santos f00400206d Merge !92: fix: capture working weight automatically 2026-09-04 16:53:52 +02:00
Duarte Santos 26847dac3b Merge !80: fix: use available width for exercise selector 2026-09-04 16:53:52 +02:00
Duarte Santos e94bd1250e Merge !82: BodyMap tests: import the geometry before the first render 2026-09-04 16:53:52 +02:00
Duarte Santos 566463c45f Merge !81: MCP: get_routine reports an exercise's own rest 2026-09-04 16:53:52 +02:00
Duarte Santos 6c22076d35 Merge !77: Show and edit progression policy during workouts 2026-09-04 16:53:52 +02:00
Duarte Santos 11bb1392f8 Merge !93: Fixed and tested deload spiral 2026-09-04 16:53:52 +02:00
Duarte Santos 953d91c806 Merge !71: fix: keep no-progression routine targets 2026-09-04 16:53:52 +02:00
Duarte Santos dca8393a7a Merge !89: Timer flash: blink the real theme instead of a black/white overlay, sk 2026-09-04 16:53:52 +02:00
Duarte Santos b301b8c81d Merge !84: fix: use exercise weight step for workout controls
# Conflicts:
#	frontend/src/views/Workout.jsx
2026-09-04 16:53:51 +02:00
Duarte Santos 8fb22e7994 Merge !97: bugfix: RIR counter ins supersets required two clicks per increment 2026-09-04 16:53:32 +02:00
Daniel Patrón Gómez 98ed4ddcb1 Merge branch 'main' into feat/workout-list-view 2026-09-04 16:14:27 +02:00
Duarte Santos dca6bcdf2d Images: alpine-Upgrades beim Bauen, npm aus dem publizierten api-Image, APK-Checksumme bei jedem Build
Der Trivy-Scan meldete 13 Funde, alle im api-Image und keiner in einer Abhaengigkeit der App:
2x openssl aus alpine (node:22-alpine hinkt alpines Fixes hinterher) und 11x in npms eigenem
gebuendelten Baum (tar, brace-expansion, pacote, ...). Beide Images ziehen jetzt `apk upgrade`
beim Bauen; das publizierte api-Image (Target default) verliert npm komplett - der Server
startet mit `node server.js`, nichts spawnt npm. build:api-check prueft das. Das coach-Target
behaelt npm fuer die Codex-CLI.

build:apk schreibt die .sha256 jetzt bei jedem Build (die Artefakt-Warnung auf Branches ist weg),
hochgeladen wird sie weiterhin nur vom Release-Tag.
2026-09-04 15:34:49 +02:00
prasad-gade05 e4139a4e9f feat: add muscle exercise explorer 2026-09-04 19:03:02 +05:30
Duarte Santos 4924ad8aeb Merge !95: gym membership QR check-in, in app and PWA, with a Settings switch 2026-09-04 15:21:53 +02:00
Duarte Santos 50a8b96285 cap sync: secure-storage and ML Kit plugin in the generated gradle/Podfile lists 2026-09-04 15:16:23 +02:00
Duarte Santos aa487d29f4 Gym check-in in the browser/PWA too
The feature was gated behind MOBILE because scanning went through the native ML Kit
plugin. iPhone users only have the PWA, so: route, Home card and Settings switch on
every platform; photo import and a live camera sheet decode in the browser with
BarcodeDetector where it exists and jsQR (Apache-2.0, lazy chunk) otherwise. The app
build keeps ML Kit. Round-trip test lean-qr -> jsQR.
2026-09-04 15:15:31 +02:00
Duarte Santos 0af9f55528 Gym check-in: Settings switch to turn the feature off
Off hides the Home card and the /checkin route; saved cards stay. On by default,
profiles without the key read as on. pt-BR: trailing comma the MR's last override
line was missing, override count 600.
2026-09-04 14:42:48 +02:00
Duarte Santos 5478b2d621 CI: Image-Digest robust auslesen (buildx druckte den ganzen Block, dotenv-Upload scheiterte) 2026-09-04 14:09:40 +02:00
Duarte Santos 2899f27fa6 CI: Pipelines fuer Fork-MRs, Testberichte im MR, Stack-Check der Images, Trivy+SBOM, Release-Preflight
Was die Pipeline neu kann:
- release:preflight prueft auf einem v*-Tag, dass frontend/api-package.json und CHANGELOG
  zum Tag passen und der Commit auf main liegt - bevor 40 Minuten Build anlaufen.
- test:* liefern JUnit (Fehler stehen im MR-Widget) und Coverage (Badge + Diff-Annotation);
  test:frontend misst das Bundle und zeigt im MR die Differenz zu main.
- verify:stack startet die gerade gepushten Images ueber die echte docker-compose.yml und
  fragt sie durch nginx ab; verify:scan (Trivy) scannt beide Images und legt je ein
  CycloneDX-SBOM ab, das der Release verlinkt.
- Der Release nennt Digests, Pull-Befehl und APK-SHA-256.
- mr:fork-pipelines startet die Pipelines von Fork-MRs bekannter Contributor hier im
  Projekt (Fork-Pipelines laufen sonst im Fork ohne Runner); Erstkontakte bekommen das
  Label ci-approval-needed. Braucht PIPELINE_API_TOKEN und den Zeitplan SCHEDULE_JOB=fork-mrs.

Korrekturen:
- web/Dockerfile: npm ci --ignore-scripts statt "npm ci || npm install" - der
  sharp/libvips-Download hatte v1.3.1 rot gemacht, und der Fallback ignorierte das Lockfile.
- interruptible + Retry bei Runner-Fehlern fuer alle Jobs, Timeouts pro Job,
  release-cli gepinnt, Docker-/Rules-Vorlagen statt Copy-Paste.
- Zeitplaene unterscheiden sich per SCHEDULE_JOB, damit Renovate und der MR-Starter sich
  nicht gegenseitig ausloesen.
2026-09-04 14:06:50 +02:00
Sebastian G 3197f9e9be Merge remote-tracking branch 'origin/main' into feat/gym-checkin-qr
# Conflicts:
#	frontend/package-lock.json
#	frontend/package.json
#	frontend/src/index.css
#	frontend/src/lib/pt-br-locale.test.js
#	frontend/src/locales/hu.js
#	frontend/src/locales/th.js
2026-09-04 13:14:01 +02:00
Sebastian G eb59240e2f fix: superset RIR counter fixed 2026-09-04 10:46:53 +02:00
Daniel Patrón Gómez e278051fae feat(workout): add configurable list view for active workouts 2026-09-04 10:09:30 +02:00
sebastian.goendoer e57eac027f fix: read fresh store value in set-stepper bump to prevent stale closure in supersets
In a superset both ExerciseBlock instances subscribe to the same store
slice. When one member's field is updated the store clone invalidates all
entry references, causing both instances to re-render. The +/- button
handlers were closing over the set object from the previous render, so
the first tap wrote the correct value but the replacement closure made
the next tap operate on stale data -- requiring two taps per visible
increment instead of one.

Fix: read the current field value directly from the store at call time
instead of relying on the render-time snapshot.
2026-09-03 21:40:11 +02:00
Luke M 44138e07d7 feat: add starter plan chooser and loading flow 2026-09-03 11:36:39 +02:00
Luke M 89fdd1b787 feat: add additional starter plan definitions 2026-09-03 11:36:27 +02:00
Sebastian G 0f1500b102 i18n and tests 2026-09-03 11:24:17 +02:00
Sebastian G a797729dd0 feat(checkin): gym membership QR check-in (mobile-only)
Add a mobile-only gym check-in screen: saved membership codes shown as
QR codes in a swipeable carousel, reached from a 'Check in' card on Home.
Cards are added by typing the code, importing a photo, or scanning with
the camera. Only the code value + symbology are stored — never a photo;
the QR is regenerated from the value on every display.

Rendering uses lean-qr (MIT); camera scan and photo decode use
@capacitor-mlkit/barcode-scanning (Apache-2.0), pinned to the 7.x line
for Capacitor 7. Both are documented in NOTICE.md and bundled only in the
mobile build — the whole feature folds away in web/demo builds via MOBILE,
so nothing new lands in the web bundle. No backend/schema change: gymCards
rides the existing state sync and backup like every other field.

Non-QR symbologies are readable but not reproducible, so capture refuses
them rather than storing a code that would display wrong bars.

Native wiring: CAMERA permission + ML Kit barcode_ui meta-data
(AndroidManifest), NSCameraUsageDescription (iOS Info.plist), mlkit plugin
registered via cap sync. Debug builds get an applicationIdSuffix '.test'
and an 'OpenGymTest' label so a test build installs alongside the real app.
2026-09-03 11:10:58 +02:00
Manuel 6013874e99 fix: require explicit next after completed exercise 2026-09-02 21:07:48 +02:00
Manuel 697e482033 fix: capture working weight automatically 2026-09-02 17:48:53 +02:00
arhx91 c6d8e873ce Fixed and tested deload spiral 2026-09-02 17:39:09 +02:00
Sebastian G 5375dcc758 Merge remote-tracking branch 'origin/main' into feat/copy-routine
# Conflicts:
#	frontend/src/lib/pt-br-locale.test.js
2026-09-02 13:29:30 +02:00
Ameer KhanandClaude Opus 5 733dfa9d37 MCP: preview_session — what a routine will actually open with
get_routine reports what a routine stores. That is not what the athlete
sees. buildSets() consults the confirmed working weight and the previous
session's reps first, and applyPrescription() then overwrites the weight
with whatever the progression policy decided — so the routine's own
sets/reps/weight are the last fallback, not the first.

The gap is not academic. A routine holding "squat 3x8 @ 60 kg" opens at
75 kg when Greyskull deloaded from the last logged session, and an LLM
reading get_routine will confidently name a weight the app never shows.
Editing the routine to fix it changes nothing, which is worse.

preview_session mirrors beginWorkout() exactly — buildSets,
applyPrescription, applyIntensifierPlan — and returns, per exercise:
the planned target, the policy's decision with its stated reason, the
opening set rows including planned drop sets, and which of plan /
confirmed weight / history each number came from. `overridden` lists
just the exercises where the stored plan and the opening session
disagree, so the discrepancy cannot be scrolled past.

Read-only, no new dependency, one new tool registration. This is the
Phase 1.5 `progression_next` item from the README roadmap, named for
what it answers.

9 tests: precedence in both directions (plan wins with no history,
confirmed weight beats plan, policy beats both), reps carrying from
history, drop-set rows, explicit routine_id, rest day, unknown id.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DUgSPgBBqMYdy4vnKjK3bE
2026-09-02 08:18:56 +00:00
mzspicoli ad4bee99be Timer flash: blink the real theme instead of a black/white overlay, skip it while the app is backgrounded
The completion alert (Settings → "Flash screen when timer ends") laid an
opaque black/white rectangle over the whole screen, so the app's own UI
flickered into view between pulses. It now flips document.documentElement's
data-theme (light/dark) three times and settles back on whatever theme the
user actually had — same duration, no overlay, no rectangle. Fully dark ->
light, dark, light; fully light -> dark, light, dark; either way it lands
back where it started.

Separately: the rest/work timers reuse their tick on 'visibilitychange' to
stay accurate after the tab is throttled in the background. That reuse had
a side effect — reopening the app (or the tab regaining focus) after the
countdown had already finished while hidden replayed the completion beep,
vibration, flash and toast, even though nothing was actually watching when
it ended. Now those perceptible effects only fire if the countdown reaches
zero while the app is genuinely visible; finishing hidden only sends the
existing push notification, and reopening later stays silent.
2026-09-02 07:27:30 +02:00
Sebastian G ca9829d2b5 test: update pt-BR override count for Copy routine strings (338 -> 340)
The Copy routine feature added 2 pt-BR override strings but the snapshot
count in pt-br-locale.test.js was not updated, failing the pipeline.
2026-09-01 09:47:33 +02:00
Sebastian G e854d9dce7 i18n: add translations for Copy routine in all 14 locales 2026-08-31 22:21:09 +02:00
Sebastian G 19f09dcccc feat: add copy routine button to RoutineEdit view 2026-08-31 21:10:36 +02:00
Manuel 6fece17197 fix: align manual weight normalization 2026-08-31 19:12:18 +02:00
Manuel 40ae5a6f9d fix: use exercise weight step for workout controls 2026-08-31 18:54:22 +02:00
Space_Hermes 1224b05d34 fix(workout): make progression guidance actionable 2026-08-31 15:48:10 +02:00
TheophileDiot 5370e2184c BodyMap tests: import the geometry before the first render, not inside the wait 2026-08-31 10:46:54 +02:00
TheophileDiot 3214dfde9d mcp: get_routine reports an exercise's own rest 2026-08-31 10:46:54 +02:00
Manuel 1bec57bb3f fix: use available width for exercise selector 2026-08-31 09:57:54 +02:00
Manuel 63803ba2b0 fix: keep no-progression routine targets 2026-08-31 09:07:40 +02:00
Horus Gonzalez 47c1cc446f Exercise picker: the "+" adds now instead of opening the detail sheet
The "+" on a row in the exercise picker read as "add this now" but did
the same thing as tapping the row — opened the detail/config sheet —
so it added nothing until you'd scrolled past sets/reps and found the
real "Add to routine"/"Add exercise" button there.

The "+" now commits with the default config (or, mid-workout in
freestyle, the same last-session-seeded config the sheet would have
opened with) immediately, with a toast confirming what got added.
Tapping the rest of the row is unchanged — it still opens the detail
sheet, for setting sets/reps before adding.

Both call sites (routine editor, and the mid-workout "Add exercise")
get the same fix, since they share the one picker component.

No new strings — reuses 'Add "{0}"' and '"{0}" added to {1}', both
already translated in every locale.
2026-08-30 14:31:56 -06:00
94 changed files with 5317 additions and 630 deletions

No files matched your search

+5
View File
@@ -16,3 +16,8 @@ node_modules/
node_modules
.claude/
.agents/
# CI reports (test:* jobs write these next to the suites)
junit.xml
coverage/
frontend/bundle-size.json
+394 -86
View File
@@ -5,12 +5,20 @@
# gitea.com ones (.gitea/, kept only so the mirror stays buildable).
#
# What it does, in order:
# test — frontend, MCP and api (Coach) suites, on every branch, MR and tag
# build — the two container images → registry.gitlab.com/duartesantos8/opengym/{api,web},
# and a run of both api targets that proves what each one does and does not carry
# package — the signed Android APK → job artifact + generic package registry
# deploy — the browser-only demo → GitLab Pages
# release — a GitLab Release with the changelog section and links to APK + images
# test — frontend, MCP and api (Coach) suites on every branch, MR and tag, each with a
# JUnit report (failures show up in the MR widget) and coverage; the frontend
# job also measures the bundle and compares it with main's.
# On a v* tag: release:preflight checks tag, package versions and CHANGELOG
# before anything expensive starts.
# build — the two container images → registry.gitlab.com/duartesantos8/opengym/{api,web},
# and a run of both api targets that proves what each one does and does not carry
# package — the signed Android APK → job artifact + generic package registry
# verify — the images that were just pushed, started together through docker-compose.yml
# and asked to serve; plus a Trivy scan and an SBOM per image
# deploy — the browser-only demo → GitLab Pages
# release — a GitLab Release: changelog section, install commands, image digests,
# links to APK, checksum and SBOMs
# maintenance — Renovate (scheduled) and the fork-MR pipeline starter (scheduled + main)
#
# One deliberate difference from the GitHub copy: GitHub could distinguish a bare tag
# push from a *published* release, and only shipped images from the latter (issue #87 —
@@ -19,11 +27,18 @@
# rule is enforced by hand — **only push a tag when you actually mean to release it.**
# Everything version-tagged (latest images, signed APK, Release) hangs off `v*` tags,
# which are protected, so nobody else can trigger a release either.
#
# Contributor merge requests come from forks, and on gitlab.com a fork's pipeline runs in the
# fork — where almost nobody has runners enabled. So those MRs would sit at "no pipeline"
# forever. `mr:fork-pipelines` (bottom of this file) starts them here instead, for returning
# contributors; first-timers get the `ci-approval-needed` label and a maintainer presses
# "Run pipeline" on the MR after reading the diff.
stages:
- test
- build
- package
- verify
- deploy
- release
- maintenance
@@ -31,11 +46,35 @@ stages:
variables:
# node:22-alpine in web/Dockerfile and api/Dockerfile — CI must match production.
NODE_IMAGE: "node:22-alpine"
DOCKER_IMAGE: "docker:28-cli"
DOCKER_DIND_IMAGE: "docker:28-dind"
TRIVY_IMAGE: "aquasec/trivy:0.74.0"
# The demo build has no backend and no local media: the exercise images/GIFs (~140 MB)
# are never committed, so it points at the upstream dataset on jsDelivr, pinned to a
# commit so the CDN can cache it forever.
DATASET: "https://cdn.jsdelivr.net/gh/hasaneyldrm/exercises-dataset@7455efae41b330c265e7cd4b78dfa848e7ce5ebd"
GIT_DEPTH: "50"
# npm's own progress bars and funding notices are noise in a job log.
npm_config_fund: "false"
npm_config_audit: "false"
npm_config_progress: "false"
default:
# A newer push to the same branch cancels the pipeline that is still running for the old
# one — every job, not just the ones that had not started yet. Tag pipelines are never
# superseded, and `release` opts out below anyway.
interruptible: true
# Infrastructure hiccups (runner lost, docker daemon not answering) get one automatic
# second try. A failing script does not — that one is the job's actual verdict.
retry:
max: 1
when:
- runner_system_failure
- stuck_or_timeout_failure
- api_failure
- scheduler_failure
- data_integrity_failure
- unknown_failure
# Branch pipeline *or* MR pipeline, never both for the same commit.
workflow:
@@ -46,11 +85,65 @@ workflow:
- if: $CI_COMMIT_TAG
- if: $CI_COMMIT_BRANCH
# ---------------------------------------------------------------------------- test
# ------------------------------------------------------------------------- templates
# Every scheduled pipeline is a maintenance run (Renovate, the fork-MR starter) and says
# which one through its SCHEDULE_JOB variable. Nothing else may run on a schedule — the
# monthly Renovate run must not re-test the tree and republish the edge images for nothing.
.rules:
not_on_schedule:
- if: $CI_PIPELINE_SOURCE == "schedule"
when: never
.node:
image: $NODE_IMAGE
interruptible: true
timeout: 20 minutes
# docker-in-docker with TLS, the way gitlab.com's shared runners expect it.
.docker:
image: $DOCKER_IMAGE
services:
- $DOCKER_DIND_IMAGE
variables:
DOCKER_HOST: tcp://docker:2376
DOCKER_TLS_CERTDIR: "/certs"
DOCKER_TLS_VERIFY: "1"
DOCKER_CERT_PATH: "/certs/client"
timeout: 40 minutes
# The only way to tell a v* tag pipeline apart from everything else. Release-only jobs and
# the "build it like a release" paths key off this.
.release_tag: &release_tag
if: $CI_COMMIT_TAG =~ /^v\d+\.\d+\.\d+$/
# ---------------------------------------------------------------------------- test
# A release is `git tag`, nothing else — so the tag has to be checked before the pipeline
# spends forty minutes building it. Everything in the build stage `needs` this job when it
# exists, so a bad tag stops here with a one-line reason rather than a half-published release.
release:preflight:
extends: .node
stage: test
timeout: 5 minutes
script:
- apk add --no-cache git >/dev/null
- |
set -eu
SEMVER="${CI_COMMIT_TAG#v}"
fail() { echo "FATAL: $*" >&2; exit 1; }
for pkg in frontend/package.json api/package.json; do
v="$(node -p "require('./$pkg').version")"
[ "$v" = "$SEMVER" ] || fail "$CI_COMMIT_TAG but $pkg says $v — bump it (or tag the bump commit) and re-tag"
done
grep -Eq "^## $CI_COMMIT_TAG([^0-9.]|$)" CHANGELOG.md \
|| fail "CHANGELOG.md has no '## $CI_COMMIT_TAG' section — the release notes come from there"
# A release of a commit that is not on main would ship code main does not have.
git fetch --depth=1000 origin "$CI_DEFAULT_BRANCH"
git merge-base --is-ancestor "$CI_COMMIT_SHA" FETCH_HEAD \
|| fail "$CI_COMMIT_TAG points at $CI_COMMIT_SHORT_SHA, which is not on $CI_DEFAULT_BRANCH"
echo "OK: $CI_COMMIT_TAG = frontend $SEMVER = api $SEMVER, changelog section present, on $CI_DEFAULT_BRANCH"
rules:
- *release_tag
test:frontend:
extends: .node
@@ -63,10 +156,25 @@ test:frontend:
- frontend/.npm
script:
- cd frontend
- npm ci --cache .npm --prefer-offline
- npm test
# --ignore-scripts: nothing here needs a postinstall, and the one package that has a
# heavy one (@capacitor/assets → sharp, a 10 MB libvips download from GitHub) is only
# used to draw app icons. That download timing out is what turned a release red.
- npm ci --cache .npm --prefer-offline --ignore-scripts
# JUnit → the MR widget lists exactly which tests failed; cobertura → coverage on the
# diff; text-summary → the number the coverage badge shows.
- npx vitest run
--reporter=default --reporter=junit --outputFile.junit=junit.xml
--coverage --coverage.reporter=text-summary --coverage.reporter=cobertura
# A broken import or bad JSX fails the build long before any test covers it.
- npm run build
# What this commit costs on the wire, and — in an MR — what it adds compared with main.
# main's numbers are the artifact of its last green test:frontend; report-only.
- node scripts/bundle-size.mjs --out bundle-size.json
- |
if [ "$CI_COMMIT_BRANCH" != "$CI_DEFAULT_BRANCH" ]; then
wget -qO baseline.json "$CI_API_V4_URL/projects/$CI_PROJECT_ID/jobs/artifacts/$CI_DEFAULT_BRANCH/raw/frontend/bundle-size.json?job=test:frontend" || true
node scripts/bundle-size.mjs --compare baseline.json bundle-size.json
fi
- node scripts/check-locales.mjs
# check-locales compares the packs to each other, so a key missing from ALL of them is
# invisible to it. This walks src/ instead. Report-only for now: there is a known
@@ -75,11 +183,19 @@ test:frontend:
# The fatigue model must never read higher after a rest day than before it.
# Property probe over ~108k comparisons; too slow for the unit suite, cheap here.
- npm run test:fatigue-probe
coverage: '/Lines\s*:\s*(\d+\.?\d*)%/'
artifacts:
when: always
paths:
- frontend/bundle-size.json
reports:
junit: frontend/junit.xml
coverage_report:
coverage_format: cobertura
path: frontend/coverage/cobertura-coverage.xml
expire_in: 2 weeks
rules:
# A scheduled pipeline exists only to run `renovate` (bottom of this file) — it must not
# re-run the suite or republish the edge images once a month for nothing.
- if: $CI_PIPELINE_SOURCE == "schedule"
when: never
- !reference [.rules, not_on_schedule]
- when: on_success
test:mcp:
@@ -93,18 +209,25 @@ test:mcp:
- mcp/.npm
script:
- cd mcp
- npm ci --cache .npm --prefer-offline
- npm test
- npm ci --cache .npm --prefer-offline --ignore-scripts
- npx vitest run
--reporter=default --reporter=junit --outputFile.junit=junit.xml
--coverage --coverage.reporter=text-summary --coverage.reporter=cobertura
# The one check the vitest suite structurally cannot make. The MCP server is a bare node
# process, but vitest runs its tests through Vite — import.meta.glob, .jsx imports and
# ?raw all resolve happily there. That is how a Vite-only import reached a shared lib
# module with 33 green tests standing over a server that died on startup.
- npm run check:node-loadable
coverage: '/Lines\s*:\s*(\d+\.?\d*)%/'
artifacts:
when: always
reports:
junit: mcp/junit.xml
coverage_report:
coverage_format: cobertura
path: mcp/coverage/cobertura-coverage.xml
rules:
# A scheduled pipeline exists only to run `renovate` (bottom of this file) — it must not
# re-run the suite or republish the edge images once a month for nothing.
- if: $CI_PIPELINE_SOURCE == "schedule"
when: never
- !reference [.rules, not_on_schedule]
- when: on_success
test:api:
@@ -121,7 +244,11 @@ test:api:
- npm ci --cache .npm --prefer-offline --omit=optional
# The Coach tests run on node:test and drive the in-repo fixture provider plus a local mock
# of the Chat Completions shape, so the whole job works without an AI account or the network.
- npm test
# Same suite `npm test` runs, plus the JUnit file and node's own coverage table.
- node --experimental-test-coverage --test
--test-reporter=spec --test-reporter-destination=stdout
--test-reporter=junit --test-reporter-destination=junit.xml
test/*.test.js
- cd ..
# The api's copy of the exercise catalogue and the prompt module are generated and committed.
# A dataset or prompt change that forgets to regenerate them would otherwise only surface as
@@ -130,9 +257,13 @@ test:api:
# api/coach/core is imported by the server under bare node AND by the phone under Vite.
# vitest forgives what node does not (?raw, import.meta.glob); this runs outside vitest.
- node api/scripts/check-core-loadable.mjs
coverage: '/all files\s*\|\s*(\d+\.?\d*)/'
artifacts:
when: always
reports:
junit: api/junit.xml
rules:
- if: $CI_PIPELINE_SOURCE == "schedule"
when: never
- !reference [.rules, not_on_schedule]
- when: on_success
# --------------------------------------------------------------------------- images
@@ -150,17 +281,18 @@ test:api:
# `latest` and the version out of frontend/package.json — without cutting a release. It is
# there for the rebuild-without-a-code-change case: a base image picking up a CVE fix, where
# the published `latest` needs to move but the app did not change.
#
# Each matrix job hands the tag and digest of what it pushed to the later stages (images-*.env):
# verify:stack starts exactly these images, and the Release lists them.
build:images:
extends: .docker
stage: build
image: docker:28-cli
services:
- docker:28-dind
variables:
DOCKER_HOST: tcp://docker:2376
DOCKER_TLS_CERTDIR: "/certs"
DOCKER_TLS_VERIFY: "1"
DOCKER_CERT_PATH: "/certs/client"
needs: ["test:frontend", "test:mcp", "test:api"]
needs:
- test:frontend
- test:mcp
- test:api
- job: release:preflight
optional: true
parallel:
matrix:
- IMAGE: api
@@ -192,6 +324,7 @@ build:images:
echo "PUBLISH_LATEST: building $SEMVER off $CI_COMMIT_REF_NAME, no release involved"
fi
VERSION="v$SEMVER"
IMAGE_TAG="$SEMVER"
PLATFORMS="linux/amd64,linux/arm64"
TAGS="-t $REPO:$SEMVER -t $REPO:${SEMVER%.*} -t $REPO:latest"
# Only the arm64 leg needs emulation, and only for the api image (web's build
@@ -199,6 +332,7 @@ build:images:
docker run --privileged --rm tonistiigi/binfmt --install arm64
else
VERSION="main-$CI_COMMIT_SHORT_SHA"
IMAGE_TAG="$VERSION"
PLATFORMS="linux/amd64"
TAGS="-t $REPO:edge -t $REPO:$VERSION"
fi
@@ -216,12 +350,22 @@ build:images:
$TAGS \
--push \
"$CONTEXT"
# Older buildx builds ignore --format and print the whole Name/MediaType/Digest block, so
# pick the digest out of whatever comes back — a multi-line value breaks the dotenv upload.
DIGEST="$(docker buildx imagetools inspect "$REPO:$IMAGE_TAG" --format '{{.Manifest.Digest}}' | grep -oE 'sha256:[0-9a-f]{64}' | head -1)"
[ -n "$DIGEST" ] || { echo "could not read the digest of $REPO:$IMAGE_TAG" >&2; exit 1; }
echo "pushed $REPO:$IMAGE_TAG @ $DIGEST"
UPPER="$(echo "$IMAGE" | tr a-z A-Z)"
{
echo "IMAGE_TAG=$IMAGE_TAG"
echo "IMAGE_DIGEST_$UPPER=$DIGEST"
} > "images-$IMAGE.env"
artifacts:
reports:
dotenv: images-$IMAGE.env
rules:
# A scheduled pipeline exists only to run `renovate` (bottom of this file) — it must not
# re-run the suite or republish the edge images once a month for nothing.
- if: $CI_PIPELINE_SOURCE == "schedule"
when: never
- if: $CI_COMMIT_TAG =~ /^v\d+\.\d+\.\d+$/
- !reference [.rules, not_on_schedule]
- *release_tag
- if: ($CI_PIPELINE_SOURCE == "web" || $CI_PIPELINE_SOURCE == "api") && $PUBLISH_LATEST
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
@@ -235,15 +379,8 @@ build:images:
# the coach one additionally resolves the Agent SDK's per-platform runtime (musl on this base),
# which is the one thing that cannot be checked from the source tree. amd64 only, never pushed.
build:api-check:
extends: .docker
stage: build
image: docker:28-cli
services:
- docker:28-dind
variables:
DOCKER_HOST: tcp://docker:2376
DOCKER_TLS_CERTDIR: "/certs"
DOCKER_TLS_VERIFY: "1"
DOCKER_CERT_PATH: "/certs/client"
needs: ["test:api"]
script:
- docker build --target default -t opengym-api:default ./api
@@ -258,6 +395,10 @@ build:api-check:
'import("@anthropic-ai/claude-agent-sdk").then(()=>{console.error("AI runtime present in the published image -- the last Dockerfile stage is no longer the runtime-free one");process.exit(1)},()=>process.exit(0))'
! docker run --rm opengym-api:published codex --version 2>/dev/null
! docker run --rm opengym-api:published bwrap --version 2>/dev/null
# npm is stripped from the published image (see api/Dockerfile) — its bundled tree was
# the only source of scanner findings, and nothing at runtime needs it.
! docker run --rm opengym-api:published npm --version 2>/dev/null
! docker run --rm opengym-api:published test -d /usr/local/lib/node_modules/npm
docker run --rm opengym-api:published node --input-type=module -e '
const { adapterFor } = await import("./coach/adapters/index.js");
for (const id of ["anthropic", "openai", "gemini", "compatible"]) {
@@ -305,9 +446,8 @@ build:api-check:
# user disables every one of their jobs — including the fixture. Cheaper to assert here.
docker run --rm opengym-api:default id coach
rules:
- if: $CI_PIPELINE_SOURCE == "schedule"
when: never
- if: $CI_COMMIT_TAG =~ /^v\d+\.\d+\.\d+$/
- !reference [.rules, not_on_schedule]
- *release_tag
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
changes:
@@ -323,15 +463,8 @@ build:api-check:
# Pages build goes through that Dockerfile, so an MR could pass everything and still ship an
# image that does not build (v1.2.15 did). Built here, never pushed.
build:web-check:
extends: .docker
stage: build
image: docker:28-cli
services:
- docker:28-dind
variables:
DOCKER_HOST: tcp://docker:2376
DOCKER_TLS_CERTDIR: "/certs"
DOCKER_TLS_VERIFY: "1"
DOCKER_CERT_PATH: "/certs/client"
needs: ["test:frontend"]
script:
- docker build -f web/Dockerfile -t opengym-web:check .
@@ -344,9 +477,8 @@ build:web-check:
docker exec web-check sh -c 'grep -l "coach" /usr/share/nginx/html/assets/index-*.js >/dev/null'
docker rm -f web-check
rules:
- if: $CI_PIPELINE_SOURCE == "schedule"
when: never
- if: $CI_COMMIT_TAG =~ /^v\d+\.\d+\.\d+$/
- !reference [.rules, not_on_schedule]
- *release_tag
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
changes:
@@ -374,7 +506,11 @@ build:web-check:
build:apk:
stage: package
image: cimg/android:2026.08-node
needs: ["test:frontend"]
timeout: 40 minutes
needs:
- test:frontend
- job: release:preflight
optional: true
variables:
GRADLE_USER_HOME: "$CI_PROJECT_DIR/.gradle"
GRADLE_OPTS: "-Dorg.gradle.daemon=false"
@@ -424,11 +560,12 @@ build:apk:
set -eu
cd "$CI_PROJECT_DIR"
. ./apk.env
# Sideloading means nobody's app store checked this file for you, so publish the
# digest next to it rather than leaving people to trust the download. Written for
# every build (branch artifacts too), uploaded only from a release tag.
for apk in openGym-*.apk; do sha256sum "$apk" > "$apk.sha256"; cat "$apk.sha256"; done
if [ -n "${CI_COMMIT_TAG:-}" ] && [ -f "openGym-$APK_VERSION.apk" ]; then
# Sideloading means nobody's app store checked this file for you, so publish the
# digest next to it rather than leaving people to trust the download.
sha256sum "openGym-$APK_VERSION.apk" > "openGym-$APK_VERSION.apk.sha256"
cat "openGym-$APK_VERSION.apk.sha256"
echo "APK_SHA256=$(cut -d' ' -f1 "openGym-$APK_VERSION.apk.sha256")" >> apk.env
for f in "openGym-$APK_VERSION.apk" "openGym-$APK_VERSION.apk.sha256"; do
curl --fail --silent --show-error \
--header "JOB-TOKEN: $CI_JOB_TOKEN" \
@@ -446,11 +583,8 @@ build:apk:
dotenv: apk.env
expire_in: 30 days
rules:
# A scheduled pipeline exists only to run `renovate` (bottom of this file) — it must not
# re-run the suite or republish the edge images once a month for nothing.
- if: $CI_PIPELINE_SOURCE == "schedule"
when: never
- if: $CI_COMMIT_TAG =~ /^v\d+\.\d+\.\d+$/
- !reference [.rules, not_on_schedule]
- *release_tag
# An APK build is ~8 minutes of shared-runner time; on main and MRs it is one click
# away rather than automatic. Flip `when: manual` off to have every push build one.
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
@@ -460,6 +594,116 @@ build:apk:
when: manual
allow_failure: true
# --------------------------------------------------------------------------- verify
# The two images that were just pushed, started the way a self-hoster starts them — through
# the repository's own docker-compose.yml — and asked to serve through nginx. build:api-check
# and build:web-check each prove one container on its own; this is the only place the
# proxy between them, the compose file and the *pushed* artifacts are exercised together.
# On a tag the Release waits for it.
verify:stack:
extends: .docker
stage: verify
timeout: 15 minutes
needs:
- job: build:images
artifacts: true
script:
- docker compose version
- |
set -eu
# The compose file reads .env (RP_ID/ORIGIN for passkeys); none of it matters for GET.
cp .env.example .env
cat > ci-images.override.yml <<EOF
services:
api:
image: "$CI_REGISTRY_IMAGE/api:$IMAGE_TAG"
pull_policy: always
web:
image: "$CI_REGISTRY_IMAGE/web:$IMAGE_TAG"
pull_policy: always
EOF
docker compose -f docker-compose.yml -f ci-images.override.yml config --quiet
# --no-deps skips the `media` service (a 140 MB clone the smoke test does not need).
docker compose -f docker-compose.yml -f ci-images.override.yml up -d --no-deps --no-build api web
NET="$(docker network ls --filter name=opengym --format '{{.Name}}' | head -1)"
curl() { docker run --rm --network "$NET" curlimages/curl:8.12.1 "$@"; }
for i in $(seq 1 30); do
curl -fsS http://web/api/health >/dev/null 2>&1 && break
sleep 1
done
echo "--- /api/health through nginx"; curl -fsS http://web/api/health | grep -q '"ok":true'
echo "--- /api/config through nginx"; curl -fsS http://web/api/config | tee /dev/stderr | grep -q '"invite_only"'
echo "--- the app shell"; curl -fsS http://web/ | grep -q '<div id="root">'
echo "--- revision labels"
for i in api web; do
docker inspect --format '{{index .Config.Labels "org.opencontainers.image.revision"}}' "$CI_REGISTRY_IMAGE/$i:$IMAGE_TAG" \
| grep -q "$CI_COMMIT_SHA" || { echo "$i image does not carry this commit's revision label" >&2; exit 1; }
done
docker compose -f docker-compose.yml -f ci-images.override.yml logs --no-color api | tail -20
docker compose -f docker-compose.yml -f ci-images.override.yml down -v
echo "OK: api:$IMAGE_TAG + web:$IMAGE_TAG serve together"
rules:
- !reference [.rules, not_on_schedule]
- *release_tag
- if: ($CI_PIPELINE_SOURCE == "web" || $CI_PIPELINE_SOURCE == "api") && $PUBLISH_LATEST
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
# What the pushed images carry: a Trivy scan of OS packages and the npm trees (fixable
# HIGH/CRITICAL only — an unfixed CVE in alpine is not something a release can wait for), and
# a CycloneDX SBOM per image. On a tag the SBOMs go to the package registry and the Release
# links them. Findings turn the job yellow, never the pipeline red: the point is that the
# maintainer *sees* them next to the release, and Renovate opens the fix.
verify:scan:
stage: verify
image:
name: $TRIVY_IMAGE
entrypoint: [""]
timeout: 15 minutes
needs:
- job: build:images
artifacts: true
variables:
TRIVY_CACHE_DIR: "$CI_PROJECT_DIR/.trivycache"
TRIVY_NO_PROGRESS: "true"
TRIVY_USERNAME: "$CI_REGISTRY_USER"
TRIVY_PASSWORD: "$CI_REGISTRY_PASSWORD"
cache:
key: trivy-db
paths:
- .trivycache/
script:
- apk add --no-cache curl >/dev/null
- |
set -u
rc=0
for i in api web; do
REF="$CI_REGISTRY_IMAGE/$i:$IMAGE_TAG"
echo "=================== $REF"
trivy image --format cyclonedx --output "opengym-$i-$IMAGE_TAG.cdx.json" "$REF"
trivy image --scanners vuln --severity HIGH,CRITICAL --ignore-unfixed --exit-code 1 "$REF" || rc=1
done
if [ -n "${CI_COMMIT_TAG:-}" ]; then
for f in opengym-*.cdx.json; do
curl --fail --silent --show-error --header "JOB-TOKEN: $CI_JOB_TOKEN" --upload-file "$f" \
"$CI_API_V4_URL/projects/$CI_PROJECT_ID/packages/generic/opengym-sbom/$IMAGE_TAG/$f"
echo "uploaded $f to the generic package registry"
done
fi
[ "$rc" = 0 ] || echo "fixable HIGH/CRITICAL findings above — see the tables; the release is not blocked"
exit $rc
artifacts:
when: always
paths:
- "opengym-*.cdx.json"
expire_in: 90 days
allow_failure: true
rules:
- !reference [.rules, not_on_schedule]
- *release_tag
- if: ($CI_PIPELINE_SOURCE == "web" || $CI_PIPELINE_SOURCE == "api") && $PUBLISH_LATEST
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
# ---------------------------------------------------------------------------- pages
# The browser-only demo: https://opengym-bc111a.gitlab.io/
@@ -474,9 +718,15 @@ pages:
needs: ["test:frontend"]
variables:
VITE_DEMO: "1"
cache:
key:
files:
- frontend/package-lock.json
paths:
- frontend/.npm
script:
- cd frontend
- npm ci
- npm ci --cache .npm --prefer-offline --ignore-scripts
- VITE_IMG_BASE="$DATASET/images/" VITE_GIF_BASE="$DATASET/videos/" npm run build
- cd ..
- rm -rf public && mv frontend/dist public
@@ -484,14 +734,12 @@ pages:
paths:
- public
rules:
# A scheduled pipeline exists only to run `renovate` (bottom of this file) — it must not
# re-run the suite or republish the edge images once a month for nothing.
- if: $CI_PIPELINE_SOURCE == "schedule"
when: never
- !reference [.rules, not_on_schedule]
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
changes:
paths:
- "frontend/**/*"
- "api/coach/core/**/*"
- ".gitlab-ci.yml"
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
when: manual
@@ -501,16 +749,25 @@ pages:
release:
stage: release
image: registry.gitlab.com/gitlab-org/release-cli:latest
image: registry.gitlab.com/gitlab-org/release-cli:v0.24.0
interruptible: false
timeout: 10 minutes
needs:
- job: build:images
artifacts: true
- job: build:apk
artifacts: true
- job: verify:stack
artifacts: false
- job: verify:scan
artifacts: false
rules:
- if: $CI_COMMIT_TAG =~ /^v\d+\.\d+\.\d+$/
- *release_tag
script:
# The release notes are the matching section of CHANGELOG.md, verbatim — headings
# there are "## v1.2.9 — 2026-08-23", so take everything up to the next "## ".
# release:preflight already made sure the section exists. Below it: how to install
# this exact build, with the digests the images were pushed under.
- |
set -eu
awk -v tag="$CI_COMMIT_TAG" '
@@ -518,10 +775,26 @@ release:
inside && /^## / { exit }
inside { print }
' CHANGELOG.md > release-notes.md
if [ ! -s release-notes.md ]; then
echo "openGym $CI_COMMIT_TAG" > release-notes.md
fi
head -40 release-notes.md
SEMVER="${CI_COMMIT_TAG#v}"
MINOR="${SEMVER%.*}"
cat >> release-notes.md <<EOF
---
### Install or upgrade
\`\`\`sh
docker compose pull && docker compose up -d
\`\`\`
| Image | Tags | Digest |
|---|---|---|
| \`$CI_REGISTRY_IMAGE/api\` | \`$SEMVER\` \`$MINOR\` \`latest\` | \`$IMAGE_DIGEST_API\` |
| \`$CI_REGISTRY_IMAGE/web\` | \`$SEMVER\` \`$MINOR\` \`latest\` | \`$IMAGE_DIGEST_WEB\` |
Both images are linux/amd64 + linux/arm64. Android: \`openGym-$APK_VERSION.apk\`, SHA-256 \`$APK_SHA256\` — check it with \`sha256sum -c openGym-$APK_VERSION.apk.sha256\`. Built from $CI_COMMIT_SHA.
EOF
cat release-notes.md
release:
tag_name: $CI_COMMIT_TAG
name: "openGym $CI_COMMIT_TAG"
@@ -537,14 +810,21 @@ release:
- name: "Container images (api + web)"
url: "$CI_PROJECT_URL/container_registry"
link_type: image
- name: "SBOM api image (CycloneDX)"
url: "$CI_API_V4_URL/projects/$CI_PROJECT_ID/packages/generic/opengym-sbom/$IMAGE_TAG/opengym-api-$IMAGE_TAG.cdx.json"
link_type: other
- name: "SBOM web image (CycloneDX)"
url: "$CI_API_V4_URL/projects/$CI_PROJECT_ID/packages/generic/opengym-sbom/$IMAGE_TAG/opengym-web-$IMAGE_TAG.cdx.json"
link_type: other
# ---------------------------------------------------------------------- dependencies
# ---------------------------------------------------------------------- maintenance
# Dependency updates. GitLab has no Dependabot, so Renovate runs as a job — but only on a
# *scheduled* pipeline (Build → Pipeline schedules), so it never fires on a push and never
# competes with a real pipeline for runner minutes. Its policy lives in `renovate.json`
# next to this file, and it is the same policy the GitHub Dependabot config had: monthly,
# grouped per ecosystem, majors on their own, and the native mobile projects left alone.
# *scheduled* pipeline (Build → Pipeline schedules, SCHEDULE_JOB=renovate), so it never
# fires on a push and never competes with a real pipeline for runner minutes. Its policy
# lives in `renovate.json` next to this file, and it is the same policy the GitHub Dependabot
# config had: monthly, grouped per ecosystem, majors on their own, and the native mobile
# projects left alone.
#
# Needs one CI/CD variable: RENOVATE_TOKEN — a GitLab token with `api` scope, which is what
# lets it read the project and open merge requests.
@@ -553,6 +833,9 @@ renovate:
image:
name: renovate/renovate:41
entrypoint: [""]
interruptible: false
timeout: 30 minutes
needs: []
variables:
RENOVATE_PLATFORM: gitlab
RENOVATE_ENDPOINT: "$CI_API_V4_URL"
@@ -564,8 +847,33 @@ renovate:
script:
- renovate
rules:
- if: $CI_PIPELINE_SOURCE == "schedule" && $RENOVATE_TOKEN
- if: $CI_PIPELINE_SOURCE == "schedule" && $SCHEDULE_JOB == "renovate" && $RENOVATE_TOKEN
# Also runnable by hand from the pipeline page when you want to see what it would do.
- if: $CI_PIPELINE_SOURCE == "web" && $RENOVATE_TOKEN
when: manual
allow_failure: true
# Starts the pipelines contributor MRs cannot start for themselves (see the header and
# scripts/ci/fork-mr-pipelines.py for the rules: returning contributors only, never for an
# MR that edits the pipeline, never twice per commit). Runs on the SCHEDULE_JOB=fork-mrs
# schedule and after every push to main, where it costs a few seconds and needs nothing
# else in the pipeline.
#
# Needs one CI/CD variable, protected + masked: PIPELINE_API_TOKEN — a token with `api`
# scope and at least Developer on the project (a project access token does).
mr:fork-pipelines:
stage: maintenance
image: python:3.13-alpine
interruptible: false
timeout: 10 minutes
needs: []
allow_failure: true
script:
- python3 scripts/ci/fork-mr-pipelines.py
rules:
- if: $PIPELINE_API_TOKEN == null
when: never
- if: $CI_PIPELINE_SOURCE == "schedule" && $SCHEDULE_JOB == "fork-mrs"
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
- if: $CI_PIPELINE_SOURCE == "web"
when: manual
+71
View File
@@ -1,5 +1,76 @@
# Changelog
## v1.3.2 — 2026-09-05
Seventeen community merge requests from twelve contributors, each read, rebased onto a staging
instance and put through a tester round before landing, plus the fixes that round turned up. The
web bundle and the images change; the API only gains the Coach schema tightening. The Android APK
ships with a real version code again (16 — the last two releases had reused 15).
### Active workout
- 📋 **List view.** Settings → During a workout → Workout view: Cards (as before) or List, the
whole session stacked and scrollable, the current exercise outlined, "Set current" to move the
marker, supersets grouped with their own Unpair. (dpatrongomez, !96 — issues #28, #44, #50)
- ⚖️ **The working weight is captured, not asked.** Finishing an exercise no longer opens the
"confirm your working weight" sheet: the heaviest completed work set becomes the working weight,
for both members of a superset, and the current marker stays where you are until you press Next.
Working weights are stored when the workout is finished, so a typo corrected before that, or a
discarded session, never becomes your "Best". (mflova, !92 — issue #18)
- 🔢 **One tap, one step — in supersets too.** The +/− on weight, reps and RIR moved two steps
per tap on the second member of a superset. (ErrorUsernameAlreadyTaken, !97 — issue #41)
- ➕ **The weight stepper uses the exercise's own increment** (1.25 kg plates, 5 lb, whatever you
set), with progression's rounding, on set rows and drop-set rows; timed sets keep their seconds.
A value off the increment grid steps by exactly one increment rather than snapping. (mflova, !84)
- 🎯 **Routines with progression off keep their targets.** The same exercise as 2×15 in one routine
and 4×8 in another no longer opens the second with the first's reps — also when adding or swapping
an exercise mid-session and when saving the progression sheet. (mflova, !71)
- 📉 **No deload spiral.** A weight change starts a new stall streak, so one bad day at the lighter
weight after a deload cannot trigger the next one. (arhx91, !93)
- 🛡️ **The progression sheet cannot save into the wrong exercise** after the list shifted under it
or the workout was replaced. (Space-Hermes, !77)
- ⏱️ **Timer flash blinks the theme** instead of a black/white overlay and settles back on your
theme. A timer that ended while the app was in the background no longer replays the beep and
flash when you come back; a quiet toast still says the rest is over. (mzspicoli, !89)
### Planning and library
- ✨ **Four starter plans.** Home, Plan and Settings → Load starter plan open a chooser: Push/Pull/Legs,
Upper/Lower, Full Body, 5×5. Free weekdays load at once, occupied ones ask first; existing
routines are never touched. (lordlukem, !94)
- 💪 **Muscle explorer.** Library → "By muscle" (and "By muscle" inside Add exercise): tap a muscle
on the body map or its chip, filter by search, body part and equipment, open details or plan it.
Follows your equipment profile like the library does. (prasad_gade05, !87)
- 📄 **Copy routine** at the bottom of the routine editor. (ErrorUsernameAlreadyTaken, !85)
- ➕ **The "+" in the exercise picker adds immediately** with the default config (freestyle: last
session's) and says so in a toast; tapping the row still opens the config sheet. (surohsusej, !72)
- 📐 Stats → Exercise progress: long exercise names use the full width. (mflova, !80)
### MCP and Coach
- 🔍 **`preview_session`** — a ninth MCP tool: what a routine will actually open with after the
progression policy, the confirmed weight and history have had their say, with the source of every
number and a list of exercises where plan and screen disagree. Built on the app's own session
builder, so progression-off and deload routines preview exactly what the screen shows.
(koyosan, !90)
- ⏲️ `get_routine` reports each exercise's own rest as `rest_sec`. (TheophileDiot, !81 — issue #36)
- 🧠 The Coach's create schema requires a routine id and a week and caps the arrays, so a small
local model cannot answer with a plan the validator can only reject. (subdee, !99)
- 🧪 BodyMap tests import the geometry before the first render — no more one-off failures on a
slow runner. (TheophileDiot, !82 — issue #35)
### Self-hosting and infrastructure
- 🔁 **nginx re-resolves the api container per request.** Recreating only `api` (new IP) no longer
leaves `web` answering 502 until it is restarted too. (issue #16)
- 🔒 The published `api` image drops npm and both images take alpine's package fixes at build time;
the image scan reports nothing.
- 🏗️ CI: JUnit and coverage in every merge request, a bundle-size diff against main, a compose smoke
test of the pushed images, a Trivy scan with SBOMs attached to the release, a tag preflight
(versions and changelog checked before anything builds), and pipelines for contributors' fork MRs
started automatically for returning contributors.
- 🤖 Renovate runs again: its configuration had two unknown keys and had stopped opening MRs. (issue #37)
## v1.3.1 — 2026-09-04
- 📱 **"Use my self-hosted openGym" works on a paired phone.** The phone app never fetched the
+14
View File
@@ -43,6 +43,20 @@ cd frontend && npm test
rules are easy to get subtly wrong and nearly impossible to verify by clicking — the
progression engine grew two real bugs that only a test pinned down.
## What CI does with your merge request
Every MR runs the three test suites (frontend, MCP, api), with the results and the coverage
of your diff shown in the MR itself, plus a build of the web image and the api image when you
touched their inputs. The frontend job also prints how much your change adds to the gzipped
bundle compared with main. The APK and the published images are manual jobs there.
One gitlab.com quirk: an MR from a fork runs its pipeline in *your* fork, which usually has
no runners enabled — so it would show "no pipeline" forever. For that reason the project
starts the pipeline on its own runners for you: automatically if you have had an MR merged
here before, otherwise a maintainer presses "Run pipeline" after a first look at the diff
(the MR gets the `ci-approval-needed` label until then). Changes to `.gitlab-ci.yml` or
`scripts/ci/` always go through that manual step.
## Good first issues
- Additional starter plans (upper/lower, full-body, 5×5…)
+56
View File
@@ -123,3 +123,59 @@ English source produced with OpenAI Codex and Anthropic Claude Code
language-model assistance. They are not copied from a separate Portuguese
dataset. Their review status and translation policy are documented alongside
the source files.
## Gym check-in QR codes
The gym check-in feature (a saved membership code shown as a QR code on the phone, added by
typing, importing a photo, or scanning with the camera) uses three third-party packages. All are
permissively licensed and compatible with openGym's AGPL, and all load on demand: the QR renderer
and the browser decoder only when a card is shown or scanned, the ML Kit plugin only in the
Android/iOS app.
### QR/barcode rendering — `lean-qr`
openGym renders each saved code on the phone with [**lean-qr**](https://github.com/davidje13/lean-qr)
by David Evans, used under the **MIT License** and reproduced below. Only the code's stored value
is kept; the picture is generated fresh from that value each time it is shown, never stored.
It runs the same way in the app and in the browser/PWA.
```
MIT License
Copyright (c) 2021-2025 David Evans
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```
### Camera scan & photo decode in the browser — `jsQR`
In a browser (including the installed PWA), reading a code from the camera or from an imported
photo uses [**jsQR**](https://github.com/cozmo/jsQR) by Cosmo Wolfe, under the **Apache License
2.0** (text at <https://www.apache.org/licenses/LICENSE-2.0> and in the package's own `LICENSE`).
Where the browser has a native `BarcodeDetector`, that is tried first and jsQR is the fallback.
Video frames are decoded in memory and never uploaded or stored.
### Camera scan & photo decode in the app — `@capacitor-mlkit/barcode-scanning`
In the Android/iOS app, reading a code — from the camera or from an imported photo — uses the
[**@capacitor-mlkit/barcode-scanning**](https://github.com/capawesome-team/capacitor-mlkit) plugin
by the Capawesome Team (Robin Genz), a Capacitor wrapper around Google's ML Kit, used under the
**Apache License 2.0**. openGym pins the `7.x` line to stay on Capacitor 7. The full license text is
available at <https://www.apache.org/licenses/LICENSE-2.0> and in the package's own `LICENSE` file.
The decoded string is what openGym keeps; the photo itself is never stored.
+2
View File
@@ -20,6 +20,8 @@ No account on someone else's server, no subscription, no ads. Just `docker compo
![No tracking](https://img.shields.io/badge/telemetry-none-f472b6?style=flat-square)
<br>
[![Pipeline](https://gitlab.com/DuarteSantos8/opengym/badges/main/pipeline.svg?style=flat-square)](https://gitlab.com/DuarteSantos8/opengym/-/pipelines)
[![Coverage](https://gitlab.com/DuarteSantos8/opengym/badges/main/coverage.svg?job=test:frontend&style=flat-square)](https://gitlab.com/DuarteSantos8/opengym/-/pipelines?ref=main)
[![Release](https://gitlab.com/DuarteSantos8/opengym/-/badges/release.svg?style=flat-square)](https://gitlab.com/DuarteSantos8/opengym/-/releases)
![Last commit](https://img.shields.io/gitlab/last-commit/DuarteSantos8%2Fopengym?style=flat-square)
[![Stars](https://img.shields.io/gitlab/stars/DuarteSantos8%2Fopengym?style=flat-square)](https://gitlab.com/DuarteSantos8/opengym/-/starrers)
[![Issues](https://img.shields.io/gitlab/issues/open/DuarteSantos8%2Fopengym?style=flat-square)](https://gitlab.com/DuarteSantos8/opengym/-/issues)
+10
View File
@@ -31,6 +31,11 @@ LABEL maintainer="Duarte Santos https://gitlab.com/DuarteSantos8" \
WORKDIR /app
# The base image is rebuilt on node's schedule, not alpine's: between two node releases the
# alpine packages it ships (openssl above all) fall behind their fixes. Taking the upgrades at
# build time keeps the published image at alpine's current state without waiting for node.
RUN apk upgrade --no-cache
# The unprivileged user Coach jobs drop to. Its uid cannot read /data, which is the control that
# keeps a provider runtime away from users, passkeys and the session secret.
#
@@ -82,3 +87,8 @@ VOLUME ["/coach-auth"]
# ---------------------------------------------------------------------------------------------
# Last, so that a plain `docker build ./api` keeps producing the runtime-free image.
FROM base AS default
# npm itself is only a build-time tool here: the server is started with `node server.js` and
# nothing in it spawns npm. Its bundled dependency tree (tar, brace-expansion, ...) is where
# every vulnerability the image scan ever reported lived — none of them was in a package the
# app uses. Gone from the published image; the coach target keeps npm for the Codex CLI.
RUN rm -rf /usr/local/lib/node_modules/npm /usr/local/bin/npm /usr/local/bin/npx
+15 -3
View File
@@ -59,6 +59,11 @@ const EX_SCHEMA = {
required: ['id', 'sets']
};
// `week` and `routines[].id` are required, not optional: the week is the only thing that says
// which day trains which routine, and it points at a routine by id. A schema that leaves either
// out lets a small local model answer with routines that have no id and a week naming "r1" —
// grammar-valid, and something validate.js can only ever reject ("the week schedules 0 days but
// 3 were asked for"), through the repair round and out as a failed job.
export const CREATE_SCHEMA = {
type: 'object',
properties: {
@@ -67,15 +72,22 @@ export const CREATE_SCHEMA = {
summary: STR,
basedOn: STR,
week: { type: 'object' },
// The caps are the validator's own (MAX_ROUTINES, MAX_EX_PER_ROUTINE), stated here as well
// because "1-7 routines, each 3-12 exercises" in create.md is only a request. A small model
// that starts repeating itself does not stop at a request: qwen2.5:3b walks the library id by
// id, three sets of eight apiece, until it hits the output limit — twelve minutes for an
// answer that arrives cut in half and cannot be parsed. maxItems ends that run at seven
// routines instead.
routines: {
type: 'array',
maxItems: 7,
items: {
type: 'object',
properties: {
id: STR, name: STR, emoji: STR, prog: STR, why: STR,
ex: { type: 'array', items: EX_SCHEMA }
ex: { type: 'array', maxItems: 20, items: EX_SCHEMA }
},
required: ['name', 'ex']
required: ['id', 'name', 'ex']
}
},
customEx: {
@@ -83,7 +95,7 @@ export const CREATE_SCHEMA = {
items: { type: 'object', properties: { id: STR, n: STR, bp: STR, desc: STR }, required: ['id', 'n'] }
}
},
required: ['coach_contract', 'routines']
required: ['coach_contract', 'week', 'routines']
};
export const DEBRIEF_SCHEMA = {
+1 -1
View File
@@ -6,7 +6,7 @@ openapi: 3.1.0
info:
title: openGym API
version: 1.3.1
version: 1.3.2
summary: Passkey (WebAuthn) auth + per-user state storage for openGym
description: |
The backend of [openGym](https://opengym.duarte-santos.ch) — a free, open-source
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "gym-api",
"version": "1.3.1",
"version": "1.3.2",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "gym-api",
"version": "1.3.1",
"version": "1.3.2",
"license": "AGPL-3.0-or-later",
"dependencies": {
"@simplewebauthn/server": "^13.1.1",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "gym-api",
"version": "1.3.1",
"version": "1.3.2",
"private": true,
"type": "module",
"main": "server.js",
+27
View File
@@ -4,6 +4,7 @@ import { buildPrompt, buildPromptParts, taskOf } from '../coach/core/prompt.js';
import { SCHEMAS } from '../coach/core/schemas.js';
import { build, FULL_DETAIL_SESSIONS } from '../coach/core/payload.js';
import { chatCompletionsSpec } from '../coach/core/adapters/openai.js';
import { validatePlan } from '../coach/core/validate.js';
const S = (workouts = []) => ({
lang: 'en', unit: 'kg', routines: [{ id: 'r1', name: 'A', ex: [{ id: '0001', sets: 3, reps: 8 }] }],
@@ -48,6 +49,32 @@ test('every task has a flat schema — no $ref, no anyOf/oneOf (llama.cpp gramma
assert.equal(taskOf('create', { refine: 'x' }), 'refine');
});
test('the create schema requires what the week resolves through: a routine id, and a week', () => {
// A schema handed to a grammar-constrained decoder is the only thing standing between a small
// local model and an answer the validator can only reject. These two fields are where that
// showed: llama3.2:3b and qwen2.5:3b both answer with routines that carry no `id` and a week
// naming what they put in `name`, which costs a job and a repair round to find out.
assert.ok(SCHEMAS.create.properties.routines.items.required.includes('id'));
assert.ok(SCHEMAS.create.required.includes('week'));
assert.equal(SCHEMAS.refine, SCHEMAS.create); // refine reuses it, same guarantee
const noId = {
coach_contract: 1,
routines: [{ name: 'r1', ex: [{ id: '0001', sets: 3, reps: 8 }] }],
week: { 1: 'r1' }
};
const checked = validatePlan(noId, { daysPerWeek: 1 });
assert.ok(!checked.ok);
assert.ok(checked.errors.some(e => e.includes('week[1] points at "r1"')));
});
test('the create schema caps the two arrays the validator caps, so a repeating model stops', () => {
// validate.js slices at MAX_ROUTINES / MAX_EX_PER_ROUTINE; a model that never stops emitting
// otherwise runs to the output limit first and the answer arrives truncated and unparseable.
assert.equal(SCHEMAS.create.properties.routines.maxItems, 7);
assert.equal(SCHEMAS.create.properties.routines.items.properties.ex.maxItems, 20);
});
test('older sessions in a review window are compacted, the recent ones keep full sets', () => {
const many = Array.from({ length: FULL_DETAIL_SESSIONS + 4 }, (_, i) => workout('2026-08-' + String(i + 1).padStart(2, '0')));
const p = build(S(many), { handle: 'h1', kind: 'review' });
+8 -2
View File
@@ -7,8 +7,8 @@ android {
applicationId "ch.duartesantos.opengym"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 15
versionName "1.2.14"
versionCode 16
versionName "1.3.2"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
aaptOptions {
// Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps.
@@ -21,6 +21,12 @@ android {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
debug {
// Test build installs side-by-side with the real app: its own applicationId, so both
// can live on one device. The name/icon label is overridden by the debug resource
// overlay in src/debug/res. The release build (the "real" app) is untouched.
applicationIdSuffix ".test"
}
}
}
@@ -9,6 +9,8 @@ android {
apply from: "../capacitor-cordova-android-plugins/cordova.variables.gradle"
dependencies {
implementation project(':aparajita-capacitor-secure-storage')
implementation project(':capacitor-mlkit-barcode-scanning')
implementation project(':capacitor-app')
implementation project(':capacitor-filesystem')
implementation project(':capacitor-local-notifications')
@@ -0,0 +1,7 @@
<?xml version='1.0' encoding='utf-8'?>
<resources>
<!-- Debug-only overrides so the test build shows a distinct name next to the real app.
Merged over src/main/res for the debug variant only; the release build keeps openGym. -->
<string name="app_name">OpenGymTest</string>
<string name="title_activity_main">OpenGymTest</string>
</resources>
@@ -27,6 +27,10 @@
android:grantUriPermissions="true">
<meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths" />
</provider>
<!-- Gym check-in scanner (@capacitor-mlkit/barcode-scanning): pre-fetch the ML Kit
barcode model at install time so the first scan doesn't wait on a download. -->
<meta-data android:name="com.google.mlkit.vision.DEPENDENCIES" android:value="barcode_ui" />
</application>
<!-- Permissions -->
@@ -36,4 +40,6 @@
on Android 12+. Where it isn't granted, scheduling silently falls back to inexact
alarms — the reminder still arrives, just not to the minute. -->
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />
<!-- Gym check-in: scanning a membership QR/barcode with the camera. -->
<uses-permission android:name="android.permission.CAMERA" />
</manifest>
@@ -2,6 +2,12 @@
include ':capacitor-android'
project(':capacitor-android').projectDir = new File('../node_modules/@capacitor/android/capacitor')
include ':aparajita-capacitor-secure-storage'
project(':aparajita-capacitor-secure-storage').projectDir = new File('../node_modules/@aparajita/capacitor-secure-storage/android')
include ':capacitor-mlkit-barcode-scanning'
project(':capacitor-mlkit-barcode-scanning').projectDir = new File('../node_modules/@capacitor-mlkit/barcode-scanning/android')
include ':capacitor-app'
project(':capacitor-app').projectDir = new File('../node_modules/@capacitor/app/android')
+2
View File
@@ -45,5 +45,7 @@
</array>
<key>UIViewControllerBasedStatusBarAppearance</key>
<true/>
<key>NSCameraUsageDescription</key>
<string>Used to scan your gym membership QR code so you can check in from the app.</string>
</dict>
</plist>
+2
View File
@@ -11,6 +11,8 @@ install! 'cocoapods', :disable_input_output_paths => true
def capacitor_pods
pod 'Capacitor', :path => '../../node_modules/@capacitor/ios'
pod 'CapacitorCordova', :path => '../../node_modules/@capacitor/ios'
pod 'AparajitaCapacitorSecureStorage', :path => '../../node_modules/@aparajita/capacitor-secure-storage'
pod 'CapacitorMlkitBarcodeScanning', :path => '../../node_modules/@capacitor-mlkit/barcode-scanning'
pod 'CapacitorApp', :path => '../../node_modules/@capacitor/app'
pod 'CapacitorFilesystem', :path => '../../node_modules/@capacitor/filesystem'
pod 'CapacitorLocalNotifications', :path => '../../node_modules/@capacitor/local-notifications'
+313 -52
View File
@@ -1,20 +1,23 @@
{
"name": "opengym-frontend",
"version": "1.3.1",
"version": "1.3.2",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "opengym-frontend",
"version": "1.3.1",
"version": "1.3.2",
"license": "AGPL-3.0-or-later",
"dependencies": {
"@aparajita/capacitor-secure-storage": "^7.1.6",
"@capacitor-mlkit/barcode-scanning": "^7.5.0",
"@capacitor/app": "^7.1.2",
"@capacitor/core": "^7.6.8",
"@capacitor/filesystem": "^7.1.8",
"@capacitor/local-notifications": "^7.0.7",
"@capacitor/share": "^7.0.4",
"jsqr": "^1.4.0",
"lean-qr": "^2.7.3",
"react": "^19.2.7",
"react-dom": "^19.2.7",
"react-router-dom": "^7.18.2",
@@ -26,6 +29,7 @@
"@capacitor/cli": "^7.6.8",
"@capacitor/ios": "^7.6.8",
"@vitejs/plugin-react": "^6.0.3",
"@vitest/coverage-v8": "^4.1.11",
"happy-dom": "^20.11.2",
"linkedom": "^0.18.13",
"vite": "^8.1.5",
@@ -60,6 +64,16 @@
"node": ">=6.9.0"
}
},
"node_modules/@babel/helper-string-parser": {
"version": "7.29.7",
"resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.7.tgz",
"integrity": "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@babel/helper-validator-identifier": {
"version": "7.29.7",
"resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz",
@@ -69,6 +83,64 @@
"node": ">=6.9.0"
}
},
"node_modules/@babel/parser": {
"version": "7.29.8",
"resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.8.tgz",
"integrity": "sha512-E8lTAYNB1KW+FH+VGJuZM1ioAx2E6oVlvQFRrf5P8ZZmsiJXYAD9vTFV7yyEURNzgh1dFqMZuO6tUwcARbqFCA==",
"dev": true,
"license": "MIT",
"dependencies": {
"@babel/types": "^7.29.8"
},
"bin": {
"parser": "bin/babel-parser.js"
},
"engines": {
"node": ">=6.0.0"
}
},
"node_modules/@babel/types": {
"version": "7.29.8",
"resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.8.tgz",
"integrity": "sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@babel/helper-string-parser": "^7.29.7",
"@babel/helper-validator-identifier": "^7.29.7"
},
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@bcoe/v8-coverage": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/@bcoe/v8-coverage/-/v8-coverage-1.0.2.tgz",
"integrity": "sha512-6zABk/ECA/QYSCQ1NGiVwwbQerUCZ+TQbp64Q3AgmfNvurHH0j8TtXa1qbShXA6qqkpAj4V5W8pP6mLe1mcMqA==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=18"
}
},
"node_modules/@capacitor-mlkit/barcode-scanning": {
"version": "7.5.0",
"resolved": "https://registry.npmjs.org/@capacitor-mlkit/barcode-scanning/-/barcode-scanning-7.5.0.tgz",
"integrity": "sha512-DBWRykYYLW0YMj/UzlQ0sVGn83mwGAJsbZVxFsd44pppEEy88OO04lxy9Esv5QpnNBIKPjSIqLWmSLuhoFGPaQ==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/capawesome-team/"
},
{
"type": "opencollective",
"url": "https://opencollective.com/capawesome"
}
],
"peerDependencies": {
"@capacitor/core": ">=7.0.0"
}
},
"node_modules/@capacitor/android": {
"version": "7.6.8",
"resolved": "https://registry.npmjs.org/@capacitor/android/-/android-7.6.8.tgz",
@@ -1066,7 +1138,8 @@
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz",
"integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==",
"dev": true
"dev": true,
"license": "MIT"
},
"node_modules/@trapezedev/gradle-parse": {
"version": "7.1.3",
@@ -1235,6 +1308,7 @@
"resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz",
"integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/deep-eql": "*",
"assertion-error": "^2.0.1"
@@ -1244,13 +1318,15 @@
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz",
"integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==",
"dev": true
"dev": true,
"license": "MIT"
},
"node_modules/@types/estree": {
"version": "1.0.9",
"resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz",
"integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==",
"dev": true
"dev": true,
"license": "MIT"
},
"node_modules/@types/fs-extra": {
"version": "8.1.5",
@@ -1670,16 +1746,48 @@
}
}
},
"node_modules/@vitest/expect": {
"version": "4.1.10",
"resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.10.tgz",
"integrity": "sha512-YsCn+qAk1GWjQOWFEsEcL2gNQ0zmVmQu3T03qP6UyjhtmdtwtbuI+DASn/7iQB3HGTXkdBwGddzxPlmiql5vlA==",
"node_modules/@vitest/coverage-v8": {
"version": "4.1.11",
"resolved": "https://registry.npmjs.org/@vitest/coverage-v8/-/coverage-v8-4.1.11.tgz",
"integrity": "sha512-8MVGEFnJIcdGjcbfKmeq8z0pZHH0JlVtoVZH9Q/qwUp6wyFnEJUBMrw9DCaj+ra3vShGmhavjalMIhPNxZAUcw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@bcoe/v8-coverage": "^1.0.2",
"@vitest/utils": "4.1.11",
"ast-v8-to-istanbul": "^1.0.0",
"istanbul-lib-coverage": "^3.2.2",
"istanbul-lib-report": "^3.0.1",
"istanbul-reports": "^3.2.0",
"magicast": "^0.5.2",
"obug": "^2.1.1",
"std-env": "^4.0.0-rc.1",
"tinyrainbow": "^3.1.0"
},
"funding": {
"url": "https://opencollective.com/vitest"
},
"peerDependencies": {
"@vitest/browser": "4.1.11",
"vitest": "4.1.11"
},
"peerDependenciesMeta": {
"@vitest/browser": {
"optional": true
}
}
},
"node_modules/@vitest/expect": {
"version": "4.1.11",
"resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.11.tgz",
"integrity": "sha512-VX2x5vNJXET47KAFzwERI+KRMtTTCSWTfSMKsW7JsUsXV4psq++e3DvZpuTDOpHcxytiDs6p2nhVb2tVDiiUYw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@standard-schema/spec": "^1.1.0",
"@types/chai": "^5.2.2",
"@vitest/spy": "4.1.10",
"@vitest/utils": "4.1.10",
"@vitest/spy": "4.1.11",
"@vitest/utils": "4.1.11",
"chai": "^6.2.2",
"tinyrainbow": "^3.1.0"
},
@@ -1688,12 +1796,13 @@
}
},
"node_modules/@vitest/mocker": {
"version": "4.1.10",
"resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-4.1.10.tgz",
"integrity": "sha512-v0xaezt+DKEmKfaxg133ldzADrwLGd7Ze1MfQQTYfvs8OqZIwbxyxaYURivwV7sWy5fqn3rH5uOrSp07bp44Ow==",
"version": "4.1.11",
"resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-4.1.11.tgz",
"integrity": "sha512-2XJVD55d1o5AZous5CCGKS74g/riOj9odEt2bQpCVZeblHyHdnMeFl4jl0XjU21stf4mbjUkew2eXQZt65g5CQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@vitest/spy": "4.1.10",
"@vitest/spy": "4.1.11",
"estree-walker": "^3.0.3",
"magic-string": "^0.30.21"
},
@@ -1714,10 +1823,11 @@
}
},
"node_modules/@vitest/pretty-format": {
"version": "4.1.10",
"resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.1.10.tgz",
"integrity": "sha512-W1HsjSH4MXQ9YfmmhLAoIYf1HRfekQCGngeIgcei6MP5QQGWUe0gkopdZQaVCFO+JDJMrAJGwa5pRpNpvy4P8Q==",
"version": "4.1.11",
"resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.1.11.tgz",
"integrity": "sha512-yiZzPbGTS9Sr/JpFl8zHrcIkAofNbFV6k21vIgQN/cY/oxZeXhJv5sc/MBJ5jFKWmWs+oJHw0UXLZjmf931+Vw==",
"dev": true,
"license": "MIT",
"dependencies": {
"tinyrainbow": "^3.1.0"
},
@@ -1726,12 +1836,13 @@
}
},
"node_modules/@vitest/runner": {
"version": "4.1.10",
"resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-4.1.10.tgz",
"integrity": "sha512-IKI6kpIH+LmpROplyLwBBaCfMgOZOMsygVa6BARD6ahA04VRuJSa6OaVG7kRvSEMD870Vd91rSSw0eegtWyLGg==",
"version": "4.1.11",
"resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-4.1.11.tgz",
"integrity": "sha512-LztvUgdwMNJMIkj3hQnnxiC2Xy1zNxq928W/xhjCLaNCzqTZOudjwbQf6v9IntZGPw132i2Lq2rgTRZHD3JHNw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@vitest/utils": "4.1.10",
"@vitest/utils": "4.1.11",
"pathe": "^2.0.3"
},
"funding": {
@@ -1739,13 +1850,14 @@
}
},
"node_modules/@vitest/snapshot": {
"version": "4.1.10",
"resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-4.1.10.tgz",
"integrity": "sha512-xRkfOT1qpTAi/Ti4Y1LtfRc3kEuqxGw59eN2jN9pRWMtS/XDevekhcFSqvQqjUNGksfjMJu3Y+oJ+4Ypn2OaJw==",
"version": "4.1.11",
"resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-4.1.11.tgz",
"integrity": "sha512-pN7ikn1ON7h8ee4gIAp4AzyK+zBtJPzVbqOgu5LCEh4VaJVbPQcgYQYJIMGQPXVeJJq1fnfazis7a5pFNPahog==",
"dev": true,
"license": "MIT",
"dependencies": {
"@vitest/pretty-format": "4.1.10",
"@vitest/utils": "4.1.10",
"@vitest/pretty-format": "4.1.11",
"@vitest/utils": "4.1.11",
"magic-string": "^0.30.21",
"pathe": "^2.0.3"
},
@@ -1754,21 +1866,23 @@
}
},
"node_modules/@vitest/spy": {
"version": "4.1.10",
"resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.1.10.tgz",
"integrity": "sha512-PLf/Ugvoq5wO/b4rwYCR1h2PSIdXz7wnkQFMiUpLdtM7l6pqVFcQIBEHyT1+l+cj7mNwAfZHzqXqDyjvOuwbDw==",
"version": "4.1.11",
"resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.1.11.tgz",
"integrity": "sha512-apNa/prQy2qCeywhnixOHPRCgGNhvg7T4Dapfl1GahLp/R+uhBm5cPyFoNVyqsNd2h1nJxL6BqqdIjiABL60YA==",
"dev": true,
"license": "MIT",
"funding": {
"url": "https://opencollective.com/vitest"
}
},
"node_modules/@vitest/utils": {
"version": "4.1.10",
"resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-4.1.10.tgz",
"integrity": "sha512-fy9am/HWxbaGt/Sawrp90vt6Y6jQwf1RX77cz3uwoJwJVMli/e1IEwRPnMNJ7vKfPTwo0diXifkpPvwH9v7nGA==",
"version": "4.1.11",
"resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-4.1.11.tgz",
"integrity": "sha512-zTCVGpyFsGWBhllOyKlTw/vnr6D9qxsfSDyfbyZmTyjHw5N/VuvzHpHoQjm2ZJzn4RJgx5w4r7V0er69CmLgPQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@vitest/pretty-format": "4.1.10",
"@vitest/pretty-format": "4.1.11",
"convert-source-map": "^2.0.0",
"tinyrainbow": "^3.1.0"
},
@@ -1874,10 +1988,41 @@
"resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz",
"integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=12"
}
},
"node_modules/ast-v8-to-istanbul": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/ast-v8-to-istanbul/-/ast-v8-to-istanbul-1.0.5.tgz",
"integrity": "sha512-UPAgKJFSEGMWSDr3LX4tqnAb4f7KGT8O40Tyx8wbYmmZ/yn58lNCm8h3svs3eXgiGd5AXxz8NDOvXWvicq+rJA==",
"dev": true,
"license": "MIT",
"dependencies": {
"@jridgewell/trace-mapping": "^0.3.31",
"estree-walker": "^3.0.3",
"js-tokens": "^10.0.0"
}
},
"node_modules/ast-v8-to-istanbul/node_modules/@jridgewell/trace-mapping": {
"version": "0.3.31",
"resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz",
"integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@jridgewell/resolve-uri": "^3.1.0",
"@jridgewell/sourcemap-codec": "^1.4.14"
}
},
"node_modules/ast-v8-to-istanbul/node_modules/js-tokens": {
"version": "10.0.0",
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-10.0.0.tgz",
"integrity": "sha512-lM/UBzQmfJRo9ABXbPWemivdCW8V2G8FHaHdypQaIy523snUjog0W71ayWXTjiR+ixeMyVHN2XcpnTd/liPg/Q==",
"dev": true,
"license": "MIT"
},
"node_modules/astral-regex": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/astral-regex/-/astral-regex-2.0.0.tgz",
@@ -2155,6 +2300,7 @@
"resolved": "https://registry.npmjs.org/chai/-/chai-6.2.2.tgz",
"integrity": "sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=18"
}
@@ -2552,7 +2698,8 @@
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz",
"integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==",
"dev": true
"dev": true,
"license": "MIT"
},
"node_modules/cookie": {
"version": "1.1.1",
@@ -2933,6 +3080,7 @@
"resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz",
"integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/estree": "^1.0.0"
}
@@ -3676,6 +3824,75 @@
"integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",
"dev": true
},
"node_modules/istanbul-lib-coverage": {
"version": "3.2.2",
"resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-3.2.2.tgz",
"integrity": "sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg==",
"dev": true,
"license": "BSD-3-Clause",
"engines": {
"node": ">=8"
}
},
"node_modules/istanbul-lib-report": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-3.0.1.tgz",
"integrity": "sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw==",
"dev": true,
"license": "BSD-3-Clause",
"dependencies": {
"istanbul-lib-coverage": "^3.0.0",
"make-dir": "^4.0.0",
"supports-color": "^7.1.0"
},
"engines": {
"node": ">=10"
}
},
"node_modules/istanbul-lib-report/node_modules/has-flag": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz",
"integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
}
},
"node_modules/istanbul-lib-report/node_modules/supports-color": {
"version": "7.2.0",
"resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz",
"integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==",
"dev": true,
"license": "MIT",
"dependencies": {
"has-flag": "^4.0.0"
},
"engines": {
"node": ">=8"
}
},
"node_modules/istanbul-reports": {
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-3.2.0.tgz",
"integrity": "sha512-HGYWWS/ehqTV3xN10i23tkPkpH46MLCIMFNCaaKNavAXTF1RkqxawEPtnjnGZ6XKSInBKkiOA5BKS+aZiY3AvA==",
"dev": true,
"license": "BSD-3-Clause",
"dependencies": {
"html-escaper": "^2.0.0",
"istanbul-lib-report": "^3.0.0"
},
"engines": {
"node": ">=8"
}
},
"node_modules/istanbul-reports/node_modules/html-escaper": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz",
"integrity": "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==",
"dev": true,
"license": "MIT"
},
"node_modules/js-tokens": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
@@ -3737,6 +3954,11 @@
"node": "*"
}
},
"node_modules/jsqr": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/jsqr/-/jsqr-1.4.0.tgz",
"integrity": "sha512-dxLob7q65Xg2DvstYkRpkYtmKm2sPJ9oFhrhmudT1dZvNFFTlroai3AWSpLey/w5vMcLBXRgOJsbXpdN9HzU/A=="
},
"node_modules/kind-of": {
"version": "6.0.3",
"resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.3.tgz",
@@ -3755,6 +3977,14 @@
"node": ">=6"
}
},
"node_modules/lean-qr": {
"version": "2.7.3",
"resolved": "https://registry.npmjs.org/lean-qr/-/lean-qr-2.7.3.tgz",
"integrity": "sha512-/eQryMvYyTL3dSMK/IlvSjUYG0ShQv62owXiFbGkSH+lFZzf4VOsPP+UInAgeUH/rPIyz59uQE9XHRbn9o8SyQ==",
"bin": {
"lean-qr": "cli.mjs"
}
},
"node_modules/lightningcss": {
"version": "1.32.0",
"resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.32.0.tgz",
@@ -4244,10 +4474,39 @@
"resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz",
"integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@jridgewell/sourcemap-codec": "^1.5.5"
}
},
"node_modules/magicast": {
"version": "0.5.4",
"resolved": "https://registry.npmjs.org/magicast/-/magicast-0.5.4.tgz",
"integrity": "sha512-llBEhWm1SacoRwgHUoQJYtwp4PBLF4faQi5TCpIGyGs9n4y5+juI0tDgyKIfpqxckRHaHzouUEph3THklWh03w==",
"dev": true,
"license": "MIT",
"dependencies": {
"@babel/parser": "^7.29.7",
"@babel/types": "^7.29.7",
"source-map-js": "^1.2.1"
}
},
"node_modules/make-dir": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/make-dir/-/make-dir-4.0.0.tgz",
"integrity": "sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==",
"dev": true,
"license": "MIT",
"dependencies": {
"semver": "^7.5.3"
},
"engines": {
"node": ">=10"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/make-error": {
"version": "1.3.6",
"resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz",
@@ -4855,7 +5114,8 @@
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz",
"integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==",
"dev": true
"dev": true,
"license": "MIT"
},
"node_modules/pend": {
"version": "1.2.0",
@@ -6390,18 +6650,19 @@
}
},
"node_modules/vitest": {
"version": "4.1.10",
"resolved": "https://registry.npmjs.org/vitest/-/vitest-4.1.10.tgz",
"integrity": "sha512-R9jUTe5S4Qb0HCd4TNqpC7oGcrMssMRGXLW80ubjWsW9VH5GF8y1Y0SFLY9AbqSk6nt0PnOx4H4WNJYZ13GUPw==",
"version": "4.1.11",
"resolved": "https://registry.npmjs.org/vitest/-/vitest-4.1.11.tgz",
"integrity": "sha512-fhACrNXUidIbGSBr5FlbuBkO7VWC1ZyLl0DO4CU2DrQoAPxX84Ysxs+HeGQpii5lZWV1Q4gBZTTu49mF+A6Edw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@vitest/expect": "4.1.10",
"@vitest/mocker": "4.1.10",
"@vitest/pretty-format": "4.1.10",
"@vitest/runner": "4.1.10",
"@vitest/snapshot": "4.1.10",
"@vitest/spy": "4.1.10",
"@vitest/utils": "4.1.10",
"@vitest/expect": "4.1.11",
"@vitest/mocker": "4.1.11",
"@vitest/pretty-format": "4.1.11",
"@vitest/runner": "4.1.11",
"@vitest/snapshot": "4.1.11",
"@vitest/spy": "4.1.11",
"@vitest/utils": "4.1.11",
"es-module-lexer": "^2.0.0",
"expect-type": "^1.3.0",
"magic-string": "^0.30.21",
@@ -6429,12 +6690,12 @@
"@edge-runtime/vm": "*",
"@opentelemetry/api": "^1.9.0",
"@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0",
"@vitest/browser-playwright": "4.1.10",
"@vitest/browser-preview": "4.1.10",
"@vitest/browser-webdriverio": "4.1.10",
"@vitest/coverage-istanbul": "4.1.10",
"@vitest/coverage-v8": "4.1.10",
"@vitest/ui": "4.1.10",
"@vitest/browser-playwright": "4.1.11",
"@vitest/browser-preview": "4.1.11",
"@vitest/browser-webdriverio": "4.1.11",
"@vitest/coverage-istanbul": "4.1.11",
"@vitest/coverage-v8": "4.1.11",
"@vitest/ui": "4.1.11",
"happy-dom": "*",
"jsdom": "*",
"vite": "^6.0.0 || ^7.0.0 || ^8.0.0"
+5 -1
View File
@@ -1,7 +1,7 @@
{
"name": "opengym-frontend",
"private": true,
"version": "1.3.1",
"version": "1.3.2",
"type": "module",
"scripts": {
"dev": "vite",
@@ -15,11 +15,14 @@
"license": "AGPL-3.0-or-later",
"dependencies": {
"@aparajita/capacitor-secure-storage": "^7.1.6",
"@capacitor-mlkit/barcode-scanning": "^7.5.0",
"@capacitor/app": "^7.1.2",
"@capacitor/core": "^7.6.8",
"@capacitor/filesystem": "^7.1.8",
"@capacitor/local-notifications": "^7.0.7",
"@capacitor/share": "^7.0.4",
"jsqr": "^1.4.0",
"lean-qr": "^2.7.3",
"react": "^19.2.7",
"react-dom": "^19.2.7",
"react-router-dom": "^7.18.2",
@@ -31,6 +34,7 @@
"@capacitor/cli": "^7.6.8",
"@capacitor/ios": "^7.6.8",
"@vitejs/plugin-react": "^6.0.3",
"@vitest/coverage-v8": "^4.1.11",
"happy-dom": "^20.11.2",
"linkedom": "^0.18.13",
"vite": "^8.1.5",
+73
View File
@@ -0,0 +1,73 @@
#!/usr/bin/env node
// Measures the production bundle (raw + gzip, per file and total) and, given a baseline,
// prints the difference. CI runs it in every pipeline and keeps the result as an artifact,
// so a merge request can fetch main's numbers and show what it adds — the one thing
// reviewers otherwise never see until a self-hoster asks why the app got slower.
//
// node scripts/bundle-size.mjs --out bundle-size.json # measure dist/
// node scripts/bundle-size.mjs --compare baseline.json current.json # print the delta
//
// Report-only: growth is a review question, not a build failure.
import { readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'
import { join, relative } from 'node:path'
import { gzipSync } from 'node:zlib'
const args = process.argv.slice(2)
const dist = new URL('../dist/', import.meta.url).pathname
function walk(dir) {
return readdirSync(dir, { withFileTypes: true }).flatMap((e) =>
e.isDirectory() ? walk(join(dir, e.name)) : [join(dir, e.name)]
)
}
function measure() {
const files = {}
let raw = 0, gzip = 0
for (const f of walk(dist)) {
if (!/\.(js|css|html)$/.test(f)) continue
const buf = readFileSync(f)
const g = gzipSync(buf, { level: 9 }).length
// Hashed chunk names change on every build; key by the stable part so deltas line up.
const key = relative(dist, f).replace(/-[A-Za-z0-9_-]{8}\.(js|css)$/, '.$1')
files[key] = { raw: buf.length, gzip: g }
raw += buf.length
gzip += g
}
return { total: { raw, gzip }, files }
}
const kb = (n) => (n / 1024).toFixed(1).padStart(8) + ' kB'
const delta = (a, b) => {
const d = b - a
if (!a) return ' (new)'
const pct = ((d / a) * 100).toFixed(1)
return (d >= 0 ? '+' : '') + (d / 1024).toFixed(1) + ' kB (' + (d >= 0 ? '+' : '') + pct + '%)'
}
if (args[0] === '--out') {
const r = measure()
writeFileSync(args[1], JSON.stringify(r, null, 2))
console.log(`bundle: ${kb(r.total.raw).trim()} raw, ${kb(r.total.gzip).trim()} gzip, ${Object.keys(r.files).length} files`)
} else if (args[0] === '--compare') {
let base
try { base = JSON.parse(readFileSync(args[1], 'utf8')) } catch { base = null }
const cur = JSON.parse(readFileSync(args[2], 'utf8'))
if (!base) {
console.log('no baseline from main available — nothing to compare against')
process.exit(0)
}
console.log('bundle size vs main (gzip):')
const names = new Set([...Object.keys(base.files), ...Object.keys(cur.files)])
for (const n of [...names].sort()) {
const a = base.files[n]?.gzip ?? 0, b = cur.files[n]?.gzip ?? 0
if (a === b) continue
console.log(` ${n.padEnd(40)} ${kb(a)} -> ${kb(b)} ${b ? delta(a, b) : '(removed)'}`)
}
console.log(` ${'TOTAL'.padEnd(40)} ${kb(base.total.gzip)} -> ${kb(cur.total.gzip)} ${delta(base.total.gzip, cur.total.gzip)}`)
const growth = (cur.total.gzip - base.total.gzip) / base.total.gzip
if (growth > 0.1) console.log(`\n⚠ the gzipped bundle grew by ${(growth * 100).toFixed(1)}% — worth a look in review`)
} else {
console.error('usage: bundle-size.mjs --out FILE | --compare BASE CURRENT')
process.exit(2)
}
+6
View File
@@ -19,12 +19,14 @@ import TimerFlash from './components/TimerFlash.jsx'
import Login from './views/Login.jsx'
import MobileOnboarding from './views/MobileOnboarding.jsx'
import Home from './views/Home.jsx'
import CheckIn from './views/CheckIn.jsx'
import Plan from './views/Plan.jsx'
import RoutineEdit from './views/RoutineEdit.jsx'
import Workout from './views/Workout.jsx'
import Stats from './views/Stats.jsx'
import History from './views/History.jsx'
import Library from './views/Library.jsx'
import Muscles from './views/Muscles.jsx'
import Settings from './views/Settings.jsx'
import Admin from './views/Admin.jsx'
import CoachChat from './views/CoachChat.jsx'
@@ -113,12 +115,16 @@ function Shell() {
{!authed ? <Login /> : needsMobileOnboarding ? <MobileOnboarding /> : (
<Routes>
<Route path="/home" element={<Home />} />
{/* Gym check-in — switched off in Settings, the route falls through to the
catch-all redirect below. */}
{S.checkIn !== false && <Route path="/checkin" element={<CheckIn />} />}
<Route path="/plan" element={<Plan />} />
<Route path="/plan/r/:id" element={<RoutineEdit />} />
<Route path="/workout" element={<Workout />} />
<Route path="/stats" element={<Stats />} />
<Route path="/history" element={<History />} />
<Route path="/library" element={<Library />} />
<Route path="/muscles" element={<Muscles />} />
<Route path="/settings" element={<Settings />} />
{/* The Coach screens gate themselves on the instance config; the routes exist
unconditionally so a deep link from a notification lands somewhere sane
+9 -1
View File
@@ -1,7 +1,7 @@
// @vitest-environment happy-dom
import React, { act } from 'react'
import { createRoot } from 'react-dom/client'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
import BodyMap, { BodyMapLegend } from './BodyMap.jsx'
globalThis.IS_REACT_ACT_ENVIRONMENT = true
@@ -9,6 +9,14 @@ globalThis.IS_REACT_ACT_ENVIRONMENT = true
let container
let root
// BodyMap fetches its ~90 KB of geometry with a dynamic import on first render, and the
// waitFor below allows one second for it. That is ample once the module is in the ESM
// registry and not always ample when it is not: on a loaded CI runner the first map render
// in this file paid the cold import and timed out, while every later test passed on the
// component's warm CACHE. Import it here so the wait covers rendering, not module loading,
// and the file stops depending on how fast the machine is.
beforeAll(() => import('../lib/body-paths.js'))
beforeEach(() => {
container = document.createElement('div')
document.body.appendChild(container)
+69
View File
@@ -0,0 +1,69 @@
import { useEffect, useRef, useState } from 'react'
import { t } from '../lib/i18n.js'
import { decodeSource } from '../lib/scan-web.js'
import { Button } from '../components/ui.jsx'
// Live camera scanner for the browser/PWA (the app build uses ML Kit's own UI instead — see
// lib/scan.js). Opens the rear camera into a <video>, decodes a frame every ~150 ms until a QR
// shows up, then hands { value, fmt } to onFound. Cancel (or unmount) stops the camera.
//
// Errors are shown in place rather than thrown: a denied permission or a browser without
// getUserMedia leaves the sheet up with a message, and the add-card form underneath still offers
// photo import and typing.
export default function CameraScan({ onFound, onCancel }) {
const videoRef = useRef(null)
const [error, setError] = useState(null)
useEffect(() => {
let stream = null, timer = null, done = false
const stop = () => {
done = true
if (timer) clearTimeout(timer)
if (stream) stream.getTracks().forEach(tr => tr.stop())
}
;(async () => {
if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) { setError('unavailable'); return }
try {
stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: { ideal: 'environment' } }, audio: false })
} catch (e) {
setError(e && (e.name === 'NotAllowedError' || e.name === 'SecurityError') ? 'denied' : 'unavailable')
return
}
if (done) { stream.getTracks().forEach(tr => tr.stop()); return }
const v = videoRef.current
if (!v) return
v.srcObject = stream
try { await v.play() } catch (e) { /* autoplay policies; the loop below waits for frames */ }
const tick = async () => {
if (done) return
if (v.readyState >= 2) {
let code = null
try { code = await decodeSource(v) } catch (e) { /* keep trying */ }
if (code && !done) { stop(); onFound(code); return }
}
timer = setTimeout(tick, 150)
}
tick()
})()
return stop
}, [onFound])
return <>
<h3>{t('Scan')}</h3>
{error
? <div className="muted small" style={{ marginBottom: 16, lineHeight: 1.5 }}>
{error === 'denied'
? t('Camera access was denied — allow it in your browser and try again.')
: t('Camera is not available here — import a photo or type the code instead.')}
</div>
: <>
<div className="cam-wrap">
{/* playsInline keeps iOS from going full-screen; muted satisfies autoplay rules. */}
<video ref={videoRef} playsInline muted autoPlay />
<div className="cam-frame" aria-hidden="true" />
</div>
<div className="muted small" style={{ textAlign: 'center', margin: '12px 0 16px' }}>{t('Point the camera at the QR code')}</div>
</>}
<Button variant="tinted" onClick={onCancel}>{t('Cancel')}</Button>
</>
}
+5
View File
@@ -112,6 +112,11 @@ const P = {
signOut: <><path d="M14.2 4.6H7a1.9 1.9 0 0 0-1.9 1.9v11a1.9 1.9 0 0 0 1.9 1.9h7.2" /><path d="m16.8 8.4 3.6 3.6-3.6 3.6M20.4 12H10.2" /></>,
shuffle: <><path d="M3.6 7.2h2.9c1.6 0 2.8.9 3.8 2.4l3 4.8c1 1.5 2.2 2.4 3.8 2.4h2.9M3.6 16.8h2.9c1.6 0 2.8-.9 3.8-2.4l.7-1.1M15.6 9.9l.7-1.1c1-1.5 2.2-2.4 3.8-2.4h1.9" /><path d="m17.9 4.3 2.8 2.1-2.8 2.1M17.9 14.7l2.8 2.1-2.8 2.1" /></>,
info: <><circle cx="12" cy="12" r="8.2" /><path d="M12 11v5.4" /><circle cx="12" cy="7.9" r=".9" fill="currentColor" stroke="none" /></>,
// Three position-detection squares plus a scatter of modules — reads as "QR / scan this"
// at tab-bar size without trying to draw a real (unscannable) code.
qr: <><rect x="3.6" y="3.6" width="6" height="6" rx="1.2" /><rect x="14.4" y="3.6" width="6" height="6" rx="1.2" /><rect x="3.6" y="14.4" width="6" height="6" rx="1.2" /><path d="M14.4 14.4h2.4v2.4M20.4 14.4v.01M14.4 20.4h.01M17.4 17.4h3M17.4 20.4h3" /></>,
camera: <><path d="M3.6 8.8a2 2 0 0 1 2-2h1.9l1.3-2.1h6.4l1.3 2.1h1.9a2 2 0 0 1 2 2v8.4a2 2 0 0 1-2 2H5.6a2 2 0 0 1-2-2Z" /><circle cx="12" cy="12.8" r="3.3" /></>,
image: <><rect x="3.6" y="4.8" width="16.8" height="14.4" rx="2.6" /><circle cx="8.6" cy="9.6" r="1.7" /><path d="m4.4 17.4 4.8-4.6 3.3 3 3-2.6 4.1 4" /></>,
warning: <><path d="M12 3.4 21.2 19.4H2.8Z" /><path d="M12 9.6v4.4" /><circle cx="12" cy="16.6" r=".9" fill="currentColor" stroke="none" /></>,
}
@@ -0,0 +1,97 @@
import { useMemo, useState } from 'react'
import { useStore } from '../store/useStore.js'
import { BODYPARTS, allExercises, equipmentOf, matchExercise } from '../lib/exercises.js'
import { activeProfile, exAvailable } from '../lib/equipment.js'
import { bestWeightFor } from '../lib/history.js'
import { fmtNum } from '../lib/format.js'
import { MUSCLES, MUSCLE_NAME, musclesOf } from '../lib/muscles.js'
import { t, exerciseNameFor } from '../lib/i18n.js'
import BodyMap from './BodyMap.jsx'
import { Thumb } from './Media.jsx'
import Icon from './Icon.jsx'
import { Button } from './ui.jsx'
import { tappable } from '../lib/use-sheet-keyboard.js'
// One explorer for the Library and every catalogue picker. Supplying `onPick` turns
// a result into a selection; without it the explorer behaves like the normal Library.
export default function MuscleExplorer({ onPick, onDetail, onPlan }) {
const S = useStore(s => s.S)
const [selected, setSelected] = useState(null)
const [q, setQ] = useState('')
const [bp, setBp] = useState('')
const [eq, setEq] = useState('')
const [shown, setShown] = useState(40)
const [showAll, setShowAll] = useState(false) // ignore the active equipment profile for this session
// Same rule as the Library and the picker: the active equipment profile narrows the catalogue
// (and the per-muscle counts) unless the user asks for everything.
const profile = activeProfile(S)
const catalog = useMemo(() => {
const all = allExercises(S)
return (profile && !showAll) ? all.filter(e => exAvailable(S, e)) : all
}, [S.customEx, S.equipFilterOn, S.activeEquipId, S.equipProfiles, showAll])
const counts = useMemo(() => Object.fromEntries(MUSCLES.map(m => [m,
catalog.filter(e => musclesOf(e)[m]).length
])), [catalog])
const pick = muscle => { setSelected(muscle === selected ? null : muscle); setEq(''); setShown(40) }
const targeted = selected ? catalog.filter(e => musclesOf(e)[selected]) : []
const base = targeted.filter(e => (!bp || e.bp === bp) && matchExercise(e, q))
const eqOpts = equipmentOf(base)
const eqOn = eqOpts.includes(eq) ? eq : ''
const exercises = eqOn ? base.filter(e => e.eq === eqOn) : base
const choose = ex => onPick ? onPick(ex) : onDetail(ex)
return <>
{profile && <div className="small dim row" style={{ margin: '-4px 2px 10px', gap: 6, alignItems: 'center' }}>
<Icon name="dumbbell" style={{ fontSize: 13 }} />
{showAll ? t('Showing all equipment') : t('Showing what you have in "{0}"', profile.name)}
<button className="chip nocap" style={{ marginLeft: 'auto', padding: '3px 10px', fontSize: 12 }} onClick={() => { setShowAll(v => !v); setEq(''); setShown(40) }}>
{showAll ? t('Filter by "{0}"', profile.name) : t('Show all equipment')}
</button>
</div>}
<div className="card">
<BodyMap className="tappable" body={S.body} selected={selected} onMuscle={pick} />
<div className="chips" style={{ marginTop: 10 }}>
{MUSCLES.map(m => <button key={m} className={'chip' + (selected === m ? ' on' : '')}
aria-pressed={selected === m} onClick={() => pick(m)}>
{t(MUSCLE_NAME[m])} <span className="dim">{counts[m]}</span>
</button>)}
</div>
</div>
{!selected && onPick && <div className="empty"><div className="ico"><Icon name="target" /></div>{t('Choose a muscle to see exercises that train it.')}</div>}
{selected && <>
<div className="row between" style={{ margin: '2px 0 10px' }}>
<h4 className="sec" style={{ margin: 0 }}>{t('Exercises for {0}', t(MUSCLE_NAME[selected]))}</h4>
<Button size="sm" variant="ghost" onClick={() => pick(selected)}>{t('Clear selection')}</Button>
</div>
<div className="search" style={{ marginBottom: 10 }}><svg viewBox="0 0 24 24"><circle cx="11" cy="11" r="7" /><path d="m21 21-4.3-4.3" /></svg>
<input className="input" placeholder={t('Search…')} value={q} onChange={e => { setQ(e.target.value); setShown(40) }} />
</div>
<div className="chips" style={{ marginBottom: eqOpts.length > 1 ? 8 : 12 }}>
<button className={'chip nocap' + (!bp ? ' on' : '')} onClick={() => { setBp(''); setEq(''); setShown(40) }}>{t('All')}</button>
{BODYPARTS.map(b => <button key={b} className={'chip' + (bp === b ? ' on' : '')} onClick={() => { setBp(b); setEq(''); setShown(40) }}>{t(b)}</button>)}
</div>
{eqOpts.length > 1 && <div className="chips" style={{ marginBottom: 12 }}>
<button className={'chip nocap' + (!eqOn ? ' on' : '')} onClick={() => { setEq(''); setShown(40) }}>{t('Any equipment')}</button>
{eqOpts.map(x => <button key={x} className={'chip' + (eqOn === x ? ' on' : '')} onClick={() => { setEq(x); setShown(40) }}>{t(x)}</button>)}
</div>}
<div className="list">
{exercises.slice(0, shown).map(e => {
const best = bestWeightFor(S, e.id)
const primary = musclesOf(e)[selected] === 1
return <div key={e.id} className="item" {...tappable(() => choose(e))}>
<Thumb ex={e} />
<div className="grow"><div className="tt capitalize">{exerciseNameFor(e)}</div><div className="ss">{t(primary ? 'Primary target' : 'Also trains')} · <span className="capitalize">{t(e.tg || e.bp)} · {t(e.eq)}</span></div></div>
{onPick ? <Icon name="plus" className="chev" /> : <>
{best > 0 && <span className="tag acc">{fmtNum(best)}</span>}
<Button size="sm" variant="tinted" icon="plus" onClick={ev => { ev.stopPropagation(); onPlan(e) }}>{t('Plan')}</Button>
</>}
</div>
})}
{exercises.length === 0 && <div className="empty"><div className="ico"><Icon name="magnifier" /></div>{t('No match')}</div>}
</div>
{exercises.length > shown && <><div style={{ height: 10 }} /><Button onClick={() => setShown(s => s + 40)}>{t('Show more')}</Button></>}
</>}
</>
}
+33
View File
@@ -0,0 +1,33 @@
import { useEffect, useRef, useState } from 'react'
import { renderQrToCanvas } from '../lib/qr.js'
// Renders a gym check-in code as a QR image on a <canvas>. lean-qr draws one module per pixel;
// CSS (.qr-canvas) scales it up with image-rendering: pixelated so it stays razor-sharp at any
// display size without re-generating. Regenerated from `value` on every change — we never store
// the picture (see lib/qr.js).
//
// The lib loads via dynamic import, so the first paint is a frame behind; a plain box holds the
// space until then. A render failure (empty value, lib load error) shows nothing rather than a
// broken canvas — the caller decides what an unusable card looks like.
export default function QrCanvas({ value, size = 240, className = '' }) {
const ref = useRef(null)
const [ok, setOk] = useState(false)
useEffect(() => {
let alive = true
setOk(false)
renderQrToCanvas(ref.current, value)
.then(mods => { if (alive) setOk(mods > 0) })
.catch(() => { if (alive) setOk(false) })
return () => { alive = false }
}, [value])
return (
<canvas
ref={ref}
className={'qr-canvas ' + className}
style={{ width: size, height: size, opacity: ok ? 1 : 0 }}
aria-label="QR code"
/>
)
}
+1 -1
View File
@@ -13,7 +13,7 @@ export default function TabBar({ onStart }) {
const isGuest = useStore(s => s.isGuest())
if (!user && !isGuest) return null
const cur = loc.pathname.split('/')[1] || 'home'
const on = k => cur === k || (cur === 'history' && k === 'stats') || (cur === 'settings' && k === 'home')
const on = k => cur === k || (cur === 'history' && k === 'stats') || (cur === 'settings' && k === 'home') || (cur === 'muscles' && k === 'library')
const startWorkout = () => {
if (!S.active) {
+17 -3
View File
@@ -1,8 +1,22 @@
import { useEffect } from 'react'
import { useUI } from '../store/useUI.js'
// A new key restarts the CSS sequence even when two timers finish close together.
// The layer never catches taps and ends transparent, so it can safely stay mounted.
// Flips the app's real light/dark theme on and off twice (~2.4s) instead of laying an
// opaque black/white rectangle over the screen — the alert reads as the app itself
// blinking, and it always settles back on whatever theme the user actually had.
export default function TimerFlash() {
const id = useUI(s => s.timerFlashId)
return id ? <div key={id} className="timer-flash" aria-hidden="true" /> : null
useEffect(() => {
if (!id) return
const de = document.documentElement
const original = de.dataset.theme
const opposite = original === 'light' ? 'dark' : 'light'
const steps = [opposite, original, opposite, original]
const timers = steps.map((theme, i) => setTimeout(() => { de.dataset.theme = theme }, i * 600))
return () => {
timers.forEach(clearTimeout)
de.dataset.theme = original
}
}, [id])
return null
}
+55 -14
View File
@@ -262,7 +262,7 @@ h4.sec{
display:grid;grid-template-columns:minmax(0,1fr) auto;grid-template-rows:auto auto;
}
.lrow.lrow-stack-value .lrow-m{grid-column:1;grid-row:1}
.lrow.lrow-stack-value .lrow-v{grid-column:1;grid-row:2;text-align:left}
.lrow.lrow-stack-value .lrow-v{grid-column:1;grid-row:2;width:100%;max-width:none;text-align:left}
.lrow.lrow-stack-value .lrow-c{grid-column:2;grid-row:1 / span 2;align-self:center}
/* an (i) before a row's control: painted small and dim so the control stays the loud thing,
but with a finger-sized target like everything else — the padding is the hit area and the
@@ -438,6 +438,7 @@ h4.sec{
}
.chip:active{background:var(--surface-2)}
.chip.on{background:var(--acc);color:var(--on-acc);font-weight:500}
.chip.on .dim{color:color-mix(in srgb,var(--on-acc) 62%,transparent)}
/* =========================== CONTROLS ==================================== */
@@ -802,19 +803,6 @@ h4.sec{
.glyph-cell:active{transform:scale(.92)}
.glyph-cell.on{background:var(--acc);color:var(--on-acc)}
/* --- opt-in timer completion flash ---
Four deliberate pulses over 2.4s stay below three flashes per second. Transparent
gaps keep the black and white pulses visually distinct. */
.timer-flash{
position:fixed;inset:0;z-index:1000;pointer-events:none;opacity:0;
animation:timer-flash-four 2.4s linear both;
}
@keyframes timer-flash-four{
0%,20%,28%,48%,56%,76%,84%,100%{opacity:0}
4%,16%,60%,72%{background:#000;opacity:1}
32%,44%,88%,96%{background:#fff;opacity:1}
}
/* --- big weight readout --- */
.bwstep{display:flex;align-items:center;justify-content:center;gap:18px;margin:14px 0 6px}
.bw-pm{
@@ -1010,6 +998,18 @@ h4.sec{
.ss-ex{position:relative}
.ss-amp{text-align:center;font-size:15px;font-weight:600;color:var(--acc);margin:14px 0 8px}
/* --- workout list view: every unit stacked, the current one outlined --- */
.workout-list{display:grid;gap:14px}
.wl-unit{
border-radius:var(--r-lg);padding:14px 14px 4px;
background:var(--surface-2);
}
.wl-unit.cur{box-shadow:inset 0 0 0 1.5px var(--acc-line)}
.wl-hd{display:flex;align-items:center;justify-content:space-between;gap:8px;margin-bottom:10px}
@media (max-width:400px){
.wl-unit{padding:10px 8px 2px}
}
/* --- home: today's session row --- */
.today-row{
display:flex;align-items:center;justify-content:space-between;gap:10px;
@@ -1057,6 +1057,47 @@ h4.sec{
.hm-wrap{display:flex;flex-direction:column;align-items:center}
}
/* ------------------------------------------------------- gym check-in -- */
/* Mobile-only feature (views/CheckIn.jsx): saved membership codes shown as QR, swiped
through horizontally. The rail is a scroll-snap track — one card per viewport, no JS
carousel — with a trailing "+" card to add another. */
.ci-rail{
display:flex;gap:14px;overflow-x:auto;scroll-snap-type:x mandatory;
-webkit-overflow-scrolling:touch;scrollbar-width:none;
padding:4px 0 8px;margin:0 -16px;padding-left:16px;padding-right:16px;
}
.ci-rail::-webkit-scrollbar{display:none}
.ci-card{
scroll-snap-align:center;flex:0 0 100%;box-sizing:border-box;
background:var(--surface);border-radius:var(--r-xl);padding:22px 18px;
display:flex;flex-direction:column;align-items:center;gap:14px;
}
.ci-card .ci-label{font-size:19px;font-weight:600;letter-spacing:-.014em;text-align:center}
.ci-card .ci-value{font-size:14px;color:var(--label-2);word-break:break-all;text-align:center;font-variant-numeric:tabular-nums}
/* The QR itself: lean-qr paints 1 module per pixel, so scale it up with the browser's
nearest-neighbour so every module stays a crisp square instead of a blurred blob. White
quiet-zone padding is baked in by the renderer; the plate underneath just frames it. */
.ci-qr-plate{background:#fff;border-radius:var(--r-lg);padding:16px}
.qr-canvas{display:block;image-rendering:pixelated;image-rendering:crisp-edges;transition:opacity var(--fast)}
/* the trailing add card — a big + on a dashed outline, same footprint as a real card */
.ci-add{
scroll-snap-align:center;flex:0 0 100%;box-sizing:border-box;
min-height:280px;border-radius:var(--r-xl);
border:2px dashed var(--surface-3);background:none;color:var(--label-2);
display:flex;flex-direction:column;align-items:center;justify-content:center;gap:10px;
}
.ci-add:active{background:var(--surface);transform:scale(.99)}
.ci-add .icn{font-size:40px;--icon-stroke:1.8}
.ci-add .ci-add-t{font-size:16px;font-weight:500}
/* dots under the rail — which card you're on. Purely a hint; the rail itself is the control. */
.ci-dots{display:flex;justify-content:center;gap:7px;margin-top:4px}
.ci-dot{width:7px;height:7px;border-radius:50%;background:var(--surface-3);transition:background var(--fast),transform var(--fast)}
.ci-dot.on{background:var(--acc);transform:scale(1.15)}
/* browser camera sheet (components/CameraScan.jsx): the video fills a portrait plate, a dashed
square in the middle says "put the code here" — decoding reads the whole frame regardless. */
.cam-wrap{position:relative;width:100%;aspect-ratio:3/4;max-height:58vh;border-radius:var(--r-lg);overflow:hidden;background:#000}
.cam-wrap video{width:100%;height:100%;object-fit:cover;display:block}
.cam-frame{position:absolute;inset:0;margin:auto;width:62%;aspect-ratio:1;border:2px dashed rgba(255,255,255,.75);border-radius:14px;pointer-events:none}
/* ------------------------------------------------- the Coach entry on Plan -- */
.coach-cta{
display:flex;align-items:center;gap:13px;width:100%;text-align:left;
+3 -1
View File
@@ -1,11 +1,13 @@
// The persisted boundary for a finished session. Keep this pure so compatibility tests can
// exercise the exact shape the UI writes without mounting React or mutating store state.
import { bestWeightForEntry } from './history.js'
export function buildCompletedWorkout(active, { end = Date.now(), prs = [], snapshotFor } = {}) {
const entries = (active?.entries || []).map(entry => {
const completed = {
id: entry.id,
sets: entry.sets,
topW: entry.topW || null,
topW: bestWeightForEntry(entry) || null,
target: entry.target || null,
}
const snapshot = typeof snapshotFor === 'function' ? snapshotFor(entry) : null
+30
View File
@@ -15,6 +15,36 @@ describe('completed workout boundary', () => {
})
})
it('derives topW from the highest completed non-warm-up work set, not stale entry data', () => {
const active = {
id: 'active-1', d: '2026-08-08', start: 1000,
entries: [{
id: '0025', topW: 80, target: { mode: 'reps', sets: 2, reps: 8 },
sets: [
{ phase: 'warmup', done: true, w: 120, r: 8 },
{ done: true, w: 75, r: 8 },
{ done: true, w: 85, r: 7 },
{ done: false, w: 100, r: 8 },
],
}],
}
expect(buildCompletedWorkout(active).entries[0].topW).toBe(85)
expect(buildCompletedWorkout({
...active,
entries: [{ ...active.entries[0], topW: 120 }],
}).entries[0].topW).toBe(85)
})
it('keeps a legacy topW when old completed rows have no usable weight', () => {
const active = {
id: 'active-1', d: '2026-08-08', start: 1000,
entries: [{ id: '0025', topW: 60, sets: [{ done: true, r: 8 }] }],
}
expect(buildCompletedWorkout(active).entries[0].topW).toBe(60)
})
it('persists progression exclusion only for a marked session', () => {
const active = {
id: 'active-1', d: '2026-08-08', start: 1000, routineId: 'routine-1', name: 'Deload', bw: 80,
+14 -10
View File
@@ -626,20 +626,24 @@ export function bestWeightForEntry(entry = {}) {
? entry.sets.filter(s => phaseForSet(s) === 'work')
: []
const repsRows = metricRowsForEntry(entry, 'reps')
if (!repsRows.length) {
return workRows.reduce((best, set) => {
if (set?.done !== true || isWarmupRow(set)) return best
const weight = Number(set.w)
return Number.isFinite(weight) && weight > best ? weight : best
}, 0)
}
// Reps rows are the authoritative load metric for a mixed entry. Otherwise use every
// completed work row (timed holds can carry an added load too).
const completedRows = repsRows.length
? repsRows
: workRows.filter(set => set?.done === true && !isWarmupRow(set))
let best = 0
repsRows.forEach(set => {
let hasUsableWeight = false
completedRows.forEach(set => {
const weight = Number(set?.w)
if (Number.isFinite(weight) && weight > best) best = weight
if (!Number.isFinite(weight)) return
hasUsableWeight = true
if (weight > best) best = weight
})
// A real completed row, including an explicit zero for an unloaded bodyweight set, always
// wins. A manual topW is only useful for old records whose rows did not carry a usable load.
if (hasUsableWeight) return best
const parentMode = modeForSet({}, target)
const hasNonRepsWorkRow = workRows.some(set => modeForSet(set, target) !== 'reps')
const hasWarmupRow = Array.isArray(entry.sets) && entry.sets.some(isWarmupRow)
+66
View File
@@ -501,6 +501,72 @@ describe('buildSets', () => {
.toEqual([{ w: 40, r: 12, done: false }, { w: 40, r: 12, done: false }])
})
it('uses the current routine target instead of another routine\'s bodyweight history', () => {
const S = {
exWeights: {},
workouts: [{
d: '2026-01-01',
routineId: 'routine-a',
entries: [{
id: BW,
target: { sets: 2, reps: 15, weight: 0, bodyweight: true },
sets: [{ w: 0, r: 15, done: true }, { w: 0, r: 15, done: true }]
}]
}]
}
const cfg = { id: BW, sets: 4, reps: 8, weight: 0, bodyweight: true, prog: 'off' }
expect(buildSets(S, cfg, { useTarget: true })).toEqual([
{ w: 0, r: 8, done: false },
{ w: 0, r: 8, done: false },
{ w: 0, r: 8, done: false },
{ w: 0, r: 8, done: false }
])
const reverseS = {
exWeights: {},
workouts: [{
d: '2026-01-02',
routineId: 'routine-b',
entries: [{
id: BW,
target: { sets: 4, reps: 8, weight: 0, bodyweight: true },
sets: [
{ w: 0, r: 8, done: true }, { w: 0, r: 8, done: true },
{ w: 0, r: 8, done: true }, { w: 0, r: 8, done: true }
]
}]
}]
}
expect(buildSets(reverseS, { ...cfg, sets: 2, reps: 15 }, { useTarget: true })).toEqual([
{ w: 0, r: 15, done: false },
{ w: 0, r: 15, done: false }
])
})
it('preserves configured load, reps, duration and cardio targets when history is present', () => {
const repsS = {
exWeights: { [LIFT]: { w: 75 } },
workouts: [{ d: '2026-01-01', entries: [{ id: LIFT, sets: [{ w: 75, r: 15, done: true }] }] }]
}
expect(buildSets(repsS, { id: LIFT, sets: 2, reps: 8, weight: 40 }, { useTarget: true }))
.toEqual([{ w: 40, r: 8, done: false }, { w: 40, r: 8, done: false }])
const timedS = {
exWeights: {},
workouts: [{ d: '2026-01-02', entries: [{ id: LIFT, target: { mode: 'time' }, sets: [{ sec: 90, w: 20, done: true }] }] }]
}
expect(buildSets(timedS, { id: LIFT, mode: 'time', sets: 2, sec: 30, weight: 5 }, { useTarget: true }))
.toEqual([{ sec: 30, w: 5, done: false }, { sec: 30, w: 5, done: false }])
const cardioS = {
exWeights: {},
workouts: [{ d: '2026-01-03', entries: [{ id: CARDIO, sets: [{ min: 45, speed: 10, done: true }] }] }]
}
expect(buildSets(cardioS, { id: CARDIO, sets: 2, min: 20, speed: 8 }, { useTarget: true }))
.toEqual([{ min: 20, speed: 8, done: false }, { min: 20, speed: 8, done: false }])
})
})
describe('applyIntensifierPlan', () => {
+29 -8
View File
@@ -61,6 +61,11 @@ export function defaultIncrement(exId, unit) {
if (unit === 'lb') return heavy ? 10 : 5
return heavy ? 5 : 2.5
}
// Resolve the load step for reps-mode weight controls and progression. Timed exercises use
// `inc` for seconds, so their optional weight column must not call this helper.
export function weightIncrement(cfg, unit) {
return cfg && cfg.inc > 0 ? cfg.inc : defaultIncrement(cfg?.id, unit)
}
export const DEFAULT_SEC_INCREMENT = 5
// Where adding another set of push-ups stops being progress and starts being a way to spend
// an evening. Past this the honest advice is load or a harder variation (issue #33).
@@ -76,18 +81,28 @@ export function policyFor(cfg, routine, mode) {
}
const round1 = v => Math.round(v * 10) / 10
// Snap to a loadable multiple of the step.
function snap(v, step) {
// Snap to a loadable multiple of the step. Manual weight controls use this same normalization
// so fractional increments produce the same number as automatic progression.
export function snapWeight(v, step) {
if (!(step > 0)) return round1(v)
return round1(Math.round(v / step) * step)
}
// A tap moves by one step. Snapping to the grid keeps the number identical to what progression
// would prescribe (61.3 → 62.5 with a 1.25 step, not 62.55) — but only when the current value
// already sits on that grid; from 62.5 with a 5 kg step a tap gives 67.5, not 70.
export function stepWeight(value, step, direction) {
const v = Number(value) || 0
const onGrid = step > 0 && Math.abs(v - Math.round(v / step) * step) <= 0.1
const next = v + direction * step
return Math.max(0, onGrid ? snapWeight(next, step) : round1(next))
}
// Back off by DELOAD_FACTOR, landing on something you can actually load. Rounding to the
// nearest step keeps the cut close to the intended 10 %, but on small weights the nearest
// step can be the weight you started from — so a deload that did not actually reduce
// anything takes one step down instead. Never goes below a single step.
function deloadTo(cur, step) {
let next = snap(cur * DELOAD_FACTOR, step)
if (next >= cur) next = snap(cur - step, step)
let next = snapWeight(cur * DELOAD_FACTOR, step)
if (next >= cur) next = snapWeight(cur - step, step)
return Math.max(step, next)
}
@@ -145,11 +160,15 @@ export function sessionsFor(S, exId, fallback) {
return out
}
// How many sessions in a row ended in a miss, counting back from the most recent.
// How many sessions in a row ended in a miss, counting back from the most recent. A change of
// weight starts a new streak, so there won't be a perpetual stall.
// Rationale: deload should reflect the failures in sessions with weight that earned it.
// Not the lighter weight that follows.
export function stallCount(sessions) {
let n = 0
for (let i = sessions.length - 1; i >= 0; i--) {
if (sessions[i].ok) break
if (i < sessions.length -1 && sessions[i].weight !== sessions[i+1].weight) break
n++
}
return n
@@ -167,7 +186,9 @@ export function nextPrescription(S, cfg, routine) {
const mode = modeOf(cfg)
const policy = policyFor(cfg, routine, mode)
const unit = S.unit || 'kg'
const inc = cfg.inc > 0 ? cfg.inc : (mode === 'time' ? DEFAULT_SEC_INCREMENT : defaultIncrement(cfg.id, unit))
const inc = mode === 'time'
? (cfg.inc > 0 ? cfg.inc : DEFAULT_SEC_INCREMENT)
: weightIncrement(cfg, unit)
if (policy === 'off') return { policy, kind: 'off' }
const sessions = sessionsFor(S, cfg.id, cfg).filter(s => s.mode === mode)
@@ -218,7 +239,7 @@ export function nextPrescription(S, cfg, routine) {
const range = normalizeRepRange(cfg.reps || last.goal || 10, cfg.repsMin, repStep(cfg))
const top = range.reps
const bottom = range.repsMin
if (last.ok) return { policy, kind: 'up', weight: snap(w + inc, inc), reps: bottom, why: ['Top of the rep range in every set — {0} {1} more, back to {2} reps.', inc, unit, bottom] }
if (last.ok) return { policy, kind: 'up', weight: snapWeight(w + inc, inc), reps: bottom, why: ['Top of the rep range in every set — {0} {1} more, back to {2} reps.', inc, unit, bottom] }
if (stalls >= deloadAt) {
const dw = deloadTo(w, inc)
return { policy, kind: 'deload', weight: dw, reps: bottom, why: ['Stalled {0} sessions — deload to {1} {2}.', stalls, dw, unit] }
@@ -234,7 +255,7 @@ export function nextPrescription(S, cfg, routine) {
const dbl = policy === 'greyskull' && last.goal > 0 && last.amrap >= last.goal * 2
const step = dbl ? inc * 2 : inc
return {
policy, kind: 'up', weight: snap(w + step, inc),
policy, kind: 'up', weight: snapWeight(w + step, inc),
why: dbl
? ['Last set hit {0} reps — twice the target, so take a double jump of {1} {2}.', last.amrap, step, unit]
: ['Every rep last time — {0} {1} more.', step, unit]
+38 -1
View File
@@ -1,7 +1,7 @@
import { describe, it, expect } from 'vitest'
import {
readSession, sessionsFor, stallCount, nextPrescription, applyPrescription,
policyFor, defaultIncrement, POLICIES_FOR, DELOAD_AFTER, MAX_BW_SETS
policyFor, defaultIncrement, weightIncrement, POLICIES_FOR, DELOAD_AFTER, MAX_BW_SETS
} from './progression.js'
import { EXDB } from './exercises.js'
@@ -103,6 +103,14 @@ describe('defaultIncrement', () => {
})
})
describe('weightIncrement', () => {
it('uses a positive exercise override and otherwise the exercise/unit default', () => {
expect(weightIncrement({ id: LIFT, inc: 1 }, 'kg')).toBe(1)
expect(weightIncrement({ id: LIFT }, 'kg')).toBe(2.5)
expect(weightIncrement({ id: HEAVY, inc: 0 }, 'kg')).toBe(5)
})
})
describe('linear progression', () => {
const cfg = { id: LIFT, sets: 3, reps: 5, weight: 60, prog: 'linear' }
@@ -142,6 +150,19 @@ describe('linear progression', () => {
expect(p.kind).toBe('hold')
})
it('a deload starts a new streak, so one miss at the new weight does not deload again', () => {
// Three misses at 60 kg earn a deload.
const stalled = [[60, 4, 4, 4], [60, 4, 4, 4], [60, 4, 4, 4]]
const deload = nextPrescription(hist(LIFT, stalled), cfg)
expect(deload.kind).toBe('deload')
// A bad day at the lighter weight is the first miss of a new run, not the fourth of the old
// one. A deload is owed a fresh set of attempts, not an immediate second cut.
const next = nextPrescription(hist(LIFT, [...stalled, [deload.weight, 4, 4, 4]]), cfg)
expect(next.kind).toBe('hold')
expect(next.weight).toBe(deload.weight)
})
it('never deloads below one increment, however light the lift already is', () => {
const p = nextPrescription(hist(LIFT, [[2.5, 1, 1, 1], [2.5, 1, 1, 1], [2.5, 1, 1, 1]]), cfg)
expect(p.kind).toBe('deload')
@@ -292,6 +313,22 @@ describe('double progression', () => {
expect(p.reps).toBe(8)
})
it('does not deload again when the deload was performed exactly as prescribed', () => {
const target = { sets: 3, reps: 12 }
// Three sessions stuck mid-range where every set misses the top, so a deload falls due (see DELOAD_POLICY)
const stalled = [[40, 9, 9, 9], [40, 9, 9, 9], [40, 9, 9, 9]]
const deload = nextPrescription(hist(LIFT, stalled, target), cfg)
expect(deload.kind).toBe('deload')
// Training exactly what it asked for: its weight, its reps, every set checked off.
const asPrescribed = [deload.weight, ...Array(target.sets).fill(deload.reps)]
const next = nextPrescription(hist(LIFT, [...stalled, asPrescribed], target), cfg)
// Complying with the app's own prescription must not be scored as another failure.
expect(next.kind).not.toBe('deload')
expect(next.weight).toBeGreaterThanOrEqual(deload.weight)
})
it('keeps the weight and asks for one more rep while inside the range', () => {
const p = nextPrescription(hist(LIFT, [[40, 10, 9, 9]], { sets: 3, reps: 12 }), cfg)
expect(p.kind).toBe('hold')
+4 -4
View File
@@ -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(586)
expect(inherited).toHaveLength(553)
expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(612)
expect(inherited).toHaveLength(583)
// 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('4a550b06e44cabd2b69834c15607220ca547854f2b0934843cadaa60a7f61a27')
expect(fingerprint, 'pt-PT inheritance changed; review the inherited pt-BR wording').toBe('c7ddbc412a3e758704289b4414372f2cbc0e26be4c0a0d95676cb3316ecae85a')
})
test('does not leak European Portuguese UI terms', () => {
@@ -49,6 +49,6 @@ describe('Brazilian Portuguese locale', () => {
expect(ptBR['resistance band']).toBe('faixa elástica')
expect(ptBR.soleus).toBe('sóleo')
expect(ptBR.Unpair).toBe('Desvincular')
expect(ptBR['Starter plan loaded — Mon Push · Wed Pull · Fri Legs']).toContain('Seg Push · Qua Pull')
expect(ptBR['Choose starter plan']).toBe('Escolha um plano inicial')
})
})
+66
View File
@@ -0,0 +1,66 @@
// QR rendering for the gym check-in cards (see views/CheckIn.jsx).
//
// We never store a photo of a membership card, only its decoded value (+ its symbology in
// `fmt`). The picture a turnstile scanner reads is regenerated from that value every time the
// card is shown, here.
//
// lean-qr (MIT, see NOTICE.md) is loaded with a dynamic import so its ~4kB only loads when a
// card is actually shown, on every platform — the PWA renders the same code as the app.
//
// Scope: lean-qr generates QR codes only. A gym card is virtually always a QR code, and the
// capture flow (lib/scan.js) refuses any symbology we cannot faithfully reproduce, so a stored
// card is guaranteed renderable here — canRenderFmt() is the single source of that truth, shared
// by both sides.
let _leanqr = null
// Cached loader for lean-qr. Resolves once; every card after the first reuses the same module.
async function loadLeanQr() {
if (!_leanqr) _leanqr = await import('lean-qr')
return _leanqr
}
// The symbologies we can both read (mlkit) AND redraw (lean-qr). Stored `fmt` is a lower-cased
// BarcodeFormat. Only QR qualifies: reproducing an EAN/Code128/etc. would need a 1D renderer we
// deliberately did not add, and a code we can't redraw faithfully is worse than not storing it —
// it would look scannable but carry the wrong bars.
export function canRenderFmt(fmt) {
return normalizeFmt(fmt) === 'qrcode'
}
// mlkit reports BarcodeFormat as e.g. 'QR_CODE' | 'QrCode'; older callers may pass 'qr'. Fold
// them all to a stable lower-case token we store and compare on.
export function normalizeFmt(fmt) {
const s = String(fmt || '').toLowerCase().replace(/[^a-z0-9]/g, '')
if (s === 'qr' || s === 'qrcode') return 'qrcode'
return s
}
// Draw `value` as a QR code onto `canvas` at 1 module per pixel; CSS scales it up with
// image-rendering: pixelated (see .qr-canvas in index.css) so it stays crisp at any size.
// `on`/`off` default to solid black on white — turnstile scanners want maximum contrast, not
// the app's theme colours, and a themed (e.g. lime-on-black) code fails to read on many
// readers. Returns the module count (QR size) so the caller can react if it wants.
export async function renderQrToCanvas(canvas, value, { on = '#000000', off = '#ffffff' } = {}) {
if (!canvas || !value) return 0
const { generate, correction } = await loadLeanQr()
// Medium error correction: a good default that survives a scratched or partly-obscured phone
// screen without inflating the code so much it gets dense on small screens.
const code = generate(value, { minCorrectionLevel: correction.M })
code.toCanvas(canvas, {
on: hexToRgba(on),
off: hexToRgba(off),
padX: 2,
padY: 2,
})
return code.size
}
// lean-qr wants colours as [r,g,b,a]. Accept a #rrggbb (or #rgb) string; anything else is
// treated as opaque black/white by the caller's defaults, so this only has to handle hex.
function hexToRgba(hex) {
let h = String(hex).replace('#', '')
if (h.length === 3) h = h.split('').map(c => c + c).join('')
const n = parseInt(h, 16)
return [(n >> 16) & 255, (n >> 8) & 255, n & 255, 255]
}
+51
View File
@@ -0,0 +1,51 @@
import { describe, it, expect } from 'vitest'
import { normalizeFmt, canRenderFmt } from './qr.js'
// The QR helpers decide which scanned/typed codes the check-in feature will store: it can read
// many symbologies but only redraw QR, so canRenderFmt is the gate, and normalizeFmt is what
// folds every spelling mlkit might report into the single token everything else compares on.
describe('normalizeFmt', () => {
it('folds every QR spelling to "qrcode"', () => {
// mlkit's BarcodeFormat, the enum-ish casings, and the casual 'qr' all mean the same thing.
expect(normalizeFmt('QR_CODE')).toBe('qrcode')
expect(normalizeFmt('QrCode')).toBe('qrcode')
expect(normalizeFmt('qrcode')).toBe('qrcode')
expect(normalizeFmt('qr')).toBe('qrcode')
expect(normalizeFmt('QR')).toBe('qrcode')
})
it('lower-cases and strips separators for other formats', () => {
expect(normalizeFmt('EAN_13')).toBe('ean13')
expect(normalizeFmt('Code128')).toBe('code128')
expect(normalizeFmt('CODE_128')).toBe('code128')
})
it('treats empty / nullish as an empty token rather than throwing', () => {
expect(normalizeFmt('')).toBe('')
expect(normalizeFmt(null)).toBe('')
expect(normalizeFmt(undefined)).toBe('')
})
})
describe('canRenderFmt', () => {
it('accepts only QR, in any spelling', () => {
expect(canRenderFmt('QR_CODE')).toBe(true)
expect(canRenderFmt('QrCode')).toBe(true)
expect(canRenderFmt('qr')).toBe(true)
})
it('rejects 1D and other 2D symbologies we cannot faithfully redraw', () => {
// These are readable by the scanner but lean-qr can't reproduce them, so a card in one of
// these formats must never be stored — it would display as the wrong bars at the turnstile.
for (const fmt of ['EAN_13', 'EAN_8', 'CODE_128', 'CODE_39', 'ITF', 'UPC_A', 'PDF_417', 'AZTEC', 'DATA_MATRIX']) {
expect(canRenderFmt(fmt)).toBe(false)
}
})
it('rejects empty / unknown formats', () => {
expect(canRenderFmt('')).toBe(false)
expect(canRenderFmt(null)).toBe(false)
expect(canRenderFmt('something-else')).toBe(false)
})
})
+12
View File
@@ -0,0 +1,12 @@
import { uid } from './format.js'
/**
* Create a deep copy of a routine with a new id and a "(Copy)" suffix.
* All exercises and their configuration are preserved independently.
*/
export function copyRoutine(routine, suffix = 'Copy') {
const copy = structuredClone(routine)
copy.id = uid()
copy.name = routine.name + ' (' + suffix + ')'
return copy
}
+79
View File
@@ -0,0 +1,79 @@
import { describe, it, expect } from 'vitest'
import { copyRoutine } from './routines.js'
const routine = {
id: 'r1',
name: 'Push Day',
emoji: 'arm',
prog: 'linear',
ex: [
{ id: 'ex1', sets: 3, reps: 10, weight: 60, sg: 'sg1' },
{ id: 'ex2', sets: 4, reps: 8, weight: 80, sg: 'sg1' },
{ id: 'ex3', sets: 3, reps: 12, weight: 20 }
]
}
describe('copyRoutine', () => {
it('returns a new routine with a different id', () => {
const copy = copyRoutine(routine)
expect(copy.id).not.toBe(routine.id)
expect(copy.id).toBeTruthy()
})
it('appends "(Copy)" to the name by default', () => {
const copy = copyRoutine(routine)
expect(copy.name).toBe('Push Day (Copy)')
})
it('uses a custom suffix when provided', () => {
const copy = copyRoutine(routine, 'Kopie')
expect(copy.name).toBe('Push Day (Kopie)')
})
it('deep-copies all exercises with their configuration', () => {
const copy = copyRoutine(routine)
expect(copy.ex).toHaveLength(3)
expect(copy.ex[0]).toEqual(routine.ex[0])
expect(copy.ex[1]).toEqual(routine.ex[1])
expect(copy.ex[2]).toEqual(routine.ex[2])
})
it('preserves exercise ids (references to the global library)', () => {
const copy = copyRoutine(routine)
expect(copy.ex[0].id).toBe('ex1')
expect(copy.ex[1].id).toBe('ex2')
expect(copy.ex[2].id).toBe('ex3')
})
it('preserves superset groupings', () => {
const copy = copyRoutine(routine)
expect(copy.ex[0].sg).toBe('sg1')
expect(copy.ex[1].sg).toBe('sg1')
expect(copy.ex[2].sg).toBeUndefined()
})
it('preserves the emoji and progression settings', () => {
const copy = copyRoutine(routine)
expect(copy.emoji).toBe('arm')
expect(copy.prog).toBe('linear')
})
it('produces an independent copy — mutating it does not affect the original', () => {
const copy = copyRoutine(routine)
copy.name = 'Modified'
copy.ex[0].weight = 999
copy.ex.push({ id: 'ex4', sets: 5, reps: 5 })
expect(routine.name).toBe('Push Day')
expect(routine.ex[0].weight).toBe(60)
expect(routine.ex).toHaveLength(3)
})
it('handles a routine with no exercises', () => {
const empty = { id: 'r2', name: 'Empty', emoji: 'dumbbell', ex: [] }
const copy = copyRoutine(empty)
expect(copy.ex).toEqual([])
expect(copy.name).toBe('Empty (Copy)')
expect(copy.id).not.toBe('r2')
})
})
+83
View File
@@ -0,0 +1,83 @@
// Browser-side QR decoding for the gym check-in — the PWA half of lib/scan.js. The app build
// hands scanning to ML Kit; here in a browser tab (installed PWA on a phone, most often) we do
// it ourselves: draw the source — an uploaded photo or a live <video> frame — onto an offscreen
// canvas and decode the pixels.
//
// Two decoders, tried in order:
// 1. BarcodeDetector — the browser's own (Chrome/Edge on Android, Samsung Internet). Native
// speed and quality when it exists; asked for QR only.
// 2. jsQR (Apache-2.0, see NOTICE.md) — pure JS, works everywhere including iOS Safari, which
// has no BarcodeDetector. Loaded with a dynamic import so it only ships when someone scans.
//
// decodeImageData is the pure core (pixels in, string out) and is what the unit test exercises;
// decodeSource wraps it with the canvas plumbing the browser paths need.
import { normalizeFmt } from './qr.js'
let _jsqr = null
async function loadJsQr() {
if (!_jsqr) _jsqr = (await import('jsqr')).default
return _jsqr
}
let _detector = null
function nativeDetector() {
if (_detector !== null) return _detector
try {
_detector = (typeof BarcodeDetector === 'function') ? new BarcodeDetector({ formats: ['qr_code'] }) : false
} catch (e) { _detector = false }
return _detector
}
// { data, width, height } (an ImageData or anything shaped like one) → { value, fmt } | null.
// jsQR only; the native detector wants a drawable, not raw pixels, so it lives in decodeSource.
export async function decodeImageData(img) {
if (!img || !img.data || !img.width || !img.height) return null
const jsQR = await loadJsQr()
const hit = jsQR(img.data, img.width, img.height, { inversionAttempts: 'attemptBoth' })
return hit && hit.data ? { value: hit.data, fmt: 'qrcode' } : null
}
// Decode from anything drawImage accepts: <video>, <img>, ImageBitmap, canvas. The source is
// scaled down to at most MAX px on its long edge — plenty for a QR, and it keeps jsQR fast enough
// to run on every few video frames on a phone. Reuses one canvas across calls.
const MAX = 800
let _canvas = null
export async function decodeSource(source) {
const sw = source.videoWidth || source.naturalWidth || source.width || 0
const sh = source.videoHeight || source.naturalHeight || source.height || 0
if (!sw || !sh) return null
const k = Math.min(1, MAX / Math.max(sw, sh))
const w = Math.max(1, Math.round(sw * k)), h = Math.max(1, Math.round(sh * k))
if (!_canvas) _canvas = document.createElement('canvas')
_canvas.width = w; _canvas.height = h
const ctx = _canvas.getContext('2d', { willReadFrequently: true })
ctx.drawImage(source, 0, 0, w, h)
const det = nativeDetector()
if (det) {
try {
const found = await det.detect(_canvas)
const b = found && found.find(x => x.rawValue)
if (b) return { value: b.rawValue, fmt: normalizeFmt(b.format) || 'qrcode' }
} catch (e) { /* fall through to jsQR */ }
}
return decodeImageData(ctx.getImageData(0, 0, w, h))
}
// A picked File → { value, fmt } | null. createImageBitmap honours EXIF orientation where the
// browser supports it, which matters for photos of a card taken in portrait.
export async function importCodeFromImageWeb(file) {
if (!file) return null
let bmp
if (typeof createImageBitmap === 'function') {
bmp = await createImageBitmap(file)
} else {
bmp = await new Promise((resolve, reject) => {
const img = new Image()
img.onload = () => resolve(img)
img.onerror = () => reject(new Error('bad image'))
img.src = URL.createObjectURL(file)
})
}
try { return await decodeSource(bmp) } finally { if (bmp.close) bmp.close() }
}
+44
View File
@@ -0,0 +1,44 @@
import { describe, it, expect } from 'vitest'
import { generate } from 'lean-qr'
import { decodeImageData } from './scan-web.js'
// Round trip through the two libraries the browser path relies on: lean-qr draws a code (the
// same renderer the card view uses), jsQR reads it back. Pixels are built by hand from
// code.get(x, y) — no canvas in this environment — scaled 4× with a 4-module quiet zone, which
// is what a phone camera would roughly see.
function rasterize(code, scale = 4, quiet = 4) {
const n = code.size + quiet * 2
const w = n * scale
const data = new Uint8ClampedArray(w * w * 4)
for (let y = 0; y < w; y++) {
for (let x = 0; x < w; x++) {
const mx = Math.floor(x / scale) - quiet, my = Math.floor(y / scale) - quiet
const dark = mx >= 0 && my >= 0 && mx < code.size && my < code.size && code.get(mx, my)
const v = dark ? 0 : 255
const i = (y * w + x) * 4
data[i] = v; data[i + 1] = v; data[i + 2] = v; data[i + 3] = 255
}
}
return { data, width: w, height: w }
}
describe('decodeImageData', () => {
it('reads back a code lean-qr generated', async () => {
const value = 'MEMBER-0042-FITZONE'
const hit = await decodeImageData(rasterize(generate(value)))
expect(hit).toEqual({ value, fmt: 'qrcode' })
})
it('reads a URL-shaped code, the other common gym format', async () => {
const value = 'https://checkin.example.com/m/8f3a1c?v=2'
const hit = await decodeImageData(rasterize(generate(value)))
expect(hit?.value).toBe(value)
})
it('returns null for blank pixels and for junk input', async () => {
const blank = { data: new Uint8ClampedArray(64 * 64 * 4).fill(255), width: 64, height: 64 }
expect(await decodeImageData(blank)).toBeNull()
expect(await decodeImageData(null)).toBeNull()
expect(await decodeImageData({ data: null, width: 1, height: 1 })).toBeNull()
})
})
+112
View File
@@ -0,0 +1,112 @@
// Capturing a gym check-in code (see views/CheckIn.jsx). Three ways in:
// 1. type it — no plugin, handled entirely in the view
// 2. import a photo — importCodeFromImage(file): decode a picture the user already has
// 3. scan with camera — scanCode(): live camera via ML Kit's own scanner UI (app build);
// in a browser the view opens components/CameraScan.jsx instead
//
// The app build (MOBILE) decodes with @capacitor-mlkit/barcode-scanning (Apache-2.0, see
// NOTICE.md), dynamic-imported so it never lands in the web bundle. In a browser — the PWA on a
// phone is the common case — photo import goes through lib/scan-web.js (BarcodeDetector where the
// browser has one, jsQR otherwise). scanCode() itself is app-only: ML Kit brings its own camera
// UI, the browser path is a React sheet and lives with the view.
//
// What comes back is a normalized { value, fmt } (or null when the user cancels / nothing was
// found). `value` is the code's machine-readable content; `fmt` is a lower-cased symbology token
// matching lib/qr.js's normalizeFmt. The caller checks canRenderFmt(fmt) before saving — we can
// read many barcode kinds but only redraw QR, so a non-QR code is reported and refused there, not
// silently stored.
import { MOBILE } from './mobile.js'
import { normalizeFmt } from './qr.js'
// A found barcode from either path → our stored shape. mlkit gives rawValue (machine-readable,
// what a turnstile actually reads) and a BarcodeFormat; we keep rawValue and fold the format.
function toCode(barcode) {
if (!barcode) return null
const value = barcode.rawValue || barcode.displayValue || ''
if (!value) return null
return { value, fmt: normalizeFmt(barcode.format) }
}
// Live camera scan. On Android this opens Google's own full-screen scanner UI (no camera view we
// have to host); on iOS the plugin's native scanner. Returns the first barcode found, or null if
// the user backed out without scanning. Throws if scanning isn't supported or permission is hard-
// denied so the caller can explain why.
export async function scanCode() {
if (!MOBILE) throw new Error('Scanning is only available in the app')
const { BarcodeScanner } = await import('@capacitor-mlkit/barcode-scanning')
const { supported } = await BarcodeScanner.isSupported()
if (!supported) throw new Error('unsupported')
await ensureCameraPermission(BarcodeScanner)
await ensureScannerModule(BarcodeScanner)
const { barcodes } = await BarcodeScanner.scan()
return barcodes && barcodes.length ? toCode(barcodes[0]) : null
}
// Decode a barcode out of an image the user picked. mlkit's readBarcodesFromImage wants a local
// file PATH, and a browser <input type=file> only hands us a File/blob — so we bounce the bytes
// through the app's cache dir (reusing @capacitor/filesystem, already a dependency) to get a real
// path, decode, then delete the temp file. Returns the first barcode, or null if none was found.
export async function importCodeFromImage(file) {
if (!file) return null
if (!MOBILE) return (await import('./scan-web.js')).importCodeFromImageWeb(file)
const { BarcodeScanner } = await import('@capacitor-mlkit/barcode-scanning')
const { Filesystem, Directory } = await import('@capacitor/filesystem')
const base64 = await fileToBase64(file)
const name = `checkin-import-${Date.now()}.${extOf(file.name)}`
let uri = null
try {
const w = await Filesystem.writeFile({ path: name, directory: Directory.Cache, data: base64 })
uri = w.uri
const { barcodes } = await BarcodeScanner.readBarcodesFromImage({ path: uri })
return barcodes && barcodes.length ? toCode(barcodes[0]) : null
} finally {
// Best effort — a leftover temp image in the cache dir is harmless, but tidy up anyway.
try { await Filesystem.deleteFile({ path: name, directory: Directory.Cache }) } catch (e) { /* */ }
}
}
// Camera permission for the live scanner. checkPermissions first so an already-granted user never
// sees a prompt; request only when needed. A hard denial throws so the caller can point the user
// at Settings rather than silently doing nothing.
async function ensureCameraPermission(BarcodeScanner) {
let { camera } = await BarcodeScanner.checkPermissions()
if (camera !== 'granted' && camera !== 'limited') {
({ camera } = await BarcodeScanner.requestPermissions())
}
if (camera !== 'granted' && camera !== 'limited') throw new Error('permission-denied')
}
// On Android the ML Kit scanner ships as an on-demand Google Play module, absent on first use.
// Install it (once) before scanning; a no-op / not-applicable on iOS, where the check simply
// reports available. Failures here are non-fatal — scan() will surface a clearer error if it
// truly can't proceed.
async function ensureScannerModule(BarcodeScanner) {
try {
if (!BarcodeScanner.isGoogleBarcodeScannerModuleAvailable) return
const { available } = await BarcodeScanner.isGoogleBarcodeScannerModuleAvailable()
if (!available) await BarcodeScanner.installGoogleBarcodeScannerModule()
} catch (e) { /* let scan() decide whether it can still run */ }
}
// A File/Blob → bare base64 (no data: prefix), which Filesystem.writeFile expects.
function fileToBase64(file) {
return new Promise((resolve, reject) => {
const r = new FileReader()
r.onerror = () => reject(r.error || new Error('read failed'))
r.onload = () => {
const s = String(r.result || '')
const comma = s.indexOf(',')
resolve(comma === -1 ? s : s.slice(comma + 1))
}
r.readAsDataURL(file)
})
}
function extOf(filename) {
const m = /\.([a-z0-9]+)$/i.exec(filename || '')
return m ? m[1].toLowerCase() : 'jpg'
}
+17
View File
@@ -0,0 +1,17 @@
import { describe, it, expect } from 'vitest'
import { scanCode, importCodeFromImage } from './scan.js'
// In the test environment VITE_MOBILE is unset, so MOBILE is false — the same as a web build.
// The native ML Kit scanner must refuse to run there rather than reach for a plugin that isn't
// present; the view opens the browser camera sheet instead. (On-device decoding is exercised by
// hand; the browser decoder has its own round-trip test in scan-web.test.js.)
describe('scan off mobile', () => {
it('scanCode rejects — the native scanner is app-only', async () => {
await expect(scanCode()).rejects.toThrow(/only available in the app/)
})
it('importCodeFromImage takes the browser path and is a no-op without a file', async () => {
expect(await importCodeFromImage(null)).toBeNull()
})
})
+1 -1
View File
@@ -14,7 +14,7 @@ export function buildSessionEntries(st, r) {
const entries = (r ? r.ex : []).map(cfg => {
const plan = excluded ? { policy: 'off', kind: 'off' } : nextPrescription(st, cfg, r)
const step = defaultIncrement(cfg.id, st.unit)
const sets = applyIntensifierPlan(applyPrescription(buildSets(st, cfg, { step, useTarget: excluded }), plan, step), cfg)
const sets = applyIntensifierPlan(applyPrescription(buildSets(st, cfg, { step, useTarget: plan.kind === 'off' }), plan, step), cfg)
return { id: cfg.id, sg: cfg.sg, target: { ...cfg }, plan, sets }
})
return { entries, excluded }
+64 -9
View File
@@ -1,13 +1,68 @@
// The Push/Pull/Legs starter plan. Shared by the "Load starter plan" action in Settings
// and by the demo build, which seeds a history on top of exactly these routines.
// The starter-plan catalog. Training data only: the chooser's plan names and descriptions are
// written as string literals inside t() calls in sheets.jsx, because check-source-strings.mjs
// only finds them there — copy parked in here would silently ship English in every language.
//
// A routine is [key, name, emoji, [[exerciseId, sets, reps], …]]. The key is what a plan's
// schedule points at, so a weekday never depends on the position of a routine in the array.
// Names stay canonical English — they become ordinary user routines, which are not translated.
import { uid } from './format.js'
const SPEC = [
['Push Day', 'barbell', [['0025', 4, 8], ['0047', 3, 10], ['0426', 3, 10], ['0334', 3, 12], ['0241', 3, 12], ['0251', 3, 10]]],
['Pull Day', 'pullup', [['2330', 4, 10], ['0027', 4, 8], ['1323', 3, 10], ['0031', 3, 10], ['0313', 3, 12]]],
['Leg Day', 'legs', [['0043', 4, 8], ['0085', 3, 10], ['0739', 3, 12], ['0585', 3, 12], ['0586', 3, 12], ['0605', 4, 15]]]
const PPL = [
['push', 'Push Day', 'barbell', [['0025', 4, 8], ['0047', 3, 10], ['0426', 3, 10], ['0334', 3, 12], ['0241', 3, 12], ['0251', 3, 10]]],
['pull', 'Pull Day', 'pullup', [['2330', 4, 10], ['0027', 4, 8], ['1323', 3, 10], ['0031', 3, 10], ['0313', 3, 12]]],
['legs', 'Leg Day', 'legs', [['0043', 4, 8], ['0085', 3, 10], ['0739', 3, 12], ['0585', 3, 12], ['0586', 3, 12], ['0605', 4, 15]]]
]
// Fresh routine objects (new ids) — [push, pull, legs].
export const starterRoutines = () =>
SPEC.map(([name, emoji, list]) => ({ id: uid(), name, emoji, ex: list.map(([id, sets, reps]) => ({ id, sets, reps, weight: 0 })) }))
const UPPER_LOWER = [
['upper-a', 'Upper A', 'barbell', [['0025', 3, 8], ['2330', 3, 10], ['0047', 2, 10], ['1323', 2, 10], ['0334', 2, 12], ['0241', 2, 12], ['0031', 2, 12]]],
['lower-a', 'Lower A', 'legs', [['0043', 3, 8], ['0085', 3, 8], ['0739', 2, 10], ['0586', 2, 12], ['0605', 3, 15]]],
['upper-b', 'Upper B', 'barbell', [['0047', 3, 8], ['0027', 3, 8], ['0426', 2, 10], ['2330', 2, 10], ['0334', 2, 12], ['0241', 2, 12], ['0313', 2, 12]]],
['lower-b', 'Lower B', 'legs', [['0739', 3, 10], ['0085', 2, 10], ['0585', 2, 12], ['0586', 3, 12], ['0605', 3, 15]]]
]
const FULL_BODY = [
['fb-a', 'Full Body A', 'figureStrength', [['0043', 3, 8], ['0025', 3, 8], ['2330', 3, 10], ['0586', 3, 12], ['0334', 2, 12], ['0031', 2, 12]]],
['fb-b', 'Full Body B', 'figureStrength', [['0085', 3, 8], ['0047', 3, 10], ['1323', 3, 10], ['0585', 3, 12], ['0334', 2, 12], ['0241', 2, 12]]],
['fb-c', 'Full Body C', 'figureStrength', [['0739', 3, 10], ['0025', 2, 10], ['0027', 3, 10], ['0426', 2, 10], ['0586', 3, 12], ['0605', 3, 15]]]
]
const FIVE_BY_FIVE = [
['5x5-a', '5×5 A', 'barbell', [['0043', 5, 5], ['0025', 5, 5], ['0027', 5, 5]]],
['5x5-b', '5×5 B', 'barbell', [['0085', 5, 5], ['0426', 5, 5], ['2330', 5, 5]]],
['5x5-c', '5×5 C', 'barbell', [['0739', 5, 5], ['0047', 5, 5], ['1323', 5, 5]]]
]
// [weekday, routineKey] — weekday is a DAYN index, so 1 is Monday. Fixed weeks only: every
// plan repeats the same seven days, which is all the weekly plan model can represent.
const PLANS = {
ppl: { routines: PPL, schedule: [[1, 'push'], [3, 'pull'], [5, 'legs']] },
'upper-lower': { routines: UPPER_LOWER, schedule: [[1, 'upper-a'], [2, 'lower-a'], [4, 'upper-b'], [5, 'lower-b']] },
'full-body': { routines: FULL_BODY, schedule: [[1, 'fb-a'], [3, 'fb-b'], [5, 'fb-c']] },
'5x5': { routines: FIVE_BY_FIVE, schedule: [[1, '5x5-a'], [3, '5x5-b'], [5, '5x5-c']] }
}
const build = routines =>
routines.map(([, name, emoji, list]) => ({ id: uid(), name, emoji, ex: list.map(([id, sets, reps]) => ({ id, sets, reps, weight: 0 })) }))
// Fresh routine objects (new ids) — [push, pull, legs]. The demo build seeds a history on
// top of exactly these three, so this entry point keeps its shape.
export const starterRoutines = () => build(PPL)
// [{ id, days }] for the chooser. The day count is read off the schedule rather than stored
// beside it, so the two can never disagree.
export const starterPlanOptions = () =>
Object.entries(PLANS).map(([id, { schedule }]) => ({ id, days: schedule.length }))
// The weekdays a plan would claim, or null for an unknown id.
export const starterPlanDays = id => PLANS[id]?.schedule.map(([day]) => day) ?? null
// Fresh routines plus the weekdays to put them on, or null for an unknown id — a caller that
// treats null as "change nothing" can never half-apply a plan.
export const buildStarterPlan = id => {
const plan = PLANS[id]
if (!plan) return null
const routines = build(plan.routines)
// key → the id just minted for it, so the schedule below names its routine
const byKey = Object.fromEntries(plan.routines.map(([key], i) => [key, routines[i].id]))
return { routines, schedule: plan.schedule.map(([day, key]) => ({ day, routineId: byKey[key] })) }
}
+104
View File
@@ -0,0 +1,104 @@
import { describe, expect, it } from 'vitest'
import { EXIDX } from './exercises.js'
import { buildStarterPlan, starterPlanDays, starterPlanOptions, starterRoutines } from './starter.js'
// The approved prescription, written out again rather than imported: a test that reads the
// same table as the code would pass no matter what that table said. [weekday, name, sets].
const APPROVED = {
ppl: [
[1, 'Push Day', [['0025', 4, 8], ['0047', 3, 10], ['0426', 3, 10], ['0334', 3, 12], ['0241', 3, 12], ['0251', 3, 10]]],
[3, 'Pull Day', [['2330', 4, 10], ['0027', 4, 8], ['1323', 3, 10], ['0031', 3, 10], ['0313', 3, 12]]],
[5, 'Leg Day', [['0043', 4, 8], ['0085', 3, 10], ['0739', 3, 12], ['0585', 3, 12], ['0586', 3, 12], ['0605', 4, 15]]],
],
'upper-lower': [
[1, 'Upper A', [['0025', 3, 8], ['2330', 3, 10], ['0047', 2, 10], ['1323', 2, 10], ['0334', 2, 12], ['0241', 2, 12], ['0031', 2, 12]]],
[2, 'Lower A', [['0043', 3, 8], ['0085', 3, 8], ['0739', 2, 10], ['0586', 2, 12], ['0605', 3, 15]]],
[4, 'Upper B', [['0047', 3, 8], ['0027', 3, 8], ['0426', 2, 10], ['2330', 2, 10], ['0334', 2, 12], ['0241', 2, 12], ['0313', 2, 12]]],
[5, 'Lower B', [['0739', 3, 10], ['0085', 2, 10], ['0585', 2, 12], ['0586', 3, 12], ['0605', 3, 15]]],
],
'full-body': [
[1, 'Full Body A', [['0043', 3, 8], ['0025', 3, 8], ['2330', 3, 10], ['0586', 3, 12], ['0334', 2, 12], ['0031', 2, 12]]],
[3, 'Full Body B', [['0085', 3, 8], ['0047', 3, 10], ['1323', 3, 10], ['0585', 3, 12], ['0334', 2, 12], ['0241', 2, 12]]],
[5, 'Full Body C', [['0739', 3, 10], ['0025', 2, 10], ['0027', 3, 10], ['0426', 2, 10], ['0586', 3, 12], ['0605', 3, 15]]],
],
'5x5': [
[1, '5×5 A', [['0043', 5, 5], ['0025', 5, 5], ['0027', 5, 5]]],
[3, '5×5 B', [['0085', 5, 5], ['0426', 5, 5], ['2330', 5, 5]]],
[5, '5×5 C', [['0739', 5, 5], ['0047', 5, 5], ['1323', 5, 5]]],
],
}
const shape = r => r.ex.map(e => [e.id, e.sets, e.reps])
describe('starter plan catalog', () => {
it('offers exactly the four plans, with the day count read off the schedule', () => {
expect(starterPlanOptions()).toEqual([
{ id: 'ppl', days: 3 }, { id: 'upper-lower', days: 4 },
{ id: 'full-body', days: 3 }, { id: '5x5', days: 3 },
])
for (const { id, days } of starterPlanOptions()) expect(starterPlanDays(id)).toHaveLength(days)
})
it('changes nothing for an unknown plan id', () => {
expect(buildStarterPlan('nope')).toBeNull()
expect(buildStarterPlan(undefined)).toBeNull()
// A click handler wired straight to a loader would hand the event in as the plan.
expect(buildStarterPlan({ type: 'click' })).toBeNull()
expect(starterPlanDays('nope')).toBeNull()
})
})
describe.each(Object.keys(APPROVED))('%s', planId => {
const approved = APPROVED[planId]
it('builds the approved exercises, sets and reps in order', () => {
const { routines } = buildStarterPlan(planId)
expect(routines.map(r => r.name)).toEqual(approved.map(([, name]) => name))
routines.forEach((r, i) => expect(shape(r)).toEqual(approved[i][2]))
})
it('puts each routine on its approved weekday, by identity not position', () => {
const { routines, schedule } = buildStarterPlan(planId)
const nameOf = Object.fromEntries(routines.map(r => [r.id, r.name]))
expect(schedule.map(({ day, routineId }) => [day, nameOf[routineId]]))
.toEqual(approved.map(([day, name]) => [day, name]))
})
it('references only real exercises and starts every one at weight 0', () => {
for (const r of buildStarterPlan(planId).routines) {
for (const e of r.ex) {
expect(EXIDX[e.id], e.id).toBeTruthy()
expect(e.sets).toBeGreaterThan(0)
expect(e.reps).toBeGreaterThan(0)
expect(e.weight).toBe(0)
}
}
})
it('mints fresh ids and independent objects on every build', () => {
const first = buildStarterPlan(planId)
const second = buildStarterPlan(planId)
const ids = first.routines.map(r => r.id)
expect(new Set(ids).size).toBe(ids.length)
expect(second.routines.some(r => ids.includes(r.id))).toBe(false)
expect(first.routines[0].ex[0]).not.toBe(second.routines[0].ex[0])
// and the static definition survives a caller mutating what it got back
first.routines[0].ex[0].sets = 99
expect(buildStarterPlan(planId).routines[0].ex[0].sets).toBe(approved[0][2][0][1])
})
})
describe('starterRoutines (the demo build entry point)', () => {
it('still returns push, pull and legs unchanged', () => {
const routines = starterRoutines()
expect(routines.map(r => r.name)).toEqual(['Push Day', 'Pull Day', 'Leg Day'])
routines.forEach((r, i) => expect(shape(r)).toEqual(APPROVED.ppl[i][2]))
expect(routines.map(r => r.emoji)).toEqual(['barbell', 'pullup', 'legs'])
})
it('mints fresh ids on every invocation', () => {
const first = starterRoutines().map(r => r.id)
const second = starterRoutines().map(r => r.id)
expect(new Set([...first, ...second]).size).toBe(6)
})
})
+61 -4
View File
@@ -24,6 +24,13 @@ export default {
'Resume': 'Weiter',
'Stats': 'Statistik',
'Exercises': 'Übungen',
'By muscle': 'Nach Muskel',
'Explore muscles': 'Muskeln entdecken',
'Choose a muscle to see exercises that train it.': 'Wähle einen Muskel, um Übungen zu sehen, die ihn trainieren.',
'Exercises for {0}': 'Übungen für {0}',
'Clear selection': 'Auswahl aufheben',
'Primary target': 'Hauptmuskel',
'Also trains': 'Trainiert auch',
'History': 'Verlauf',
'Settings': 'Einstellungen',
'Freestyle': 'Freies Training',
@@ -210,8 +217,22 @@ export default {
'{0} — in progress': '{0} — läuft',
'Resume ▶': 'Weiter ▶',
'Welcome!': 'Willkommen!',
'Set up your weekly routine to get going — or load a ready-made Push / Pull / Legs plan.': 'Richte deinen Wochenplan ein — oder lade einen fertigen Push-/Pull-/Beine-Plan.',
'Load starter plan (PPL)': 'Starterplan laden (PPL)',
'Set up your weekly routine to get going — or load a ready-made starter plan.': 'Richte deinen Wochenplan ein — oder lade einen fertigen Starterplan.',
'Load starter plan': 'Starterplan laden',
'Choose starter plan': 'Starterplan wählen',
'{0} days per week': '{0} Tage pro Woche',
'{0} loaded': '{0} geladen',
'Load {0}?': '{0} laden?',
'Load plan': 'Plan laden',
'The new plan will be scheduled on {0}. Existing routines are kept — only those days of the weekly plan change.': 'Der neue Plan kommt auf {0}. Deine Routinen bleiben alle erhalten — nur diese Tage im Wochenplan ändern sich.',
'Push / Pull / Legs': 'Push / Pull / Beine',
'Push, pull and legs each get their own day.': 'Drücken, Ziehen und Beine an je eigenen Tagen.',
'Upper / Lower': 'Oberkörper / Unterkörper',
'Upper body twice, lower body twice.': 'Oberkörper zweimal, Unterkörper zweimal.',
'Full Body': 'Ganzkörper',
'Three sessions, the whole body each time.': 'Drei Einheiten, jedes Mal der ganze Körper.',
'5×5': '5×5',
'Five sets of five on the main barbell lifts.': 'Fünf Sätze à fünf bei den großen Langhantelübungen.',
'Build my own plan': 'Eigenen Plan erstellen',
'{0} week streak': '{0} Wochen in Folge',
'this week': 'diese Woche',
@@ -238,7 +259,6 @@ export default {
'Week schedule': 'Wochenplan',
'No routines yet.': 'Noch keine Routinen.',
'Create one or load the starter plan.': 'Erstelle eine oder lade den Starterplan.',
'Load starter plan (Push / Pull / Legs)': 'Starterplan laden (Push / Pull / Beine)',
// --- routine edit ---
'Superset with exercise above': 'Supersatz mit der Übung darüber',
'Note (optional) — loading cues, "bar only then +1 plate/side each set", anything worth remembering here': 'Notiz (optional) — Hinweise zur Belastung, z. B. „nur die Stange, dann pro Satz +1 Scheibe pro Seite“, was immer du dir merken willst',
@@ -247,11 +267,12 @@ export default {
'Delete routine?': 'Routine löschen?',
'“{0}” and its exercises will be removed.': '„{0}“ und ihre Übungen werden entfernt.',
'Delete routine': 'Routine löschen',
'Copy routine': 'Routine kopieren',
'Copy': 'Kopie',
// --- library / history ---
'{0} exercises with animations': '{0} Übungen mit Animationen',
'Search…': 'Suchen…',
'No workouts yet.': 'Noch keine Trainings.',
'Starter plan loaded — Mon Push · Wed Pull · Fri Legs': 'Starterplan geladen — Mo Push · Mi Pull · Fr Beine',
// --- login / account ---
'Enter a name': 'Gib einen Namen ein',
'Profile created — data from this device moved into it': 'Profil erstellt — Daten von diesem Gerät wurden übernommen',
@@ -412,6 +433,12 @@ export default {
'Minimize': 'Verkleinern',
'Expand': 'Vergrössern',
'Exercise animations': 'Übungs-Animationen',
'Workout view': 'Trainingsansicht',
'Cards': 'Karten',
'List': 'Liste',
'Current': 'Aktuell',
'Set current': 'Als aktuell markieren',
'Move, swap and remove below act on the exercise marked {0}.': 'Verschieben, Tauschen und Entfernen unten wirken auf die als {0} markierte Übung.',
'Full': 'Gross',
'Small': 'Klein',
'Hidden': 'Versteckt',
@@ -1099,4 +1126,34 @@ export default {
'Set to 0 to go back to the default ({0}).': 'Auf 0 stellen, um zum Standard ({0}) zurückzukehren.',
'Applies to this exercise everywhere, not just this plan.': 'Gilt überall für diese Übung, nicht nur in diesem Plan.',
'You still log the total weight — the bar only feeds the per-side plate math.': 'Eingetragen wird weiterhin das Gesamtgewicht — die Stange zählt nur für die Scheiben-Rechnung pro Seite.',
// Gym check-in (mobile-only)
'Check in': 'Einchecken',
'At the gym': 'Im Studio',
'Show this at the gym': 'Im Studio vorzeigen',
'Add your gym card': 'Studio-Karte hinzufügen',
'Add a card': 'Karte hinzufügen',
'Type the number on your membership card, import a photo of it, or scan it with the camera. No extra app needed at the gym — just open this screen.': 'Tippe die Nummer deiner Mitgliedskarte ein, importiere ein Foto oder scanne sie mit der Kamera. Keine zusätzliche App im Studio nötig — öffne einfach diesen Bildschirm.',
'Remove this card?': 'Diese Karte entfernen?',
'Scan it, import a photo, or type the code by hand.': 'Scanne sie, importiere ein Foto oder tippe den Code von Hand ein.',
'Scan': 'Scannen',
'Import photo': 'Foto importieren',
'Label': 'Bezeichnung',
'e.g. FitZone downtown': 'z. B. FitZone Zentrum',
'Code': 'Code',
'Membership number or code': 'Mitgliedsnummer oder Code',
'Save card': 'Karte speichern',
'Gym card': 'Studio-Karte',
'Card added': 'Karte hinzugefügt',
'Nothing to save yet': 'Noch nichts zu speichern',
"That's not a QR code — only QR cards can be shown here": 'Das ist kein QR-Code — hier lassen sich nur QR-Karten anzeigen',
'No QR code found in that image': 'Kein QR-Code im Bild gefunden',
'Could not read that image': 'Bild konnte nicht gelesen werden',
'Camera permission is needed to scan. Enable it in Settings.': 'Zum Scannen wird die Kamera-Berechtigung benötigt. Aktiviere sie in den Einstellungen.',
'Scanning is not available on this device.': 'Scannen ist auf diesem Gerät nicht verfügbar.',
'Could not start the scanner': 'Scanner konnte nicht gestartet werden',
'Gym check-in': 'Gym-Check-in',
'Show a card on Home with your membership QR codes.': 'Zeigt auf Start eine Karte mit deinen Mitglieds-QR-Codes.',
'Point the camera at the QR code': 'Richte die Kamera auf den QR-Code',
'Camera is not available here — import a photo or type the code instead.': 'Die Kamera ist hier nicht verfügbar — importiere ein Foto oder tippe den Code ein.',
'Camera access was denied — allow it in your browser and try again.': 'Kamerazugriff wurde verweigert — erlaube ihn im Browser und versuche es erneut.',
}
+61 -4
View File
@@ -23,6 +23,13 @@ export default {
'Resume': 'Seguir',
'Stats': 'Progreso',
'Exercises': 'Ejercicios',
'By muscle': 'Por músculo',
'Explore muscles': 'Explorar músculos',
'Choose a muscle to see exercises that train it.': 'Elige un músculo para ver los ejercicios que lo entrenan.',
'Exercises for {0}': 'Ejercicios para {0}',
'Clear selection': 'Borrar selección',
'Primary target': 'Músculo principal',
'Also trains': 'También trabaja',
'History': 'Historial',
'Settings': 'Ajustes',
'Freestyle': 'Libre',
@@ -202,8 +209,22 @@ export default {
'{0} — in progress': '{0} — en curso',
'Resume ▶': 'Seguir ▶',
'Welcome!': '¡Bienvenido!',
'Set up your weekly routine to get going — or load a ready-made Push / Pull / Legs plan.': 'Configura tu rutina semanal para empezar — o carga un plan Push / Pull / Piernas ya hecho.',
'Load starter plan (PPL)': 'Cargar plan inicial (PPL)',
'Set up your weekly routine to get going — or load a ready-made starter plan.': 'Configura tu rutina semanal para empezar — o carga un plan inicial ya hecho.',
'Load starter plan': 'Cargar plan inicial',
'Choose starter plan': 'Elige un plan inicial',
'{0} days per week': '{0} días por semana',
'{0} loaded': '{0} cargado',
'Load {0}?': '¿Cargar {0}?',
'Load plan': 'Cargar plan',
'The new plan will be scheduled on {0}. Existing routines are kept — only those days of the weekly plan change.': 'El nuevo plan se programará en {0}. Tus rutinas se conservan — solo cambian esos días del plan semanal.',
'Push / Pull / Legs': 'Push / Pull / Piernas',
'Push, pull and legs each get their own day.': 'Empuje, tirón y piernas, cada uno en su día.',
'Upper / Lower': 'Superior / Inferior',
'Upper body twice, lower body twice.': 'Tren superior dos veces, tren inferior dos veces.',
'Full Body': 'Cuerpo completo',
'Three sessions, the whole body each time.': 'Tres sesiones, todo el cuerpo en cada una.',
'5×5': '5×5',
'Five sets of five on the main barbell lifts.': 'Cinco series de cinco en los básicos con barra.',
'Build my own plan': 'Crear mi propio plan',
'{0} week streak': 'racha de {0} semanas',
'this week': 'esta semana',
@@ -228,7 +249,6 @@ export default {
'Week schedule': 'Horario semanal',
'No routines yet.': 'Aún no hay rutinas.',
'Create one or load the starter plan.': 'Crea una o carga el plan inicial.',
'Load starter plan (Push / Pull / Legs)': 'Cargar plan inicial (Push / Pull / Piernas)',
'Superset with exercise above': 'Superserie con el ejercicio de arriba',
'Note (optional) — loading cues, "bar only then +1 plate/side each set", anything worth remembering here': 'Nota (opcional) — indicaciones de carga, ej. «solo barra y +1 disco por lado en cada serie», lo que quieras recordar',
'No exercises yet — add your first one.': 'Aún no hay ejercicios — añade el primero.',
@@ -236,10 +256,11 @@ export default {
'Delete routine?': '¿Eliminar rutina?',
'“{0}” and its exercises will be removed.': '«{0}» y sus ejercicios se eliminarán.',
'Delete routine': 'Eliminar rutina',
'Copy routine': 'Copiar rutina',
'Copy': 'Copia',
'{0} exercises with animations': '{0} ejercicios con animaciones',
'Search…': 'Buscar…',
'No workouts yet.': 'Aún no hay entrenamientos.',
'Starter plan loaded — Mon Push · Wed Pull · Fri Legs': 'Plan inicial cargado — Lun Push · Mié Pull · Vie Piernas',
'Enter a name': 'Introduce un nombre',
'Profile created — data from this device moved into it': 'Perfil creado — los datos de este dispositivo se han movido a él',
'Profile created — data moved into it': 'Perfil creado — datos movidos a él',
@@ -394,6 +415,12 @@ export default {
'Minimize': 'Minimizar',
'Expand': 'Ampliar',
'Exercise animations': 'Animaciones de los ejercicios',
'Workout view': 'Vista del entrenamiento',
'Cards': 'Tarjetas',
'List': 'Lista',
'Current': 'Actual',
'Set current': 'Marcar actual',
'Move, swap and remove below act on the exercise marked {0}.': 'Mover, cambiar y eliminar actúan sobre el ejercicio marcado como {0}.',
'Full': 'Completa',
'Small': 'Pequeña',
'Hidden': 'Oculta',
@@ -1080,4 +1107,34 @@ export default {
'Set to 0 to go back to the default ({0}).': 'Pon 0 para volver al valor por defecto ({0}).',
'Applies to this exercise everywhere, not just this plan.': 'Se aplica a este ejercicio en todas partes, no solo en este plan.',
'You still log the total weight — the bar only feeds the per-side plate math.': 'Sigues registrando el peso total — la barra solo se usa para calcular los discos por lado.',
// Gym check-in (mobile-only)
'Check in': 'Registrarse',
'At the gym': 'En el gimnasio',
'Show this at the gym': 'Muestra esto en el gimnasio',
'Add your gym card': 'Añade tu tarjeta del gimnasio',
'Add a card': 'Añadir una tarjeta',
'Type the number on your membership card, import a photo of it, or scan it with the camera. No extra app needed at the gym — just open this screen.': 'Escribe el número de tu tarjeta de socio, importa una foto o escanéala con la cámara. No hace falta otra app en el gimnasio — solo abre esta pantalla.',
'Remove this card?': '¿Eliminar esta tarjeta?',
'Scan it, import a photo, or type the code by hand.': 'Escanéala, importa una foto o escribe el código a mano.',
'Scan': 'Escanear',
'Import photo': 'Importar foto',
'Label': 'Etiqueta',
'e.g. FitZone downtown': 'p. ej. FitZone centro',
'Code': 'Código',
'Membership number or code': 'Número de socio o código',
'Save card': 'Guardar tarjeta',
'Gym card': 'Tarjeta del gimnasio',
'Card added': 'Tarjeta añadida',
'Nothing to save yet': 'Nada que guardar todavía',
"That's not a QR code — only QR cards can be shown here": 'Eso no es un código QR — aquí solo se pueden mostrar tarjetas QR',
'No QR code found in that image': 'No se encontró ningún código QR en esa imagen',
'Could not read that image': 'No se pudo leer esa imagen',
'Camera permission is needed to scan. Enable it in Settings.': 'Se necesita permiso de cámara para escanear. Actívalo en Ajustes.',
'Scanning is not available on this device.': 'El escaneo no está disponible en este dispositivo.',
'Could not start the scanner': 'No se pudo iniciar el escáner',
'Gym check-in': 'Check-in del gimnasio',
'Show a card on Home with your membership QR codes.': 'Muestra en Inicio una tarjeta con tus códigos QR de socio.',
'Point the camera at the QR code': 'Apunta la cámara al código QR',
'Camera is not available here — import a photo or type the code instead.': 'La cámara no está disponible aquí — importa una foto o escribe el código.',
'Camera access was denied — allow it in your browser and try again.': 'Se denegó el acceso a la cámara — permítelo en el navegador e inténtalo de nuevo.',
}
+61 -4
View File
@@ -23,6 +23,13 @@ export default {
'Resume': 'Reprendre',
'Stats': 'Stats',
'Exercises': 'Exercices',
'By muscle': 'Par muscle',
'Explore muscles': 'Explorer les muscles',
'Choose a muscle to see exercises that train it.': 'Choisissez un muscle pour voir les exercices qui le sollicitent.',
'Exercises for {0}': 'Exercices pour {0}',
'Clear selection': 'Effacer la sélection',
'Primary target': 'Cible principale',
'Also trains': 'Sollicite aussi',
'History': 'Historique',
'Settings': 'Réglages',
'Freestyle': 'Libre',
@@ -202,8 +209,22 @@ export default {
'{0} — in progress': '{0} — en cours',
'Resume ▶': 'Reprendre ▶',
'Welcome!': 'Bienvenue !',
'Set up your weekly routine to get going — or load a ready-made Push / Pull / Legs plan.': 'Configure ta routine hebdo pour commencer — ou charge un plan Push / Pull / Jambes tout prêt.',
'Load starter plan (PPL)': 'Charger le plan de départ (PPL)',
'Set up your weekly routine to get going — or load a ready-made starter plan.': 'Configure ta routine hebdo pour commencer — ou charge un plan de départ tout prêt.',
'Load starter plan': 'Charger un plan de départ',
'Choose starter plan': 'Choisis un plan de départ',
'{0} days per week': '{0} jours par semaine',
'{0} loaded': '{0} chargé',
'Load {0}?': 'Charger {0} ?',
'Load plan': 'Charger le plan',
'The new plan will be scheduled on {0}. Existing routines are kept — only those days of the weekly plan change.': 'Le nouveau plan sera placé sur {0}. Tes routines sont toutes conservées — seuls ces jours du plan hebdo changent.',
'Push / Pull / Legs': 'Push / Pull / Jambes',
'Push, pull and legs each get their own day.': 'Poussée, tirage et jambes, chacun son jour.',
'Upper / Lower': 'Haut / Bas',
'Upper body twice, lower body twice.': 'Haut du corps deux fois, bas du corps deux fois.',
'Full Body': 'Corps entier',
'Three sessions, the whole body each time.': 'Trois séances, tout le corps à chaque fois.',
'5×5': '5×5',
'Five sets of five on the main barbell lifts.': 'Cinq séries de cinq sur les gros mouvements à la barre.',
'Build my own plan': 'Créer mon propre plan',
'{0} week streak': 'série de {0} semaines',
'this week': 'cette semaine',
@@ -228,7 +249,6 @@ export default {
'Week schedule': 'Planning de la semaine',
'No routines yet.': 'Aucune routine pour l’instant.',
'Create one or load the starter plan.': 'Crées-en une ou charge le plan de départ.',
'Load starter plan (Push / Pull / Legs)': 'Charger le plan de départ (Push / Pull / Jambes)',
'Superset with exercise above': "Superset avec l'exercice au-dessus",
'Note (optional) — loading cues, "bar only then +1 plate/side each set", anything worth remembering here': 'Note (optionnelle) — indications de charge, ex. « barre seule puis +1 disque par côté à chaque série », tout ce que tu veux te rappeler',
'No exercises yet — add your first one.': 'Aucun exercice — ajoute le premier.',
@@ -236,10 +256,11 @@ export default {
'Delete routine?': 'Supprimer la routine ?',
'“{0}” and its exercises will be removed.': '« {0} » et ses exercices seront supprimés.',
'Delete routine': 'Supprimer la routine',
'Copy routine': 'Copier la routine',
'Copy': 'Copie',
'{0} exercises with animations': '{0} exercices avec animations',
'Search…': 'Rechercher…',
'No workouts yet.': 'Aucune séance pour l’instant.',
'Starter plan loaded — Mon Push · Wed Pull · Fri Legs': 'Plan de départ chargé — Lun Push · Mer Pull · Ven Jambes',
'Enter a name': 'Entre un nom',
'Profile created — data from this device moved into it': 'Profil créé — les données de cet appareil y ont été transférées',
'Profile created — data moved into it': 'Profil créé — données transférées',
@@ -394,6 +415,12 @@ export default {
'Minimize': 'Réduire',
'Expand': 'Agrandir',
'Exercise animations': 'Animations des exercices',
'Workout view': 'Vue de l’entraînement',
'Cards': 'Cartes',
'List': 'Liste',
'Current': 'En cours',
'Set current': 'Marquer comme en cours',
'Move, swap and remove below act on the exercise marked {0}.': 'Déplacer, échanger et supprimer ci-dessous s’appliquent à l’exercice marqué {0}.',
'Full': 'Grande',
'Small': 'Petite',
'Hidden': 'Masquée',
@@ -1080,4 +1107,34 @@ export default {
'Set to 0 to go back to the default ({0}).': 'Mets 0 pour revenir à la valeur par défaut ({0}).',
'Applies to this exercise everywhere, not just this plan.': 'S’applique à cet exercice partout, pas seulement dans ce plan.',
'You still log the total weight — the bar only feeds the per-side plate math.': 'Tu enregistres toujours le poids total — la barre ne sert qu’au calcul des disques par côté.',
// Gym check-in (mobile-only)
'Check in': 'Enregistrement',
'At the gym': 'À la salle',
'Show this at the gym': 'À présenter à la salle',
'Add your gym card': 'Ajoute ta carte de salle',
'Add a card': 'Ajouter une carte',
'Type the number on your membership card, import a photo of it, or scan it with the camera. No extra app needed at the gym — just open this screen.': 'Saisis le numéro de ta carte de membre, importe une photo ou scanne-la avec l’appareil photo. Aucune autre appli nécessaire à la salle — ouvre simplement cet écran.',
'Remove this card?': 'Supprimer cette carte ?',
'Scan it, import a photo, or type the code by hand.': 'Scanne-la, importe une photo ou saisis le code à la main.',
'Scan': 'Scanner',
'Import photo': 'Importer une photo',
'Label': 'Libellé',
'e.g. FitZone downtown': 'p. ex. FitZone centre-ville',
'Code': 'Code',
'Membership number or code': 'Numéro de membre ou code',
'Save card': 'Enregistrer la carte',
'Gym card': 'Carte de salle',
'Card added': 'Carte ajoutée',
'Nothing to save yet': 'Rien à enregistrer pour l’instant',
"That's not a QR code — only QR cards can be shown here": 'Ce n’est pas un code QR — seules les cartes QR peuvent être affichées ici',
'No QR code found in that image': 'Aucun code QR trouvé dans cette image',
'Could not read that image': 'Impossible de lire cette image',
'Camera permission is needed to scan. Enable it in Settings.': 'L’autorisation caméra est nécessaire pour scanner. Active-la dans les Réglages.',
'Scanning is not available on this device.': 'Le scan n’est pas disponible sur cet appareil.',
'Could not start the scanner': 'Impossible de démarrer le scanner',
'Gym check-in': 'Enregistrement à la salle',
'Show a card on Home with your membership QR codes.': 'Affiche sur l’Accueil une carte avec vos codes QR d’abonné.',
'Point the camera at the QR code': 'Pointez la caméra vers le code QR',
'Camera is not available here — import a photo or type the code instead.': 'La caméra n’est pas disponible ici — importez une photo ou saisissez le code.',
'Camera access was denied — allow it in your browser and try again.': 'L’accès à la caméra a été refusé — autorisez-le dans le navigateur et réessayez.',
}
+61 -4
View File
@@ -23,6 +23,13 @@ export default {
'Resume': 'जारी रखें',
'Stats': 'आँकड़े',
'Exercises': 'व्यायाम',
'By muscle': 'मांसपेशी से',
'Explore muscles': 'मांसपेशियाँ खोजें',
'Choose a muscle to see exercises that train it.': 'उस मांसपेशी को प्रशिक्षित करने वाले व्यायाम देखने के लिए एक मांसपेशी चुनें।',
'Exercises for {0}': '{0} के लिए व्यायाम',
'Clear selection': 'चयन साफ़ करें',
'Primary target': 'मुख्य लक्ष्य',
'Also trains': 'यह भी प्रशिक्षित करता है',
'History': 'इतिहास',
'Settings': 'सेटिंग्स',
'Freestyle': 'फ्रीस्टाइल',
@@ -202,8 +209,22 @@ export default {
'{0} — in progress': '{0} — चल रहा है',
'Resume ▶': 'जारी रखें ▶',
'Welcome!': 'स्वागत है!',
'Set up your weekly routine to get going — or load a ready-made Push / Pull / Legs plan.': 'शुरू करने के लिए अपना साप्ताहिक रूटीन बनाएँ — या बना-बनाया पुश / पुल / लेग्स प्लान लोड करें।',
'Load starter plan (PPL)': 'स्टार्टर प्लान लोड करें (PPL)',
'Set up your weekly routine to get going — or load a ready-made starter plan.': 'शुरू करने के लिए अपना साप्ताहिक रूटीन बनाएँ — या बना-बनाया स्टार्टर प्लान लोड करें।',
'Load starter plan': 'स्टार्टर प्लान लोड करें',
'Choose starter plan': 'स्टार्टर प्लान चुनें',
'{0} days per week': 'हफ़्ते में {0} दिन',
'{0} loaded': '{0} लोड हुआ',
'Load {0}?': '{0} लोड करें?',
'Load plan': 'प्लान लोड करें',
'The new plan will be scheduled on {0}. Existing routines are kept — only those days of the weekly plan change.': 'नया प्लान {0} पर लगेगा। आपकी सभी रूटीन बनी रहेंगी — साप्ताहिक प्लान में सिर्फ़ ये दिन बदलेंगे।',
'Push / Pull / Legs': 'पुश / पुल / लेग्स',
'Push, pull and legs each get their own day.': 'पुश, पुल और लेग्स, हर एक का अपना दिन।',
'Upper / Lower': 'ऊपरी / निचला',
'Upper body twice, lower body twice.': 'ऊपरी शरीर दो बार, निचला शरीर दो बार।',
'Full Body': 'फ़ुल बॉडी',
'Three sessions, the whole body each time.': 'तीन सेशन, हर बार पूरा शरीर।',
'5×5': '5×5',
'Five sets of five on the main barbell lifts.': 'मुख्य बारबेल लिफ़्ट पर पाँच सेट, पाँच रेप।',
'Build my own plan': 'अपनी योजना बनाएँ',
'{0} week streak': '{0} हफ़्तों की स्ट्रीक',
'this week': 'इस हफ़्ते',
@@ -228,7 +249,6 @@ export default {
'Week schedule': 'हफ़्ते का कार्यक्रम',
'No routines yet.': 'अभी कोई रूटीन नहीं।',
'Create one or load the starter plan.': 'एक बनाएँ या स्टार्टर प्लान लोड करें।',
'Load starter plan (Push / Pull / Legs)': 'स्टार्टर प्लान लोड करें (पुश / पुल / लेग्स)',
'Superset with exercise above': 'ऊपर वाले व्यायाम के साथ सुपरसेट',
'Note (optional) — loading cues, "bar only then +1 plate/side each set", anything worth remembering here': 'नोट (वैकल्पिक) — लोडिंग संकेत, जैसे "सिर्फ़ खाली बार, फिर हर सेट में हर तरफ़ +1 प्लेट", जो भी याद रखना चाहें',
'No exercises yet — add your first one.': 'अभी कोई व्यायाम नहीं — पहला जोड़ें।',
@@ -236,10 +256,11 @@ export default {
'Delete routine?': 'रूटीन हटाएँ?',
'“{0}” and its exercises will be removed.': '"{0}" और उसके व्यायाम हटा दिए जाएँगे।',
'Delete routine': 'रूटीन हटाएँ',
'Copy routine': 'रूटीन कॉपी करें',
'Copy': 'कॉपी',
'{0} exercises with animations': 'एनिमेशन के साथ {0} व्यायाम',
'Search…': 'खोजें…',
'No workouts yet.': 'अभी कोई वर्कआउट नहीं।',
'Starter plan loaded — Mon Push · Wed Pull · Fri Legs': 'स्टार्टर प्लान लोड हुआ — सोम पुश · बुध पुल · शुक्र लेग्स',
'Enter a name': 'नाम दर्ज करें',
'Profile created — data from this device moved into it': 'प्रोफ़ाइल बनी — इस डिवाइस का डेटा उसमें चला गया',
'Profile created — data moved into it': 'प्रोफ़ाइल बनी — डेटा स्थानांतरित',
@@ -394,6 +415,12 @@ export default {
'Minimize': 'छोटा करें',
'Expand': 'बड़ा करें',
'Exercise animations': 'व्यायाम एनिमेशन',
'Workout view': 'वर्कआउट दृश्य',
'Cards': 'कार्ड',
'List': 'सूची',
'Current': 'वर्तमान',
'Set current': 'वर्तमान के रूप में चिह्नित करें',
'Move, swap and remove below act on the exercise marked {0}.': 'नीचे दिए गए मूव, स्वैप और रिमूव {0} के रूप में चिह्नित व्यायाम पर लागू होते हैं।',
'Full': 'पूर्ण',
'Small': 'छोटा',
'Hidden': 'छिपा',
@@ -1080,4 +1107,34 @@ export default {
'Set to 0 to go back to the default ({0}).': 'डिफ़ॉल्ट ({0}) पर लौटने के लिए 0 सेट करें।',
'Applies to this exercise everywhere, not just this plan.': 'यह इस एक्सरसाइज़ पर हर जगह लागू होता है, सिर्फ़ इसी प्लान पर नहीं।',
'You still log the total weight — the bar only feeds the per-side plate math.': 'आप अब भी कुल वज़न ही दर्ज करते हैं — बार सिर्फ़ हर तरफ़ की प्लेट गिनती में काम आता है।',
// Gym check-in (mobile-only)
'Check in': 'चेक इन',
'At the gym': 'जिम में',
'Show this at the gym': 'इसे जिम में दिखाएँ',
'Add your gym card': 'अपना जिम कार्ड जोड़ें',
'Add a card': 'कार्ड जोड़ें',
'Type the number on your membership card, import a photo of it, or scan it with the camera. No extra app needed at the gym — just open this screen.': 'अपने मेंबरशिप कार्ड का नंबर लिखें, उसकी फ़ोटो इम्पोर्ट करें, या कैमरे से स्कैन करें। जिम में किसी और ऐप की ज़रूरत नहीं — बस यह स्क्रीन खोलें।',
'Remove this card?': 'यह कार्ड हटाएँ?',
'Scan it, import a photo, or type the code by hand.': 'इसे स्कैन करें, फ़ोटो इम्पोर्ट करें, या कोड हाथ से लिखें।',
'Scan': 'स्कैन करें',
'Import photo': 'फ़ोटो इम्पोर्ट करें',
'Label': 'लेबल',
'e.g. FitZone downtown': 'जैसे FitZone डाउनटाउन',
'Code': 'कोड',
'Membership number or code': 'मेंबरशिप नंबर या कोड',
'Save card': 'कार्ड सहेजें',
'Gym card': 'जिम कार्ड',
'Card added': 'कार्ड जोड़ा गया',
'Nothing to save yet': 'अभी सहेजने के लिए कुछ नहीं',
"That's not a QR code — only QR cards can be shown here": 'यह QR कोड नहीं है — यहाँ केवल QR कार्ड दिखाए जा सकते हैं',
'No QR code found in that image': 'उस छवि में कोई QR कोड नहीं मिला',
'Could not read that image': 'वह छवि पढ़ी नहीं जा सकी',
'Camera permission is needed to scan. Enable it in Settings.': 'स्कैन करने के लिए कैमरा अनुमति चाहिए। इसे सेटिंग्स में चालू करें।',
'Scanning is not available on this device.': 'इस डिवाइस पर स्कैनिंग उपलब्ध नहीं है।',
'Could not start the scanner': 'स्कैनर शुरू नहीं हो सका',
'Gym check-in': 'जिम चेक-इन',
'Show a card on Home with your membership QR codes.': 'होम पर आपके सदस्यता QR कोड वाला कार्ड दिखाता है।',
'Point the camera at the QR code': 'कैमरे को QR कोड पर रखें',
'Camera is not available here — import a photo or type the code instead.': 'कैमरा यहाँ उपलब्ध नहीं है — फ़ोटो इंपोर्ट करें या कोड टाइप करें।',
'Camera access was denied — allow it in your browser and try again.': 'कैमरे की अनुमति नहीं मिली — ब्राउज़र में अनुमति दें और फिर कोशिश करें।',
}
+61 -4
View File
@@ -25,6 +25,13 @@ export default {
'Resume': 'Folytatás',
'Stats': 'Statisztika',
'Exercises': 'Gyakorlatok',
'By muscle': 'Izom szerint',
'Explore muscles': 'Izmok felfedezése',
'Choose a muscle to see exercises that train it.': 'Válassz izmot, hogy lásd a gyakorlatokat, amelyek edzik.',
'Exercises for {0}': '{0} gyakorlatai',
'Clear selection': 'Kijelölés törlése',
'Primary target': 'Elsődleges célizom',
'Also trains': 'Emellett edzi',
'History': 'Előzmények',
'Settings': 'Beállítások',
'Freestyle': 'Szabad edzés',
@@ -202,8 +209,22 @@ export default {
'{0} — in progress': '{0} — folyamatban',
'Resume ▶': 'Folytatás ▶',
'Welcome!': 'Üdvözlünk!',
'Set up your weekly routine to get going — or load a ready-made Push / Pull / Legs plan.': 'Állítsd be a heti rutinod, hogy elindulhass — vagy tölts be egy kész Push / Pull / Legs tervet.',
'Load starter plan (PPL)': 'Kezdő terv betöltése (PPL)',
'Set up your weekly routine to get going — or load a ready-made starter plan.': 'Állítsd be a heti rutinod, hogy elindulhass — vagy tölts be egy kész kezdő tervet.',
'Load starter plan': 'Kezdő terv betöltése',
'Choose starter plan': 'Válassz kezdő tervet',
'{0} days per week': 'Heti {0} nap',
'{0} loaded': '{0} betöltve',
'Load {0}?': 'Betöltöd: {0}?',
'Load plan': 'Terv betöltése',
'The new plan will be scheduled on {0}. Existing routines are kept — only those days of the weekly plan change.': 'Az új terv ide kerül: {0}. A meglévő rutinjaid megmaradnak — a heti tervben csak ezek a napok változnak.',
'Push / Pull / Legs': 'Push / Pull / Legs',
'Push, pull and legs each get their own day.': 'Tolás, húzás és láb, mind a maga napján.',
'Upper / Lower': 'Felső / Alsó',
'Upper body twice, lower body twice.': 'Felsőtest kétszer, alsótest kétszer.',
'Full Body': 'Teljes test',
'Three sessions, the whole body each time.': 'Három edzés, mindegyiken az egész test.',
'5×5': '5×5',
'Five sets of five on the main barbell lifts.': 'Öt ötös sorozat a fő rúdgyakorlatokon.',
'Build my own plan': 'Saját terv készítése',
'{0} week streak': '{0} hetes sorozat',
'this week': 'ezen a héten',
@@ -231,7 +252,6 @@ export default {
'Routines': 'Rutinok',
'No routines yet.': 'Még nincs rutin.',
'Create one or load the starter plan.': 'Hozz létre egyet, vagy töltsd be a kezdő tervet.',
'Load starter plan (Push / Pull / Legs)': 'Kezdő terv betöltése (Push / Pull / Legs)',
// --- routine edit ---
'Superset with exercise above': 'Szuperszett a fenti gyakorlattal',
'Note (optional) — loading cues, "bar only then +1 plate/side each set", anything worth remembering here': 'Megjegyzés (opcionális) — súlyozási tippek, pl. „csak a rúd, majd sorozatonként +1 tárcsa oldalanként”, bármi, amit érdemes megjegyezni',
@@ -240,11 +260,12 @@ export default {
'Delete routine?': 'Törlöd a rutint?',
'“{0}” and its exercises will be removed.': '„{0}” és a gyakorlatai el lesznek távolítva.',
'Delete routine': 'Rutin törlése',
'Copy routine': 'Rutin másolása',
'Copy': 'Másolat',
// --- library / history ---
'{0} exercises with animations': '{0} gyakorlat animációval',
'Search…': 'Keresés…',
'No workouts yet.': 'Még nincs edzés.',
'Starter plan loaded — Mon Push · Wed Pull · Fri Legs': 'Kezdő terv betöltve — H Push · Sze Pull · P Legs',
// --- login / account ---
'Enter a name': 'Adj meg egy nevet',
'Profile created — data from this device moved into it': 'Profil létrehozva — az eszközön lévő adatok átkerültek bele',
@@ -404,6 +425,12 @@ export default {
'Minimize': 'Kicsinyítés',
'Expand': 'Kibontás',
'Exercise animations': 'Gyakorlat-animációk',
'Workout view': 'Edzésnézet',
'Cards': 'Kártyák',
'List': 'Lista',
'Current': 'Aktuális',
'Set current': 'Megjelölés aktuálisként',
'Move, swap and remove below act on the exercise marked {0}.': 'Az alábbi áthelyezés, csere és törlés a {0} jelölésű gyakorlatra vonatkozik.',
'Full': 'Teljes',
'Small': 'Kicsi',
'Hidden': 'Rejtett',
@@ -748,6 +775,31 @@ export default {
'Set to 0 to go back to the default ({0}).': 'Állítsd 0-ra az alapérték ({0}) visszaállításához.',
'Applies to this exercise everywhere, not just this plan.': 'Mindenhol érvényes erre a gyakorlatra, nem csak ebben a tervben.',
'You still log the total weight — the bar only feeds the per-side plate math.': 'Továbbra is a teljes súlyt rögzíted — a rúd csak az oldalankénti tárcsaszámításhoz kell.',
// Gym check-in (mobile-only)
'Check in': 'Bejelentkezés',
'At the gym': 'A teremben',
'Show this at the gym': 'Mutasd fel a teremben',
'Add your gym card': 'Add hozzá a terembérleted',
'Add a card': 'Kártya hozzáadása',
'Type the number on your membership card, import a photo of it, or scan it with the camera. No extra app needed at the gym — just open this screen.': 'Írd be a tagsági kártyád számát, importálj róla egy fotót, vagy olvasd be a kamerával. Nincs szükség külön alkalmazásra a teremben — csak nyisd meg ezt a képernyőt.',
'Remove this card?': 'Törlöd ezt a kártyát?',
'Scan it, import a photo, or type the code by hand.': 'Olvasd be, importálj egy fotót, vagy írd be a kódot kézzel.',
'Scan': 'Beolvasás',
'Import photo': 'Fotó importálása',
'Label': 'Címke',
'e.g. FitZone downtown': 'pl. FitZone belváros',
'Code': 'Kód',
'Membership number or code': 'Tagsági szám vagy kód',
'Save card': 'Kártya mentése',
'Gym card': 'Terembérlet',
'Card added': 'Kártya hozzáadva',
'Nothing to save yet': 'Még nincs mit menteni',
"That's not a QR code — only QR cards can be shown here": 'Ez nem QR-kód — itt csak QR-kártyák jeleníthetők meg',
'No QR code found in that image': 'Nem található QR-kód a képen',
'Could not read that image': 'A kép nem olvasható be',
'Camera permission is needed to scan. Enable it in Settings.': 'A beolvasáshoz kameraengedély szükséges. Engedélyezd a Beállításokban.',
'Scanning is not available on this device.': 'A beolvasás nem érhető el ezen az eszközön.',
'Could not start the scanner': 'A szkenner nem indítható el',
// --- AI Coach ---
'The Coach is reading your training…': 'Az Edző az edzéseidet olvassa…',
'Could not ask the Coach': 'Nem sikerült megkérdezni az Edzőt',
@@ -1083,4 +1135,9 @@ export default {
'What should change?': 'Mi változzon?',
'Coach is thinking…': 'Az Edző gondolkodik…',
'Message the Coach…': 'Üzenet az Edzőnek…',
'Gym check-in': 'Bejelentkezés a teremben',
'Show a card on Home with your membership QR codes.': 'A Kezdőlapon egy kártyát mutat a tagsági QR-kódjaiddal.',
'Point the camera at the QR code': 'Irányítsd a kamerát a QR-kódra',
'Camera is not available here — import a photo or type the code instead.': 'A kamera itt nem elérhető — importálj egy fotót vagy írd be a kódot.',
'Camera access was denied — allow it in your browser and try again.': 'A kamera-hozzáférés elutasítva — engedélyezd a böngészőben, és próbáld újra.',
}
+61 -4
View File
@@ -23,6 +23,13 @@ export default {
'Resume': 'Riprendi',
'Stats': 'Statistiche',
'Exercises': 'Esercizi',
'By muscle': 'Per muscolo',
'Explore muscles': 'Esplora i muscoli',
'Choose a muscle to see exercises that train it.': 'Scegli un muscolo per vedere gli esercizi che lo allenano.',
'Exercises for {0}': 'Esercizi per {0}',
'Clear selection': 'Cancella selezione',
'Primary target': 'Muscolo principale',
'Also trains': 'Allena anche',
'History': 'Cronologia',
'Settings': 'Impostazioni',
'Freestyle': 'Libero',
@@ -202,8 +209,22 @@ export default {
'{0} — in progress': '{0} — in corso',
'Resume ▶': 'Riprendi ▶',
'Welcome!': 'Benvenuto!',
'Set up your weekly routine to get going — or load a ready-made Push / Pull / Legs plan.': 'Imposta la tua routine settimanale — o carica un piano Push / Pull / Gambe già pronto.',
'Load starter plan (PPL)': 'Carica piano iniziale (PPL)',
'Set up your weekly routine to get going — or load a ready-made starter plan.': 'Imposta la tua routine settimanale — o carica un piano iniziale già pronto.',
'Load starter plan': 'Carica piano iniziale',
'Choose starter plan': 'Scegli un piano iniziale',
'{0} days per week': '{0} giorni a settimana',
'{0} loaded': '{0} caricato',
'Load {0}?': 'Caricare {0}?',
'Load plan': 'Carica piano',
'The new plan will be scheduled on {0}. Existing routines are kept — only those days of the weekly plan change.': 'Il nuovo piano andrà su {0}. Le tue routine restano tutte — cambiano solo quei giorni del piano settimanale.',
'Push / Pull / Legs': 'Push / Pull / Gambe',
'Push, pull and legs each get their own day.': 'Spinta, trazione e gambe, ognuna nel suo giorno.',
'Upper / Lower': 'Superiore / Inferiore',
'Upper body twice, lower body twice.': 'Parte superiore due volte, parte inferiore due volte.',
'Full Body': 'Total body',
'Three sessions, the whole body each time.': 'Tre sedute, ogni volta tutto il corpo.',
'5×5': '5×5',
'Five sets of five on the main barbell lifts.': 'Cinque serie da cinque sui fondamentali con bilanciere.',
'Build my own plan': 'Crea il mio piano',
'{0} week streak': 'serie di {0} settimane',
'this week': 'questa settimana',
@@ -228,7 +249,6 @@ export default {
'Week schedule': 'Programma settimanale',
'No routines yet.': 'Ancora nessuna routine.',
'Create one or load the starter plan.': 'Creane una o carica il piano iniziale.',
'Load starter plan (Push / Pull / Legs)': 'Carica piano iniziale (Push / Pull / Gambe)',
'Superset with exercise above': "Superset con l'esercizio sopra",
'Note (optional) — loading cues, "bar only then +1 plate/side each set", anything worth remembering here': 'Nota (facoltativa) — indicazioni di carico, es. "solo bilanciere poi +1 disco per lato a ogni serie", qualsiasi cosa tu voglia ricordare',
'No exercises yet — add your first one.': 'Ancora nessun esercizio — aggiungi il primo.',
@@ -236,10 +256,11 @@ export default {
'Delete routine?': 'Eliminare routine?',
'“{0}” and its exercises will be removed.': '«{0}» e i suoi esercizi verranno rimossi.',
'Delete routine': 'Elimina routine',
'Copy routine': 'Copia routine',
'Copy': 'Copia',
'{0} exercises with animations': '{0} esercizi con animazioni',
'Search…': 'Cerca…',
'No workouts yet.': 'Ancora nessun allenamento.',
'Starter plan loaded — Mon Push · Wed Pull · Fri Legs': 'Piano iniziale caricato — Lun Push · Mer Pull · Ven Gambe',
'Enter a name': 'Inserisci un nome',
'Profile created — data from this device moved into it': 'Profilo creato — i dati di questo dispositivo sono stati trasferiti',
'Profile created — data moved into it': 'Profilo creato — dati trasferiti',
@@ -394,6 +415,12 @@ export default {
'Minimize': 'Riduci',
'Expand': 'Ingrandisci',
'Exercise animations': 'Animazioni degli esercizi',
'Workout view': 'Vista allenamento',
'Cards': 'Schede',
'List': 'Elenco',
'Current': 'Corrente',
'Set current': 'Imposta come corrente',
'Move, swap and remove below act on the exercise marked {0}.': 'Spostamento, scambio e rimozione qui sotto agiscono sull’esercizio contrassegnato come {0}.',
'Full': 'Grande',
'Small': 'Piccola',
'Hidden': 'Nascosta',
@@ -1080,4 +1107,34 @@ export default {
'Set to 0 to go back to the default ({0}).': 'Imposta 0 per tornare al valore predefinito ({0}).',
'Applies to this exercise everywhere, not just this plan.': 'Vale per questo esercizio ovunque, non solo in questo piano.',
'You still log the total weight — the bar only feeds the per-side plate math.': 'Registri comunque il peso totale — il bilanciere serve solo al calcolo dei dischi per lato.',
// Gym check-in (mobile-only)
'Check in': 'Check-in',
'At the gym': 'In palestra',
'Show this at the gym': 'Mostralo in palestra',
'Add your gym card': 'Aggiungi la tua tessera',
'Add a card': 'Aggiungi una tessera',
'Type the number on your membership card, import a photo of it, or scan it with the camera. No extra app needed at the gym — just open this screen.': 'Digita il numero della tua tessera, importa una foto o scansionala con la fotocamera. Nessuna app extra in palestra — apri semplicemente questa schermata.',
'Remove this card?': 'Rimuovere questa tessera?',
'Scan it, import a photo, or type the code by hand.': 'Scansionala, importa una foto o digita il codice a mano.',
'Scan': 'Scansiona',
'Import photo': 'Importa foto',
'Label': 'Etichetta',
'e.g. FitZone downtown': 'es. FitZone centro',
'Code': 'Codice',
'Membership number or code': 'Numero tessera o codice',
'Save card': 'Salva tessera',
'Gym card': 'Tessera palestra',
'Card added': 'Tessera aggiunta',
'Nothing to save yet': 'Ancora niente da salvare',
"That's not a QR code — only QR cards can be shown here": 'Non è un codice QR — qui si possono mostrare solo tessere QR',
'No QR code found in that image': 'Nessun codice QR trovato nell’immagine',
'Could not read that image': 'Impossibile leggere l’immagine',
'Camera permission is needed to scan. Enable it in Settings.': 'Per scansionare serve l’autorizzazione alla fotocamera. Attivala nelle Impostazioni.',
'Scanning is not available on this device.': 'La scansione non è disponibile su questo dispositivo.',
'Could not start the scanner': 'Impossibile avviare lo scanner',
'Gym check-in': 'Check-in in palestra',
'Show a card on Home with your membership QR codes.': 'Mostra nella Home una scheda con i tuoi codici QR di iscrizione.',
'Point the camera at the QR code': 'Inquadra il codice QR con la fotocamera',
'Camera is not available here — import a photo or type the code instead.': 'La fotocamera non è disponibile qui — importa una foto o digita il codice.',
'Camera access was denied — allow it in your browser and try again.': 'Accesso alla fotocamera negato — consentilo nel browser e riprova.',
}
+61 -4
View File
@@ -23,6 +23,13 @@ export default {
'Resume': '이어하기',
'Stats': '통계',
'Exercises': '운동',
'By muscle': '근육별',
'Explore muscles': '근육 탐색',
'Choose a muscle to see exercises that train it.': '운동하는 부위를 선택해 해당 근육을 훈련하는 운동을 확인하세요.',
'Exercises for {0}': '{0} 운동',
'Clear selection': '선택 지우기',
'Primary target': '주요 목표',
'Also trains': '함께 훈련',
'History': '기록',
'Settings': '설정',
'Freestyle': '자유 운동',
@@ -202,8 +209,22 @@ export default {
'{0} — in progress': '{0} — 진행 중',
'Resume ▶': '이어하기 ▶',
'Welcome!': '환영합니다!',
'Set up your weekly routine to get going — or load a ready-made Push / Pull / Legs plan.': '주간 루틴을 설정해 시작하세요 — 또는 미리 만들어진 푸시 / 풀 / 레그 계획을 불러오세요.',
'Load starter plan (PPL)': '스타터 계획 불러오기 (PPL)',
'Set up your weekly routine to get going — or load a ready-made starter plan.': '주간 루틴을 설정해 시작하세요 — 또는 미리 만들어진 스타터 계획을 불러오세요.',
'Load starter plan': '스타터 계획 불러오기',
'Choose starter plan': '스타터 계획 선택',
'{0} days per week': '주 {0}일',
'{0} loaded': '{0} 불러옴',
'Load {0}?': '{0} 불러올까요?',
'Load plan': '계획 불러오기',
'The new plan will be scheduled on {0}. Existing routines are kept — only those days of the weekly plan change.': '새 계획은 {0}에 배치됩니다. 기존 루틴은 모두 유지되고 주간 계획에서 해당 요일만 바뀝니다.',
'Push / Pull / Legs': '푸시 / 풀 / 레그',
'Push, pull and legs each get their own day.': '푸시, 풀, 레그를 각각 다른 날에.',
'Upper / Lower': '상체 / 하체',
'Upper body twice, lower body twice.': '상체 두 번, 하체 두 번.',
'Full Body': '전신',
'Three sessions, the whole body each time.': '세 번의 세션, 매번 전신.',
'5×5': '5×5',
'Five sets of five on the main barbell lifts.': '주요 바벨 종목을 5세트 5회로.',
'Build my own plan': '내 계획 만들기',
'{0} week streak': '{0}주 연속',
'this week': '이번 주',
@@ -228,7 +249,6 @@ export default {
'Week schedule': '주간 일정',
'No routines yet.': '아직 루틴이 없어요.',
'Create one or load the starter plan.': '루틴을 만들거나 스타터 계획을 불러오세요.',
'Load starter plan (Push / Pull / Legs)': '스타터 계획 불러오기 (푸시 / 풀 / 레그)',
'Superset with exercise above': '위 운동과 슈퍼세트',
'Note (optional) — loading cues, "bar only then +1 plate/side each set", anything worth remembering here': '메모(선택 사항) — 중량 안내, 예: "빈 바로 시작 후 세트마다 양쪽 +1플레이트", 기억하고 싶은 모든 것',
'No exercises yet — add your first one.': '아직 운동이 없어요 — 첫 운동을 추가하세요.',
@@ -236,10 +256,11 @@ export default {
'Delete routine?': '루틴을 삭제할까요?',
'“{0}” and its exercises will be removed.': '"{0}"과(와) 그 운동들이 삭제됩니다.',
'Delete routine': '루틴 삭제',
'Copy routine': '루틴 복사',
'Copy': '복사본',
'{0} exercises with animations': '애니메이션이 있는 운동 {0}개',
'Search…': '검색…',
'No workouts yet.': '아직 운동 기록이 없어요.',
'Starter plan loaded — Mon Push · Wed Pull · Fri Legs': '스타터 계획 불러옴 — 월 푸시 · 수 풀 · 금 레그',
'Enter a name': '이름을 입력하세요',
'Profile created — data from this device moved into it': '프로필 생성됨 — 이 기기의 데이터가 이동됨',
'Profile created — data moved into it': '프로필 생성됨 — 데이터 이동됨',
@@ -394,6 +415,12 @@ export default {
'Minimize': '축소',
'Expand': '확대',
'Exercise animations': '운동 애니메이션',
'Workout view': '운동 보기',
'Cards': '카드',
'List': '목록',
'Current': '현재',
'Set current': '현재 운동으로 설정',
'Move, swap and remove below act on the exercise marked {0}.': '아래의 이동, 교체, 삭제는 {0} 표시된 운동에 적용됩니다.',
'Full': '전체',
'Small': '작게',
'Hidden': '숨김',
@@ -1080,4 +1107,34 @@ export default {
'Set to 0 to go back to the default ({0}).': '0으로 두면 기본값({0})으로 돌아갑니다.',
'Applies to this exercise everywhere, not just this plan.': '이 플랜만이 아니라 어디서든 이 운동에 적용됩니다.',
'You still log the total weight — the bar only feeds the per-side plate math.': '기록은 여전히 총 무게입니다 — 바 무게는 한쪽에 끼울 원판 계산에만 쓰입니다.',
// Gym check-in (mobile-only)
'Check in': '체크인',
'At the gym': '헬스장에서',
'Show this at the gym': '헬스장에서 이것을 보여주세요',
'Add your gym card': '헬스장 카드 추가',
'Add a card': '카드 추가',
'Type the number on your membership card, import a photo of it, or scan it with the camera. No extra app needed at the gym — just open this screen.': '멤버십 카드 번호를 입력하거나, 사진을 가져오거나, 카메라로 스캔하세요. 헬스장에서 별도 앱이 필요 없이 이 화면만 열면 됩니다.',
'Remove this card?': '이 카드를 삭제할까요?',
'Scan it, import a photo, or type the code by hand.': '스캔하거나 사진을 가져오거나 코드를 직접 입력하세요.',
'Scan': '스캔',
'Import photo': '사진 가져오기',
'Label': '이름',
'e.g. FitZone downtown': '예: FitZone 시내점',
'Code': '코드',
'Membership number or code': '회원 번호 또는 코드',
'Save card': '카드 저장',
'Gym card': '헬스장 카드',
'Card added': '카드가 추가되었습니다',
'Nothing to save yet': '아직 저장할 내용이 없습니다',
"That's not a QR code — only QR cards can be shown here": 'QR 코드가 아닙니다 — 여기서는 QR 카드만 표시할 수 있습니다',
'No QR code found in that image': '이미지에서 QR 코드를 찾을 수 없습니다',
'Could not read that image': '이미지를 읽을 수 없습니다',
'Camera permission is needed to scan. Enable it in Settings.': '스캔하려면 카메라 권한이 필요합니다. 설정에서 켜세요.',
'Scanning is not available on this device.': '이 기기에서는 스캔을 사용할 수 없습니다.',
'Could not start the scanner': '스캐너를 시작할 수 없습니다',
'Gym check-in': '헬스장 체크인',
'Show a card on Home with your membership QR codes.': '홈 화면에 회원 QR 코드 카드를 표시합니다.',
'Point the camera at the QR code': '카메라를 QR 코드에 맞추세요',
'Camera is not available here — import a photo or type the code instead.': '여기서는 카메라를 사용할 수 없습니다 — 사진을 가져오거나 코드를 입력하세요.',
'Camera access was denied — allow it in your browser and try again.': '카메라 접근이 거부되었습니다 — 브라우저에서 허용한 뒤 다시 시도하세요.',
}
+61 -4
View File
@@ -23,6 +23,13 @@ export default {
'Resume': 'Wznów',
'Stats': 'Statystyki',
'Exercises': 'Ćwiczenia',
'By muscle': 'Według mięśnia',
'Explore muscles': 'Poznaj mięśnie',
'Choose a muscle to see exercises that train it.': 'Wybierz mięsień, aby zobaczyć ćwiczenia, które go angażują.',
'Exercises for {0}': 'Ćwiczenia na {0}',
'Clear selection': 'Wyczyść wybór',
'Primary target': 'Główny cel',
'Also trains': 'Angażuje również',
'History': 'Historia',
'Settings': 'Ustawienia',
'Freestyle': 'Dowolny',
@@ -202,8 +209,22 @@ export default {
'{0} — in progress': '{0} — w trakcie',
'Resume ▶': 'Wznów ▶',
'Welcome!': 'Witaj!',
'Set up your weekly routine to get going — or load a ready-made Push / Pull / Legs plan.': 'Ustaw swój tygodniowy plan — albo wczytaj gotowy plan Push / Pull / Nogi.',
'Load starter plan (PPL)': 'Wczytaj plan startowy (PPL)',
'Set up your weekly routine to get going — or load a ready-made starter plan.': 'Ustaw swój tygodniowy plan — albo wczytaj gotowy plan startowy.',
'Load starter plan': 'Wczytaj plan startowy',
'Choose starter plan': 'Wybierz plan startowy',
'{0} days per week': '{0} dni w tygodniu',
'{0} loaded': 'Wczytano: {0}',
'Load {0}?': 'Wczytać {0}?',
'Load plan': 'Wczytaj plan',
'The new plan will be scheduled on {0}. Existing routines are kept — only those days of the weekly plan change.': 'Nowy plan trafi na {0}. Twoje plany treningowe zostają — zmienią się tylko te dni w planie tygodnia.',
'Push / Pull / Legs': 'Push / Pull / Nogi',
'Push, pull and legs each get their own day.': 'Pchanie, ciągnięcie i nogi — każde w swoim dniu.',
'Upper / Lower': 'Góra / Dół',
'Upper body twice, lower body twice.': 'Góra dwa razy, dół dwa razy.',
'Full Body': 'Całe ciało',
'Three sessions, the whole body each time.': 'Trzy treningi, za każdym razem całe ciało.',
'5×5': '5×5',
'Five sets of five on the main barbell lifts.': 'Pięć serii po pięć na głównych bojach ze sztangą.',
'Build my own plan': 'Utwórz własny plan',
'{0} week streak': 'seria {0} tyg.',
'this week': 'w tym tygodniu',
@@ -228,7 +249,6 @@ export default {
'Week schedule': 'Harmonogram tygodnia',
'No routines yet.': 'Brak planów.',
'Create one or load the starter plan.': 'Utwórz plan albo wczytaj startowy.',
'Load starter plan (Push / Pull / Legs)': 'Wczytaj plan startowy (Push / Pull / Nogi)',
'Superset with exercise above': 'Superseria z ćwiczeniem powyżej',
'Note (optional) — loading cues, "bar only then +1 plate/side each set", anything worth remembering here': 'Notatka (opcjonalnie) — wskazówki dot. obciążenia, np. "sama sztanga, potem +1 talerz na stronę w każdej serii", cokolwiek chcesz zapamiętać',
'No exercises yet — add your first one.': 'Brak ćwiczeń — dodaj pierwsze.',
@@ -236,10 +256,11 @@ export default {
'Delete routine?': 'Usunąć plan?',
'“{0}” and its exercises will be removed.': '„{0}” i jego ćwiczenia zostaną usunięte.',
'Delete routine': 'Usuń plan',
'Copy routine': 'Kopiuj plan',
'Copy': 'Kopia',
'{0} exercises with animations': '{0} ćwiczeń z animacjami',
'Search…': 'Szukaj…',
'No workouts yet.': 'Brak treningów.',
'Starter plan loaded — Mon Push · Wed Pull · Fri Legs': 'Plan startowy wczytany — Pn Push · Śr Pull · Pt Nogi',
'Enter a name': 'Podaj imię',
'Profile created — data from this device moved into it': 'Profil utworzony — dane z tego urządzenia zostały przeniesione',
'Profile created — data moved into it': 'Profil utworzony — dane przeniesione',
@@ -394,6 +415,12 @@ export default {
'Minimize': 'Zmniejsz',
'Expand': 'Powiększ',
'Exercise animations': 'Animacje ćwiczeń',
'Workout view': 'Widok treningu',
'Cards': 'Karty',
'List': 'Lista',
'Current': 'Bieżące',
'Set current': 'Ustaw jako bieżące',
'Move, swap and remove below act on the exercise marked {0}.': 'Przenoszenie, zamiana i usuwanie poniżej dotyczą ćwiczenia oznaczonego {0}.',
'Full': 'Pełna',
'Small': 'Mała',
'Hidden': 'Ukryta',
@@ -1080,4 +1107,34 @@ export default {
'Set to 0 to go back to the default ({0}).': 'Ustaw 0, aby wrócić do wartości domyślnej ({0}).',
'Applies to this exercise everywhere, not just this plan.': 'Dotyczy tego ćwiczenia wszędzie, nie tylko w tym planie.',
'You still log the total weight — the bar only feeds the per-side plate math.': 'Nadal zapisujesz ciężar całkowity — gryf służy tylko do wyliczenia talerzy na stronę.',
// Gym check-in (mobile-only)
'Check in': 'Zamelduj się',
'At the gym': 'Na siłowni',
'Show this at the gym': 'Pokaż to na siłowni',
'Add your gym card': 'Dodaj kartę siłowni',
'Add a card': 'Dodaj kartę',
'Type the number on your membership card, import a photo of it, or scan it with the camera. No extra app needed at the gym — just open this screen.': 'Wpisz numer karty członkowskiej, zaimportuj jej zdjęcie lub zeskanuj aparatem. Na siłowni nie potrzebujesz osobnej aplikacji — po prostu otwórz ten ekran.',
'Remove this card?': 'Usunąć tę kartę?',
'Scan it, import a photo, or type the code by hand.': 'Zeskanuj ją, zaimportuj zdjęcie lub wpisz kod ręcznie.',
'Scan': 'Skanuj',
'Import photo': 'Importuj zdjęcie',
'Label': 'Etykieta',
'e.g. FitZone downtown': 'np. FitZone centrum',
'Code': 'Kod',
'Membership number or code': 'Numer członkowski lub kod',
'Save card': 'Zapisz kartę',
'Gym card': 'Karta siłowni',
'Card added': 'Dodano kartę',
'Nothing to save yet': 'Nie ma jeszcze nic do zapisania',
"That's not a QR code — only QR cards can be shown here": 'To nie jest kod QR — tutaj można pokazać tylko karty QR',
'No QR code found in that image': 'Nie znaleziono kodu QR na tym obrazie',
'Could not read that image': 'Nie udało się odczytać tego obrazu',
'Camera permission is needed to scan. Enable it in Settings.': 'Do skanowania potrzebne jest pozwolenie na aparat. Włącz je w Ustawieniach.',
'Scanning is not available on this device.': 'Skanowanie nie jest dostępne na tym urządzeniu.',
'Could not start the scanner': 'Nie udało się uruchomić skanera',
'Gym check-in': 'Zameldowanie na siłowni',
'Show a card on Home with your membership QR codes.': 'Pokazuje na Starcie kartę z Twoimi kodami QR członkowskimi.',
'Point the camera at the QR code': 'Skieruj aparat na kod QR',
'Camera is not available here — import a photo or type the code instead.': 'Aparat nie jest tu dostępny — zaimportuj zdjęcie lub wpisz kod.',
'Camera access was denied — allow it in your browser and try again.': 'Odmówiono dostępu do aparatu — zezwól w przeglądarce i spróbuj ponownie.',
}
+34 -5
View File
@@ -62,13 +62,14 @@ export const PT_BR_OVERRIDES = {
'The sets you logged in this session will be lost.': 'As séries registradas nesta sessão serão perdidas.',
'Superset · do these back-to-back, rest when done': 'Superset · faça estes exercícios em sequência e descanse ao terminar',
'Freestyle workout — add your first exercise.': 'Treino livre — adicione seu primeiro exercício.',
'Set up your weekly routine to get going — or load a ready-made Push / Pull / Legs plan.': 'Configure sua rotina semanal para começar ou carregue um plano pronto de Push / Pull / Legs.',
'Load starter plan (PPL)': 'Carregar plano inicial (PPL)',
'Set up your weekly routine to get going — or load a ready-made starter plan.': 'Configure sua rotina semanal para começar — ou carregue um plano inicial já pronto.',
'Choose starter plan': 'Escolha um plano inicial',
'The new plan will be scheduled on {0}. Existing routines are kept — only those days of the weekly plan change.': 'O novo plano fica em {0}. Suas rotinas são todas mantidas — só esses dias do plano semanal mudam.',
'Push / Pull / Legs': 'Push / Pull / Legs',
'Build my own plan': 'Criar meu próprio plano',
'Finish your first workout to see progress curves here.': 'Finalize seu primeiro treino para ver os gráficos de progresso aqui.',
'Your weekly routine': 'Sua rotina semanal',
'Create one or load the starter plan.': 'Crie uma ou carregue o plano inicial.',
'Load starter plan (Push / Pull / Legs)': 'Carregar plano inicial (Push / Pull / Legs)',
'No exercises yet — add your first one.': 'Ainda não há exercícios — adicione o primeiro.',
'Exclude from automatic progression': 'Excluir da progressão automática',
'Use for planned deloads. Workouts stay in history and statistics.': 'Use para deloads planejados. Os treinos permanecem no histórico e nas estatísticas.',
@@ -76,8 +77,9 @@ export const PT_BR_OVERRIDES = {
'Tap the link button on an exercise to superset it with the one above — you’ll do them back-to-back.': 'Toque no botão de vínculo de um exercício para combiná-lo em um superset com o exercício acima — eles serão feitos em sequência.',
'Delete routine?': 'Excluir rotina?',
'Delete routine': 'Excluir rotina',
'Copy routine': 'Copiar rotina',
'Copy': 'Cópia',
'Search…': 'Buscar…',
'Starter plan loaded — Mon Push · Wed Pull · Fri Legs': 'Plano inicial carregado — Seg Push · Qua Pull · Sex Pernas',
'{0} planned for {1}': '{0} planejado para {1}',
'Planned': 'Planejado',
'Enter a name': 'Informe um nome',
@@ -608,7 +610,34 @@ export const PT_BR_OVERRIDES = {
'Default for this bar type.': 'Padrão para este tipo de barra.',
'Set to 0 to go back to the default ({0}).': 'Defina 0 para voltar ao padrão ({0}).',
'Applies to this exercise everywhere, not just this plan.': 'Vale para este exercício em todos os lugares, não só neste plano.',
'You still log the total weight — the bar only feeds the per-side plate math.': 'Você continua registrando o peso total — a barra só entra no cálculo das anilhas por lado.'
'You still log the total weight — the bar only feeds the per-side plate math.': 'Você continua registrando o peso total — a barra só entra no cálculo das anilhas por lado.',
// Gym check-in (mobile-only) — only where pt-BR differs from pt (inherited via ...pt)
'At the gym': 'Na academia',
'Show this at the gym': 'Mostre isto na academia',
'Add your gym card': 'Adicione seu cartão da academia',
'Type the number on your membership card, import a photo of it, or scan it with the camera. No extra app needed at the gym — just open this screen.': 'Digite o número do seu cartão de sócio, importe uma foto ou escaneie com a câmera. Não é preciso outro app na academia — é só abrir esta tela.',
'Scan it, import a photo, or type the code by hand.': 'Escaneie, importe uma foto ou digite o código à mão.',
'Scan': 'Escanear',
'e.g. FitZone downtown': 'ex. FitZone centro',
'Gym card': 'Cartão da academia',
'Could not read that image': 'Não foi possível ler essa imagem',
'Camera permission is needed to scan. Enable it in Settings.': 'É necessária a permissão da câmera para escanear. Ative-a nos Ajustes.',
'Scanning is not available on this device.': 'O escaneamento não está disponível neste dispositivo.',
'Could not start the scanner': 'Não foi possível iniciar o scanner',
'Gym check-in': 'Check-in na academia',
'Show a card on Home with your membership QR codes.': 'Mostra no Início um cartão com seus códigos QR de sócio.',
'Point the camera at the QR code': 'Aponte a câmera para o código QR',
'Camera is not available here — import a photo or type the code instead.': 'A câmera não está disponível aqui — importe uma foto ou digite o código.',
'Camera access was denied — allow it in your browser and try again.': 'O acesso à câmera foi negado — permita-o no navegador e tente de novo.',
// --- muscle explorer ---
'By muscle': 'Por músculo',
'Explore muscles': 'Explorar músculos',
'Choose a muscle to see exercises that train it.': 'Escolha um músculo para ver os exercícios que o treinam.',
'Exercises for {0}': 'Exercícios para {0}',
'Clear selection': 'Limpar seleção',
'Primary target': 'Músculo principal',
'Also trains': 'Também trabalha',
}
export default { ...pt, ...PT_BR_OVERRIDES }
+61 -4
View File
@@ -23,6 +23,13 @@ export default {
'Resume': 'Retomar',
'Stats': 'Estatísticas',
'Exercises': 'Exercícios',
'By muscle': 'Por músculo',
'Explore muscles': 'Explorar músculos',
'Choose a muscle to see exercises that train it.': 'Escolha um músculo para ver os exercícios que o treinam.',
'Exercises for {0}': 'Exercícios para {0}',
'Clear selection': 'Limpar seleção',
'Primary target': 'Alvo principal',
'Also trains': 'Também trabalha',
'History': 'Histórico',
'Settings': 'Definições',
'Freestyle': 'Livre',
@@ -202,8 +209,22 @@ export default {
'{0} — in progress': '{0} — em curso',
'Resume ▶': 'Retomar ▶',
'Welcome!': 'Bem-vindo!',
'Set up your weekly routine to get going — or load a ready-made Push / Pull / Legs plan.': 'Configura a tua rotina semanal — ou carrega um plano Push / Pull / Pernas já feito.',
'Load starter plan (PPL)': 'Carregar plano inicial (PPL)',
'Set up your weekly routine to get going — or load a ready-made starter plan.': 'Configura a tua rotina semanal — ou carrega um plano inicial já feito.',
'Load starter plan': 'Carregar plano inicial',
'Choose starter plan': 'Escolhe um plano inicial',
'{0} days per week': '{0} dias por semana',
'{0} loaded': '{0} carregado',
'Load {0}?': 'Carregar {0}?',
'Load plan': 'Carregar plano',
'The new plan will be scheduled on {0}. Existing routines are kept — only those days of the weekly plan change.': 'O novo plano fica em {0}. As tuas rotinas mantêm-se todas — só esses dias do plano semanal mudam.',
'Push / Pull / Legs': 'Push / Pull / Pernas',
'Push, pull and legs each get their own day.': 'Empurrar, puxar e pernas, cada um no seu dia.',
'Upper / Lower': 'Superior / Inferior',
'Upper body twice, lower body twice.': 'Tronco superior duas vezes, inferior duas vezes.',
'Full Body': 'Corpo inteiro',
'Three sessions, the whole body each time.': 'Três sessões, o corpo todo de cada vez.',
'5×5': '5×5',
'Five sets of five on the main barbell lifts.': 'Cinco séries de cinco nos básicos com barra.',
'Build my own plan': 'Criar o meu próprio plano',
'{0} week streak': 'sequência de {0} semanas',
'this week': 'esta semana',
@@ -228,7 +249,6 @@ export default {
'Week schedule': 'Horário semanal',
'No routines yet.': 'Ainda sem rotinas.',
'Create one or load the starter plan.': 'Cria uma ou carrega o plano inicial.',
'Load starter plan (Push / Pull / Legs)': 'Carregar plano inicial (Push / Pull / Pernas)',
'Superset with exercise above': 'Supersérie com o exercício acima',
'Note (optional) — loading cues, "bar only then +1 plate/side each set", anything worth remembering here': 'Nota (opcional) — dicas de carga, ex. "só a barra, depois +1 anilha por lado a cada série", o que quiser lembrar',
'No exercises yet — add your first one.': 'Ainda sem exercícios — adiciona o primeiro.',
@@ -236,10 +256,11 @@ export default {
'Delete routine?': 'Eliminar rotina?',
'“{0}” and its exercises will be removed.': '«{0}» e os seus exercícios serão removidos.',
'Delete routine': 'Eliminar rotina',
'Copy routine': 'Copiar rotina',
'Copy': 'Cópia',
'{0} exercises with animations': '{0} exercícios com animações',
'Search…': 'Pesquisar…',
'No workouts yet.': 'Ainda sem treinos.',
'Starter plan loaded — Mon Push · Wed Pull · Fri Legs': 'Plano inicial carregado — Seg Push · Qua Pull · Sex Pernas',
'Enter a name': 'Introduz um nome',
'Profile created — data from this device moved into it': 'Perfil criado — os dados deste dispositivo foram movidos para ele',
'Profile created — data moved into it': 'Perfil criado — dados movidos',
@@ -394,6 +415,12 @@ export default {
'Minimize': 'Minimizar',
'Expand': 'Ampliar',
'Exercise animations': 'Animações dos exercícios',
'Workout view': 'Vista do treino',
'Cards': 'Cartões',
'List': 'Lista',
'Current': 'Atual',
'Set current': 'Marcar como atual',
'Move, swap and remove below act on the exercise marked {0}.': 'Mover, trocar e remover abaixo atuam sobre o exercício marcado como {0}.',
'Full': 'Grande',
'Small': 'Pequena',
'Hidden': 'Oculta',
@@ -1080,4 +1107,34 @@ export default {
'Set to 0 to go back to the default ({0}).': 'Coloca 0 para voltar à predefinição ({0}).',
'Applies to this exercise everywhere, not just this plan.': 'Aplica-se a este exercício em todo o lado, não só neste plano.',
'You still log the total weight — the bar only feeds the per-side plate math.': 'Continuas a registar o peso total — a barra só conta para o cálculo dos discos por lado.',
// Gym check-in (mobile-only)
'Check in': 'Check-in',
'At the gym': 'No ginásio',
'Show this at the gym': 'Mostra isto no ginásio',
'Add your gym card': 'Adiciona o teu cartão de sócio',
'Add a card': 'Adicionar um cartão',
'Type the number on your membership card, import a photo of it, or scan it with the camera. No extra app needed at the gym — just open this screen.': 'Escreve o número do teu cartão de sócio, importa uma foto ou digitaliza-o com a câmara. Não é preciso outra app no ginásio — basta abrir este ecrã.',
'Remove this card?': 'Remover este cartão?',
'Scan it, import a photo, or type the code by hand.': 'Digitaliza-o, importa uma foto ou escreve o código à mão.',
'Scan': 'Digitalizar',
'Import photo': 'Importar foto',
'Label': 'Etiqueta',
'e.g. FitZone downtown': 'p. ex. FitZone centro',
'Code': 'Código',
'Membership number or code': 'Número de sócio ou código',
'Save card': 'Guardar cartão',
'Gym card': 'Cartão do ginásio',
'Card added': 'Cartão adicionado',
'Nothing to save yet': 'Ainda não há nada para guardar',
"That's not a QR code — only QR cards can be shown here": 'Isto não é um código QR — aqui só podem ser mostrados cartões QR',
'No QR code found in that image': 'Nenhum código QR encontrado nessa imagem',
'Could not read that image': 'Não foi possível ler essa imagem',
'Camera permission is needed to scan. Enable it in Settings.': 'É necessária a permissão da câmara para digitalizar. Ativa-a nas Definições.',
'Scanning is not available on this device.': 'A digitalização não está disponível neste dispositivo.',
'Could not start the scanner': 'Não foi possível iniciar o scanner',
'Gym check-in': 'Check-in no ginásio',
'Show a card on Home with your membership QR codes.': 'Mostra no Início um cartão com os teus códigos QR de sócio.',
'Point the camera at the QR code': 'Aponta a câmara para o código QR',
'Camera is not available here — import a photo or type the code instead.': 'A câmara não está disponível aqui — importa uma foto ou escreve o código.',
'Camera access was denied — allow it in your browser and try again.': 'O acesso à câmara foi recusado — permite-o no navegador e tenta de novo.',
}
+61 -4
View File
@@ -23,6 +23,13 @@ export default {
'Resume': 'Продолжить',
'Stats': 'Статистика',
'Exercises': 'Упражнения',
'By muscle': 'По мышцам',
'Explore muscles': 'Изучить мышцы',
'Choose a muscle to see exercises that train it.': 'Выберите мышцу, чтобы увидеть упражнения, которые её тренируют.',
'Exercises for {0}': 'Упражнения для {0}',
'Clear selection': 'Очистить выбор',
'Primary target': 'Основная мышца',
'Also trains': 'Также тренирует',
'History': 'История',
'Settings': 'Настройки',
'Freestyle': 'Свободная',
@@ -202,8 +209,22 @@ export default {
'{0} — in progress': '{0} — идёт',
'Resume ▶': 'Продолжить ▶',
'Welcome!': 'Добро пожаловать!',
'Set up your weekly routine to get going — or load a ready-made Push / Pull / Legs plan.': 'Настрой свой недельный план — или загрузи готовый план Push / Pull / Ноги.',
'Load starter plan (PPL)': 'Загрузить стартовый план (PPL)',
'Set up your weekly routine to get going — or load a ready-made starter plan.': 'Настрой свой недельный план — или загрузи готовый стартовый план.',
'Load starter plan': 'Загрузить стартовый план',
'Choose starter plan': 'Выбери стартовый план',
'{0} days per week': 'Дней в неделю: {0}',
'{0} loaded': '{0} загружен',
'Load {0}?': 'Загрузить {0}?',
'Load plan': 'Загрузить план',
'The new plan will be scheduled on {0}. Existing routines are kept — only those days of the weekly plan change.': 'Новый план встанет на {0}. Все твои программы сохранятся — в плане недели изменятся только эти дни.',
'Push / Pull / Legs': 'Push / Pull / Ноги',
'Push, pull and legs each get their own day.': 'Жимы, тяги и ноги — каждому свой день.',
'Upper / Lower': 'Верх / Низ',
'Upper body twice, lower body twice.': 'Верх тела дважды, низ дважды.',
'Full Body': 'Всё тело',
'Three sessions, the whole body each time.': 'Три тренировки, каждый раз всё тело.',
'5×5': '5×5',
'Five sets of five on the main barbell lifts.': 'Пять подходов по пять в основных движениях со штангой.',
'Build my own plan': 'Создать свой план',
'{0} week streak': 'серия: {0} нед.',
'this week': 'на этой неделе',
@@ -228,7 +249,6 @@ export default {
'Week schedule': 'Расписание недели',
'No routines yet.': 'Программ пока нет.',
'Create one or load the starter plan.': 'Создай программу или загрузи стартовый план.',
'Load starter plan (Push / Pull / Legs)': 'Загрузить стартовый план (Push / Pull / Ноги)',
'Superset with exercise above': 'Суперсет с упражнением выше',
'Note (optional) — loading cues, "bar only then +1 plate/side each set", anything worth remembering here': 'Заметка (необязательно) — подсказки по нагрузке, напр. «только гриф, затем +1 блин на сторону каждый подход», всё, что стоит запомнить',
'No exercises yet — add your first one.': 'Упражнений пока нет — добавь первое.',
@@ -236,10 +256,11 @@ export default {
'Delete routine?': 'Удалить программу?',
'“{0}” and its exercises will be removed.': '«{0}» и её упражнения будут удалены.',
'Delete routine': 'Удалить программу',
'Copy routine': 'Копировать программу',
'Copy': 'Копия',
'{0} exercises with animations': '{0} упражнений с анимациями',
'Search…': 'Поиск…',
'No workouts yet.': 'Тренировок пока нет.',
'Starter plan loaded — Mon Push · Wed Pull · Fri Legs': 'Стартовый план загружен — Пн Push · Ср Pull · Пт Ноги',
'Enter a name': 'Введите имя',
'Profile created — data from this device moved into it': 'Профиль создан — данные с этого устройства перенесены в него',
'Profile created — data moved into it': 'Профиль создан — данные перенесены',
@@ -394,6 +415,12 @@ export default {
'Minimize': 'Свернуть',
'Expand': 'Развернуть',
'Exercise animations': 'Анимации упражнений',
'Workout view': 'Вид тренировки',
'Cards': 'Карточки',
'List': 'Список',
'Current': 'Текущее',
'Set current': 'Сделать текущим',
'Move, swap and remove below act on the exercise marked {0}.': 'Кнопки перемещения, замены и удаления ниже действуют на упражнение с пометкой {0}.',
'Full': 'Полная',
'Small': 'Малая',
'Hidden': 'Скрыта',
@@ -1080,4 +1107,34 @@ export default {
'Set to 0 to go back to the default ({0}).': 'Поставь 0, чтобы вернуться к значению по умолчанию ({0}).',
'Applies to this exercise everywhere, not just this plan.': 'Действует для этого упражнения везде, а не только в этом плане.',
'You still log the total weight — the bar only feeds the per-side plate math.': 'Записывается по-прежнему общий вес — гриф нужен только для расчёта блинов на сторону.',
// Gym check-in (mobile-only)
'Check in': 'Отметиться',
'At the gym': 'В зале',
'Show this at the gym': 'Покажите это в зале',
'Add your gym card': 'Добавьте карту зала',
'Add a card': 'Добавить карту',
'Type the number on your membership card, import a photo of it, or scan it with the camera. No extra app needed at the gym — just open this screen.': 'Введите номер клубной карты, импортируйте её фото или отсканируйте камерой. В зале не нужно отдельное приложение — просто откройте этот экран.',
'Remove this card?': 'Удалить эту карту?',
'Scan it, import a photo, or type the code by hand.': 'Отсканируйте её, импортируйте фото или введите код вручную.',
'Scan': 'Сканировать',
'Import photo': 'Импортировать фото',
'Label': 'Название',
'e.g. FitZone downtown': 'напр. FitZone в центре',
'Code': 'Код',
'Membership number or code': 'Номер участника или код',
'Save card': 'Сохранить карту',
'Gym card': 'Карта зала',
'Card added': 'Карта добавлена',
'Nothing to save yet': 'Пока нечего сохранять',
"That's not a QR code — only QR cards can be shown here": 'Это не QR-код — здесь можно показывать только QR-карты',
'No QR code found in that image': 'На изображении не найден QR-код',
'Could not read that image': 'Не удалось прочитать изображение',
'Camera permission is needed to scan. Enable it in Settings.': 'Для сканирования нужен доступ к камере. Включите его в настройках.',
'Scanning is not available on this device.': 'Сканирование недоступно на этом устройстве.',
'Could not start the scanner': 'Не удалось запустить сканер',
'Gym check-in': 'Отметка в зале',
'Show a card on Home with your membership QR codes.': 'Показывает на Главной карточку с вашими QR-кодами абонемента.',
'Point the camera at the QR code': 'Наведите камеру на QR-код',
'Camera is not available here — import a photo or type the code instead.': 'Камера здесь недоступна — импортируйте фото или введите код.',
'Camera access was denied — allow it in your browser and try again.': 'Доступ к камере запрещён — разрешите его в браузере и попробуйте снова.',
}
+61 -4
View File
@@ -25,6 +25,13 @@ export default {
'Resume': 'เล่นต่อ',
'Stats': 'สถิติ',
'Exercises': 'ท่าออกกำลังกาย',
'By muscle': 'ตามกล้ามเนื้อ',
'Explore muscles': 'สำรวจกล้ามเนื้อ',
'Choose a muscle to see exercises that train it.': 'เลือกกล้ามเนื้อเพื่อดูท่าออกกำลังกายที่ฝึกกล้ามเนื้อนั้น',
'Exercises for {0}': 'ท่าออกกำลังกายสำหรับ {0}',
'Clear selection': 'ล้างการเลือก',
'Primary target': 'กล้ามเนื้อหลัก',
'Also trains': 'ฝึกกล้ามเนื้อนี้ด้วย',
'History': 'ประวัติ',
'Settings': 'ตั้งค่า',
'Freestyle': 'ฟรีสไตล์',
@@ -202,8 +209,22 @@ export default {
'{0} — in progress': '{0} — กำลังดำเนินการ',
'Resume ▶': 'เล่นต่อ ▶',
'Welcome!': 'ยินดีต้อนรับ!',
'Set up your weekly routine to get going — or load a ready-made Push / Pull / Legs plan.': 'ตั้งค่ารูทีนรายสัปดาห์เพื่อเริ่มต้น — หรือโหลดแผนสำเร็จรูป Push / Pull / Legs',
'Load starter plan (PPL)': 'โหลดแผนเริ่มต้น (PPL)',
'Set up your weekly routine to get going — or load a ready-made starter plan.': 'ตั้งค่ารูทีนรายสัปดาห์เพื่อเริ่มต้น — หรือโหลดแผนเริ่มต้นสำเร็จรูป',
'Load starter plan': 'โหลดแผนเริ่มต้น',
'Choose starter plan': 'เลือกแผนเริ่มต้น',
'{0} days per week': 'สัปดาห์ละ {0} วัน',
'{0} loaded': 'โหลด {0} แล้ว',
'Load {0}?': 'โหลด {0} ไหม',
'Load plan': 'โหลดแผน',
'The new plan will be scheduled on {0}. Existing routines are kept — only those days of the weekly plan change.': 'แผนใหม่จะลงใน {0} รูทีนเดิมของคุณยังอยู่ครบ — เปลี่ยนเฉพาะวันเหล่านี้ในแผนรายสัปดาห์',
'Push / Pull / Legs': 'Push / Pull / Legs',
'Push, pull and legs each get their own day.': 'ดัน ดึง และขา แยกกันคนละวัน',
'Upper / Lower': 'บน / ล่าง',
'Upper body twice, lower body twice.': 'ลำตัวบนสองครั้ง ลำตัวล่างสองครั้ง',
'Full Body': 'เต็มตัว',
'Three sessions, the whole body each time.': 'สามครั้ง ครบทั้งตัวทุกครั้ง',
'5×5': '5×5',
'Five sets of five on the main barbell lifts.': 'ห้าเซ็ต เซ็ตละห้าครั้ง ในท่าบาร์เบลหลัก',
'Build my own plan': 'สร้างแผนของตัวเอง',
'{0} week streak': 'ต่อเนื่อง {0} สัปดาห์',
'this week': 'สัปดาห์นี้',
@@ -231,7 +252,6 @@ export default {
'Routines': 'รูทีน',
'No routines yet.': 'ยังไม่มีรูทีน',
'Create one or load the starter plan.': 'สร้างใหม่หรือโหลดแผนเริ่มต้น',
'Load starter plan (Push / Pull / Legs)': 'โหลดแผนเริ่มต้น (Push / Pull / Legs)',
// --- routine edit ---
'Superset with exercise above': 'ซูเปอร์เซ็ตกับท่าด้านบน',
'Note (optional) — loading cues, "bar only then +1 plate/side each set", anything worth remembering here': 'บันทึก (ไม่บังคับ) — เคล็ดลับการตั้งน้ำหนัก เช่น "เอาแค่บาร์เปล่าก่อน แล้วค่อยเพิ่มแผ่นละ 1 แผ่นต่อข้างทุกเซ็ต" หรืออะไรก็ตามที่อยากจดจำไว้',
@@ -240,11 +260,12 @@ export default {
'Delete routine?': 'ลบรูทีนนี้?',
'“{0}” and its exercises will be removed.': '“{0}” และท่าทั้งหมดในนั้นจะถูกลบ',
'Delete routine': 'ลบรูทีน',
'Copy routine': 'คัดลอกรูทีน',
'Copy': 'สำเนา',
// --- library / history ---
'{0} exercises with animations': '{0} ท่าพร้อมภาพเคลื่อนไหว',
'Search…': 'ค้นหา…',
'No workouts yet.': 'ยังไม่มีการออกกำลังกาย',
'Starter plan loaded — Mon Push · Wed Pull · Fri Legs': 'โหลดแผนเริ่มต้นแล้ว — จ. Push · พ. Pull · ศ. Legs',
// --- login / account ---
'Enter a name': 'กรอกชื่อ',
'Profile created — data from this device moved into it': 'สร้างโปรไฟล์แล้ว — ย้ายข้อมูลจากเครื่องนี้เข้าไปแล้ว',
@@ -404,6 +425,12 @@ export default {
'Minimize': 'ย่อ',
'Expand': 'ขยาย',
'Exercise animations': 'ภาพเคลื่อนไหวท่าออกกำลังกาย',
'Workout view': 'มุมมองการฝึก',
'Cards': 'การ์ด',
'List': 'รายการ',
'Current': 'ปัจจุบัน',
'Set current': 'ตั้งเป็นปัจจุบัน',
'Move, swap and remove below act on the exercise marked {0}.': 'การย้าย สลับ และลบด้านล่างจะมีผลกับท่าที่ทำเครื่องหมาย {0} ไว้',
'Full': 'เต็ม',
'Small': 'เล็ก',
'Hidden': 'ซ่อน',
@@ -756,6 +783,31 @@ export default {
'Set to 0 to go back to the default ({0}).': 'ตั้งเป็น 0 เพื่อกลับไปใช้ค่าเริ่มต้น ({0})',
'Applies to this exercise everywhere, not just this plan.': 'มีผลกับท่านี้ทุกที่ ไม่ใช่เฉพาะในแผนนี้',
'You still log the total weight — the bar only feeds the per-side plate math.': 'คุณยังบันทึกน้ำหนักรวมเหมือนเดิม — บาร์ใช้สำหรับคำนวณแผ่นน้ำหนักต่อข้างเท่านั้น',
// Gym check-in (mobile-only)
'Check in': 'เช็คอิน',
'At the gym': 'ที่ยิม',
'Show this at the gym': 'แสดงสิ่งนี้ที่ยิม',
'Add your gym card': 'เพิ่มบัตรสมาชิกยิมของคุณ',
'Add a card': 'เพิ่มบัตร',
'Type the number on your membership card, import a photo of it, or scan it with the camera. No extra app needed at the gym — just open this screen.': 'พิมพ์หมายเลขบนบัตรสมาชิก นำเข้ารูปถ่าย หรือสแกนด้วยกล้อง ไม่ต้องใช้แอปอื่นที่ยิม — แค่เปิดหน้าจอนี้',
'Remove this card?': 'ลบบัตรนี้หรือไม่?',
'Scan it, import a photo, or type the code by hand.': 'สแกน นำเข้ารูปถ่าย หรือพิมพ์รหัสด้วยตนเอง',
'Scan': 'สแกน',
'Import photo': 'นำเข้ารูปถ่าย',
'Label': 'ป้ายชื่อ',
'e.g. FitZone downtown': 'เช่น FitZone ใจกลางเมือง',
'Code': 'รหัส',
'Membership number or code': 'หมายเลขสมาชิกหรือรหัส',
'Save card': 'บันทึกบัตร',
'Gym card': 'บัตรยิม',
'Card added': 'เพิ่มบัตรแล้ว',
'Nothing to save yet': 'ยังไม่มีอะไรให้บันทึก',
"That's not a QR code — only QR cards can be shown here": 'นี่ไม่ใช่คิวอาร์โค้ด — ที่นี่แสดงได้เฉพาะบัตรคิวอาร์โค้ดเท่านั้น',
'No QR code found in that image': 'ไม่พบคิวอาร์โค้ดในรูปภาพนั้น',
'Could not read that image': 'ไม่สามารถอ่านรูปภาพนั้นได้',
'Camera permission is needed to scan. Enable it in Settings.': 'ต้องมีสิทธิ์กล้องเพื่อสแกน เปิดใช้งานในการตั้งค่า',
'Scanning is not available on this device.': 'อุปกรณ์นี้ไม่รองรับการสแกน',
'Could not start the scanner': 'ไม่สามารถเริ่มเครื่องสแกนได้',
// --- AI Coach ---
'The Coach is reading your training…': 'โค้ชกำลังอ่านการฝึกของคุณ…',
'Could not ask the Coach': 'ไม่สามารถถามโค้ชได้',
@@ -1091,4 +1143,9 @@ export default {
'What should change?': 'ควรเปลี่ยนอะไร',
'Coach is thinking…': 'โค้ชกำลังคิด…',
'Message the Coach…': 'ส่งข้อความถึงโค้ช…',
'Gym check-in': 'เช็คอินที่ยิม',
'Show a card on Home with your membership QR codes.': 'แสดงการ์ดพร้อม QR โค้ดสมาชิกของคุณบนหน้าหลัก',
'Point the camera at the QR code': 'เล็งกล้องไปที่ QR โค้ด',
'Camera is not available here — import a photo or type the code instead.': 'ใช้กล้องที่นี่ไม่ได้ — นำเข้ารูปภาพหรือพิมพ์รหัสแทน',
'Camera access was denied — allow it in your browser and try again.': 'การเข้าถึงกล้องถูกปฏิเสธ — อนุญาตในเบราว์เซอร์แล้วลองอีกครั้ง',
}
+61 -4
View File
@@ -23,6 +23,13 @@ export default {
'Resume': 'Devam et',
'Stats': 'İstatistik',
'Exercises': 'Egzersizler',
'By muscle': 'Kasa göre',
'Explore muscles': 'Kasları keşfet',
'Choose a muscle to see exercises that train it.': 'Çalıştıran egzersizleri görmek için bir kas seçin.',
'Exercises for {0}': '{0} için egzersizler',
'Clear selection': 'Seçimi temizle',
'Primary target': 'Ana hedef',
'Also trains': 'Ayrıca çalıştırır',
'History': 'Geçmiş',
'Settings': 'Ayarlar',
'Freestyle': 'Serbest',
@@ -202,8 +209,22 @@ export default {
'{0} — in progress': '{0} — devam ediyor',
'Resume ▶': 'Devam et ▶',
'Welcome!': 'Hoş geldin!',
'Set up your weekly routine to get going — or load a ready-made Push / Pull / Legs plan.': 'Başlamak için haftalık rutinini kur — ya da hazır bir Push / Pull / Bacak planı yükle.',
'Load starter plan (PPL)': 'Başlangıç planını yükle (PPL)',
'Set up your weekly routine to get going — or load a ready-made starter plan.': 'Başlamak için haftalık rutinini kur — ya da hazır bir başlangıç planı yükle.',
'Load starter plan': 'Başlangıç planı yükle',
'Choose starter plan': 'Başlangıç planı seç',
'{0} days per week': 'Haftada {0} gün',
'{0} loaded': '{0} yüklendi',
'Load {0}?': '{0} yüklensin mi?',
'Load plan': 'Planı yükle',
'The new plan will be scheduled on {0}. Existing routines are kept — only those days of the weekly plan change.': 'Yeni plan {0} günlerine yerleşecek. Mevcut rutinlerin duruyor — haftalık planda yalnızca bu günler değişiyor.',
'Push / Pull / Legs': 'Push / Pull / Bacak',
'Push, pull and legs each get their own day.': 'İtiş, çekiş ve bacak; her biri kendi gününde.',
'Upper / Lower': 'Üst / Alt',
'Upper body twice, lower body twice.': 'Üst vücut iki kez, alt vücut iki kez.',
'Full Body': 'Tüm vücut',
'Three sessions, the whole body each time.': 'Üç antrenman, her seferinde tüm vücut.',
'5×5': '5×5',
'Five sets of five on the main barbell lifts.': 'Ana halter hareketlerinde beşer tekrarlı beş set.',
'Build my own plan': 'Kendi planımı oluştur',
'{0} week streak': '{0} haftalık seri',
'this week': 'bu hafta',
@@ -228,7 +249,6 @@ export default {
'Week schedule': 'Hafta programı',
'No routines yet.': 'Henüz rutin yok.',
'Create one or load the starter plan.': 'Bir tane oluştur ya da başlangıç planını yükle.',
'Load starter plan (Push / Pull / Legs)': 'Başlangıç planını yükle (Push / Pull / Bacak)',
'Superset with exercise above': 'Üstteki egzersizle süperset',
'Note (optional) — loading cues, "bar only then +1 plate/side each set", anything worth remembering here': 'Not (isteğe bağlı) — yükleme ipuçları, örn. "sadece bar, sonra her sette +1 disk/taraf", aklında tutmak istediğin her şey',
'No exercises yet — add your first one.': 'Henüz egzersiz yok — ilkini ekle.',
@@ -236,10 +256,11 @@ export default {
'Delete routine?': 'Rutin silinsin mi?',
'“{0}” and its exercises will be removed.': '“{0}” ve egzersizleri kaldırılacak.',
'Delete routine': 'Rutini sil',
'Copy routine': 'Rutini kopyala',
'Copy': 'Kopya',
'{0} exercises with animations': 'animasyonlu {0} egzersiz',
'Search…': 'Ara…',
'No workouts yet.': 'Henüz antrenman yok.',
'Starter plan loaded — Mon Push · Wed Pull · Fri Legs': 'Başlangıç planı yüklendi — Pzt Push · Çar Pull · Cum Bacak',
'Enter a name': 'Bir isim gir',
'Profile created — data from this device moved into it': 'Profil oluşturuldu — bu cihazdaki veriler profile taşındı',
'Profile created — data moved into it': 'Profil oluşturuldu — veriler taşındı',
@@ -394,6 +415,12 @@ export default {
'Minimize': 'Küçült',
'Expand': 'Büyüt',
'Exercise animations': 'Egzersiz animasyonları',
'Workout view': 'Antrenman görünümü',
'Cards': 'Kartlar',
'List': 'Liste',
'Current': 'Aktif',
'Set current': 'Aktif olarak işaretle',
'Move, swap and remove below act on the exercise marked {0}.': 'Aşağıdaki taşıma, değiştirme ve kaldırma işlemleri {0} olarak işaretli egzersiz için geçerlidir.',
'Full': 'Tam',
'Small': 'Küçük',
'Hidden': 'Gizli',
@@ -1080,4 +1107,34 @@ export default {
'Set to 0 to go back to the default ({0}).': 'Varsayılana ({0}) dönmek için 0 yap.',
'Applies to this exercise everywhere, not just this plan.': 'Yalnızca bu planda değil, bu egzersiz için her yerde geçerli.',
'You still log the total weight — the bar only feeds the per-side plate math.': 'Yine de toplam ağırlığı kaydedersin — bar yalnızca taraf başına plaka hesabına girer.',
// Gym check-in (mobile-only)
'Check in': 'Giriş yap',
'At the gym': 'Salonda',
'Show this at the gym': 'Bunu salonda göster',
'Add your gym card': 'Salon kartını ekle',
'Add a card': 'Kart ekle',
'Type the number on your membership card, import a photo of it, or scan it with the camera. No extra app needed at the gym — just open this screen.': 'Üyelik kartındaki numarayı yaz, fotoğrafını içe aktar ya da kamerayla tara. Salonda ekstra bir uygulamaya gerek yok — sadece bu ekranı aç.',
'Remove this card?': 'Bu kart kaldırılsın mı?',
'Scan it, import a photo, or type the code by hand.': 'Tara, bir fotoğraf içe aktar ya da kodu elle yaz.',
'Scan': 'Tara',
'Import photo': 'Fotoğraf içe aktar',
'Label': 'Etiket',
'e.g. FitZone downtown': 'örn. FitZone merkez',
'Code': 'Kod',
'Membership number or code': 'Üyelik numarası veya kodu',
'Save card': 'Kartı kaydet',
'Gym card': 'Salon kartı',
'Card added': 'Kart eklendi',
'Nothing to save yet': 'Henüz kaydedilecek bir şey yok',
"That's not a QR code — only QR cards can be shown here": 'Bu bir QR kod değil — burada yalnızca QR kartlar gösterilebilir',
'No QR code found in that image': 'Bu görüntüde QR kod bulunamadı',
'Could not read that image': 'Bu görüntü okunamadı',
'Camera permission is needed to scan. Enable it in Settings.': 'Taramak için kamera izni gerekir. Ayarlar’dan etkinleştir.',
'Scanning is not available on this device.': 'Tarama bu cihazda kullanılamıyor.',
'Could not start the scanner': 'Tarayıcı başlatılamadı',
'Gym check-in': 'Salon girişi',
'Show a card on Home with your membership QR codes.': 'Ana sayfada üyelik QR kodlarınızı içeren bir kart gösterir.',
'Point the camera at the QR code': 'Kamerayı QR koda tutun',
'Camera is not available here — import a photo or type the code instead.': 'Kamera burada kullanılamıyor — bir fotoğraf içe aktarın veya kodu yazın.',
'Camera access was denied — allow it in your browser and try again.': 'Kamera erişimi reddedildi — tarayıcıda izin verip tekrar deneyin.',
}
+61 -4
View File
@@ -23,6 +23,13 @@ export default {
'Resume': '继续',
'Stats': '统计',
'Exercises': '动作库',
'By muscle': '按肌肉',
'Explore muscles': '探索肌肉',
'Choose a muscle to see exercises that train it.': '选择一块肌肉以查看训练它的动作。',
'Exercises for {0}': '{0} 训练动作',
'Clear selection': '清除选择',
'Primary target': '主要目标',
'Also trains': '同时训练',
'History': '历史',
'Settings': '设置',
'Freestyle': '自由训练',
@@ -202,8 +209,22 @@ export default {
'{0} — in progress': '{0}——进行中',
'Resume ▶': '继续 ▶',
'Welcome!': '欢迎!',
'Set up your weekly routine to get going — or load a ready-made Push / Pull / Legs plan.': '设置每周计划开始训练——或加载现成的推 / 拉 / 腿计划。',
'Load starter plan (PPL)': '加载入门计划(PPL)',
'Set up your weekly routine to get going — or load a ready-made starter plan.': '设置每周计划开始训练——或加载现成的入门计划。',
'Load starter plan': '加载入门计划',
'Choose starter plan': '选择入门计划',
'{0} days per week': '每周 {0} 天',
'{0} loaded': '已加载{0}',
'Load {0}?': '加载{0}?',
'Load plan': '加载计划',
'The new plan will be scheduled on {0}. Existing routines are kept — only those days of the weekly plan change.': '新计划将安排在{0}。你现有的训练日都会保留——每周计划中只有这几天会改变。',
'Push / Pull / Legs': '推 / 拉 / 腿',
'Push, pull and legs each get their own day.': '推、拉、腿各占一天。',
'Upper / Lower': '上肢 / 下肢',
'Upper body twice, lower body twice.': '上肢两次,下肢两次。',
'Full Body': '全身',
'Three sessions, the whole body each time.': '三次训练,每次练全身。',
'5×5': '5×5',
'Five sets of five on the main barbell lifts.': '主要杠铃动作五组五次。',
'Build my own plan': '创建自己的计划',
'{0} week streak': '连续 {0} 周',
'this week': '本周',
@@ -228,7 +249,6 @@ export default {
'Week schedule': '每周日程',
'No routines yet.': '还没有训练日。',
'Create one or load the starter plan.': '创建一个或加载入门计划。',
'Load starter plan (Push / Pull / Legs)': '加载入门计划(推 / 拉 / 腿)',
'Superset with exercise above': '与上面的动作组成超级组',
'Note (optional) — loading cues, "bar only then +1 plate/side each set", anything worth remembering here': '备注(可选)— 加重提示,例如"空杠开始,之后每组每侧+1片",任何你想记住的内容',
'No exercises yet — add your first one.': '还没有动作——添加第一个吧。',
@@ -236,10 +256,11 @@ export default {
'Delete routine?': '删除训练日?',
'“{0}” and its exercises will be removed.': '“{0}”及其动作将被移除。',
'Delete routine': '删除训练日',
'Copy routine': '复制训练日',
'Copy': '副本',
'{0} exercises with animations': '{0} 个带动画的动作',
'Search…': '搜索…',
'No workouts yet.': '还没有训练。',
'Starter plan loaded — Mon Push · Wed Pull · Fri Legs': '入门计划已加载——周一推 · 周三拉 · 周五腿',
'Enter a name': '请输入名字',
'Profile created — data from this device moved into it': '档案已创建——本设备数据已转入',
'Profile created — data moved into it': '档案已创建——数据已转入',
@@ -394,6 +415,12 @@ export default {
'Minimize': '缩小',
'Expand': '放大',
'Exercise animations': '动作动画',
'Workout view': '训练视图',
'Cards': '卡片',
'List': '列表',
'Current': '当前',
'Set current': '设为当前',
'Move, swap and remove below act on the exercise marked {0}.': '下方的移动、替换和删除将作用于标记为{0}的动作。',
'Full': '完整',
'Small': '小',
'Hidden': '隐藏',
@@ -1080,4 +1107,34 @@ export default {
'Set to 0 to go back to the default ({0}).': '设为 0 即恢复默认值({0})。',
'Applies to this exercise everywhere, not just this plan.': '对这个动作处处生效,不只在此计划中。',
'You still log the total weight — the bar only feeds the per-side plate math.': '记录的仍是总重量——杆重只用于每侧杠铃片的计算。',
// Gym check-in (mobile-only)
'Check in': '签到',
'At the gym': '在健身房',
'Show this at the gym': '在健身房出示这个',
'Add your gym card': '添加你的会员卡',
'Add a card': '添加卡片',
'Type the number on your membership card, import a photo of it, or scan it with the camera. No extra app needed at the gym — just open this screen.': '输入会员卡上的号码、导入卡片照片,或用相机扫描。在健身房无需额外应用——打开此界面即可。',
'Remove this card?': '删除这张卡片?',
'Scan it, import a photo, or type the code by hand.': '扫描它、导入照片,或手动输入代码。',
'Scan': '扫描',
'Import photo': '导入照片',
'Label': '名称',
'e.g. FitZone downtown': '例如 FitZone 市中心店',
'Code': '代码',
'Membership number or code': '会员号或代码',
'Save card': '保存卡片',
'Gym card': '健身房卡片',
'Card added': '已添加卡片',
'Nothing to save yet': '暂无可保存的内容',
"That's not a QR code — only QR cards can be shown here": '这不是二维码——此处只能显示二维码卡片',
'No QR code found in that image': '在该图片中未找到二维码',
'Could not read that image': '无法读取该图片',
'Camera permission is needed to scan. Enable it in Settings.': '扫描需要相机权限。请在设置中开启。',
'Scanning is not available on this device.': '此设备不支持扫描。',
'Could not start the scanner': '无法启动扫描器',
'Gym check-in': '健身房签到',
'Show a card on Home with your membership QR codes.': '在首页显示一张包含会员二维码的卡片。',
'Point the camera at the QR code': '将摄像头对准二维码',
'Camera is not available here — import a photo or type the code instead.': '此处无法使用摄像头 — 请导入照片或手动输入代码。',
'Camera access was denied — allow it in your browser and try again.': '摄像头访问被拒绝 — 请在浏览器中允许后重试。',
}
+82 -14
View File
@@ -4,18 +4,19 @@ import { useUI } from './store/useUI.js'
import { EXDB, EXIDX, BODYPARTS, isCardio, isBodyweightEq, allExercises, equipmentOf, smOf, matchExercise, exOr } from './lib/exercises.js'
import { activeProfile, exAvailable, ALL_EQUIPMENT, newProfile } from './lib/equipment.js'
import { fmtDate, fmtNum, fmtVol, fmtDur, durPart, todayISO, isoOf, uid, exCount, DAYN, DAYS, weekOrder, weekStartOf, weekDayOffset, 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, applyIntensifierPlan, MAX_PLANNED_WARMUPS, NOTE_MAX } from './lib/history.js'
import { lastEntryFor, bestWeightFor, bestWeightForEntry, buildSets, effectiveRoutineId, workoutVolume, setsDone, setsDoneActive, lastBW, supersetUnits, unitOf, setLabel, defaultConfig, cleanupSg, modeOf, effortOf, isBw, isPerSide, sideReps, workSetsDone, applyIntensifierPlan, MAX_PLANNED_WARMUPS, NOTE_MAX } from './lib/history.js'
import { usesBar, barWeightFor, defaultBarWeight, hasBarOverride } from './lib/bar.js'
import { beep, vibrate } from './lib/sound.js'
import { t, instrFor, exerciseNameFor, getLang, INSTR_LANGS } from './lib/i18n.js'
import { t, dateLocale, instrFor, exerciseNameFor, getLang, INSTR_LANGS } from './lib/i18n.js'
import { nav } from './lib/nav.js'
import { starterRoutines } from './lib/starter.js'
import { buildStarterPlan, starterPlanDays, starterPlanOptions } from './lib/starter.js'
import Media, { Thumb } from './components/Media.jsx'
import Stepper from './components/Stepper.jsx'
import Icon from './components/Icon.jsx'
import { Button, Slider, Switch, Segmented, SelectRow, Row, TextField, MultiSelectRow } from './components/ui.jsx'
import { glyphOf, GLYPH_GROUPS, DEFAULT_GLYPH } from './lib/glyphs.js'
import BodyMap from './components/BodyMap.jsx'
import MuscleExplorer from './components/MuscleExplorer.jsx'
import { exerciseMuscleSnapshot, loadOfWorkouts, MUSCLES, MUSCLE_NAME, normalizeMuscleGroups, hasExplicitMuscleMetadata } from './lib/muscles.js'
import { parseImport, mergeImport } from './lib/import-csv.js'
import { importHevyData, HevyApiError, HEVY_DEV_SETTINGS, mergeHevyRoutines } from './lib/import-hevy.js'
@@ -54,15 +55,65 @@ export function confirmSheet(opts) {
}
/* ============================ starter plan ============================ */
export function loadStarterPlan() {
const [push, pull, legs] = starterRoutines()
update(st => {
st.routines.push(push, pull, legs)
st.week[1] = push.id; st.week[3] = pull.id; st.week[5] = legs.id
})
toast(t('Starter plan loaded — Mon Push · Wed Pull · Fri Legs'))
// Plan names and blurbs live here, not in lib/starter.js: check-source-strings.mjs only finds
// string literals written inside a t() call, so copy parked in the catalog and passed in as a
// variable is invisible to it — it would quietly stay English in every language.
const PLAN_COPY = {
ppl: () => ({ name: t('Push / Pull / Legs'), about: t('Push, pull and legs each get their own day.') }),
'upper-lower': () => ({ name: t('Upper / Lower'), about: t('Upper body twice, lower body twice.') }),
'full-body': () => ({ name: t('Full Body'), about: t('Three sessions, the whole body each time.') }),
'5x5': () => ({ name: t('5×5'), about: t('Five sets of five on the main barbell lifts.') })
}
// Adds the plan's routines and puts them on its weekdays. Existing routines are never touched
// and only the weekdays the plan asks for are reassigned; an id with no plan behind it changes
// nothing at all. planId is deliberately required — a default invites `onClick={loadStarterPlan}`,
// which hands the click event in as the plan and silently loads nothing.
export function loadStarterPlan(planId) {
const plan = buildStarterPlan(planId)
if (!plan) return false
update(st => {
st.routines.push(...plan.routines)
plan.schedule.forEach(({ day, routineId }) => { st.week[day] = routineId })
})
toast(t('{0} loaded', PLAN_COPY[planId]().name))
return true
}
// Intl joins the days the way each language does it — "and" vs "und", "、" in Chinese.
const dayList = days => new Intl.ListFormat(dateLocale()).format(days.map(d => t(DAYN[d])))
function StarterPlanChooser({ close }) {
const week = useStore(s => s.S.week)
const choose = (id, name) => {
const days = starterPlanDays(id)
close()
// A confirmation is only worth showing when one of those days is actually occupied.
if (!days.some(day => week[day])) { loadStarterPlan(id); return }
confirmSheet({
title: t('Load {0}?', name),
message: t('The new plan will be scheduled on {0}. Existing routines are kept — only those days of the weekly plan change.', dayList(days)),
confirmText: t('Load plan'),
onConfirm: () => loadStarterPlan(id)
})
}
return <>
<h3>{t('Choose starter plan')}</h3>
<div className="list">
{starterPlanOptions().map(({ id, days }) => {
const { name, about } = PLAN_COPY[id]()
return <div key={id} className="item" {...tappable(() => choose(id, name))}>
<span className="lrow-i" style={{ background: 'var(--surface-3)' }}><Icon name="sparkles" /></span>
<div className="grow"><div className="tt">{name}</div><div className="ss">{t('{0} days per week', days)} · {about}</div></div>
<Icon name="chevronRight" className="chev" />
</div>
})}
</div>
</>
}
export const starterPlanSheet = () => ui().openSheet(close => <StarterPlanChooser close={close} />)
/* ============================ weight picker (shared: body weight + goal) ============================ */
// Fixed range, not a moving window — a window that resizes itself mid-drag (the previous
// attempt) makes the thumb's position unpredictable: every time it grows, everything already
@@ -712,6 +763,7 @@ function ExercisePicker({ onPick, close }) {
const [eq, setEq] = useState('') // '' = any equipment
const [showAll, setShowAll] = useState(false)
const [shown, setShown] = useState(50)
const [byMuscle, setByMuscle] = useState(false)
const searchRef = useRef(null)
const bpStrip = useRef(null), eqStrip = useRef(null)
const onSearchFocus = useSheetKeyboard(searchRef)
@@ -729,8 +781,17 @@ function ExercisePicker({ onPick, close }) {
const chosenCount = Object.keys(usage).length
useRevealActiveChip(bpStrip, bp)
useRevealActiveChip(eqStrip, eqOn)
if (byMuscle) return <>
<div className="row between" style={{ marginBottom: 10 }}><h3>{t('Add exercise')}</h3>
<Button size="sm" variant="ghost" onClick={() => setByMuscle(false)}>{t('All')}</Button>
</div>
<MuscleExplorer onPick={onPick} />
</>
return <>
<h3>{t('Add exercise')}</h3>
<div className="row between" style={{ marginBottom: 10 }}><h3>{t('Add exercise')}</h3>
<Button size="sm" variant="tinted" icon="target" onClick={() => setByMuscle(true)}>{t('By muscle')}</Button>
</div>
{/* .picker-search is what index.css keys the keyboard-aware sheet layout on: the sheet
lifts above the keys and the search stays put while the list scrolls under it. */}
<div className="picker-search"><div className="search"><svg viewBox="0 0 24 24"><circle cx="11" cy="11" r="7" /><path d="m21 21-4.3-4.3" /></svg>
@@ -758,7 +819,14 @@ function ExercisePicker({ onPick, close }) {
</div>}
{f.slice(0, shown).map(e => <div key={e.id} className="item" {...tappable(() => onPick(e))}>
<Thumb ex={e} /><div className="grow"><div className="tt capitalize">{exerciseNameFor(e)}</div><div className="ss capitalize">{t(e.tg || e.bp)} · {t(e.eq)}</div></div>
{usage[e.id] && <span className="tag acc"><Icon name="starFill" /></span>}<Icon name="plus" className="chev" />
{usage[e.id] && <span className="tag acc"><Icon name="starFill" /></span>}
{/* A "+" glyph reads as "add this now" — it used to just open the same detail sheet as
tapping the row, so it added nothing until you'd scrolled past the sets/reps config
and found the real button. Now it does what it looks like: adds with the default
config right away. Tapping the row itself still opens the detail/config sheet, for
when you want to set sets/reps before adding. */}
<button className="iconbtn chev" aria-label={t('Add “{0}”', exerciseNameFor(e))} style={{ padding: 8, margin: -8 }}
onClick={ev => { ev.stopPropagation(); onPick(e, true) }}><Icon name="plus" /></button>
</div>)}
{f.length === 0 && bp === '★' && <div className="empty">{t('Nothing chosen yet — add exercises and they’ll show up here.')}</div>}
</div>
@@ -783,7 +851,7 @@ export function swapActiveWorkoutExercise(index) {
const freestyle = !st.active?.routineId
const step = defaultIncrement(ex.id, st.unit)
const plan = freestyle ? null : nextPrescription(st, full, st.routines.find(r => r.id === st.active.routineId))
const built = buildSets(st, full, { step, ...(freestyle ? { preferLast: true } : {}) })
const built = buildSets(st, full, { step, ...(freestyle ? { preferLast: true } : {}), ...(plan?.kind === 'off' ? { useTarget: true } : {}) })
const replacement = {
id: ex.id,
target: { ...cfg },
@@ -1740,7 +1808,7 @@ function doFinishWorkout() {
s.workouts = completeBackfill(s.workouts, A, w)
} else {
w.entries.forEach(e => {
const mx = Math.max(0, ...e.sets.filter(x => x.done && !isWarmupRow(x)).map(x => x.w || 0), e.topW || 0)
const mx = bestWeightForEntry(e)
if (mx > 0) { const cur = s.exWeights[e.id]; if (!cur || mx > cur.w) s.exWeights[e.id] = { w: mx, d: w.d } }
})
s.workouts.push(w)
+127
View File
@@ -0,0 +1,127 @@
// @vitest-environment happy-dom
// The chooser is where a starter plan can quietly do the wrong thing: overwrite a weekday
// without asking, ask when there was nothing to overwrite, or apply a plan the user cancelled.
import React, { act } from 'react'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { createRoot } from 'react-dom/client'
import { useStore } from './store/useStore.js'
import { useUI } from './store/useUI.js'
import { loadStarterPlan, starterPlanSheet } from './sheets.jsx'
const mounted = []
const S = () => useStore.getState().S
const nameOn = day => S().routines.find(r => r.id === S().week[day])?.name
// Renders whatever sheet is on top and returns its host element.
function renderTop() {
const sheet = useUI.getState().sheets.at(-1)
const host = document.createElement('div')
document.body.appendChild(host)
const root = createRoot(host)
mounted.push(root)
act(() => root.render(sheet.render(() => useUI.getState().closeSheet(sheet.id))))
return host
}
const rowFor = (host, name) => [...host.querySelectorAll('.item')].find(el => el.querySelector('.tt')?.textContent === name)
const buttonFor = (host, label) => [...host.querySelectorAll('button')].find(b => b.textContent === label)
// Opens the chooser and taps one of its rows.
function choose(name) {
starterPlanSheet()
const host = renderTop()
act(() => { rowFor(host, name).click() })
}
beforeEach(() => {
globalThis.IS_REACT_ACT_ENVIRONMENT = true
useUI.setState({ sheets: [], toastMsg: '' })
useStore.setState(s => ({
S: { ...s.S, routines: [{ id: 'mine', name: 'My routine', emoji: 'star', ex: [] }], week: {}, active: null },
}))
document.body.innerHTML = ''
})
afterEach(() => {
act(() => { mounted.splice(0).forEach(root => root.unmount()) })
})
describe('starter plan chooser', () => {
it('lists every plan with its day count', () => {
starterPlanSheet()
const host = renderTop()
expect([...host.querySelectorAll('.item .tt')].map(el => el.textContent))
.toEqual(['Push / Pull / Legs', 'Upper / Lower', 'Full Body', '5×5'])
expect(rowFor(host, 'Upper / Lower').querySelector('.ss').textContent).toContain('4 days per week')
})
it('loads straight away when the plan’s weekdays are free, without asking', () => {
useStore.setState(s => ({ S: { ...s.S, week: { 0: 'mine', 6: 'mine' } } }))
choose('Upper / Lower')
expect(useUI.getState().sheets).toHaveLength(0) // no confirmation was raised
expect(nameOn(1)).toBe('Upper A')
expect(nameOn(2)).toBe('Lower A')
expect(nameOn(4)).toBe('Upper B')
expect(nameOn(5)).toBe('Lower B')
expect(S().week[0]).toBe('mine') // untouched weekdays stay put
expect(S().week[6]).toBe('mine')
expect(S().routines[0].name).toBe('My routine') // and nothing is deleted
expect(useUI.getState().toastMsg).toBe('Upper / Lower loaded')
})
it('asks first when a weekday the plan wants is already taken', () => {
useStore.setState(s => ({ S: { ...s.S, week: { 3: 'mine' } } }))
choose('Full Body')
const confirm = renderTop()
expect(confirm.querySelector('h3').textContent).toBe('Load Full Body?')
expect(confirm.textContent).toContain('Monday, Wednesday and Friday')
expect(S().week[3]).toBe('mine') // nothing applied yet
expect(S().routines).toHaveLength(1)
act(() => { buttonFor(confirm, 'Load plan').click() })
expect(nameOn(1)).toBe('Full Body A')
expect(nameOn(3)).toBe('Full Body B')
expect(nameOn(5)).toBe('Full Body C')
})
it('leaves everything alone when the confirmation is cancelled', () => {
useStore.setState(s => ({ S: { ...s.S, week: { 1: 'mine' } } }))
const before = structuredClone(S())
choose('5×5')
const confirm = renderTop()
act(() => { buttonFor(confirm, 'Cancel').click() })
expect(S()).toEqual(before)
expect(useUI.getState().toastMsg).toBe('')
})
it('does not ask when only weekdays outside the plan are occupied', () => {
useStore.setState(s => ({ S: { ...s.S, week: { 2: 'mine', 4: 'mine' } } })) // Tue + Thu
choose('5×5') // wants Mon/Wed/Fri
expect(useUI.getState().sheets).toHaveLength(0)
expect(nameOn(1)).toBe('5×5 A')
})
})
describe('loadStarterPlan', () => {
it('appends independent routines each time the same plan is loaded', () => {
loadStarterPlan('ppl')
const first = S().routines.slice(1).map(r => r.id)
loadStarterPlan('ppl')
const second = S().routines.slice(4).map(r => r.id)
expect(S().routines).toHaveLength(7)
expect(new Set([...first, ...second]).size).toBe(6)
expect(second.some(id => first.includes(id))).toBe(false)
})
it('refuses a plan it does not know and changes nothing', () => {
const before = structuredClone(S())
expect(loadStarterPlan('nope')).toBe(false)
expect(loadStarterPlan(undefined)).toBe(false)
expect(S()).toEqual(before)
expect(useUI.getState().toastMsg).toBe('')
})
})
@@ -0,0 +1,87 @@
// @vitest-environment happy-dom
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
vi.mock('../lib/api.js', () => ({ api: vi.fn(), setRemoteAuth: vi.fn() }))
import { DEF, useStore } from './useStore.js'
const clone = value => JSON.parse(JSON.stringify(value))
beforeEach(() => {
localStorage.clear()
useStore.setState({ S: clone(DEF), user: null, ready: false })
})
afterEach(() => {
localStorage.clear()
useStore.setState({ S: clone(DEF), user: null, ready: false })
})
// gymCards is plain profile data — it rides the same update()/persist() path as everything else,
// with no backend or schema change. These pin the contract the check-in view relies on: a fresh
// profile starts empty, and adding/removing a card mutates and persists like any other field.
describe('gymCards state', () => {
it('defaults to an empty array on a fresh profile', () => {
expect(useStore.getState().S.gymCards).toEqual([])
})
it('adds a card via update and persists it to localStorage', () => {
useStore.getState().update(s => {
s.gymCards.push({ id: 'c1', label: 'FitZone', value: 'ABC123', fmt: 'qrcode' })
}, false)
const cards = useStore.getState().S.gymCards
expect(cards).toHaveLength(1)
expect(cards[0]).toMatchObject({ id: 'c1', label: 'FitZone', value: 'ABC123', fmt: 'qrcode' })
// persist() writes the whole state under the app's storage key — the card must be in it.
const saved = JSON.parse(localStorage.getItem('gym_state_v1'))
expect(saved.gymCards).toHaveLength(1)
expect(saved.gymCards[0].value).toBe('ABC123')
})
it('removes a card by id, leaving the others', () => {
useStore.getState().update(s => {
s.gymCards.push({ id: 'a', label: 'A', value: '1', fmt: 'qrcode' })
s.gymCards.push({ id: 'b', label: 'B', value: '2', fmt: 'qrcode' })
}, false)
useStore.getState().update(s => {
s.gymCards = s.gymCards.filter(c => c.id !== 'a')
}, false)
const cards = useStore.getState().S.gymCards
expect(cards).toHaveLength(1)
expect(cards[0].id).toBe('b')
})
it('keeps multiple cards in insertion order', () => {
useStore.getState().update(s => {
s.gymCards.push({ id: '1', label: 'One', value: 'x', fmt: 'qrcode' })
s.gymCards.push({ id: '2', label: 'Two', value: 'y', fmt: 'qrcode' })
s.gymCards.push({ id: '3', label: 'Three', value: 'z', fmt: 'qrcode' })
}, false)
expect(useStore.getState().S.gymCards.map(c => c.id)).toEqual(['1', '2', '3'])
})
})
// The Settings switch. On by default; an older profile that predates the key must read as on
// too, and off only hides the feature — the cards themselves survive the round trip.
describe('checkIn switch', () => {
it('is on for a fresh profile', () => {
expect(useStore.getState().S.checkIn).toBe(true)
})
it('turning it off keeps the saved cards', () => {
useStore.getState().update(s => {
s.gymCards.push({ id: 'c1', label: 'FitZone', value: 'ABC123', fmt: 'qrcode' })
s.checkIn = false
}, false)
const S = useStore.getState().S
expect(S.checkIn).toBe(false)
expect(S.gymCards).toHaveLength(1)
})
})
+16
View File
@@ -14,6 +14,10 @@ export const DEF = {
theme: 'dark', accent: 'lime', body: 'male', targetW: null,
bodyweight: [], routines: [], week: {}, dayPlan: {},
exWeights: {}, workouts: [], active: null, customEx: [], gifSize: 'full',
// How the active workout is laid out — 'cards' (one exercise at a time with Prev/Next)
// or 'list' (every exercise stacked and scrollable). Purely presentational: profiles
// written before this setting existed overlay onto DEF and keep the 'cards' behaviour.
workoutView: 'cards',
// effort: which per-set effort scale is logged — 'none' | 'rir' | 'rpe'. null, not 'none', so
// 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
@@ -34,6 +38,18 @@ export const DEF = {
// lib/bar.js). Personal equipment, so it syncs with the account but never travels in a
// shared plan. Logged weights stay the total — this only feeds the plate math.
barWeights: {},
// Gym check-in cards (see views/CheckIn.jsx). Each is a membership
// code shown as a QR/barcode at the gym's turnstile — added by typing it, importing a photo
// of the card, or scanning it. We only ever keep the code's VALUE, never a photo: the image
// is regenerated from `value` every time it's shown (lib/qr.js). `fmt` is the barcode symbology
// ('qrcode' | 'ean13' | 'code128' | … — lower-cased BarcodeFormat) so it renders as the same
// kind of code the gym issued. Just data, so it syncs and backs up like everything else.
// [{ id, label, value, fmt }]
gymCards: [],
// Whether the check-in feature is on at all (Settings toggle). Off hides the Home
// card and the /checkin route; the saved gymCards stay so turning it back on restores them.
// Defaults on; an older profile without the key reads as on (`!== false`).
checkIn: true,
}
const clone = o => JSON.parse(JSON.stringify(o))
+28 -5
View File
@@ -13,6 +13,16 @@ const cancelPushRestTimer = () => { if (useStore.getState().user) api('/api/push
const notificationsSupported = () => typeof window !== 'undefined' && 'Notification' in window
let requestRestNotificationPermissionP = null
// Set the moment the tab goes hidden, never cleared here — timerTick/workTick read and
// clear it themselves once they're running visible again. Lets a completion tick tell
// "the countdown hit zero while the app was actually open" from "it hit zero while
// backgrounded/closed and we're only just catching up now that it's open again" — the
// latter must skip beep/vibrate/flash/toast and rely solely on the push notification.
let pageHiddenAt = null
if (typeof document !== 'undefined') {
document.addEventListener('visibilitychange', () => { if (document.hidden) pageHiddenAt = Date.now() })
}
const requestRestNotificationPermission = async () => {
if (!notificationsSupported()) return false
if (Notification.permission === 'granted') return true
@@ -59,7 +69,7 @@ export const useUI = create((set, get) => ({
timer: null, // rest countdown between sets — { left, total, endsAt, forIdx }
// forIdx: index of the active entry whose set started the rest (undefined when unknown)
work: null, // work countdown DURING a timed set (issue #16) — { left, total, endsAt, label }
timerFlashId: 0, // changing the id remounts the four-pulse visual alert
timerFlashId: 0, // changing the id retriggers the theme-blink visual alert
flashTimer() {
if (!useStore.getState().S.timerFlash) return
@@ -94,11 +104,20 @@ export const useUI = create((set, get) => ({
const tm = get().timer
if (!tm) return
const left = Math.max(0, Math.round((tm.endsAt - Date.now()) / 1000))
const seenLive = !document.hidden && pageHiddenAt === null
if (!document.hidden) pageHiddenAt = null
if (left === tm.left) return
const snd = useStore.getState().S.sound
if (left <= 0) {
beep(snd, 880, 0.15); beep(snd, 880, 0.15, 0.25); beep(snd, 1320, 0.4, 0.5)
vibrate([200, 100, 200]); get().flashTimer(); maybeRestNotification(); get().toast(t('Rest over — next set!')); get().stopRest(); return
if (seenLive) {
beep(snd, 880, 0.15); beep(snd, 880, 0.15, 0.25); beep(snd, 1320, 0.4, 0.5)
vibrate([200, 100, 200]); get().flashTimer()
}
// The toast stays even when the rest ran out while the app was hidden: a guest, or anyone
// without push permission, gets no notification, and a countdown that silently vanishes
// on reopen reads like a bug. Only the loud parts (beep, vibration, flash) are gated.
get().toast(t('Rest over — next set!'))
maybeRestNotification(); get().stopRest(); return
}
if (left <= 3) beep(snd, 660, 0.1)
set({ timer: { ...tm, left } })
@@ -149,11 +168,15 @@ export const useUI = create((set, get) => ({
const wk = get().work
if (!wk) return
const left = Math.max(0, Math.round((wk.endsAt - Date.now()) / 1000))
const seenLive = !document.hidden && pageHiddenAt === null
if (!document.hidden) pageHiddenAt = null
if (left === wk.left) return
const snd = useStore.getState().S.sound
if (left <= 0) {
beep(snd, 880, 0.15); beep(snd, 880, 0.15, 0.25); beep(snd, 1320, 0.4, 0.5)
vibrate([200, 100, 200]); get().flashTimer()
if (seenLive) {
beep(snd, 880, 0.15); beep(snd, 880, 0.15, 0.25); beep(snd, 1320, 0.4, 0.5)
vibrate([200, 100, 200]); get().flashTimer()
}
const done = workDone
get().stopWork()
if (done) done(wk.total)
+31
View File
@@ -64,4 +64,35 @@ describe('opt-in timer screen flash', () => {
vi.advanceTimersByTime(1000)
expect(useUI.getState().timerFlashId).toBe(1)
})
const goHidden = () => { Object.defineProperty(document, 'hidden', { value: true, configurable: true }); document.dispatchEvent(new Event('visibilitychange')) }
const goVisible = () => { Object.defineProperty(document, 'hidden', { value: false, configurable: true }); document.dispatchEvent(new Event('visibilitychange')) }
afterEach(() => goVisible()) // leave document.hidden the way every other test expects it
it('does not flash a rest that expires while the app is hidden, even once reopened', () => {
useStore.setState({ S: { ...useStore.getState().S, timerFlash: true } })
useUI.getState().startRest(90)
goHidden()
vi.setSystemTime(Date.now() + 91_000) // deadline passes with no ticks — the app was actually closed/suspended
goVisible() // reopening re-fires visibilitychange, which is how the bug used to trigger
expect(useUI.getState().timerFlashId).toBe(0)
expect(useUI.getState().timer).toBe(null)
})
it('does not flash a timed exercise that finishes while the app is hidden', () => {
useStore.setState({ S: { ...useStore.getState().S, timerFlash: true } })
useUI.getState().startWork(90, 'Plank', vi.fn())
goHidden()
vi.setSystemTime(Date.now() + 91_000)
goVisible()
expect(useUI.getState().timerFlashId).toBe(0)
expect(useUI.getState().work).toBe(null)
})
it('still flashes a rest that expires normally while the app stays visible', () => {
useStore.setState({ S: { ...useStore.getState().S, timerFlash: true } })
useUI.getState().startRest(1)
vi.advanceTimersByTime(1000)
expect(useUI.getState().timerFlashId).toBe(1)
})
})
+188
View File
@@ -0,0 +1,188 @@
import { useEffect, useRef, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useStore } from '../store/useStore.js'
import { useUI } from '../store/useUI.js'
import { uid } from '../lib/format.js'
import { t } from '../lib/i18n.js'
import { canRenderFmt } from '../lib/qr.js'
import { scanCode, importCodeFromImage } from '../lib/scan.js'
import { MOBILE } from '../lib/mobile.js'
import Icon from '../components/Icon.jsx'
import QrCanvas from '../components/QrCanvas.jsx'
import CameraScan from '../components/CameraScan.jsx'
import { Button, TextField } from '../components/ui.jsx'
import { confirmSheet } from '../sheets.jsx'
import { tappable } from '../lib/use-sheet-keyboard.js'
// Gym check-in (reached from the Home "Check in" card; app and PWA alike). Shows each saved membership
// code as a QR the turnstile can read, swiped through horizontally, with a trailing "+" to add
// another. We only ever store the code's value + symbology; the QR is regenerated from it here
// every time (see lib/qr.js), so nothing sensitive is kept as an image.
export default function CheckIn() {
const nav = useNavigate()
const cards = useStore(s => s.S.gymCards) || []
const railRef = useRef(null)
const [active, setActive] = useState(0)
// Which card the horizontal scroll has settled on — drives the little dots. Reading it off the
// scroll position keeps the rail itself the single control; no separate paging state to sync.
const onScroll = () => {
const rail = railRef.current
if (!rail) return
const i = Math.round(rail.scrollLeft / rail.clientWidth)
setActive(i)
}
return <div className="narrow">
<div className="hdr">
<button className="iconbtn" onClick={() => nav('/home')} aria-label={t('Home')}><Icon name="chevronLeft" /></button>
<div style={{ flex: 1 }}>
<h1 style={{ fontSize: 28 }}>{t('Check in')}</h1>
<div className="sub">{cards.length ? t('Show this at the gym') : t('Add your gym card')}</div>
</div>
</div>
<div className="ci-rail" ref={railRef} onScroll={onScroll}>
{cards.map(card => <CardFace key={card.id} card={card} />)}
<button className="ci-add" onClick={openAddCard}>
<Icon name="plus" />
<span className="ci-add-t">{t('Add a card')}</span>
</button>
</div>
{(cards.length > 0) && <div className="ci-dots">
{cards.map((c, i) => <span key={c.id} className={'ci-dot' + (i === active ? ' on' : '')} />)}
{/* the add card is a slide too, so it gets a dot */}
<span className={'ci-dot' + (active >= cards.length ? ' on' : '')} />
</div>}
{!cards.length && <div className="muted small" style={{ textAlign: 'center', marginTop: 18, lineHeight: 1.5 }}>
{t('Type the number on your membership card, import a photo of it, or scan it with the camera. No extra app needed at the gym — just open this screen.')}
</div>}
</div>
}
// One saved card: its label, the QR, and the raw value underneath (handy when a reader is fussy
// and a staff member types it in). Long-press / the trash button removes it.
function CardFace({ card }) {
const update = useStore(s => s.update)
const remove = () => confirmSheet({
title: t('Remove this card?'),
message: card.label,
confirmText: t('Remove'),
danger: true,
onConfirm: () => update(s => { s.gymCards = (s.gymCards || []).filter(c => c.id !== card.id) }),
})
return <div className="ci-card">
<div className="row between" style={{ width: '100%', alignItems: 'flex-start' }}>
<div className="ci-label" style={{ flex: 1 }}>{card.label}</div>
<button className="iconbtn" style={{ width: 30, height: 30, fontSize: 14, color: 'var(--red)' }} onClick={remove} aria-label={t('Remove')}><Icon name="trash" /></button>
</div>
<div className="ci-qr-plate"><QrCanvas value={card.value} size={230} /></div>
<div className="ci-value">{card.value}</div>
</div>
}
/* ------------------------------------------------------------- add-card sheet -- */
// Opens the add-card sheet. Co-located with the view (not sheets.jsx) because it pulls in the
// scanner paths — keeping it here keeps them out of the shared sheets module.
export function openAddCard() {
useUI.getState().openSheet(close => <AddCard close={close} />)
}
function saveCard({ label, value, fmt }) {
const update = useStore.getState().update
const toast = useUI.getState().toast
const trimmed = (value || '').trim()
if (!trimmed) { toast(t('Nothing to save yet')); return false }
// We can read many barcode kinds but only redraw QR faithfully — refuse anything else rather
// than store a code that would display as the wrong bars at the turnstile.
if (fmt && !canRenderFmt(fmt)) { toast(t("That's not a QR code — only QR cards can be shown here")); return false }
update(s => {
if (!Array.isArray(s.gymCards)) s.gymCards = []
s.gymCards.push({ id: uid(), label: (label || '').trim() || t('Gym card'), value: trimmed, fmt: 'qrcode' })
})
toast(t('Card added'))
return true
}
function AddCard({ close }) {
const [label, setLabel] = useState('')
const [value, setValue] = useState('')
const [busy, setBusy] = useState(false)
const fileRef = useRef(null)
const toast = useUI(s => s.toast)
const commitTyped = () => { if (saveCard({ label, value, fmt: 'qrcode' })) close() }
// Camera scan: in the app, hands off to the native scanner; in a browser, opens our own camera
// sheet on top of this one. Either way the value drops straight into the form so the user can
// still name it before saving.
const doScan = async () => {
if (!MOBILE) {
useUI.getState().openSheet(close => <CameraScan
onCancel={close}
onFound={code => {
close()
if (!canRenderFmt(code.fmt)) { toast(t("That's not a QR code — only QR cards can be shown here")); return }
setValue(code.value)
}} />)
return
}
setBusy(true)
try {
const code = await scanCode()
if (!code) return // user backed out
if (!canRenderFmt(code.fmt)) { toast(t("That's not a QR code — only QR cards can be shown here")); return }
setValue(code.value)
} catch (e) {
toast(scanErrorMessage(e))
} finally { setBusy(false) }
}
const onFile = async ev => {
const file = ev.target.files && ev.target.files[0]
ev.target.value = '' // let the same file be picked again later
if (!file) return
setBusy(true)
try {
const code = await importCodeFromImage(file)
if (!code) { toast(t('No QR code found in that image')); return }
if (!canRenderFmt(code.fmt)) { toast(t("That's not a QR code — only QR cards can be shown here")); return }
setValue(code.value)
} catch (e) {
toast(t('Could not read that image'))
} finally { setBusy(false) }
}
return <>
<h3>{t('Add a card')}</h3>
<div className="muted small" style={{ marginBottom: 14 }}>{t('Scan it, import a photo, or type the code by hand.')}</div>
<div className="row" style={{ gap: 8, marginBottom: 16 }}>
<Button variant="tinted" icon="camera" onClick={doScan} disabled={busy}>{t('Scan')}</Button>
<Button variant="tinted" icon="image" onClick={() => fileRef.current?.click()} disabled={busy}>{t('Import photo')}</Button>
</div>
<label className="sect-t">{t('Label')}</label>
<TextField value={label} onChange={e => setLabel(e.target.value)} placeholder={t('e.g. FitZone downtown')} style={{ marginBottom: 12 }} />
<label className="sect-t">{t('Code')}</label>
<TextField value={value} onChange={e => setValue(e.target.value)} placeholder={t('Membership number or code')} inputMode="text" style={{ marginBottom: 16 }} />
{value.trim() && <div className="ci-qr-plate" style={{ alignSelf: 'center', marginBottom: 16 }}><QrCanvas value={value.trim()} size={150} /></div>}
<Button variant="primary" onClick={commitTyped} disabled={busy || !value.trim()}>{t('Save card')}</Button>
<input ref={fileRef} type="file" accept="image/*" hidden onChange={onFile} />
</>
}
// Map the thrown reasons from lib/scan.js to something a person can act on.
function scanErrorMessage(e) {
const m = String(e && e.message)
if (m === 'permission-denied') return t('Camera permission is needed to scan. Enable it in Settings.')
if (m === 'unsupported') return t('Scanning is not available on this device.')
return t('Could not start the scanner')
}
+20 -3
View File
@@ -4,7 +4,7 @@ import { useStore } from '../store/useStore.js'
import { effectiveRoutine, effectiveRoutineId, nextTrainingDay, streakWeeks, lastBW, setsDoneActive } from '../lib/history.js'
import { fmtNum, fmtDate, todayISO, isoOf, weekKey, weekStartOf, weekDayOffset, DAYS, DAYN } from '../lib/format.js'
import { t, dateLocale } from '../lib/i18n.js'
import { bwSheet, goalSheet, dayOverrideSheet, calendarSheet, startFlow, loadStarterPlan, bwDeltaColor } from '../sheets.jsx'
import { bwSheet, goalSheet, dayOverrideSheet, calendarSheet, startFlow, starterPlanSheet, bwDeltaColor } from '../sheets.jsx'
import LineChart from '../components/LineChart.jsx'
import Icon from '../components/Icon.jsx'
import { Button } from '../components/ui.jsx'
@@ -94,14 +94,31 @@ export default function Home() {
</div>
</div>
{/* Jump to the gym check-in cards (QR membership codes). Shown here as a quick tap on
arrival at the gym; folds away per user via the "Gym check-in" switch in Settings. */}
{S.checkIn !== false && (
<div className="card tappable" style={{ cursor: 'pointer' }} {...tappable(() => nav('/checkin'))}>
<div className="row between">
<div className="row" style={{ gap: 9 }}>
<span className="lrow-i" style={{ background: 'var(--blue)' }}><Icon name="qr" /></span>
<div>
<div className="lbl2">{t('At the gym')}</div>
<div className="ttl">{t('Check in')}</div>
</div>
</div>
<Icon name="chevronRight" className="chev" />
</div>
</div>
)}
{!S.routines.length && !S.active && (
<div className="card">
<div className="row" style={{ gap: 10, marginBottom: 6 }}>
<span className="lrow-i"><Icon name="sparkles" /></span>
<div className="big" style={{ fontSize: 22 }}>{t('Welcome!')}</div>
</div>
<div className="muted small" style={{ marginBottom: 12 }}>{t('Set up your weekly routine to get going — or load a ready-made Push / Pull / Legs plan.')}</div>
<Button variant="primary" icon="sparkles" onClick={loadStarterPlan}>{t('Load starter plan (PPL)')}</Button>
<div className="muted small" style={{ marginBottom: 12 }}>{t('Set up your weekly routine to get going — or load a ready-made starter plan.')}</div>
<Button variant="primary" icon="sparkles" onClick={starterPlanSheet}>{t('Load starter plan')}</Button>
<div style={{ height: 8 }} /><Button onClick={() => nav('/plan')}>{t('Build my own plan')}</Button>
</div>
)}
+5 -1
View File
@@ -1,4 +1,5 @@
import { useRef, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useStore } from '../store/useStore.js'
import { EXDB, BODYPARTS, allExercises, equipmentOf, matchExercise } from '../lib/exercises.js'
import { activeProfile, exAvailable } from '../lib/equipment.js'
@@ -12,6 +13,7 @@ import { Button } from '../components/ui.jsx'
import { tappable, useRevealActiveChip } from '../lib/use-sheet-keyboard.js'
export default function Library() {
const nav = useNavigate()
const S = useStore(s => s.S)
const [q, setQ] = useState('')
const [bp, setBp] = useState('')
@@ -30,7 +32,9 @@ export default function Library() {
useRevealActiveChip(eqStrip, eqOn)
return <>
<div className="hdr"><div><h1>{t('Exercises')}</h1><div className="sub">{t('{0} exercises with animations', EXDB.length)}</div></div></div>
<div className="hdr"><div><h1>{t('Exercises')}</h1><div className="sub">{t('{0} exercises with animations', EXDB.length)}</div></div>
<Button size="sm" variant="tinted" icon="target" onClick={() => nav('/muscles')}>{t('By muscle')}</Button>
</div>
<div className="search" style={{ marginBottom: 10 }}><svg viewBox="0 0 24 24"><circle cx="11" cy="11" r="7" /><path d="m21 21-4.3-4.3" /></svg>
<input className="input" placeholder={t('Search…')} value={q} onChange={e => { setQ(e.target.value); setShown(40) }} /></div>
{profile && <div className="small dim row" style={{ margin: '-4px 2px 10px', gap: 6, alignItems: 'center' }}>
+15
View File
@@ -0,0 +1,15 @@
import { useNavigate } from 'react-router-dom'
import { t } from '../lib/i18n.js'
import MuscleExplorer from '../components/MuscleExplorer.jsx'
import { exerciseDetailSheet, addToRoutineSheet } from '../sheets.jsx'
import Icon from '../components/Icon.jsx'
export default function Muscles() {
const nav = useNavigate()
return <>
<div className="hdr"><button className="iconbtn" onClick={() => nav('/library')} aria-label={t('Exercises')}><Icon name="chevronLeft" /></button>
<div style={{ flex: 1, marginLeft: 12 }}><h1>{t('Explore muscles')}</h1><div className="sub">{t('Choose a muscle to see exercises that train it.')}</div></div></div>
<MuscleExplorer onDetail={exerciseDetailSheet} onPlan={addToRoutineSheet} />
</>
}
+2 -2
View File
@@ -2,7 +2,7 @@ import { useNavigate } from 'react-router-dom'
import { useStore } from '../store/useStore.js'
import { DAYN, weekOrder, weekStartOf, uid, exCount } from '../lib/format.js'
import { t } from '../lib/i18n.js'
import { dayAssignSheet, loadStarterPlan, planToolsSheet } from '../sheets.jsx'
import { dayAssignSheet, starterPlanSheet, planToolsSheet } from '../sheets.jsx'
import Icon from '../components/Icon.jsx'
import { Button } from '../components/ui.jsx'
import { tappable } from '../lib/use-sheet-keyboard.js'
@@ -66,7 +66,7 @@ export default function Plan() {
<div className="grow"><div className="tt">{r.name}</div><div className="ss">{exCount(r.ex.length)}</div></div>
<Icon name="chevronRight" className="chev" /></div>)}</div> : <>
<div className="empty"><div className="ico"><Icon name="clipboard" /></div>{t('No routines yet.')}<br />{t('Create one or load the starter plan.')}</div>
<Button icon="sparkles" onClick={loadStarterPlan}>{t('Load starter plan (Push / Pull / Legs)')}</Button>
<Button icon="sparkles" onClick={starterPlanSheet}>{t('Load starter plan')}</Button>
</>}
</div></div>
</>
+18 -2
View File
@@ -1,16 +1,18 @@
import { useNavigate, useParams } from 'react-router-dom'
import { useEffect, useRef, useState } from 'react'
import { useStore } from '../store/useStore.js'
import { useUI } from '../store/useUI.js'
import { exOr } from '../lib/exercises.js'
import { activeProfile, exAvailable } from '../lib/equipment.js'
import { uid } from '../lib/format.js'
import { t, exerciseNameFor } from '../lib/i18n.js'
import { supersetUnits, moveSupersetUnit, cleanupSg, exLine } from '../lib/history.js'
import { supersetUnits, moveSupersetUnit, cleanupSg, exLine, defaultConfig } from '../lib/history.js'
import { Thumb } from '../components/Media.jsx'
import { glyphPicker, exercisePicker, exConfigSheet, confirmSheet } from '../sheets.jsx'
import Icon from '../components/Icon.jsx'
import { glyphOf } from '../lib/glyphs.js'
import { Button, Row, SelectRow, Switch } from '../components/ui.jsx'
import { copyRoutine } from '../lib/routines.js'
import { POLICIES_FOR, POLICY_NAME, POLICY_DESC } from '../lib/progression.js'
import BodyMap from '../components/BodyMap.jsx'
import { loadOfRoutine, rankOf, MUSCLE_NAME } from '../lib/muscles.js'
@@ -305,6 +307,7 @@ export default function RoutineEdit() {
const { id } = useParams()
const S = useStore(s => s.S)
const update = useStore(s => s.update)
const toast = useUI(s => s.toast)
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
@@ -423,7 +426,20 @@ export default function RoutineEdit() {
})()}
<div className="small dim row" style={{ margin: '10px 2px', gap: 5 }}><Icon name="link" style={{ fontSize: 13 }} />{t('Tap the link button on an exercise to superset it with the one above — you’ll do them back-to-back.')}</div>
<Button variant="primary" onClick={() => exercisePicker(ex => exConfigSheet(ex, null, cfg => edit(x => { x.push({ id: ex.id, ...cfg }) }), null, r))} icon="plus">{t('Add exercise')}</Button>
<Button variant="primary" onClick={() => exercisePicker((ex, quick) => {
if (quick) {
edit(x => x.push({ id: ex.id, ...defaultConfig(ex.id) }))
toast(t('“{0}” added to {1}', exerciseNameFor(ex), r.name))
} else {
exConfigSheet(ex, null, cfg => edit(x => { x.push({ id: ex.id, ...cfg }) }), null, r)
}
})} icon="plus">{t('Add exercise')}</Button>
<div style={{ height: 10 }} />
<Button onClick={() => {
const copy = copyRoutine(r, t('Copy'))
update(s => { s.routines.push(copy) })
nav('/plan/r/' + copy.id)
}}>{t('Copy routine')}</Button>
<div style={{ height: 10 }} />
<Button variant="danger" onClick={() => confirmSheet({
title: t('Delete routine?'), message: t('“{0}” and its exercises will be removed.', r.name), confirmText: t('Delete'), danger: true,
+1 -1
View File
@@ -41,7 +41,7 @@ vi.mock('../lib/wakelock.js', () => ({ wakeLockSupported: () => false }))
vi.mock('../lib/mobile.js', () => ({ MOBILE: false, shareExport: vi.fn(), syncReminder: vi.fn() }))
vi.mock('./MobileOnboarding.jsx', () => ({ ConnectSheet: () => null }))
vi.mock('../sheets.jsx', () => ({
loadStarterPlan: vi.fn(), confirmSheet: vi.fn(), importFromApp: vi.fn(),
starterPlanSheet: vi.fn(), confirmSheet: vi.fn(), importFromApp: vi.fn(),
importFromHevy: vi.fn(), equipmentProfileSheet: vi.fn(),
}))
+15 -2
View File
@@ -11,7 +11,7 @@ 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, importFromHevy, equipmentProfileSheet } from '../sheets.jsx'
import { starterPlanSheet, confirmSheet, importFromApp, importFromHevy, equipmentProfileSheet } from '../sheets.jsx'
import Icon from '../components/Icon.jsx'
import { Section, Row, SelectRow, Switch, Segmented, Button, TextField } from '../components/ui.jsx'
@@ -140,10 +140,23 @@ export default function Settings() {
options={[{ value: MONDAY, label: t('Monday') }, { value: SUNDAY, label: t('Sunday') }]}
value={weekStartOf(S)} onChange={v => update(s => { s.weekStart = v })} />
</Row>
{/* Membership QR codes on Home (views/CheckIn.jsx); off = no Home card, no route. */}
<Row icon="qr" iconTint="var(--blue)" title={t('Gym check-in')}
subtitle={t('Show a card on Home with your membership QR codes.')}>
<Switch checked={S.checkIn !== false} onChange={v => update(s => { s.checkIn = v })} />
</Row>
</Section>
{/* ---------- during a workout ---------- */}
<Section title={t('During a workout')} footer={wakeOK ? t('The screen stays on while a workout is running, so you don’t have to unlock your phone between sets.') : null}>
{/* One exercise at a time (cards with Prev/Next) or the whole session stacked as a
scrollable list. Legacy/unknown values read as cards. */}
<Row icon="list" iconTint="var(--blue)" title={t('Workout view')}>
<Segmented className="seg-inline"
options={[{ value: 'cards', label: t('Cards') }, { value: 'list', label: t('List') }]}
value={S.workoutView === 'list' ? 'list' : 'cards'}
onChange={v => update(s => { s.workoutView = v })} />
</Row>
<SelectRow icon="timer" iconTint="var(--orange)" title={t('Rest timer')}
value={S.restSec} onChange={v => update(s => { s.restSec = v })}
options={[{ value: 0, label: t('Off') }, ...[60, 90, 120, 150, 180].map(v => ({ value: v, label: v + 's' }))]} />
@@ -226,7 +239,7 @@ export default function Settings() {
{/* ---------- data: fill it, bring things over, back it up, wipe it ---------- */}
<Section title={t('Data')}>
<Row icon="sparkles" iconTint="var(--acc)" title={t('Load starter plan (PPL)')} accessory="chevron" onClick={loadStarterPlan} />
<Row icon="sparkles" iconTint="var(--acc)" title={t('Load starter plan')} accessory="chevron" onClick={starterPlanSheet} />
<Row icon="shuffle" iconTint="var(--teal)" title={t('Import from another app')}
subtitle={t('FitNotes, Strong, Hevy — or body weight from Apple Health')}
accessory="chevron" onClick={() => importRef.current.click()} />
@@ -0,0 +1,89 @@
// @vitest-environment happy-dom
import React, { act } from 'react'
import { createRoot } from 'react-dom/client'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import Settings from './Settings.jsx'
globalThis.IS_REACT_ACT_ENVIRONMENT = true
const mocks = vi.hoisted(() => {
const state = { S: null }
state.snapshot = () => ({
S: state.S,
user: null,
update: mut => {
const next = structuredClone(state.S)
mut(next)
state.S = next
},
replaceState: vi.fn(), setUser: vi.fn(), pullState: vi.fn(), pushState: vi.fn(),
signOut: vi.fn(), signOutAll: vi.fn(), resetDemo: vi.fn(), disconnectServer: vi.fn(),
})
return state
})
vi.mock('../store/useStore.js', () => {
const useStore = selector => selector ? selector(mocks.snapshot()) : mocks.snapshot()
useStore.getState = mocks.snapshot
return { useStore, DEF: { reminder: { time: '17:30' } }, hasData: () => false }
})
vi.mock('../store/useUI.js', () => {
const snap = () => ({ toast: vi.fn(), openSheet: vi.fn() })
const useUI = selector => selector ? selector(snap()) : snap()
useUI.getState = snap
return { useUI }
})
vi.mock('react-router-dom', () => ({ useNavigate: () => () => {} }))
vi.mock('../lib/api.js', () => ({
api: vi.fn(), webauthnOK: () => false, passkeyLogin: vi.fn(), passkeyRegister: vi.fn(), IS_ANDROID: false,
}))
vi.mock('../lib/push.js', () => ({ pushSupported: () => false, enablePush: vi.fn(), disablePush: vi.fn(), sendTestPush: vi.fn() }))
vi.mock('../lib/wakelock.js', () => ({ wakeLockSupported: () => false }))
vi.mock('../lib/mobile.js', () => ({ MOBILE: false, shareExport: vi.fn(), syncReminder: vi.fn() }))
vi.mock('./MobileOnboarding.jsx', () => ({ ConnectSheet: () => null }))
vi.mock('../sheets.jsx', () => ({
loadStarterPlan: vi.fn(), starterPlanSheet: vi.fn(), confirmSheet: vi.fn(), importFromApp: vi.fn(),
importFromHevy: vi.fn(), equipmentProfileSheet: vi.fn(),
}))
// The Settings view reads the build-time version constant at render time.
globalThis.__APP_VERSION__ ??= 'test'
let host, root
beforeEach(() => {
mocks.S = {
unit: 'kg', restSec: 90, restPauseSec: 15, sound: false, effort: 'none',
gifSize: 'full', workouts: [], routines: [], exWeights: {},
}
host = document.createElement('div')
document.body.appendChild(host)
root = createRoot(host)
})
afterEach(() => {
act(() => root.unmount())
host.remove()
})
const mount = () => act(() => root.render(<Settings />))
const segButton = label => [...host.querySelectorAll('.seg button')].find(b => b.textContent === label)
describe('Settings — workout view', () => {
it('offers Cards / List and writes workoutView to the store', () => {
mount()
expect(segButton('Cards')).toBeTruthy()
expect(segButton('List')).toBeTruthy()
expect(segButton('Cards').getAttribute('aria-pressed')).toBe('true')
act(() => { segButton('List').click() })
expect(mocks.S.workoutView).toBe('list')
mount()
expect(segButton('List').getAttribute('aria-pressed')).toBe('true')
act(() => { segButton('Cards').click() })
expect(mocks.S.workoutView).toBe('cards')
})
it('shows a legacy/absent value as Cards', () => {
delete mocks.S.workoutView
mount()
expect(segButton('Cards').getAttribute('aria-pressed')).toBe('true')
expect(segButton('List').getAttribute('aria-pressed')).toBe('false')
})
})
+2 -1
View File
@@ -35,7 +35,8 @@ describe('Stats mixed-entry metric contract', () => {
expect(uiSource).toContain('sheetTitle, stackedValue = false')
expect(uiSource).toContain("className={stackedValue ? 'lrow-stack-value' : ''}")
expect(cssSource).toContain('.lrow.lrow-stack-value .lrow-m{grid-column:1;grid-row:1}')
expect(cssSource).toContain('.lrow.lrow-stack-value .lrow-v{grid-column:1;grid-row:2;text-align:left}')
expect(cssSource).toContain('.lrow.lrow-stack-value .lrow-v{grid-column:1;grid-row:2;width:100%;max-width:none;text-align:left}')
expect(cssSource).toContain('flex:0 1 auto;max-width:45%;min-width:0;')
expect(cssSource).toContain('overflow:hidden;text-overflow:ellipsis;white-space:nowrap')
})
})
+157 -66
View File
@@ -4,17 +4,17 @@ import { useStore } from '../store/useStore.js'
import { useUI } from '../store/useUI.js'
import { exOr } from '../lib/exercises.js'
import { usesBar, barWeightFor, plateSplit } from '../lib/bar.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, pinnedNoteFor, exNoteFor } from '../lib/history.js'
import { effectiveRoutine, lastEntryFor, bestWeightFor, bestWeightForEntry, buildSets, freestyleConfig, defaultConfig, setsDoneActive, supersetUnits, unitOf, setLabel, modeOf, isBw, isPerSide, sideReps, repStep, EFFORT, effortOf, stepEffort, capEffort, cascadeWeight, insertWarmupRow, removeRowAt, pairAdjacent, unpairSuperset, cleanupSg, applyIntensifierPlan, pinnedNoteFor, exNoteFor } 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'
import { api } from '../lib/api.js'
import { insertionIndexAfterCurrentUnit, nextUnfinishedUnit, setProgressHighWater, supersetFlowStep, restAfterSet, restOnRecheck, restSecFor } from '../lib/supersetFlow.js'
import Media from '../components/Media.jsx'
import { startFlow, exercisePicker, exConfigSheet, exerciseDetailSheet, topWeightSheet, finishWorkout, workoutCompleteSheet, confirmSheet, exerciseNoteSheet, sessionNoteSheet, swapActiveWorkoutExercise, barWeightSheet } from '../sheets.jsx'
import { startFlow, exercisePicker, exConfigSheet, exerciseDetailSheet, finishWorkout, workoutCompleteSheet, confirmSheet, exerciseNoteSheet, sessionNoteSheet, swapActiveWorkoutExercise, barWeightSheet } from '../sheets.jsx'
import Icon from '../components/Icon.jsx'
import { Button, Check, NumberField } from '../components/ui.jsx'
import { nextPrescription, applyPrescription, defaultIncrement } from '../lib/progression.js'
import { nextPrescription, applyPrescription, defaultIncrement, weightIncrement, stepWeight } from '../lib/progression.js'
import { progressionGuidance } from '../lib/progression-copy.js'
import { glyphOf } from '../lib/glyphs.js'
import { isWarmupRow, isDropSet, isRestPauseSet, dropsOf, clustersOf, addDrop, addCluster, removeDropAt, removeClusterAt, setDropAt, setClusterAt, nextDropWeight, nextBurstReps } from '../lib/workout-model.js'
@@ -107,8 +107,7 @@ function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemov
// Only worth surfacing while there is still work left: once the exercise is finished, a note
// telling you what to do in it is behind you, and the block is already long.
const pinnedNote = entry.sets.some(s => !s.done) ? pinnedNoteFor(S, entry.id) : null
// The same number the "confirm your working weight" sheet calls your best, so the two
// never disagree inside one session: heaviest logged set, or the working weight you kept.
// The number is the heaviest logged set, or the working weight you kept.
const best = cardio ? 0 : Math.max(bestWeightFor(S, entry.id), (S.exWeights[entry.id] || {}).w || 0)
// What the progression policy decided for this session, and why (issue #17). Computed when
// the session was built so the reason matches the numbers already in the rows.
@@ -120,7 +119,8 @@ function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemov
const cfg = { ...(entry.target || {}), id: entry.id }
const bw = !cardio && isBw(cfg)
const added = bw && entry.sets.some(s => s.w > 0)
const loadCol = { f: 'w', step: 2.5, dec: true, hd: bw ? t('Added ({0})', S.unit) : t('Weight ({0})', S.unit) }
const loadStep = mode === 'reps' ? weightIncrement(cfg, S.unit) : 2.5
const loadCol = { f: 'w', step: loadStep, dec: true, hd: bw ? t('Added ({0})', S.unit) : t('Weight ({0})', S.unit) }
// The reps column is the total in every mode, unilateral included — the stepper walks in
// twos there so the number you land on is one you can actually split evenly.
const repCol = { f: 'r', step: repStep(cfg), dec: false, hd: t('Reps') }
@@ -139,8 +139,16 @@ function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemov
// The effort column walks its own scale — see stepEffort. Weight and reps step up from 0
// with no ceiling, as they always did.
const bump = (s, i, col, dir) => {
if (col.eff) return onField(i, col.f, stepEffort(col.eff, s[col.f], dir))
onField(i, col.f, Math.max(0, Math.round(((s[col.f] || 0) + dir * col.step) * 100) / 100))
// Read the current value directly from the store rather than from the render-time snapshot.
// In a superset both ExerciseBlock instances share the same store subscription, so when one
// member's field changes the partner re-renders too, replacing the closure's `s` reference
// with a fresh clone before the next tap fires. Reading from the store avoids that stale-
// closure problem entirely and keeps every tap operating on the real current value.
const fresh = useStore.getState().S.active?.entries[entryIdx]?.sets[i]
const cur = fresh ? fresh[col.f] : s[col.f]
if (col.eff) return onField(i, col.f, stepEffort(col.eff, cur, dir))
if (mode === 'reps' && col.f === 'w') return onField(i, col.f, stepWeight(cur, col.step, dir))
onField(i, col.f, Math.max(0, Math.round(((cur || 0) + dir * col.step) * 100) / 100))
}
// Uses the shared stepper markup so a set row picks up the same control styling
// as every other +/- field in the app.
@@ -155,11 +163,11 @@ function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemov
)
// 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) => (
const miniStepper = (value, step, dec, onChange, snapWeightStep = false) => (
<div className="stp mini">
<button aria-label="Decrease" onClick={() => onChange(Math.max(0, Math.round(((value || 0) - step) * 100) / 100))}><Icon name="minus" /></button>
<button aria-label="Decrease" onClick={() => onChange(snapWeightStep ? stepWeight(value, step, -1) : 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>
<button aria-label="Increase" onClick={() => onChange(snapWeightStep ? stepWeight(value, step, 1) : Math.max(0, Math.round(((value || 0) + step) * 100) / 100))}><Icon name="plus" /></button>
</div>
)
return <>
@@ -252,7 +260,7 @@ function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemov
{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.w, loadStep, true, v => setDropField(i, di, 'w', v), true)}
{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>
@@ -320,6 +328,12 @@ function ActiveWorkout() {
const unit = A.entries.length ? unitOf(units, cur) : []
const unitIdx = units.findIndex(u => u === unit)
const isSuperset = unit.length > 1
// Cards show one unit at a time with Prev/Next + swipe; list stacks every unit so the
// whole session is visible and scrollable (Settings → During a workout → Workout view).
// Every set handler below is already entry-index parameterised, so list mode only changes
// what is rendered — completion, rest, top-weight and auto-advance share one path.
// Unknown/absent values read as cards, keeping every pre-existing profile as it was.
const listMode = S.workoutView === 'list'
// Superset flow: center the actionable row when completing a set moves to the partner or
// back to the first exercise of the next round. Entry-bound maps keep repeated exercise IDs
// distinct, while each rendered set index identifies the existing row within that entry.
@@ -360,13 +374,13 @@ function ActiveWorkout() {
}
})
useEffect(() => {
if (!isSuperset) return
if (!isSuperset || listMode) return
const entry = A.entries[cur]
const firstIncomplete = entry?.sets.findIndex(s => !s.done) ?? -1
const setIdx = firstIncomplete >= 0 ? firstIncomplete : (entry?.sets.length ?? 0) - 1
const el = (setIdx >= 0 && setRefs.current.get(entry)?.get(setIdx)) || exRefs.current.get(entry)
if (el && typeof el.scrollIntoView === 'function') el.scrollIntoView({ behavior: 'smooth', block: 'center' })
}, [cur, isSuperset, A.entries.length])
}, [cur, isSuperset, listMode, A.entries.length])
const total = A.entries.reduce((n, e) => n + e.sets.length, 0)
const done = setsDoneActive(A)
@@ -423,6 +437,17 @@ function ActiveWorkout() {
}, true)
}
// One prop object per entry so the card and list layouts share the exact same wiring.
const blockProps = idx => ({
onToggle: i => toggle(idx, i),
onField: (i, f, v) => setField(idx, i, f, v),
onAddSet: () => addSet(idx),
onRemoveSet: () => removeSet(idx),
onAddWarmup: () => addWarmup(idx),
onRemoveSetAt: i => removeSetAt(idx, i),
onStartTimed: i => startTimed(idx, i),
onProgressionSettings: () => openProgressionSettings(idx),
})
const navigateUnit = direction => {
const targetFor = active => {
if (!active || !Array.isArray(active.entries) || !Number.isInteger(active.cur)) return null
@@ -437,6 +462,10 @@ function ActiveWorkout() {
if (target != null) s.active.cur = target
})
}
// List mode shows every unit at once, so the "current" exercise is chosen by tapping
// "Set current" on its header instead of Prev/Next. The bottom Move/Swap/Remove actions
// keep operating on it, and completing sets still advances it on its own.
const focusUnit = firstIdx => update(s => { if (s.active) s.active.cur = firstIdx })
const onSwipePointerDown = event => {
if (swipe.current || (event.pointerType && event.pointerType !== 'touch' && event.pointerType !== 'pen')) return
if (event.target.closest?.(SWIPE_IGNORED_TARGETS)) return
@@ -459,28 +488,43 @@ function ActiveWorkout() {
const state = useStore.getState().S
const entry = state.active?.entries?.[idx]
if (!entry) return
const activeId = state.active.id
const entryId = entry.id
const entryCount = state.active.entries.length
const routine = state.routines.find(r => r.id === state.active.routineId)
exConfigSheet(exOr(entry.id), entry.target, cfg => update(s => {
const activeEntry = s.active?.entries?.[idx]
if (!activeEntry) return
const full = { ...cfg, id: activeEntry.id }
const activeRoutine = s.routines.find(r => r.id === s.active.routineId)
const step = defaultIncrement(activeEntry.id, s.unit)
// A config without a set count keeps the rows the session already has.
if (!(full.sets > 0)) full.sets = activeEntry.sets.filter(x => !isWarmupRow(x)).length || 1
const plan = nextPrescription(s, full, activeRoutine)
// The sheet edits sets, reps, weight and warm-ups as well as the rule — so the rows are
// rebuilt from the new config the way the session was, and only what you already logged
// is kept in place (done warm-ups first, then done work sets, then the fresh remainder).
const fresh = applyIntensifierPlan(applyPrescription(buildSets(s, full, { step }), plan, step), full)
const doneWarm = activeEntry.sets.filter(x => x.done && isWarmupRow(x))
const doneWork = activeEntry.sets.filter(x => x.done && !isWarmupRow(x))
const freshWarm = fresh.filter(isWarmupRow)
const freshWork = fresh.filter(x => !isWarmupRow(x))
activeEntry.target = { ...cfg }
activeEntry.plan = plan
activeEntry.sets = [...doneWarm, ...freshWarm.slice(doneWarm.length), ...doneWork, ...freshWork.slice(doneWork.length)]
}), null, routine)
exConfigSheet(exOr(entryId), entry.target, cfg => {
// Store updates clone the state tree. If this exact object is no longer at the captured
// index, the list changed while the sheet was open; an id check alone cannot distinguish
// duplicate occurrences of the same exercise, so fail closed before cloning again.
// Every store write clones the tree (the bar-weight stepper inside this very sheet does
// one), so object identity is useless here. Same workout, same list length and the same
// exercise at the captured index is what "nothing shifted" means.
const current = useStore.getState().S
if (current.active?.id !== activeId || current.active.entries?.length !== entryCount || current.active.entries?.[idx]?.id !== entryId) return
update(s => {
const activeEntry = s.active?.id === activeId ? s.active.entries?.[idx] : null
// The sheet may outlive its workout or entry. Never apply its result to whatever later
// happens to occupy the same index.
if (!activeEntry || activeEntry.id !== entryId) return
const full = { ...cfg, id: activeEntry.id }
const activeRoutine = s.routines.find(r => r.id === s.active.routineId)
const step = defaultIncrement(activeEntry.id, s.unit)
// A config without a set count keeps the rows the session already has.
if (!(full.sets > 0)) full.sets = activeEntry.sets.filter(x => !isWarmupRow(x)).length || 1
const plan = nextPrescription(s, full, activeRoutine)
// The sheet edits sets, reps, weight and warm-ups as well as the rule — so the rows are
// rebuilt from the new config the way the session was, and only what you already logged
// is kept in place (done warm-ups first, then done work sets, then the fresh remainder).
const fresh = applyIntensifierPlan(applyPrescription(buildSets(s, full, { step, useTarget: plan.kind === 'off' }), plan, step), full)
const doneWarm = activeEntry.sets.filter(x => x.done && isWarmupRow(x))
const doneWork = activeEntry.sets.filter(x => x.done && !isWarmupRow(x))
const freshWarm = fresh.filter(isWarmupRow)
const freshWork = fresh.filter(x => !isWarmupRow(x))
activeEntry.target = { ...cfg }
activeEntry.plan = plan
activeEntry.sets = [...doneWarm, ...freshWarm.slice(doneWarm.length), ...doneWork, ...freshWork.slice(doneWork.length)]
})
}, null, routine)
}
// Remove a whole exercise from the session. The confirmation always asks first; in a
@@ -530,25 +574,28 @@ function ActiveWorkout() {
const toggle = (idx, i) => {
const m = modeAt(idx)
const cardioEntry = m === 'cardio'
let askTop = false, exJustDone = false, workoutDone = false, checked = false
mutEntry(idx, e => {
let exJustDone = false, workoutDone = false, checked = false
update(s => {
const e = s.active.entries[idx]
e.sets[i].done = !e.sets[i].done
checked = e.sets[i].done
if (e.sets[i].done) {
beep(S.sound, 1040, 0.12); vibrate(30)
const unitDone = unit.every(ui => (ui === idx ? e : A.entries[ui]).sets.every(x => x.done))
// The unit that owns the ticked set — not the marked one. Since !92 the marker no longer
// follows a finished exercise, and in list mode any exercise can be worked on, so judging
// the marker's unit here declared the workout complete after one set elsewhere.
const ownUnit = unitOf(units, idx)
const unitDone = ownUnit.every(ui => (ui === idx ? e : A.entries[ui]).sets.every(x => x.done))
if (unitDone) workoutDone = !nextUnfinishedUnit(A.entries, supersetUnits(A.entries), idx)
// Only loaded reps training has a "working weight" worth confirming — a bodyweight
// plank has nothing to put in that slider, and neither does a set of push-ups
// (issue #32: the fewest taps that still record what happened).
const loaded = m === 'reps' && !(isBw({ ...(e.target || {}), id: e.id }) && !e.sets.some(x => x.w > 0))
if (e.sets.every(x => x.done)) { exJustDone = true; if (loaded && !e.asked) { e.asked = true; askTop = true } }
if (e.sets.every(x => x.done)) {
exJustDone = true
// topW is captured now; exWeights only at the finish (doFinishWorkout), so a typo you
// correct before finishing, or a discarded workout, never becomes the remembered best.
e.topW = bestWeightForEntry(e) || null
}
}
})
// reps: topWeight first (it chains into the finish/continue prompt on the last unit).
// cardio/timed or already-confirmed: go straight to the prompt.
if (askTop) topWeightSheet(idx)
else if (workoutDone) workoutCompleteSheet()
}, true)
if (workoutDone) workoutCompleteSheet()
else if (exJustDone && cardioEntry) useUI.getState().toast(t('Cardio logged'))
else if (exJustDone && m === 'time') useUI.getState().toast(t('Hold logged'))
@@ -584,7 +631,6 @@ function ActiveWorkout() {
// stopRest() first so a rest that belongs after this set replaces the one that was running.
if (freshUnitDone) stopRest()
if (!freshUnit || freshUnit.length <= 1) {
if (freshUnitDone && !askTop && nextUnit?.length) update(s => { if (s.active) s.active.cur = nextUnit[0] })
if (!restBeforeWarmup && restAfterSet({ unitDone: freshUnitDone, lastUnit: freshWorkoutDone })) startRest(restSec, idx)
return
}
@@ -592,11 +638,7 @@ function ActiveWorkout() {
const step = supersetFlowStep(fresh.entries, freshUnit, idx)
if (!step) return
if (step.unitDone) {
if (nextUnit?.length) {
// The top-weight sheet's explicit "Just close" path owns the choice not to advance.
if (!askTop) update(s => { if (s.active) s.active.cur = nextUnit[0] })
if (!restBeforeWarmup) startRest(restSec, idx)
}
if (nextUnit?.length && !restBeforeWarmup) startRest(restSec, idx)
} else {
if (step.nextIdx != null) update(s => { if (s.active) s.active.cur = step.nextIdx })
if (step.roundDone) startRest(restSec, idx)
@@ -640,7 +682,43 @@ function ActiveWorkout() {
<div className="wprog"><i style={{ width: (total ? done / total * 100 : 0) + '%' }} /></div>
{A.backfill && <div className="muted small" style={{ marginBottom: 8 }}>{t('Logging a past workout — no rest timers.')}</div>}
{A.entries.length ? <>
{A.entries.length ? (listMode ? (
<div className="workout-list" data-testid="workout-list">
{units.map((u, ui) => {
const multi = u.length > 1
const isCur = u.includes(cur)
return <section key={u.join('-')} className={'wl-unit' + (isCur ? ' cur' : '')} data-exidx={u[0]}>
<div className="wl-hd">
<span className="muted small">{multi ? t('Superset {0} / {1}', ui + 1, units.length) : t('Exercise {0} / {1}', ui + 1, units.length)}</span>
{isCur
? <span className="tag acc">{t('Current')}</span>
: <button className="chip" onClick={() => focusUnit(u[0])}>{t('Set current')}</button>}
</div>
{multi ? (
<div className="ss-card">
<div className="ss-hd" style={{ justifyContent: 'space-between' }}>
<span className="row" style={{ gap: 5 }}><Icon name="link" />{t('Superset · do these back-to-back, rest when done')}</span>
<Button size="xs" variant="ghost" icon="link" title={t('Unpair')} onClick={() => unpairAt(u[0])}>{t('Unpair')}</Button>
</div>
{u.map((idx, k) => {
const entry = A.entries[idx]
return <div key={idx} ref={el => bindExRef(entry, el)} className="ss-ex" data-exidx={idx}>
{k > 0 && <div className="ss-amp">+</div>}
<ExerciseBlock entryIdx={idx} compact onSetRowRef={(setIdx, el) => bindSetRef(entry, setIdx, el)}
{...blockProps(idx)} />
</div>
})}
</div>
) : (
<ExerciseBlock entryIdx={u[0]}
onPairPrev={u[0] > 0 ? () => pairAt(u[0] - 1, u[0]) : null}
onPairNext={u[0] < A.entries.length - 1 ? () => pairAt(u[0], u[0] + 1) : null}
{...blockProps(u[0])} />
)}
</section>
})}
</div>
) : <>
<div className="muted small" style={{ marginBottom: 6 }}>{isSuperset ? t('Superset {0} / {1}', unitIdx + 1, units.length) : t('Exercise {0} / {1}', unitIdx + 1, units.length)}</div>
<div className="workout-swipe-surface" data-testid="workout-swipe-surface"
onPointerDown={onSwipePointerDown}
@@ -660,38 +738,51 @@ function ActiveWorkout() {
return <div key={idx} ref={el => bindExRef(entry, el)} className="ss-ex" data-exidx={idx}>
{k > 0 && <div className="ss-amp">+</div>}
<ExerciseBlock entryIdx={idx} compact onSetRowRef={(setIdx, el) => bindSetRef(entry, setIdx, el)}
onToggle={i => toggle(idx, i)} onField={(i, f, v) => setField(idx, i, f, v)} onAddSet={() => addSet(idx)} onRemoveSet={() => removeSet(idx)} onAddWarmup={() => addWarmup(idx)} onRemoveSetAt={i => removeSetAt(idx, i)} onStartTimed={i => startTimed(idx, i)} onProgressionSettings={() => openProgressionSettings(idx)} />
{...blockProps(idx)} />
</div>
})}
</div>
) : (
<ExerciseBlock entryIdx={cur} onToggle={i => toggle(cur, i)} onField={(i, f, v) => setField(cur, i, f, v)} onAddSet={() => addSet(cur)} onRemoveSet={() => removeSet(cur)} onAddWarmup={() => addWarmup(cur)} onRemoveSetAt={i => removeSetAt(cur, i)} onStartTimed={i => startTimed(cur, i)} onPairPrev={onPairPrev} onPairNext={onPairNext} onProgressionSettings={() => openProgressionSettings(cur)} />
<ExerciseBlock entryIdx={cur} onPairPrev={onPairPrev} onPairNext={onPairNext} {...blockProps(cur)} />
)}
</div>
</> : <div className="empty"><div className="ico"><Icon name="shuffle" /></div>{t('Freestyle workout — add your first exercise.')}</div>}
</>) : <div className="empty"><div className="ico"><Icon name="shuffle" /></div>{t('Freestyle workout — add your first exercise.')}</div>}
<div style={{ height: 12 }} />
<div className="row">
{!listMode && <div className="row">
<Button icon="chevronLeft" disabled={unitIdx <= 0} onClick={() => navigateUnit(-1)}>{t('Prev')}</Button>
<Button trailingIcon="chevronRight" disabled={unitIdx < 0 || unitIdx >= units.length - 1} onClick={() => navigateUnit(1)}>{t('Next')}</Button>
</div>
<div style={{ height: 10 }} />
<Button onClick={() => exercisePicker(ex => {
</div>}
{!listMode && <div style={{ height: 10 }} />}
{listMode && A.entries.length > 0 && <div className="muted small" style={{ marginBottom: 6 }}>{t('Move, swap and remove below act on the exercise marked {0}.', t('Current'))}</div>}
<Button onClick={() => exercisePicker((ex, quick) => {
const routine = S.routines.find(r => r.id === A.routineId)
const freestyle = !A.routineId
// Freestyle has no routine prescription to apply: show the last target in the config
// sheet and carry its completed rows forward. A planned session keeps its existing path.
// sheet and carry its completed rows forward. A planned session uses its configured
// target when progression is off, while progression-enabled sessions keep their path.
const seed = freestyle ? freestyleConfig(S, { id: ex.id, ...defaultConfig(ex.id) }) : null
exConfigSheet(ex, null, cfg => update(s => {
const commit = cfg => update(s => {
const full = { ...cfg, id: ex.id }
const plan = freestyle ? null : nextPrescription(s, full, s.routines.find(r => r.id === s.active.routineId))
const sets = buildSets(s, full, { step: defaultIncrement(ex.id, s.unit), ...(freestyle ? { preferLast: true } : {}) })
const sets = buildSets(s, full, {
step: defaultIncrement(ex.id, s.unit),
...(freestyle ? { preferLast: true } : {}),
...(plan?.kind === 'off' ? { useTarget: true } : {})
})
const progressed = freestyle ? sets : applyPrescription(sets, plan, defaultIncrement(ex.id, s.unit))
const insertAt = insertionIndexAfterCurrentUnit(supersetUnits(s.active.entries), s.active.cur, s.active.entries.length)
s.active.entries.splice(insertAt, 0, { id: ex.id, target: { ...cfg }, plan, sets: applyIntensifierPlan(progressed, full) })
s.active.cur = insertAt
useUI.getState().shiftRestOwner(insertAt, 1)
}), null, routine, seed)
})
// The "+" on a picker row reads as "add this now" — routed through the same detail
// sheet before, so it added nothing until you'd scrolled past it and found the real
// button. Quick-add commits with the same default (or, freestyle, last-session) config
// the sheet would have opened with; tapping the row still opens that sheet for anyone
// who wants to set sets/reps first.
if (quick) { commit(seed || defaultConfig(ex.id)); useUI.getState().toast(t('“{0}” added to {1}', exerciseNameFor(ex), routine ? routine.name : t('Freestyle'))) }
else exConfigSheet(ex, null, commit, null, routine, seed)
})} icon="plus">{t('Add exercise')}</Button>
{A.entries.length > 0 && <>
<div style={{ height: 6 }} />
+206
View File
@@ -0,0 +1,206 @@
import React, { act } from 'react'
import { createRoot } from 'react-dom/client'
import { parseHTML } from 'linkedom'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import Workout from './Workout.jsx'
// This suite pins down the superset stepper regression: one tap on a +/- button must move the
// value by exactly one step. The bug was a stale closure — in a superset both ExerciseBlock
// instances share the same store subscription, so updating one member's field re-renders the
// partner and replaces the render-time `s` snapshot the button handler had closed over. The
// fix reads the current value from the store at call time. The mocked `update` below clones the
// whole state on every write (structuredClone), which is exactly what invalidates those
// snapshots, so this environment reproduces the original two-taps-per-increment behaviour.
const mocks = vi.hoisted(() => {
const state = {
S: null,
startRest: vi.fn(),
stopRest: vi.fn(),
stopWork: vi.fn(),
toast: vi.fn(),
}
state.storeSnapshot = () => ({
S: state.S,
user: null,
update: mut => {
const next = structuredClone(state.S)
mut(next)
state.S = next
},
})
state.uiSnapshot = () => ({
timer: null,
work: null,
startRest: state.startRest,
stopRest: state.stopRest,
stopWork: state.stopWork,
shiftRestOwner: vi.fn(),
startWork: vi.fn(),
toast: state.toast,
})
return state
})
vi.mock('../store/useStore.js', () => {
const useStore = selector => selector(mocks.storeSnapshot())
useStore.getState = mocks.storeSnapshot
return { useStore }
})
vi.mock('../store/useUI.js', () => {
const useUI = selector => selector ? selector(mocks.uiSnapshot()) : mocks.uiSnapshot()
useUI.getState = mocks.uiSnapshot
return { useUI }
})
vi.mock('react-router-dom', () => ({ useNavigate: () => () => {} }))
vi.mock('../sheets.jsx', () => ({
startFlow: vi.fn(),
exercisePicker: vi.fn(),
exConfigSheet: vi.fn(),
exerciseDetailSheet: vi.fn(),
topWeightSheet: vi.fn(),
finishWorkout: vi.fn(),
workoutCompleteSheet: vi.fn(),
confirmSheet: vi.fn(),
swapActiveWorkoutExercise: vi.fn(),
barWeightSheet: vi.fn(),
exerciseNoteSheet: vi.fn(),
sessionNoteSheet: vi.fn(),
}))
vi.mock('../components/Media.jsx', () => ({ default: () => null }))
vi.mock('../lib/api.js', () => ({
api: vi.fn(() => Promise.resolve({})),
IS_APPLE: false, IS_ANDROID: false, BIO: 'biometrics',
}))
let dom
let root
let container
function exercise(id, sets, extra = {}) {
return {
id,
target: { mode: 'reps', reps: 5, weight: 60, bodyweight: false },
sets: sets.map(done => ({ w: 60, r: 5, done })),
...extra,
}
}
function workout(entries, cur = 0) {
return {
unit: 'kg', restSec: 90, sound: false, effort: 'none', gifSize: 'full',
workouts: [], exWeights: {}, routines: [],
active: { id: 'active', name: 'Test workout', start: Date.now(), cur, entries },
}
}
function installDom() {
const parsed = parseHTML('<!doctype html><html><body><div id="root"></div></body></html>')
dom = parsed.window
globalThis.window = dom
globalThis.document = dom.document
Object.defineProperty(globalThis, 'navigator', { configurable: true, value: dom.navigator })
for (const key of ['HTMLElement', 'Node', 'Element', 'Event', 'Blob']) globalThis[key] = dom[key]
dom.Element.prototype.scrollIntoView = vi.fn()
globalThis.IS_REACT_ACT_ENVIRONMENT = true
container = document.getElementById('root')
root = createRoot(container)
}
async function mount(entries, cur = 0) {
mocks.S = workout(entries, cur)
installDom()
await act(async () => { root.render(React.createElement(Workout)) })
}
async function unmount() {
if (!root) return
await act(async () => { root.unmount() })
root = null
container = null
dom = null
}
// The +/- controls live in `.stp` cells, one per editable column. For a plain reps set the
// order is [weight, reps]; this returns the Increase/Decrease button for a given column of a
// given set row inside a given exercise block (addressed by its data-exidx wrapper).
function stepperButton(exidx, setRow, col, direction) {
const block = container.querySelector(`[data-exidx="${exidx}"]`)
expect(block).toBeTruthy()
const row = block.querySelectorAll('.setrow')[setRow]
expect(row).toBeTruthy()
const cell = row.querySelectorAll('.stp')[col]
expect(cell).toBeTruthy()
return cell.querySelector(`button[aria-label="${direction}"]`)
}
async function tap(button) {
expect(button).toBeTruthy()
await act(async () => { button.dispatchEvent(new dom.Event('click', { bubbles: true })) })
}
beforeEach(() => {
vi.clearAllMocks()
})
afterEach(async () => {
await unmount()
})
describe('superset stepper — one tap moves one step', () => {
// Weight steps by 2.5. A single tap on the first exercise of a superset must land on 62.5,
// not stay at 60 waiting for a second tap.
it('increments a superset member weight by one step per tap', async () => {
await mount([
exercise('press', [false], { sg: 'group' }),
exercise('row', [false], { sg: 'group' }),
])
await tap(stepperButton(0, 0, 0, 'Increase'))
expect(mocks.S.active.entries[0].sets[0].w).toBe(62.5)
})
// Reps step by 1 and do not cascade, so they isolate the stepper from weight's carry-through.
// Three taps must reach 8 (5 -> 6 -> 7 -> 8); the stale closure made every tap after the
// first re-apply against last render's value, so the count would lag behind the taps.
it('advances reps by exactly one per tap across repeated taps', async () => {
await mount([
exercise('press', [false], { sg: 'group' }),
exercise('row', [false], { sg: 'group' }),
])
await tap(stepperButton(0, 0, 1, 'Increase'))
await tap(stepperButton(0, 0, 1, 'Increase'))
await tap(stepperButton(0, 0, 1, 'Increase'))
expect(mocks.S.active.entries[0].sets[0].r).toBe(8)
})
// The partner exercise shares the subscription that gets replaced on every write. Tapping its
// stepper after the first exercise has already been bumped must still act on the partner's own
// current value, not a snapshot from before the clone.
it('steps the partner exercise correctly after the first member was changed', async () => {
await mount([
exercise('press', [false], { sg: 'group' }),
exercise('row', [false], { sg: 'group' }),
])
await tap(stepperButton(0, 0, 1, 'Increase'))
await tap(stepperButton(1, 0, 1, 'Increase'))
expect(mocks.S.active.entries[0].sets[0].r).toBe(6)
expect(mocks.S.active.entries[1].sets[0].r).toBe(6)
})
// Decrement walks the same path and must not undershoot or need a double tap either.
it('decrements a superset member weight by one step per tap', async () => {
await mount([
exercise('press', [false], { sg: 'group' }),
exercise('row', [false], { sg: 'group' }),
])
await tap(stepperButton(0, 0, 0, 'Decrease'))
expect(mocks.S.active.entries[0].sets[0].w).toBe(57.5)
})
})
+261 -16
View File
@@ -3,6 +3,7 @@ import { createRoot } from 'react-dom/client'
import { parseHTML } from 'linkedom'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import Workout from './Workout.jsx'
import { nextPrescription } from '../lib/progression.js'
const mocks = vi.hoisted(() => {
const state = {
@@ -137,6 +138,13 @@ async function toggleSet(index) {
await act(async () => { checkbox.dispatchEvent(new dom.Event('click', { bubbles: true })) })
}
async function pressNext() {
const button = [...container.querySelectorAll('button')]
.find(button => button.textContent.trim() === 'Next')
expect(button).toBeTruthy()
await act(async () => { button.dispatchEvent(new dom.Event('click', { bubbles: true })) })
}
async function pressProgression(index = 0) {
const button = container.querySelectorAll('.progline')[index]
expect(button).toBeTruthy()
@@ -205,8 +213,50 @@ describe('Workout set completion flow', () => {
expect(mocks.startRest).not.toHaveBeenCalled()
})
it('auto-captures a completed weighted exercise without prompting, leaving navigation to Next', async () => {
await mount([exercise('plain-bench', [false]), exercise('next', [false])])
await toggleSet(0)
expect(mocks.S.active.entries[0].topW).toBe(60)
expect(mocks.S.exWeights['plain-bench']).toBeUndefined() // written at the finish, not while ticking
expect(mocks.topWeightSheet).not.toHaveBeenCalled()
expect(mocks.S.active.cur).toBe(0)
expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number))
await pressNext()
expect(mocks.S.active.cur).toBe(1)
})
it('auto-captures superset members without prompting, then leaves the completed unit for Next', async () => {
const group = 'superset-1'
await mount([
exercise('superset-a', [false], { sg: group }),
exercise('superset-b', [false], { sg: group }),
exercise('next', [false]),
])
await toggleSet(0)
expect(mocks.topWeightSheet).not.toHaveBeenCalled()
expect(mocks.S.active.cur).toBe(1)
expect(mocks.startRest).not.toHaveBeenCalled()
await rerender()
await toggleSet(1)
expect(mocks.topWeightSheet).not.toHaveBeenCalled()
expect(mocks.S.active.cur).toBe(1)
expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number))
await pressNext()
expect(mocks.S.active.cur).toBe(2)
})
it.each(['warmup', 'warm-up', 'warm_up'])(
'does not start transition rest before an incomplete %s row in the next ordinary exercise',
'does not navigate or start transition rest before an incomplete %s row in the next ordinary exercise',
async phase => {
await mount([
exercise('current', [false], { asked: true }),
@@ -221,12 +271,12 @@ describe('Workout set completion flow', () => {
await toggleSet(0)
expect(mocks.S.active.cur).toBe(1)
expect(mocks.S.active.cur).toBe(0)
expect(mocks.startRest).not.toHaveBeenCalled()
},
)
it('does not start transition rest when a completed superset advances to an incomplete warm-up', async () => {
it('does not navigate or start transition rest when a completed superset meets an incomplete warm-up', async () => {
await mount([
exercise('superset-a', [true], { sg: 'group', asked: true }),
exercise('superset-b', [false], { sg: 'group', asked: true }),
@@ -241,11 +291,11 @@ describe('Workout set completion flow', () => {
await toggleSet(1)
expect(mocks.S.active.cur).toBe(2)
expect(mocks.S.active.cur).toBe(1)
expect(mocks.startRest).not.toHaveBeenCalled()
})
it('does not start transition rest before a warm-up while top-weight confirmation owns navigation', async () => {
it('leaves the completed ordinary exercise selected without transition rest before an incomplete warm-up', async () => {
await mount([
exercise('current-loaded', [false]),
exercise('next', [false, false], {
@@ -259,7 +309,7 @@ describe('Workout set completion flow', () => {
await toggleSet(0)
expect(mocks.topWeightSheet).toHaveBeenCalledWith(0)
expect(mocks.topWeightSheet).not.toHaveBeenCalled()
expect(mocks.S.active.cur).toBe(0)
expect(mocks.startRest).not.toHaveBeenCalled()
})
@@ -284,7 +334,7 @@ describe('Workout set completion flow', () => {
expect(mocks.startRest).not.toHaveBeenCalled()
})
it('leaves a completed superset selected while its top-weight sheet owns the advance choice', async () => {
it('leaves a completed superset selected without opening a top-weight sheet', async () => {
const group = 'superset-1'
await mount([
exercise('superset-a', [true, true, true], { sg: group, asked: true }),
@@ -293,12 +343,12 @@ describe('Workout set completion flow', () => {
], 1)
await toggleSet(5)
expect(mocks.topWeightSheet).toHaveBeenCalledWith(1)
expect(mocks.topWeightSheet).not.toHaveBeenCalled()
expect(mocks.S.active.cur).toBe(1)
expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number))
})
it('skips completed intervening units and selects the next unfinished superset as one unit', async () => {
it('does not auto-select an unfinished superset after completing an ordinary exercise', async () => {
await mount([
exercise('current-hold', [false], { asked: true, target: { mode: 'time', sec: 30, weight: 0 } }),
exercise('already-done', [true], { asked: true }),
@@ -308,13 +358,13 @@ describe('Workout set completion flow', () => {
await toggleSet(0)
expect(mocks.S.active.cur).toBe(2)
expect(mocks.S.active.cur).toBe(0)
expect(mocks.workoutCompleteSheet).not.toHaveBeenCalled()
expect(mocks.toast).toHaveBeenCalledWith('Hold logged')
expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number))
})
it('wraps to earlier unfinished work instead of showing a false completion prompt', async () => {
it('does not auto-select earlier unfinished work after completing an ordinary exercise', async () => {
await mount([
exercise('pending-earlier', [false], { asked: true }),
exercise('current-hold', [false], { asked: true, target: { mode: 'time', sec: 30, weight: 0 } }),
@@ -322,12 +372,12 @@ describe('Workout set completion flow', () => {
await toggleSet(0)
expect(mocks.S.active.cur).toBe(0)
expect(mocks.S.active.cur).toBe(1)
expect(mocks.workoutCompleteSheet).not.toHaveBeenCalled()
expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number))
})
it('keeps top-weight confirmation in control without declaring completion while work remains', async () => {
it('leaves a completed ordinary exercise selected without declaring completion while work remains', async () => {
await mount([
exercise('current-loaded', [false]),
exercise('pending', [false], { asked: true }),
@@ -335,9 +385,10 @@ describe('Workout set completion flow', () => {
await toggleSet(0)
expect(mocks.topWeightSheet).toHaveBeenCalledWith(0)
expect(mocks.topWeightSheet).not.toHaveBeenCalled()
expect(mocks.workoutCompleteSheet).not.toHaveBeenCalled()
expect(mocks.S.active.cur).toBe(0)
expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number))
})
it('shows workout completion only when no unfinished unit remains', async () => {
@@ -349,6 +400,7 @@ describe('Workout set completion flow', () => {
await toggleSet(0)
expect(mocks.workoutCompleteSheet).toHaveBeenCalledOnce()
expect(mocks.S.active.cur).toBe(1)
expect(mocks.startRest).not.toHaveBeenCalled()
})
})
@@ -360,7 +412,7 @@ describe('Workout add exercise flow', () => {
active: { routineId: 'routine-1' },
routines: [{ id: 'routine-1', ex: [] }],
}],
])('inserts after the current unit and continues to pending work in a %s session', async (_label, overrides) => {
])('inserts after the current unit and leaves the inserted exercise selected after completion in a %s session', async (_label, overrides) => {
await mount([
exercise('current', [true], { asked: true }),
exercise('pending', [false], { asked: true }),
@@ -378,7 +430,7 @@ describe('Workout add exercise flow', () => {
await toggleSet(0)
expect(mocks.S.active.entries[1].sets[0].done).toBe(true)
expect(mocks.S.active.cur).toBe(2)
expect(mocks.S.active.cur).toBe(1)
expect(mocks.workoutCompleteSheet).not.toHaveBeenCalled()
})
@@ -401,6 +453,69 @@ describe('Workout add exercise flow', () => {
})
})
describe('active workout weight controls', () => {
const press = async (label, selector) => {
const control = container.querySelector(selector)
const button = control?.querySelector(`button[aria-label="${label}"]`)
expect(button).toBeTruthy()
await act(async () => { button.dispatchEvent(new dom.Event('click', { bubbles: true })) })
await rerender()
}
it('uses the configured reps weight step for manual increases and decreases, with the default fallback', async () => {
await mount([exercise('plain-bench', [false], {
target: { mode: 'reps', reps: 5, weight: 60, bodyweight: false, inc: 1 },
})])
await press('Increase', '.setrow .stp.w')
expect(mocks.S.active.entries[0].sets[0].w).toBe(61)
await press('Decrease', '.setrow .stp.w')
expect(mocks.S.active.entries[0].sets[0].w).toBe(60)
await unmount()
await mount([exercise('plain-bench', [false])])
await press('Increase', '.setrow .stp.w')
expect(mocks.S.active.entries[0].sets[0].w).toBe(62.5)
})
it('matches automatic progression rounding for a fractional configured step', async () => {
const target = { mode: 'reps', sets: 1, reps: 5, weight: 60, bodyweight: false, inc: 1.25 }
const automatic = nextPrescription({
unit: 'kg',
workouts: [{ d: '2026-08-30', entries: [{ id: 'plain-bench', target, sets: [{ w: 60, r: 5, done: true }] }] }],
}, { id: 'plain-bench', ...target })
await mount([exercise('plain-bench', [false], { target, sets: [{ w: 60, r: 5, done: false }] })])
await press('Increase', '.setrow .stp.w')
expect(automatic.weight).toBe(61.3)
expect(mocks.S.active.entries[0].sets[0].w).toBe(automatic.weight)
})
it('uses the configured reps weight step for drop-set weight controls', async () => {
await mount([exercise('plain-bench', [false], {
target: { mode: 'reps', reps: 5, weight: 60, bodyweight: false, inc: 1 },
sets: [{ w: 60, r: 5, done: false, type: 'dropset', drops: [{ w: 50, r: 5 }] }],
})])
await press('Increase', '.subrow .stp')
expect(mocks.S.active.entries[0].sets[0].drops[0].w).toBe(51)
})
it('keeps timed seconds and optional timed weight on their existing steps', async () => {
await mount([exercise('timed-plank', [false], {
target: { mode: 'time', sec: 30, weight: 60, bodyweight: false, inc: 1 },
sets: [{ sec: 30, w: 60, done: false }],
})])
await press('Increase', '.setrow .stp.w')
expect(mocks.S.active.entries[0].sets[0].sec).toBe(35)
await press('Increase', '.setrow .stp.r')
expect(mocks.S.active.entries[0].sets[0].w).toBe(62.5)
})
})
describe('Workout discard timer lifecycle', () => {
it('preserves active timers while discard is awaiting confirmation', async () => {
const timer = { left: 30, total: 90, endsAt: Date.now() + 30_000 }
@@ -477,6 +592,47 @@ describe('progression guidance', () => {
expect(mocks.S.active.cur).toBe(0)
})
it('does not save into a different duplicate occurrence after the entry list shifts', async () => {
const plan = {
policy: 'linear', kind: 'up', weight: 62.5,
why: ['Every rep last time — {0} {1} more.', 2.5, 'kg'],
}
const first = exercise('plain-bench', [false], { plan, target: { mode: 'reps', reps: 5, weight: 60, marker: 'first' } })
const second = exercise('plain-bench', [false], { plan, target: { mode: 'reps', reps: 8, weight: 80, marker: 'second' } })
const third = exercise('plain-bench', [false], { plan, target: { mode: 'reps', reps: 10, weight: 100, marker: 'third' } })
await mount([first, second, third], 1)
await pressProgression()
const save = mocks.exConfigSheet.mock.calls[0][2]
mocks.S.active.entries.splice(0, 1)
await act(async () => { save({ ...second.target, prog: 'double', repsMin: 6 }) })
expect(mocks.S.active.entries.map(entry => entry.target.marker)).toEqual(['second', 'third'])
expect(mocks.S.active.entries[0].target.prog).toBeUndefined()
expect(mocks.S.active.entries[1].target.prog).toBeUndefined()
})
it('does not save through a sheet left open from a replaced workout', async () => {
const plan = {
policy: 'linear', kind: 'up', weight: 62.5,
why: ['Every rep last time — {0} {1} more.', 2.5, 'kg'],
}
const original = exercise('plain-bench', [false], { plan })
await mount([original])
await pressProgression()
const save = mocks.exConfigSheet.mock.calls[0][2]
const replacement = exercise('plain-bench', [false], {
plan,
target: { mode: 'reps', reps: 10, weight: 100, marker: 'replacement' },
})
mocks.S.active = { ...mocks.S.active, id: 'replacement-workout', entries: [replacement] }
await act(async () => { save({ ...original.target, prog: 'double', repsMin: 6 }) })
expect(mocks.S.active.entries[0].target).toEqual(replacement.target)
expect(mocks.S.active.entries[0].target.prog).toBeUndefined()
})
it('leaves the active entry unchanged when progression settings are cancelled', async () => {
const entry = exercise('plain-bench', [true, false], {
plan: {
@@ -697,3 +853,92 @@ describe('active exercise swap control', () => {
expect(mocks.swapActiveWorkoutExercise).toHaveBeenCalledWith(1)
})
})
describe('workout list view', () => {
const units = () => [...container.querySelectorAll('.wl-unit')]
const focusButton = unit => [...unit.querySelectorAll('button')].find(b => b.textContent.trim() === 'Set current')
it('stacks every exercise, labels each unit, and hides card navigation', async () => {
await mount([exercise('plain-bench', [false, false]), exercise('plain-row', [false])], 0, { workoutView: 'list' })
expect(container.querySelector('[data-testid="workout-list"]')).toBeTruthy()
expect(container.querySelector('[data-testid="workout-swipe-surface"]')).toBeNull()
expect(units().length).toBe(2)
// Every set in the session is visible at once: 2 + 1 checkboxes, not just the current one.
expect(container.querySelectorAll('[role="checkbox"]').length).toBe(3)
expect(units().map(u => u.querySelector('.wl-hd .muted')?.textContent)).toEqual([
'Exercise 1 / 2', 'Exercise 2 / 2',
])
expect(units()[0].textContent).toContain('Current')
expect(focusButton(units()[1])).toBeTruthy()
const navButtons = [...container.querySelectorAll('button')]
.filter(b => b.textContent.trim() === 'Prev' || b.textContent.trim() === 'Next')
expect(navButtons.length).toBe(0)
})
it('marks the current unit and moves the mark with Set current', async () => {
await mount([exercise('plain-bench', [false]), exercise('plain-row', [false])], 0, { workoutView: 'list' })
await act(async () => { focusButton(units()[1]).dispatchEvent(new dom.Event('click', { bubbles: true })) })
expect(mocks.S.active.cur).toBe(1)
await rerender()
expect(units()[0].textContent).not.toContain('Current')
expect(units()[1].textContent).toContain('Current')
expect(focusButton(units()[0])).toBeTruthy()
})
// Since !92 finishing an exercise no longer moves the current marker on its own (cards use
// Next, the list uses "Set current"); completion still starts the rest like cards do.
it('completing a set in list mode starts the rest and leaves the current marker in place, like cards do', async () => {
await mount([
exercise('plain-bench', [false], { asked: true }),
exercise('plain-row', [false], { asked: true }),
], 0, { workoutView: 'list' })
await toggleSet(0)
expect(mocks.S.active.entries[0].sets[0].done).toBe(true)
expect(mocks.S.active.cur).toBe(0)
expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number))
})
it('does not declare the workout complete after a set of a non-current exercise while sets remain', async () => {
// The marker stays on the finished bench (!92); ticking the first of three row sets must
// not open the completion sheet — the row's own unit still has two sets to go.
await mount([
exercise('plain-bench', [true], { asked: true }),
exercise('plain-row', [false, false, false], { asked: true }),
], 0, { workoutView: 'list' })
await toggleSet(1)
expect(mocks.S.active.entries[1].sets[0].done).toBe(true)
expect(mocks.workoutCompleteSheet).not.toHaveBeenCalled()
expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number))
})
it('renders a superset as one grouped unit with its own unpair control', async () => {
await mount([
exercise('bench', [false], { sg: 'g1', asked: true }),
exercise('row', [false], { sg: 'g1', asked: true }),
exercise('squat', [false], { asked: true }),
], 0, { workoutView: 'list' })
expect(units().length).toBe(2)
expect(units()[0].querySelector('.ss-card')).toBeTruthy()
expect(units()[1].querySelector('.ss-card')).toBeNull()
expect(units().map(u => u.querySelector('.wl-hd .muted')?.textContent)).toEqual([
'Superset 1 / 2', 'Exercise 2 / 2',
])
})
it('defaults to cards when the setting is absent (pre-existing profiles)', async () => {
await mount([exercise('plain-bench', [false]), exercise('plain-row', [false])])
expect(container.querySelector('[data-testid="workout-list"]')).toBeNull()
expect(container.querySelector('[data-testid="workout-swipe-surface"]')).toBeTruthy()
// Only the current exercise's sets are on screen.
expect(container.querySelectorAll('[role="checkbox"]').length).toBe(1)
})
})
+51
View File
@@ -0,0 +1,51 @@
// @vitest-environment happy-dom
// Home and Plan both offer the starter plan to someone who has no routines yet. Both used to
// wire the button straight to the loader, which quietly handed the click event in as the plan
// id and loaded nothing at all — so both entry points are pinned here.
import React, { act } from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { createRoot } from 'react-dom/client'
import { useStore } from '../store/useStore.js'
import { starterPlanSheet } from '../sheets.jsx'
import Home from './Home.jsx'
import Plan from './Plan.jsx'
vi.mock('react-router-dom', () => ({ useNavigate: () => () => {} }))
vi.mock('../sheets.jsx', () => ({
starterPlanSheet: vi.fn(), bwSheet: vi.fn(), goalSheet: vi.fn(), dayOverrideSheet: vi.fn(),
calendarSheet: vi.fn(), startFlow: vi.fn(), bwDeltaColor: () => '',
dayAssignSheet: vi.fn(), planToolsSheet: vi.fn(),
}))
let host, root
beforeEach(() => {
globalThis.IS_REACT_ACT_ENVIRONMENT = true
starterPlanSheet.mockClear()
useStore.setState(s => ({ S: { ...s.S, routines: [], week: {}, active: null }, user: null }))
host = document.createElement('div')
document.body.appendChild(host)
root = createRoot(host)
})
afterEach(() => {
act(() => root.unmount())
host.remove()
})
const starterButton = () => [...host.querySelectorAll('button')].find(b => b.textContent === 'Load starter plan')
describe.each([['Home', Home], ['Plan', Plan]])('%s empty state', (_name, View) => {
it('opens the starter plan chooser instead of loading one plan blind', () => {
act(() => root.render(<View />))
const button = starterButton()
expect(button).toBeTruthy()
act(() => { button.click() })
expect(starterPlanSheet).toHaveBeenCalledTimes(1)
})
it('drops the offer once the user has routines', () => {
useStore.setState(s => ({ S: { ...s.S, routines: [{ id: 'r', name: 'Mine', emoji: 'star', ex: [] }] } }))
act(() => root.render(<View />))
expect(starterButton()).toBeFalsy()
})
})
+1 -1
View File
@@ -44,7 +44,7 @@ vi.mock('../lib/wakelock.js', () => ({ wakeLockSupported: () => false }))
vi.mock('../lib/mobile.js', () => ({ MOBILE: false, shareExport: vi.fn(), syncReminder: vi.fn() }))
vi.mock('./MobileOnboarding.jsx', () => ({ ConnectSheet: () => null }))
vi.mock('../sheets.jsx', () => ({
loadStarterPlan: vi.fn(), confirmSheet: vi.fn(), importFromApp: vi.fn(),
starterPlanSheet: vi.fn(), confirmSheet: vi.fn(), importFromApp: vi.fn(),
importFromHevy: vi.fn(), equipmentProfileSheet: vi.fn(),
dayAssignSheet: vi.fn(), planToolsSheet: vi.fn(),
}))
+13 -5
View File
@@ -67,12 +67,13 @@ the server's stderr.
## Tools
Eight read-only tools in v1:
Nine read-only tools in v1:
| Tool | What it answers |
|---|---|
| `list_routines` | What routines are saved in my profile? (names + exercise counts) |
| `get_routine` | What does the Push Day routine prescribe? (sets/reps/weight per exercise) |
| `get_routine` | What does the Push Day routine prescribe? (sets/reps/weight and rest per exercise) |
| `preview_session` | What will the app actually put on screen when I start this routine — after the progression policy and my history have overridden the plan? |
| `get_week_plan` | What's on my plan this week, including today with any date-specific override? |
| `list_workouts` | Recent sessions — newest first, with dates, sets done/planned, volume, duration, PRs. |
| `get_workout` | Full set-by-set breakdown of one session, by `workout_id` or by date. On a day with two sessions the date alone returns both ids to pick from rather than guessing at one. |
@@ -80,6 +81,13 @@ Eight read-only tools in v1:
| `estimate_1rm` | All-time best 1RM for an exercise + the trend, or a PR table across all exercises. |
| `muscle_balance` | Which muscles I've trained this week/month/all-time, ranked + which I've neglected. |
`get_routine` and `preview_session` answer two different questions, and confusing them is the
easiest way for a coach to give wrong advice. `get_routine` reports what the routine *stores*.
`preview_session` reports what the athlete will actually *see*: a routine holding "squat 3×8 @
60 kg" opens at 75 kg if the policy deloaded from the last logged session, and the rep counts
come from history, not the plan. The routine's own numbers are the last fallback the session
builder consults, not the first. Ask `preview_session` before naming a weight.
Each tool returns JSON the LLM can format as it likes; structured fields (sets, dates, levels)
are pre-formatted into human-readable labels in `src/labels.js` so the LLM doesn't need to
re-interpret them.
@@ -112,7 +120,7 @@ dependencies landed in `frontend/`, no public exports changed.
cd mcp && npm test
```
32 cases seeding state from `frontend/src/lib/demoSeed.js` (the same deterministic fixture
58 cases seeding state from `frontend/src/lib/demoSeed.js` (the same deterministic fixture
the public demo runs on). Pins JSON shape and the user-facing edge cases: rest-day override,
missing routine, zero-workout history, no synced state, superset links, three 1RM formulas.
"Today" is pinned via `vi.useFakeTimers({ now: ..., toFake: ['Date'] })` so date-dependent
@@ -122,8 +130,8 @@ their own 92 tests in `frontend/src/lib/*.test.js`.
## Roadmap
- **Done (Phase 1):** read-only stdio, 8 tools, direct `./data` access.
- **Phase 1.5:** a `progression_next` tool (what does the policy prescribe next?). No new
deps; small surface area.
- **Done (Phase 1.5):** `preview_session` — the policy's next prescription, the opening set
rows it produces, and which of plan / confirmed weight / history each number came from.
- **Phase 2:** read+write over stdio. Requires a long-lived token auth path minted from the
admin dashboard (new `./data/tokens.json`) and a write-lock against the web UI's read-modify-
write of `state-<uid>.json`. Tools: `log_workout`, `add_bodyweight`, `edit_routine`,
+374 -206
View File
@@ -16,41 +16,68 @@
"opengym-mcp": "src/index.js"
},
"devDependencies": {
"@vitest/coverage-v8": "^4.1.11",
"vitest": "^4.1.10"
}
},
"node_modules/@emnapi/core": {
"version": "2.0.0-alpha.3",
"resolved": "https://registry.npmjs.org/@emnapi/core/-/core-2.0.0-alpha.3.tgz",
"integrity": "sha512-AZypUeJ/yByuxyS7BlSNRDOMLMlROYtjYdIAuBmJssVz1UJDSeYxLrdizhXCFYhedC5bqd/ASy8EuNXbVVXp9g==",
"node_modules/@babel/helper-string-parser": {
"version": "7.29.7",
"resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.7.tgz",
"integrity": "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==",
"dev": true,
"license": "MIT",
"optional": true,
"dependencies": {
"@emnapi/wasi-threads": "2.0.1",
"tslib": "^2.4.0"
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@emnapi/runtime": {
"version": "2.0.0-alpha.3",
"resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-2.0.0-alpha.3.tgz",
"integrity": "sha512-hFPAhMUjJD9BSyCANEISPOogeXC9Zo9ZQl7L6vKnaVsMkCtzznaW/naYypeyl0Gv5rYfWYsZbpixTMpjDJzQeA==",
"node_modules/@babel/helper-validator-identifier": {
"version": "7.29.7",
"resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz",
"integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==",
"dev": true,
"license": "MIT",
"optional": true,
"dependencies": {
"tslib": "^2.4.0"
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@emnapi/wasi-threads": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-2.0.1.tgz",
"integrity": "sha512-9DsSk+o5NBX0CCJT8s0EROGSGxjR/tKu6aBTaVyq+SjAEQH4XcdcRxPBRzsBLizTTJ49MJjF+jgu3qnO9GLQcQ==",
"node_modules/@babel/parser": {
"version": "7.29.8",
"resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.8.tgz",
"integrity": "sha512-E8lTAYNB1KW+FH+VGJuZM1ioAx2E6oVlvQFRrf5P8ZZmsiJXYAD9vTFV7yyEURNzgh1dFqMZuO6tUwcARbqFCA==",
"dev": true,
"license": "MIT",
"optional": true,
"dependencies": {
"tslib": "^2.4.0"
"@babel/types": "^7.29.8"
},
"bin": {
"parser": "bin/babel-parser.js"
},
"engines": {
"node": ">=6.0.0"
}
},
"node_modules/@babel/types": {
"version": "7.29.8",
"resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.8.tgz",
"integrity": "sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@babel/helper-string-parser": "^7.29.7",
"@babel/helper-validator-identifier": "^7.29.7"
},
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@bcoe/v8-coverage": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/@bcoe/v8-coverage/-/v8-coverage-1.0.2.tgz",
"integrity": "sha512-6zABk/ECA/QYSCQ1NGiVwwbQerUCZ+TQbp64Q3AgmfNvurHH0j8TtXa1qbShXA6qqkpAj4V5W8pP6mLe1mcMqA==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=18"
}
},
"node_modules/@hono/node-server": {
@@ -65,13 +92,34 @@
"hono": "^4"
}
},
"node_modules/@jridgewell/resolve-uri": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz",
"integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=6.0.0"
}
},
"node_modules/@jridgewell/sourcemap-codec": {
"version": "1.5.5",
"resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz",
"integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==",
"version": "1.6.0",
"resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz",
"integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==",
"dev": true,
"license": "MIT"
},
"node_modules/@jridgewell/trace-mapping": {
"version": "0.3.31",
"resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz",
"integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@jridgewell/resolve-uri": "^3.1.0",
"@jridgewell/sourcemap-codec": "^1.4.14"
}
},
"node_modules/@modelcontextprotocol/sdk": {
"version": "1.30.0",
"resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.30.0.tgz",
@@ -112,42 +160,37 @@
}
}
},
"node_modules/@napi-rs/wasm-runtime": {
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.2.2.tgz",
"integrity": "sha512-JfB4kuJQjaoHuCTseIINHtHWeJnvgEcxjwA5t/Y00ZgaOO1Crz3fjT/p8kT28zA/Caz7oiUMn3d6H2yOVCVwuw==",
"node_modules/@oxc-project/types": {
"version": "0.148.0",
"resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.148.0.tgz",
"integrity": "sha512-Nm4s/jB+4FpFsPhWGEC4h7rzksesmtnMXomo6rCMcg/b8zLQuOziRgkCS1fxDCXOlJB/6Q8oABOZ/OP6RIPj9A==",
"dev": true,
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/oxc-project"
}
},
"node_modules/@rolldown/binding-android-arm-eabi": {
"version": "1.2.7",
"resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.7.tgz",
"integrity": "sha512-EypzgnYCwyVY4NDHKzGmNJT5b+XaQEBniHxsMdeIQLB/tcCzZnhqrzHpZFbX9iaxx+5RiB8caATBtfvZP7zVxQ==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"dependencies": {
"@tybys/wasm-util": "^0.10.3"
},
"os": [
"android"
],
"engines": {
"node": "^20.19.0 || ^22.13.0 || >=23.5.0"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
},
"peerDependencies": {
"@emnapi/core": "^1.7.1 || ^2.0.0-alpha.3",
"@emnapi/runtime": "^1.7.1 || ^2.0.0-alpha.3"
}
},
"node_modules/@oxc-project/types": {
"version": "0.142.0",
"resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.142.0.tgz",
"integrity": "sha512-7W+2q5AKQVU36fkaryontrHn3YDt1RyUYXatw9i5H8ocYe2sPKSFB6eS8WNPeRKiN1qAWWZUPm7gwFzJGrccqQ==",
"dev": true,
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/Boshen"
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-android-arm64": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.1.tgz",
"integrity": "sha512-02hOeOSryYxVrOIphmLAsqnCJWxwlzFk+pEt/N/i6OgT3lShHO7xGCU5cpgchRDHboAEbSjzgGh+O/u1GswQmA==",
"version": "1.2.7",
"resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.7.tgz",
"integrity": "sha512-l17HE9EweWaqJZhuUuNBN/FzM62xw+DECVnJyvMsxn8vJFAGLy5QfLDoYAcronkAN8VxKZHezDpulHDPx95vFw==",
"cpu": [
"arm64"
],
@@ -162,9 +205,9 @@
}
},
"node_modules/@rolldown/binding-darwin-arm64": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.1.tgz",
"integrity": "sha512-fMsTOnN0OjFm3CyppWPitKnc8UlliVARUULW6cfU6AIqjdtgmSFWSk9vecHzZduv/yMWIHDlRhM1e8Iff9uAfA==",
"version": "1.2.7",
"resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.7.tgz",
"integrity": "sha512-8ED8ELFvHXc6OCETIn4gXObPiaR6bckM/ipXtbzlPVDRMBfEGjCKgO90F9YtfdpDatVx/ZQw7aZ1vUMf/+T3Mw==",
"cpu": [
"arm64"
],
@@ -179,9 +222,9 @@
}
},
"node_modules/@rolldown/binding-darwin-x64": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.1.tgz",
"integrity": "sha512-1wjKdz/XLGKHaTNHjQveQ/B23TKx4ItAqm1JbyVuvNPc4Ze0Fb48s49TAd/2zcplPl8okE/UbTgmlVfwT7eFeQ==",
"version": "1.2.7",
"resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.7.tgz",
"integrity": "sha512-/WPripjtiAIZ2tWY7ddijORT0Ujg87wxWW/qcoFVCKAWVDPhtY0xr7Dj0M3GyNGz60jGwTElhro/mkF9dT7dDQ==",
"cpu": [
"x64"
],
@@ -196,9 +239,9 @@
}
},
"node_modules/@rolldown/binding-freebsd-x64": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.1.tgz",
"integrity": "sha512-Fa0jHR07E7YBN4vOEsbVf2briYNsuOowfLJaXULZM0ldMlaCaj2LJgLMbMe4iacRyZmvR8efFhgR9wKuGclQUg==",
"version": "1.2.7",
"resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.7.tgz",
"integrity": "sha512-14DI4NcqpvbICxSnGLx3PmtDaWqRP/KGSGb6C+JLLVPeZRl6dKdHba3pGsqT3vpdTqhEYIPG0MMQ8c0xYqoJxA==",
"cpu": [
"x64"
],
@@ -213,9 +256,9 @@
}
},
"node_modules/@rolldown/binding-linux-arm-gnueabihf": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.1.tgz",
"integrity": "sha512-pzkgu1SSHGgRRyRZ4fbmSgmajbVt+epaLP99NDjFft69v/ypfTi6swBMiVdh2EkQ0OSnHE1lZDM7DRGkyAzUpA==",
"version": "1.2.7",
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.7.tgz",
"integrity": "sha512-bxrWIRvHWQvbJwi+VIie/kDJmQxcNE6xxWwZdqF/ExVAigtHkv54WTLQPb+QsZdnFy18fg7JPfWGL0RH6vwIlQ==",
"cpu": [
"arm"
],
@@ -230,9 +273,9 @@
}
},
"node_modules/@rolldown/binding-linux-arm64-gnu": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.1.tgz",
"integrity": "sha512-QI5SEDY8cbiYWHx0VO4vIc3UlS6a32vXHjU8Qy/17adEmZIPuByJg13UEvo9c/UCiUkdcVWY83C+b+JrwnNyUg==",
"version": "1.2.7",
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.7.tgz",
"integrity": "sha512-toOY2BChBZyuxU7OYX6Tn389di4IzAqPTycVcci0O7FSfBqzRB3RZn+K5Is6ANf4tmgRd/K1yZTsNTXbkXsnLg==",
"cpu": [
"arm64"
],
@@ -250,9 +293,9 @@
}
},
"node_modules/@rolldown/binding-linux-arm64-musl": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.1.tgz",
"integrity": "sha512-Sm41FyCeXqmYcERoYOCbGIL5hNfd8w9LQ7Y61Bev48HkcjaJqV/iiVOaiDxjVTRMS+QKrZmD8cfPt4uMVnvM+A==",
"version": "1.2.7",
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.7.tgz",
"integrity": "sha512-lAIXTH/aiLRLxsTgQvfhjo4K1ydWIp00+V0voOr9beb/9ZmkUFrSIb03dXNFRgMNvkE6oGsF10ioQ6UsI+vS5Q==",
"cpu": [
"arm64"
],
@@ -270,9 +313,9 @@
}
},
"node_modules/@rolldown/binding-linux-ppc64-gnu": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.1.tgz",
"integrity": "sha512-2x+WhXTGl9yJYPbltW/BSEPTVz9OIWQyER4N+gJEDWkkn904eRcBzELqh/Hf7K0w/ubGbKNMv0ZC+94QK/IFEg==",
"version": "1.2.7",
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.7.tgz",
"integrity": "sha512-kdnwS28Pkenp/mZMRwjXXXwxQ7pIsm+bF919LUK93BOyhcLsrVKdP2p9fxpiPNPAbNuch8ypQt0pm2P2LYCAGg==",
"cpu": [
"ppc64"
],
@@ -290,9 +333,9 @@
}
},
"node_modules/@rolldown/binding-linux-s390x-gnu": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.1.tgz",
"integrity": "sha512-eEjmQpuRQayHPWWnywaWHkFT3ToPbP3RYy42VVd/B9aBGDA+Ol25EIWHxKQST3IiWJjikCWUF7KtbfqwZrzVwQ==",
"version": "1.2.7",
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.7.tgz",
"integrity": "sha512-516OdsyLdr5E65paF3yBF55t8mfm9+gmtCsK3xI7XKXIT7EfRlHhxL8K/NR6Hu8BWSgF5+1w74lTL0+nxcc8Qw==",
"cpu": [
"s390x"
],
@@ -310,9 +353,9 @@
}
},
"node_modules/@rolldown/binding-linux-x64-gnu": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.1.tgz",
"integrity": "sha512-/Orga1fZYkLc/56jBICcHrKchl8Z2UKdDSr3LG9ToWO1lQ6a4Livk9Xz+9WN91zsz5QR3XQz2NNoSDEvP6qadw==",
"version": "1.2.7",
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.7.tgz",
"integrity": "sha512-r8/z8n7GFaYRln3xmP1Cxy0HH/HLM0uBUPkEuSVEfKGDA89M0FsZRZJRSwe/tJjRx+fpH/gjorfhB8tmEbSFLA==",
"cpu": [
"x64"
],
@@ -330,9 +373,9 @@
}
},
"node_modules/@rolldown/binding-linux-x64-musl": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.1.tgz",
"integrity": "sha512-xxBJRL+0q0Kce7orznGWLuylHDY65vuARXZRpX+hPdv+DqK2c3NlCsVA98tlWzWNEE7yPqA/1NQ5nnCrj49Y5A==",
"version": "1.2.7",
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.7.tgz",
"integrity": "sha512-pAsE8iiDxUg1xBqdhrTfg45AVDVpirjz00sblEYClGNNcMnDb+e8beQgqIAw6LvauX/APvgxUnwrgun/YYGBhw==",
"cpu": [
"x64"
],
@@ -350,9 +393,9 @@
}
},
"node_modules/@rolldown/binding-openharmony-arm64": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.1.tgz",
"integrity": "sha512-M6AdXIXw3s+/8XpKMzdGDEXGS1S7kwUsy+rcTIUIOx5Ge4nXKCtAFHFV9YKkXvGcC5WMoTjAteLzlsQROVI0Yw==",
"version": "1.2.7",
"resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.7.tgz",
"integrity": "sha512-lTcIYmmnQQA8Or/2DatS6oSqcdLHvendjS+zLu+FwgToynWMRSmQdpM65fTANJgIS4mjbMOo5KT2lnT9SAb96w==",
"cpu": [
"arm64"
],
@@ -366,26 +409,10 @@
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-wasm32-wasi": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.2.1.tgz",
"integrity": "sha512-/TX0SoRGojHzSAHpfVBbavRVSazg5U3h3Y3VXfcc0cdugq6kxdqw8LPGFiPr+/7gE/60zRcsOY2Vi9b9eT0jww==",
"dev": true,
"license": "MIT",
"optional": true,
"dependencies": {
"@emnapi/core": "2.0.0-alpha.3",
"@emnapi/runtime": "2.0.0-alpha.3",
"@napi-rs/wasm-runtime": "^1.2.0"
},
"engines": {
"node": "^20.19.0 || ^22.13.0 || >=23.5.0"
}
},
"node_modules/@rolldown/binding-win32-arm64-msvc": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.1.tgz",
"integrity": "sha512-EvRrivJieyHG+AO9lleZWgq+g0+S7oV2C51yuqlcyU/R9net+sI4Pj0F+lUoP2bEr6TWX3SqFaaS0SzfLxSzkw==",
"version": "1.2.7",
"resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.7.tgz",
"integrity": "sha512-e3Gu3WxbNk/UqQhxqU7YIYO+9ZBvWNz3U+h/qRFosscMFzdRPbXYSaSWgSnklv2fz1TgzBTcti2z35c/7irsHw==",
"cpu": [
"arm64"
],
@@ -400,9 +427,9 @@
}
},
"node_modules/@rolldown/binding-win32-x64-msvc": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.1.tgz",
"integrity": "sha512-Z4eCmn5QJ/5+azF9knpLWKfVd9aidn0mAe9TpJgvBLId9Ax3t0+JVxBmT25Bv7NBbVW1TZyKjQjQReouMeH5UQ==",
"version": "1.2.7",
"resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.7.tgz",
"integrity": "sha512-W/jg5qoRSqjsEv0+dZi4e687mcHqmVuU0P4fK6qS/xjetW2Gmc1W8j//z5nAeNcC8Ttm0hV46IjcYeuVwYhuiw==",
"cpu": [
"x64"
],
@@ -430,17 +457,6 @@
"dev": true,
"license": "MIT"
},
"node_modules/@tybys/wasm-util": {
"version": "0.10.3",
"resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.3.tgz",
"integrity": "sha512-F3fo1MYrRJYL3zER0OUOmkutjr1Vp23m7OsSgp7nq4SP6OqX6C/56XFIPAl5bt3zaBRjmW7SGz3u/6LwFpYcOg==",
"dev": true,
"license": "MIT",
"optional": true,
"dependencies": {
"tslib": "^2.4.0"
}
},
"node_modules/@types/chai": {
"version": "5.2.3",
"resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz",
@@ -466,17 +482,48 @@
"dev": true,
"license": "MIT"
},
"node_modules/@vitest/coverage-v8": {
"version": "4.1.11",
"resolved": "https://registry.npmjs.org/@vitest/coverage-v8/-/coverage-v8-4.1.11.tgz",
"integrity": "sha512-8MVGEFnJIcdGjcbfKmeq8z0pZHH0JlVtoVZH9Q/qwUp6wyFnEJUBMrw9DCaj+ra3vShGmhavjalMIhPNxZAUcw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@bcoe/v8-coverage": "^1.0.2",
"@vitest/utils": "4.1.11",
"ast-v8-to-istanbul": "^1.0.0",
"istanbul-lib-coverage": "^3.2.2",
"istanbul-lib-report": "^3.0.1",
"istanbul-reports": "^3.2.0",
"magicast": "^0.5.2",
"obug": "^2.1.1",
"std-env": "^4.0.0-rc.1",
"tinyrainbow": "^3.1.0"
},
"funding": {
"url": "https://opencollective.com/vitest"
},
"peerDependencies": {
"@vitest/browser": "4.1.11",
"vitest": "4.1.11"
},
"peerDependenciesMeta": {
"@vitest/browser": {
"optional": true
}
}
},
"node_modules/@vitest/expect": {
"version": "4.1.10",
"resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.10.tgz",
"integrity": "sha512-YsCn+qAk1GWjQOWFEsEcL2gNQ0zmVmQu3T03qP6UyjhtmdtwtbuI+DASn/7iQB3HGTXkdBwGddzxPlmiql5vlA==",
"version": "4.1.11",
"resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.11.tgz",
"integrity": "sha512-VX2x5vNJXET47KAFzwERI+KRMtTTCSWTfSMKsW7JsUsXV4psq++e3DvZpuTDOpHcxytiDs6p2nhVb2tVDiiUYw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@standard-schema/spec": "^1.1.0",
"@types/chai": "^5.2.2",
"@vitest/spy": "4.1.10",
"@vitest/utils": "4.1.10",
"@vitest/spy": "4.1.11",
"@vitest/utils": "4.1.11",
"chai": "^6.2.2",
"tinyrainbow": "^3.1.0"
},
@@ -485,13 +532,13 @@
}
},
"node_modules/@vitest/mocker": {
"version": "4.1.10",
"resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-4.1.10.tgz",
"integrity": "sha512-v0xaezt+DKEmKfaxg133ldzADrwLGd7Ze1MfQQTYfvs8OqZIwbxyxaYURivwV7sWy5fqn3rH5uOrSp07bp44Ow==",
"version": "4.1.11",
"resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-4.1.11.tgz",
"integrity": "sha512-2XJVD55d1o5AZous5CCGKS74g/riOj9odEt2bQpCVZeblHyHdnMeFl4jl0XjU21stf4mbjUkew2eXQZt65g5CQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@vitest/spy": "4.1.10",
"@vitest/spy": "4.1.11",
"estree-walker": "^3.0.3",
"magic-string": "^0.30.21"
},
@@ -512,9 +559,9 @@
}
},
"node_modules/@vitest/pretty-format": {
"version": "4.1.10",
"resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.1.10.tgz",
"integrity": "sha512-W1HsjSH4MXQ9YfmmhLAoIYf1HRfekQCGngeIgcei6MP5QQGWUe0gkopdZQaVCFO+JDJMrAJGwa5pRpNpvy4P8Q==",
"version": "4.1.11",
"resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.1.11.tgz",
"integrity": "sha512-yiZzPbGTS9Sr/JpFl8zHrcIkAofNbFV6k21vIgQN/cY/oxZeXhJv5sc/MBJ5jFKWmWs+oJHw0UXLZjmf931+Vw==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -525,13 +572,13 @@
}
},
"node_modules/@vitest/runner": {
"version": "4.1.10",
"resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-4.1.10.tgz",
"integrity": "sha512-IKI6kpIH+LmpROplyLwBBaCfMgOZOMsygVa6BARD6ahA04VRuJSa6OaVG7kRvSEMD870Vd91rSSw0eegtWyLGg==",
"version": "4.1.11",
"resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-4.1.11.tgz",
"integrity": "sha512-LztvUgdwMNJMIkj3hQnnxiC2Xy1zNxq928W/xhjCLaNCzqTZOudjwbQf6v9IntZGPw132i2Lq2rgTRZHD3JHNw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@vitest/utils": "4.1.10",
"@vitest/utils": "4.1.11",
"pathe": "^2.0.3"
},
"funding": {
@@ -539,14 +586,14 @@
}
},
"node_modules/@vitest/snapshot": {
"version": "4.1.10",
"resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-4.1.10.tgz",
"integrity": "sha512-xRkfOT1qpTAi/Ti4Y1LtfRc3kEuqxGw59eN2jN9pRWMtS/XDevekhcFSqvQqjUNGksfjMJu3Y+oJ+4Ypn2OaJw==",
"version": "4.1.11",
"resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-4.1.11.tgz",
"integrity": "sha512-pN7ikn1ON7h8ee4gIAp4AzyK+zBtJPzVbqOgu5LCEh4VaJVbPQcgYQYJIMGQPXVeJJq1fnfazis7a5pFNPahog==",
"dev": true,
"license": "MIT",
"dependencies": {
"@vitest/pretty-format": "4.1.10",
"@vitest/utils": "4.1.10",
"@vitest/pretty-format": "4.1.11",
"@vitest/utils": "4.1.11",
"magic-string": "^0.30.21",
"pathe": "^2.0.3"
},
@@ -555,9 +602,9 @@
}
},
"node_modules/@vitest/spy": {
"version": "4.1.10",
"resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.1.10.tgz",
"integrity": "sha512-PLf/Ugvoq5wO/b4rwYCR1h2PSIdXz7wnkQFMiUpLdtM7l6pqVFcQIBEHyT1+l+cj7mNwAfZHzqXqDyjvOuwbDw==",
"version": "4.1.11",
"resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.1.11.tgz",
"integrity": "sha512-apNa/prQy2qCeywhnixOHPRCgGNhvg7T4Dapfl1GahLp/R+uhBm5cPyFoNVyqsNd2h1nJxL6BqqdIjiABL60YA==",
"dev": true,
"license": "MIT",
"funding": {
@@ -565,13 +612,13 @@
}
},
"node_modules/@vitest/utils": {
"version": "4.1.10",
"resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-4.1.10.tgz",
"integrity": "sha512-fy9am/HWxbaGt/Sawrp90vt6Y6jQwf1RX77cz3uwoJwJVMli/e1IEwRPnMNJ7vKfPTwo0diXifkpPvwH9v7nGA==",
"version": "4.1.11",
"resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-4.1.11.tgz",
"integrity": "sha512-zTCVGpyFsGWBhllOyKlTw/vnr6D9qxsfSDyfbyZmTyjHw5N/VuvzHpHoQjm2ZJzn4RJgx5w4r7V0er69CmLgPQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@vitest/pretty-format": "4.1.10",
"@vitest/pretty-format": "4.1.11",
"convert-source-map": "^2.0.0",
"tinyrainbow": "^3.1.0"
},
@@ -635,6 +682,18 @@
"node": ">=12"
}
},
"node_modules/ast-v8-to-istanbul": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/ast-v8-to-istanbul/-/ast-v8-to-istanbul-1.0.5.tgz",
"integrity": "sha512-UPAgKJFSEGMWSDr3LX4tqnAb4f7KGT8O40Tyx8wbYmmZ/yn58lNCm8h3svs3eXgiGd5AXxz8NDOvXWvicq+rJA==",
"dev": true,
"license": "MIT",
"dependencies": {
"@jridgewell/trace-mapping": "^0.3.31",
"estree-walker": "^3.0.3",
"js-tokens": "^10.0.0"
}
},
"node_modules/body-parser": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.3.0.tgz",
@@ -1170,6 +1229,16 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/has-flag": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz",
"integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
}
},
"node_modules/has-symbols": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",
@@ -1203,6 +1272,13 @@
"node": ">=16.9.0"
}
},
"node_modules/html-escaper": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz",
"integrity": "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==",
"dev": true,
"license": "MIT"
},
"node_modules/http-errors": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz",
@@ -1275,6 +1351,45 @@
"integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",
"license": "ISC"
},
"node_modules/istanbul-lib-coverage": {
"version": "3.2.2",
"resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-3.2.2.tgz",
"integrity": "sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg==",
"dev": true,
"license": "BSD-3-Clause",
"engines": {
"node": ">=8"
}
},
"node_modules/istanbul-lib-report": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-3.0.1.tgz",
"integrity": "sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw==",
"dev": true,
"license": "BSD-3-Clause",
"dependencies": {
"istanbul-lib-coverage": "^3.0.0",
"make-dir": "^4.0.0",
"supports-color": "^7.1.0"
},
"engines": {
"node": ">=10"
}
},
"node_modules/istanbul-reports": {
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-3.2.0.tgz",
"integrity": "sha512-HGYWWS/ehqTV3xN10i23tkPkpH46MLCIMFNCaaKNavAXTF1RkqxawEPtnjnGZ6XKSInBKkiOA5BKS+aZiY3AvA==",
"dev": true,
"license": "BSD-3-Clause",
"dependencies": {
"html-escaper": "^2.0.0",
"istanbul-lib-report": "^3.0.0"
},
"engines": {
"node": ">=8"
}
},
"node_modules/jose": {
"version": "6.2.7",
"resolved": "https://registry.npmjs.org/jose/-/jose-6.2.7.tgz",
@@ -1284,6 +1399,13 @@
"url": "https://github.com/sponsors/panva"
}
},
"node_modules/js-tokens": {
"version": "10.0.0",
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-10.0.0.tgz",
"integrity": "sha512-lM/UBzQmfJRo9ABXbPWemivdCW8V2G8FHaHdypQaIy523snUjog0W71ayWXTjiR+ixeMyVHN2XcpnTd/liPg/Q==",
"dev": true,
"license": "MIT"
},
"node_modules/json-schema-traverse": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz",
@@ -1579,6 +1701,34 @@
"@jridgewell/sourcemap-codec": "^1.5.5"
}
},
"node_modules/magicast": {
"version": "0.5.4",
"resolved": "https://registry.npmjs.org/magicast/-/magicast-0.5.4.tgz",
"integrity": "sha512-llBEhWm1SacoRwgHUoQJYtwp4PBLF4faQi5TCpIGyGs9n4y5+juI0tDgyKIfpqxckRHaHzouUEph3THklWh03w==",
"dev": true,
"license": "MIT",
"dependencies": {
"@babel/parser": "^7.29.7",
"@babel/types": "^7.29.7",
"source-map-js": "^1.2.1"
}
},
"node_modules/make-dir": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/make-dir/-/make-dir-4.0.0.tgz",
"integrity": "sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==",
"dev": true,
"license": "MIT",
"dependencies": {
"semver": "^7.5.3"
},
"engines": {
"node": ">=10"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/math-intrinsics": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
@@ -1645,9 +1795,9 @@
"license": "MIT"
},
"node_modules/nanoid": {
"version": "3.3.16",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.16.tgz",
"integrity": "sha512-bzlKTyNJ7+LdGIIwy8ijFpIqEQIvafahV7eYykJ8Cvh42EdJeODoJ6gUJXpQJvej1BddH8OqTXZNE/KfbWAu8Q==",
"version": "3.3.18",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.18.tgz",
"integrity": "sha512-DTg4MJbGMWkfi6VZFdNt2/caMbQy4Ou+Op/hJQvGEWcnVfoA1QA+xzRKAzw9jD6+GVOOeYr/mIcuDSdug6F6+w==",
"dev": true,
"funding": [
{
@@ -1771,9 +1921,9 @@
"license": "ISC"
},
"node_modules/picomatch": {
"version": "4.0.5",
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.5.tgz",
"integrity": "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==",
"version": "4.0.7",
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz",
"integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==",
"dev": true,
"license": "MIT",
"engines": {
@@ -1793,9 +1943,9 @@
}
},
"node_modules/postcss": {
"version": "8.5.25",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.25.tgz",
"integrity": "sha512-DTPx3RWSSnWyzLxQnlH0rJP+EW5ekl16ZU4/psbIhA0e53kJfdgaN5vKM+xP7yJtXVu+nfdVFmlgFDEKAe4Pyw==",
"version": "8.5.28",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.28.tgz",
"integrity": "sha512-RRuzqDtt5Y9h3quz5hWhK+TPnsmVs6WwSU6LkJMeY4HstUEDuYTG8UJSdawMRzmzAtV+KEoG8N3Qg2qLy5vM/A==",
"dev": true,
"funding": [
{
@@ -1813,7 +1963,7 @@
],
"license": "MIT",
"dependencies": {
"nanoid": "^3.3.16",
"nanoid": "^3.3.18",
"picocolors": "^1.1.1",
"source-map-js": "^1.2.1"
},
@@ -1888,13 +2038,13 @@
}
},
"node_modules/rolldown": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.1.tgz",
"integrity": "sha512-4FKJhg8d3OiyQOA6Q1Q0hoFFpW9/OoX+VsHzpECsdsIZoOArrAK90gl59YK/Z+gnDel45bgJZK03ozH/9bCqEw==",
"version": "1.2.7",
"resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.7.tgz",
"integrity": "sha512-g0EtLvBjTUB7jhyV0S/TCup3v/XSVl45vUIGbOGU4QPiyjTenCe4mKuFvW9fEgYmS2Fo42AUssRmNuMziXdrig==",
"dev": true,
"license": "MIT",
"dependencies": {
"@oxc-project/types": "=0.142.0",
"@oxc-project/types": "=0.148.0",
"@rolldown/pluginutils": "^1.0.0"
},
"bin": {
@@ -1904,21 +2054,21 @@
"node": "^20.19.0 || >=22.12.0"
},
"optionalDependencies": {
"@rolldown/binding-android-arm64": "1.2.1",
"@rolldown/binding-darwin-arm64": "1.2.1",
"@rolldown/binding-darwin-x64": "1.2.1",
"@rolldown/binding-freebsd-x64": "1.2.1",
"@rolldown/binding-linux-arm-gnueabihf": "1.2.1",
"@rolldown/binding-linux-arm64-gnu": "1.2.1",
"@rolldown/binding-linux-arm64-musl": "1.2.1",
"@rolldown/binding-linux-ppc64-gnu": "1.2.1",
"@rolldown/binding-linux-s390x-gnu": "1.2.1",
"@rolldown/binding-linux-x64-gnu": "1.2.1",
"@rolldown/binding-linux-x64-musl": "1.2.1",
"@rolldown/binding-openharmony-arm64": "1.2.1",
"@rolldown/binding-wasm32-wasi": "1.2.1",
"@rolldown/binding-win32-arm64-msvc": "1.2.1",
"@rolldown/binding-win32-x64-msvc": "1.2.1"
"@rolldown/binding-android-arm-eabi": "1.2.7",
"@rolldown/binding-android-arm64": "1.2.7",
"@rolldown/binding-darwin-arm64": "1.2.7",
"@rolldown/binding-darwin-x64": "1.2.7",
"@rolldown/binding-freebsd-x64": "1.2.7",
"@rolldown/binding-linux-arm-gnueabihf": "1.2.7",
"@rolldown/binding-linux-arm64-gnu": "1.2.7",
"@rolldown/binding-linux-arm64-musl": "1.2.7",
"@rolldown/binding-linux-ppc64-gnu": "1.2.7",
"@rolldown/binding-linux-s390x-gnu": "1.2.7",
"@rolldown/binding-linux-x64-gnu": "1.2.7",
"@rolldown/binding-linux-x64-musl": "1.2.7",
"@rolldown/binding-openharmony-arm64": "1.2.7",
"@rolldown/binding-win32-arm64-msvc": "1.2.7",
"@rolldown/binding-win32-x64-msvc": "1.2.7"
}
},
"node_modules/router": {
@@ -1943,6 +2093,19 @@
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
"license": "MIT"
},
"node_modules/semver": {
"version": "7.8.5",
"resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz",
"integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==",
"dev": true,
"license": "ISC",
"bin": {
"semver": "bin/semver.js"
},
"engines": {
"node": ">=10"
}
},
"node_modules/send": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz",
@@ -2127,6 +2290,19 @@
"dev": true,
"license": "MIT"
},
"node_modules/supports-color": {
"version": "7.2.0",
"resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz",
"integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==",
"dev": true,
"license": "MIT",
"dependencies": {
"has-flag": "^4.0.0"
},
"engines": {
"node": ">=8"
}
},
"node_modules/tinybench": {
"version": "2.9.0",
"resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz",
@@ -2180,14 +2356,6 @@
"node": ">=0.6"
}
},
"node_modules/tslib": {
"version": "2.8.1",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
"dev": true,
"license": "0BSD",
"optional": true
},
"node_modules/type-is": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/type-is/-/type-is-2.1.0.tgz",
@@ -2238,16 +2406,16 @@
}
},
"node_modules/vite": {
"version": "8.2.0",
"resolved": "https://registry.npmjs.org/vite/-/vite-8.2.0.tgz",
"integrity": "sha512-pn+CFpM0lwDeKwmOq1ZaBK/9sjorZcgqxki6MbY/jPEVd9vichIlmlD4HmQ5wdP5EgqQCFRaACBxMC7uEGc6lQ==",
"version": "8.2.2",
"resolved": "https://registry.npmjs.org/vite/-/vite-8.2.2.tgz",
"integrity": "sha512-cFKLV/PRgAUlIRm5WjMjJ86jrftzpqcgH+Us+DS8mI3CDNiH30Whrz8uHL3+MOLPAgqbMBAqWdAHAphOAM+z/Q==",
"dev": true,
"license": "MIT",
"dependencies": {
"lightningcss": "^1.33.0",
"picomatch": "^4.0.5",
"postcss": "^8.5.23",
"rolldown": "~1.2.0",
"postcss": "^8.5.26",
"rolldown": "~1.2.4",
"tinyglobby": "^0.2.17"
},
"bin": {
@@ -2264,7 +2432,7 @@
},
"peerDependencies": {
"@types/node": "^20.19.0 || >=22.12.0",
"@vitejs/devtools": "^0.4.0",
"@vitejs/devtools": "^0.4.0 || ^0.5.0",
"esbuild": "^0.27.0 || ^0.28.0",
"jiti": ">=1.21.0",
"less": "^4.0.0",
@@ -2316,19 +2484,19 @@
}
},
"node_modules/vitest": {
"version": "4.1.10",
"resolved": "https://registry.npmjs.org/vitest/-/vitest-4.1.10.tgz",
"integrity": "sha512-R9jUTe5S4Qb0HCd4TNqpC7oGcrMssMRGXLW80ubjWsW9VH5GF8y1Y0SFLY9AbqSk6nt0PnOx4H4WNJYZ13GUPw==",
"version": "4.1.11",
"resolved": "https://registry.npmjs.org/vitest/-/vitest-4.1.11.tgz",
"integrity": "sha512-fhACrNXUidIbGSBr5FlbuBkO7VWC1ZyLl0DO4CU2DrQoAPxX84Ysxs+HeGQpii5lZWV1Q4gBZTTu49mF+A6Edw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@vitest/expect": "4.1.10",
"@vitest/mocker": "4.1.10",
"@vitest/pretty-format": "4.1.10",
"@vitest/runner": "4.1.10",
"@vitest/snapshot": "4.1.10",
"@vitest/spy": "4.1.10",
"@vitest/utils": "4.1.10",
"@vitest/expect": "4.1.11",
"@vitest/mocker": "4.1.11",
"@vitest/pretty-format": "4.1.11",
"@vitest/runner": "4.1.11",
"@vitest/snapshot": "4.1.11",
"@vitest/spy": "4.1.11",
"@vitest/utils": "4.1.11",
"es-module-lexer": "^2.0.0",
"expect-type": "^1.3.0",
"magic-string": "^0.30.21",
@@ -2356,12 +2524,12 @@
"@edge-runtime/vm": "*",
"@opentelemetry/api": "^1.9.0",
"@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0",
"@vitest/browser-playwright": "4.1.10",
"@vitest/browser-preview": "4.1.10",
"@vitest/browser-webdriverio": "4.1.10",
"@vitest/coverage-istanbul": "4.1.10",
"@vitest/coverage-v8": "4.1.10",
"@vitest/ui": "4.1.10",
"@vitest/browser-playwright": "4.1.11",
"@vitest/browser-preview": "4.1.11",
"@vitest/browser-webdriverio": "4.1.11",
"@vitest/coverage-istanbul": "4.1.11",
"@vitest/coverage-v8": "4.1.11",
"@vitest/ui": "4.1.11",
"happy-dom": "*",
"jsdom": "*",
"vite": "^6.0.0 || ^7.0.0 || ^8.0.0"
+2 -1
View File
@@ -3,7 +3,7 @@
"version": "0.1.0",
"private": true,
"type": "module",
"description": "MCP (Model Context Protocol) bridge for openGym \u2014 lets an external LLM read your routines, workouts, body-weight log, estimated 1RMs and muscle balance from your self-hosted data. Read-only, stdio transport; no extra container.",
"description": "MCP (Model Context Protocol) bridge for openGym — lets an external LLM read your routines, workouts, body-weight log, estimated 1RMs and muscle balance from your self-hosted data. Read-only, stdio transport; no extra container.",
"license": "AGPL-3.0-or-later",
"main": "src/index.js",
"bin": {
@@ -19,6 +19,7 @@
"zod": "^3.23.8"
},
"devDependencies": {
"@vitest/coverage-v8": "^4.1.11",
"vitest": "^4.1.10"
}
}
+159 -4
View File
@@ -4,10 +4,10 @@
import { z } from 'zod'
import { getState, getUser } from './state.js'
import {
setLabel, exLine, muscleName, policyName, friendlyDuration, ratio, muscleOrder
fmt, setLabel, exLine, muscleName, policyName, friendlyDuration, ratio, muscleOrder
} from './labels.js'
import {
modeOf, workoutVolume, setsDone, effectiveRoutine, effectiveRoutineId
modeOf, workoutVolume, setsDone, effectiveRoutine, effectiveRoutineId, lastEntryFor
} from '../../frontend/src/lib/history.js'
import { exOr } from '../../frontend/src/lib/exercises.js'
import { isWarmupRow } from '../../frontend/src/lib/workout-model.js'
@@ -16,6 +16,7 @@ import {
} from '../../frontend/src/lib/onerm.js'
import { loadOfWorkouts, rankOf, levelsOf } from '../../frontend/src/lib/muscles.js'
import { policyFor } from '../../frontend/src/lib/progression.js'
import { buildSessionEntries } from '../../frontend/src/lib/session-start.js'
/* ---------- helpers ---------- */
@@ -105,7 +106,7 @@ export const listRoutines = {
/** get_routine — the full exercise list for one routine, including set/rep targets. */
export const getRoutine = {
name: 'get_routine',
description: 'Get the full exercise list for a single routine (the same view the routine editor shows). Returns mode (reps/time/cardio), set/rep/weight targets, superset links, and any per-exercise custom increment you can override. Use routine_id from list_routines.',
description: 'Get the full exercise list for a single routine (the same view the routine editor shows). Returns mode (reps/time/cardio), set/rep/weight targets, superset links, any per-exercise custom increment you can override, and each exercise\'s own rest in seconds (absent means it inherits the global rest timer). Use routine_id from list_routines.',
schema: { routine_id: z.string().min(1) },
handler: ({ routine_id }) => {
const S = getState()
@@ -138,6 +139,9 @@ export const getRoutine = {
speed: mode === 'cardio' ? (cfg.speed || 0) : undefined,
weight: cfg.weight != null ? cfg.weight : undefined,
increment: cfg.inc != null ? cfg.inc : undefined,
// The exercise's own rest (issue #10). Absent means it inherits the global rest
// timer; a superset rests once, taking the longest its members ask for.
rest_sec: cfg.restSec > 0 ? cfg.restSec : undefined,
policy: policyFor(cfg, r, mode),
policy_override: cfg.prog || null,
superset_group: cfg.sg || null,
@@ -407,10 +411,161 @@ export const muscleBalance = {
}
}
/* ---------- preview_session ---------- */
// Where a number on the session screen actually came from. A routine's own sets/reps/weight
// are the LAST fallback, not the first: buildSets() prefers the confirmed working weight and
// the previous session's reps, and applyPrescription() then overwrites the weight with
// whatever the progression policy decided. Reporting the winner is the whole point of this
// tool — "the plan says 60" is not an answer to "what will the app show me".
function sourceOf(S, cfg, plan, field) {
// Progression off (or a deload routine): the session is built from the routine's own target,
// exactly as session-start.js does with useTarget — history and the confirmed weight are ignored.
if (!plan || plan.kind === 'off') return 'routine_plan'
const decided = plan.kind !== 'first' && plan[field] != null
if (decided) return 'progression'
if (field === 'weight') {
const conf = (S.exWeights || {})[cfg.id]
if (conf && conf.w > 0) return 'confirmed_weight'
}
return lastEntryFor(S, cfg.id) ? 'last_session' : 'routine_plan'
}
const SOURCE_TEXT = {
progression: 'the progression policy overrode the routine',
confirmed_weight: 'your confirmed working weight for this exercise',
last_session: 'carried over from the last time you did this exercise',
routine_plan: "the routine's own target"
}
/** preview_session — what starting this routine will actually put on screen. */
export const previewSession = {
name: 'preview_session',
description:
'Preview the session a routine will actually open with — the numbers the user will see after the progression policy and their training history have overridden the routine\'s own targets. This is NOT the same as get_routine: a routine storing "squat 3x8 @ 60kg" can open at 75kg because the policy deloaded from the last logged session, and reps carry from history rather than from the plan. Always call this (not get_routine) before telling someone what weight they are about to lift, or before judging whether an edit to a routine had any effect. Returns, per exercise, the planned target, the policy\'s decision and its stated reason, the opening set rows, and where each number came from. Defaults to today\'s scheduled routine.',
schema: {
routine_id: z.string().min(1).optional().describe('Routine to preview. Defaults to the routine scheduled for `date`.'),
date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional().describe('Date the session would be started on, YYYY-MM-DD. Affects which routine is scheduled and any one-off day override. Defaults to today.')
},
handler: ({ routine_id, date }) => {
const S = getState()
if (!S) return noState()
const now = new Date()
const iso = date || (now.getFullYear() + '-' + String(now.getMonth() + 1).padStart(2, '0') + '-' + String(now.getDate()).padStart(2, '0'))
let r
if (routine_id) {
r = (S.routines || []).find(x => x.id === routine_id)
if (!r) { const e = new Error(`no routine with id ${JSON.stringify(routine_id)}`); e.code = 'ENOENT'; throw e }
} else {
r = effectiveRoutine(S, iso)
if (!r) return { date: iso, routine_id: null, routine_name: null, rest_day: true, note: 'no routine is scheduled for this date (rest day)', exercises: [] }
}
const unit = S.unit || 'kg'
// The same builder the app starts a session with (sheets.jsx beginWorkout → session-start.js):
// prescription, step, progression-off targets, deload routines and warm-up ramps all come from
// there, so the preview cannot drift from what the screen shows.
const built = buildSessionEntries(S, r).entries
const exercises = (r.ex || []).map((cfg, i) => {
const ex = exerciseOf(cfg.id, S)
const mode = modeOf({ ...cfg, id: cfg.id })
const plan = built[i].plan
const rows = built[i].sets
const work = rows.filter(s => !isWarmupRow(s))
const openW = work.length ? (work[0].w || 0) : 0
const openR = work.length ? (work[0].r || 0) : 0
const openSec = work.length ? (work[0].sec || 0) : 0
const openMin = work.length ? (work[0].min || 0) : 0
const wSrc = sourceOf(S, cfg, plan, 'weight')
const rSrc = sourceOf(S, cfg, plan, 'reps')
return {
position: i + 1,
id: cfg.id,
name: ex.n,
mode,
policy: plan.policy,
policy_name: policyName(plan.policy),
planned: {
sets: cfg.sets || 1,
reps: mode === 'reps' ? (cfg.reps || 0) : undefined,
sec: mode === 'time' ? (cfg.sec || 0) : undefined,
min: mode === 'cardio' ? (cfg.min || 0) : undefined,
weight: cfg.weight != null ? cfg.weight : undefined,
summary: exLine(cfg, unit)
},
prescription: {
kind: plan.kind,
weight: plan.weight != null ? plan.weight : undefined,
reps: plan.reps != null ? plan.reps : undefined,
sets: plan.sets != null ? plan.sets : undefined,
sec: plan.sec != null ? plan.sec : undefined,
why: plan.why ? fmt(plan.why[0], plan.why.slice(1)) : null
},
opening_sets: rows.map(s => ({
phase: isWarmupRow(s) ? 'warmup' : 'work',
type: s.type || 'straight',
label: setLabel(cfg.id, { ...s, done: undefined }, { ...cfg, id: cfg.id }),
w: Number(s.w) || 0,
r: Number(s.r) || 0,
sec: Number(s.sec) || 0,
min: Number(s.min) || 0,
speed: Number(s.speed) || 0
})),
weight_source: wSrc,
weight_source_text: SOURCE_TEXT[wSrc],
reps_source: mode === 'reps' ? rSrc : undefined,
reps_source_text: mode === 'reps' ? SOURCE_TEXT[rSrc] : undefined,
// The headline: did editing the routine change anything the user will see? Tracked per
// dimension — a bodyweight exercise whose weight is 0 either way still counts when the
// rep target moved, and saying which one moved saves the caller diffing it themselves.
changed: [
...(mode === 'reps' && cfg.weight != null && openW !== cfg.weight ? ['weight'] : []),
...(mode === 'reps' && (cfg.reps || 0) > 0 && openR !== cfg.reps ? ['reps'] : []),
...(mode === 'time' && (cfg.sec || 0) > 0 && openSec !== cfg.sec ? ['sec'] : []),
...(mode === 'cardio' && (cfg.min || 0) > 0 && openMin !== cfg.min ? ['min'] : [])
],
differs_from_plan:
(mode === 'reps' && cfg.weight != null && openW !== cfg.weight) ||
(mode === 'reps' && (cfg.reps || 0) > 0 && openR !== cfg.reps) ||
(mode === 'time' && (cfg.sec || 0) > 0 && openSec !== cfg.sec) ||
(mode === 'cardio' && (cfg.min || 0) > 0 && openMin !== cfg.min)
}
})
const differing = exercises.filter(e => e.differs_from_plan)
return {
date: iso,
routine_id: r.id,
routine_name: r.name,
unit,
policy: policyFor(null, r, 'reps'),
policy_name: policyName(policyFor(null, r, 'reps')),
exercises,
// Surfaced separately so a coach reading this cannot miss it: these are the exercises
// where what the routine stores and what the athlete will see are two different numbers.
overridden_count: differing.length,
overridden: differing.map(e => ({
name: e.name,
planned_weight: e.planned.weight,
opening_weight: e.opening_sets.filter(s => s.phase === 'work')[0]?.w ?? null,
planned_reps: e.planned.reps,
opening_reps: e.opening_sets.filter(s => s.phase === 'work')[0]?.r ?? null,
planned_sec: e.planned.sec,
opening_sec: e.opening_sets.filter(s => s.phase === 'work')[0]?.sec ?? null,
planned_min: e.planned.min,
opening_min: e.opening_sets.filter(s => s.phase === 'work')[0]?.min ?? null,
changed: e.changed,
reason: e.prescription.why || e.weight_source_text
}))
}
}
}
/* ---------- registration list ---------- */
export const TOOLS = [
listRoutines, getRoutine, getWeekPlan, listWorkouts, getWorkout, getBodyweight, estimate1rm, muscleBalance
listRoutines, getRoutine, previewSession, getWeekPlan, listWorkouts, getWorkout, getBodyweight, estimate1rm, muscleBalance
]
function noState() {
+185
View File
@@ -129,6 +129,17 @@ describe('get_routine', () => {
expect(r.exercises[0]).toMatchObject({ reps: 8, reps_min: 8, reps_max: 12 })
})
test('reports an exercise\'s own rest, and leaves it out when it inherits the timer', () => {
S.routines[0].ex[0].restSec = 180
delete S.routines[0].ex[1]?.restSec
const r = call('get_routine', { routine_id: S.routines[0].id })
expect(r.exercises[0].rest_sec).toBe(180)
// An exercise with no rest of its own inherits the global timer. Absent says that;
// a zero would read as "no rest at all", which is a different prescription.
expect(JSON.parse(JSON.stringify(r)).exercises[1]).not.toHaveProperty('rest_sec')
})
test('projects routine and exercise progression rules from prog', () => {
S.routines[0].prog = 'greyskull'
S.routines[0].ex[0].prog = 'double'
@@ -663,3 +674,177 @@ describe('shared: no-state fallback', () => {
// failure rather than inherits null silently.
afterAll(() => { _seedStateForTests(S = freshState()) })
})
/* ---------- preview_session ---------- */
// The gap this tool exists to close: a routine stores sets/reps/weight, but those are the
// LAST fallback the session builder consults. These tests pin the precedence — progression
// beats the confirmed working weight, which beats the routine's own number — because getting
// it backwards is how a coach ends up telling someone to squat a weight the app never shows.
describe('preview_session', () => {
const WD = new Date(FAKE_TODAY_ISO + 'T12:00:00Z').getDay()
// One routine, one exercise, scheduled for the pinned "today". Nothing from the demo seed,
// so the arithmetic below is checkable by hand.
// Linear by default: with progression off the app opens the routine's own numbers (see the
// two tests at the end), so history-vs-plan precedence is only observable under a policy.
function only(cfg, { prog = 'linear', workouts = [], exWeights = {}, routine = {} } = {}) {
S.routines = [{ id: 'r-preview', name: 'Preview', emoji: 'barbell', prog, ex: [cfg], ...routine }]
S.week = { [WD]: 'r-preview' }
S.dayPlan = {}
S.workouts = workouts
S.exWeights = exWeights
_seedStateForTests(S)
}
test('defaults to the routine scheduled for today', () => {
only({ id: '0025', sets: 3, reps: 8, weight: 50 })
const r = call('preview_session')
expect(r.date).toBe(FAKE_TODAY_ISO)
expect(r.routine_name).toBe('Preview')
expect(r.exercises).toHaveLength(1)
expect(r.exercises[0].name).toBe('barbell bench press')
})
test('with no history and no confirmed weight, the routine\'s own number is what opens', () => {
only({ id: '0025', sets: 3, reps: 8, weight: 50 })
const e = call('preview_session').exercises[0]
expect(e.weight_source).toBe('routine_plan')
expect(e.opening_sets.map(s => s.w)).toEqual([50, 50, 50])
expect(e.opening_sets.map(s => s.r)).toEqual([8, 8, 8])
expect(e.differs_from_plan).toBe(false)
expect(call('preview_session').overridden_count).toBe(0)
})
test('a confirmed working weight beats the routine\'s number', () => {
only({ id: '0025', sets: 2, reps: 8, weight: 50 }, { exWeights: { '0025': { w: 72.5, d: '2026-07-20' } } })
const e = call('preview_session').exercises[0]
expect(e.weight_source).toBe('confirmed_weight')
expect(e.opening_sets.every(s => s.w === 72.5)).toBe(true)
expect(e.changed).toEqual(['weight'])
})
test('the progression policy beats both, and its reason is reported', () => {
// Every rep hit at 60 last time under linear progression → +2.5, regardless of the 100
// the routine stores.
only({ id: '0025', sets: 3, reps: 5, weight: 100 }, {
prog: 'linear',
exWeights: { '0025': { w: 100, d: '2026-07-20' } },
workouts: [{
id: 'w1', d: '2026-07-20', routineId: 'r-preview', name: 'Preview',
entries: [{
id: '0025',
target: { id: '0025', sets: 3, reps: 5, weight: 60 },
sets: [{ w: 60, r: 5, done: true }, { w: 60, r: 5, done: true }, { w: 60, r: 5, done: true }]
}]
}]
})
const out = call('preview_session')
const e = out.exercises[0]
expect(e.prescription.kind).toBe('up')
expect(e.weight_source).toBe('progression')
expect(e.opening_sets.every(s => s.w === 62.5)).toBe(true)
expect(e.prescription.why).toMatch(/Every rep last time/)
expect(e.changed).toEqual(['weight'])
expect(out.overridden_count).toBe(1)
expect(out.overridden[0]).toMatchObject({
name: 'barbell bench press', planned_weight: 100, opening_weight: 62.5
})
expect(out.overridden[0].reason).toMatch(/Every rep last time/)
})
test('reps carry from the last session even when the routine asks for something else', () => {
only({ id: '0025', sets: 2, reps: 12, weight: 60 }, {
workouts: [{
id: 'w1', d: '2026-07-20', routineId: 'r-preview', name: 'Preview',
entries: [{
id: '0025',
target: { id: '0025', sets: 2, reps: 5, weight: 60 },
sets: [{ w: 60, r: 5, done: true }, { w: 60, r: 5, done: true }]
}]
}]
})
const e = call('preview_session').exercises[0]
expect(e.opening_sets.map(s => s.r)).toEqual([5, 5]) // not the 12 the routine stores
expect(e.reps_source).toBe('last_session')
expect(e.changed).toContain('reps')
})
test('planned drop sets show up on the opening rows', () => {
only({ id: '0025', sets: 2, reps: 10, weight: 50, intensifier: { type: 'dropset', count: 1, pct: 20 } })
const e = call('preview_session').exercises[0]
expect(e.opening_sets.every(s => s.type === 'dropset')).toBe(true)
})
test('an explicit routine_id overrides the schedule', () => {
only({ id: '0025', sets: 3, reps: 8, weight: 50 })
const other = { id: 'r-other', name: 'Other', prog: 'off', ex: [{ id: '0043', sets: 5, reps: 5, weight: 80 }] }
S.routines.push(other)
_seedStateForTests(S)
expect(call('preview_session', { routine_id: 'r-other' }).routine_name).toBe('Other')
})
test('a rest day returns no exercises rather than an error', () => {
only({ id: '0025', sets: 3, reps: 8, weight: 50 })
S.week = {}
_seedStateForTests(S)
const r = call('preview_session')
expect(r.rest_day).toBe(true)
expect(r.exercises).toEqual([])
})
test('with progression off the routine\'s own numbers open, whatever history says (matches session-start.js)', () => {
only({ id: '0025', sets: 3, reps: 8, weight: 50 }, {
prog: 'off',
exWeights: { '0025': { w: 72.5, d: '2026-07-20' } },
workouts: [{
id: 'w1', d: '2026-07-20', routineId: 'r-preview', name: 'Preview',
entries: [{ id: '0025', target: { id: '0025', sets: 3, reps: 5, weight: 60 }, sets: [{ w: 60, r: 5, done: true }] }]
}]
})
const out = call('preview_session')
const e = out.exercises[0]
expect(e.prescription.kind).toBe('off')
expect(e.opening_sets.map(s => [s.w, s.r])).toEqual([[50, 8], [50, 8], [50, 8]])
expect(e.weight_source).toBe('routine_plan')
expect(e.reps_source).toBe('routine_plan')
expect(e.differs_from_plan).toBe(false)
expect(out.overridden_count).toBe(0)
})
test('a deload routine (excludeFromProgression) opens its own numbers even under a policy', () => {
only({ id: '0025', sets: 3, reps: 5, weight: 50 }, {
prog: 'linear', routine: { excludeFromProgression: true },
workouts: [{
id: 'w1', d: '2026-07-20', routineId: 'r-preview', name: 'Preview',
entries: [{ id: '0025', target: { id: '0025', sets: 3, reps: 5, weight: 60 }, sets: [{ w: 60, r: 5, done: true }, { w: 60, r: 5, done: true }, { w: 60, r: 5, done: true }] }]
}]
})
const e = call('preview_session').exercises[0]
expect(e.prescription.kind).toBe('off')
expect(e.opening_sets.every(s => s.w === 50 && s.r === 5)).toBe(true)
expect(e.weight_source).toBe('routine_plan')
})
test('a timed exercise that progressed is listed as overridden too', () => {
only({ id: '0025', mode: 'time', sets: 3, sec: 30, inc: 10 }, {
prog: 'time',
workouts: [{
id: 'w1', d: '2026-07-20', routineId: 'r-preview', name: 'Preview',
entries: [{ id: '0025', target: { id: '0025', mode: 'time', sets: 3, sec: 30 }, sets: [{ sec: 45, done: true }, { sec: 45, done: true }, { sec: 45, done: true }] }]
}]
})
const out = call('preview_session')
const e = out.exercises[0]
expect(e.prescription.kind).toBe('up')
expect(e.changed).toEqual(['sec'])
expect(e.differs_from_plan).toBe(true)
expect(out.overridden[0].opening_sec).toBeGreaterThan(30)
})
test('an unknown routine_id is an error, not an empty session', () => {
only({ id: '0025', sets: 3, reps: 8, weight: 50 })
expect(() => call('preview_session', { routine_id: 'nope' })).toThrow(/no routine with id/)
})
})
+85 -38
View File
@@ -1,90 +1,137 @@
{
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
"extends": ["config:recommended", ":semanticCommitsDisabled"],
"_comment": [
"description": [
"Dependency updates, deliberately quiet — the GitLab counterpart of .github/dependabot.yml,",
"with the same policy behind it. openGym is dependency-light on purpose: the frontend is",
"React + Router + Zustand, api/ has two runtime dependencies. A default setup would still",
"open an MR per package per week, which on a solo project means the MRs stop being read —",
"the opposite of what this is for. So: monthly, everything in an ecosystem grouped into one",
"MR, and a low cap on open MRs.",
"Run by the `renovate` job in .gitlab-ci.yml, which fires only on *scheduled* pipelines."
],
"timezone": "Europe/Zurich",
"schedule": ["* 0-6 1 * *"],
"prConcurrentLimit": 5,
"prHourlyLimit": 0,
"labels": ["dependencies"],
"rangeStrategy": "bump",
"dependencyDashboard": true,
"_managers": [
"Run by the `renovate` job in .gitlab-ci.yml, which fires only on *scheduled* pipelines.",
"gradle (frontend/android) and cocoapods (frontend/ios) are deliberately NOT managed:",
"Capacitor generates those shells and pins the native versions to the @capacitor/* npm",
"packages. Bumping them independently desyncs the two and breaks the mobile build; they",
"follow the npm update instead."
],
"enabledManagers": ["npm", "dockerfile", "gitlabci"],
"extends": [
"config:recommended",
":semanticCommitsDisabled"
],
"timezone": "Europe/Zurich",
"schedule": [
"* 0-6 1 * *"
],
"prConcurrentLimit": 5,
"prHourlyLimit": 0,
"labels": [
"dependencies"
],
"rangeStrategy": "bump",
"dependencyDashboard": true,
"enabledManagers": [
"npm",
"dockerfile",
"gitlabci"
],
"packageRules": [
{
"description": "Frontend routine bumps arrive as one MR. Runtime and build tooling move together anyway (a Vite bump usually wants its plugin bumped), and splitting them doubles the review without splitting the risk.",
"matchManagers": ["npm"],
"matchFileNames": ["frontend/package.json"],
"matchUpdateTypes": ["minor", "patch"],
"matchManagers": [
"npm"
],
"matchFileNames": [
"frontend/package.json"
],
"matchUpdateTypes": [
"minor",
"patch"
],
"groupName": "frontend"
},
{
"description": "Frontend majors get their own MR. The first grouped run on GitHub bundled a Capacitor 7 → 8 migration in with six siblings, where it read as housekeeping — and CI would have gone green on it, because the test job builds the web app and never touches the mobile flavour. A major that lands alone is at least obviously a decision.",
"matchManagers": ["npm"],
"matchFileNames": ["frontend/package.json"],
"matchUpdateTypes": ["major"],
"matchManagers": [
"npm"
],
"matchFileNames": [
"frontend/package.json"
],
"matchUpdateTypes": [
"major"
],
"groupName": "frontend-major"
},
{
"description": "Capacitor 8 needs Node >= 22 and frontend/android + frontend/ios are committed, so a major also means migrating the native projects — Gradle/AGP, the Podfile. That is a deliberate piece of work, not a dependency bump. Drop this rule when you want to do it.",
"matchPackageNames": ["@capacitor/**"],
"matchUpdateTypes": ["major"],
"matchPackageNames": [
"@capacitor/**"
],
"matchUpdateTypes": [
"major"
],
"enabled": false
},
{
"description": "Backend, api/package.json (@simplewebauthn/server, web-push).",
"matchManagers": ["npm"],
"matchFileNames": ["api/package.json"],
"matchUpdateTypes": ["minor", "patch"],
"matchManagers": [
"npm"
],
"matchFileNames": [
"api/package.json"
],
"matchUpdateTypes": [
"minor",
"patch"
],
"groupName": "api"
},
{
"description": "Two dependencies, but one of them verifies passkeys — a major there is worth reading on its own rather than alongside anything else.",
"matchManagers": ["npm"],
"matchFileNames": ["api/package.json"],
"matchUpdateTypes": ["major"],
"matchManagers": [
"npm"
],
"matchFileNames": [
"api/package.json"
],
"matchUpdateTypes": [
"major"
],
"groupName": "api-major"
},
{
"description": "Base images in api/Dockerfile and web/Dockerfile.",
"matchManagers": ["dockerfile"],
"matchManagers": [
"dockerfile"
],
"groupName": "base images"
},
{
"description": "Odd-numbered Node majors are 'Current', never LTS — they stop getting fixes in about six months. Dependabot's first run offered 22 → 25, which for something other people self-host is a stability downgrade for nothing. Even majors (22 → 24 → 26) are still proposed, which is the move actually worth reviewing.",
"matchDatasources": ["docker"],
"matchPackageNames": ["node"],
"matchDatasources": [
"docker"
],
"matchPackageNames": [
"node"
],
"allowedVersions": "/^(\\d*[02468])\\./"
},
{
"description": "The images the pipeline itself runs on. Same reasoning as the GitHub-Actions rule this replaces: these jobs publish the container images and build the signed APK, so the blast radius is real — but they move in lockstep and none is worth an MR of its own.",
"matchManagers": ["gitlabci"],
"matchManagers": [
"gitlabci"
],
"groupName": "ci images"
}
],
"vulnerabilityAlerts": {
"description": "Security fixes ignore the monthly schedule and the group — they land immediately, on their own.",
"schedule": ["at any time"],
"labels": ["dependencies", "security"],
"schedule": [
"at any time"
],
"labels": [
"dependencies",
"security"
],
"prPriority": 10
}
}
+124
View File
@@ -0,0 +1,124 @@
#!/usr/bin/env python3
"""Start merge-request pipelines for contributor MRs that would otherwise never get one.
On gitlab.com a merge request from a fork runs its pipeline in the *fork*, on the fork
owner's runner minutes — and most contributors have never enabled shared runners there
(it needs identity verification), so their MR sits at "no pipeline" forever. A maintainer
can press "Run pipeline" on the MR page to run it in this project instead; this script
presses that button for them, with the same care a maintainer would take:
* only for authors who are already trusted — project members, or people with at
least one merged MR here (the GitHub "first-time contributor" rule). Everyone else
gets the `ci-approval-needed` label so a maintainer can find and start them by hand.
* never when the MR touches `.gitlab-ci.yml`: the pipeline runs with this project's
job token, and a changed pipeline definition is exactly where that token could be
misused. Same label, a maintainer reads the diff first.
* never twice for the same commit, never for drafts, and at most MAX_TRIGGERS per run.
Runs from the `mr:fork-pipelines` job (scheduled, and after every push to main). Needs
PIPELINE_API_TOKEN — a token with `api` scope and at least Developer on the project.
"""
import json
import os
import sys
import urllib.parse
import urllib.request
API = os.environ["CI_API_V4_URL"]
PROJECT = os.environ["CI_PROJECT_ID"]
TOKEN = os.environ["PIPELINE_API_TOKEN"]
MAX_TRIGGERS = int(os.environ.get("FORK_MR_MAX_TRIGGERS", "8"))
LABEL = "ci-approval-needed"
DRY_RUN = "--dry-run" in sys.argv
def call(method, path, body=None, params=None):
url = f"{API}/projects/{PROJECT}/{path}"
if params:
url += "?" + urllib.parse.urlencode(params)
data = json.dumps(body).encode() if body is not None else None
req = urllib.request.Request(url, data=data, method=method)
req.add_header("PRIVATE-TOKEN", TOKEN)
req.add_header("Content-Type", "application/json")
with urllib.request.urlopen(req, timeout=60) as r:
return json.load(r)
def paged(path, **params):
page = 1
while True:
batch = call("GET", path, params={**params, "per_page": 100, "page": page})
if not batch:
return
yield from batch
if len(batch) < 100:
return
page += 1
def trusted_authors():
members = {m["username"] for m in paged("members/all") if m["access_level"] >= 30}
merged = {m["author"]["username"] for m in paged("merge_requests", state="merged")}
return members | merged
def ensure_label():
if any(l["name"] == LABEL for l in paged("labels")):
return
if not DRY_RUN:
call("POST", "labels", {"name": LABEL, "color": "#ed9121",
"description": "Fork MR whose pipeline a maintainer has to start by hand"})
def set_label(mr, present):
has = LABEL in mr["labels"]
if has == present or DRY_RUN:
return
key = "add_labels" if present else "remove_labels"
call("PUT", f"merge_requests/{mr['iid']}", {key: LABEL})
def main():
trusted = trusted_authors()
ensure_label()
triggered = 0
for mr in paged("merge_requests", state="opened", order_by="updated_at"):
iid, author, sha = mr["iid"], mr["author"]["username"], mr["sha"]
tag = f"!{iid} ({author}, {mr['source_branch']})"
if mr["source_project_id"] == mr["target_project_id"]:
continue # same-project branch: gets its pipeline on push like any other
if mr.get("draft"):
print(f"skip {tag}: draft")
continue
if author not in trusted:
print(f"hold {tag}: first-time contributor — a maintainer starts this one")
set_label(mr, True)
continue
touched = {c["new_path"] for c in call("GET", f"merge_requests/{iid}/changes")["changes"]}
if ".gitlab-ci.yml" in touched or any(p.startswith("scripts/ci/") for p in touched):
print(f"hold {tag}: changes the pipeline itself — a maintainer reads it first")
set_label(mr, True)
continue
set_label(mr, False)
# A pipeline that exists but never got a runner (created/pending in a fork with none)
# is the very thing this script is for, so only a pipeline that actually ran counts.
STUCK = {"created", "pending", "waiting_for_resource", "preparing"}
ran = [p for p in call("GET", f"merge_requests/{iid}/pipelines") if p["sha"] == sha and p["status"] not in STUCK]
if ran:
where = "here" if ran[0]["project_id"] == int(PROJECT) else "in the fork"
print(f"ok {tag}: {sha[:8]} already has a pipeline {where} ({ran[0]['status']})")
continue
if triggered >= MAX_TRIGGERS:
print(f"defer {tag}: per-run cap of {MAX_TRIGGERS} reached, next run picks it up")
continue
if DRY_RUN:
print(f"would {tag}: start pipeline for {sha[:8]}")
else:
p = call("POST", f"merge_requests/{iid}/pipelines")
print(f"start {tag}: pipeline {p['id']} for {sha[:8]} — {p['web_url']}")
triggered += 1
print(f"done: {triggered} pipeline(s) started")
if __name__ == "__main__":
main()
+6 -1
View File
@@ -14,12 +14,17 @@ FROM --platform=$BUILDPLATFORM node:22-alpine AS build
# is exactly what made the v1.2.15 web image fail to build.
WORKDIR /app/frontend
COPY frontend/package.json frontend/package-lock.json* ./
RUN npm ci 2>/dev/null || npm install
# --ignore-scripts: the web image only needs `vite build`; the one heavy postinstall in this tree
# (@capacitor/assets -> sharp, a libvips download from GitHub) is for drawing app icons and has
# timed out on the shared runners — a lockfile-ignoring `npm install` fallback is no answer to that.
RUN npm ci --ignore-scripts
COPY api/coach/core/ /app/api/coach/core/
COPY frontend/ ./
RUN npm run build
FROM nginx:alpine
# Same reason as in api/Dockerfile: alpine fixes land faster than the nginx image is rebuilt.
RUN apk upgrade --no-cache
ARG VERSION=dev
ARG VCS_REF=dev
ARG BUILD_DATE=unknown
+7 -1
View File
@@ -20,7 +20,13 @@ server {
# 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};
# Resolved per request through Docker's DNS, not once at start-up: nginx otherwise pins
# the api container's IP when it boots, and a recreated api (new IP) means 502 on every
# /api call until web is restarted too (issue #16). The variable is what makes nginx
# re-resolve; lowercase so the entrypoint's envsubst leaves it alone.
resolver 127.0.0.11 valid=10s ipv6=off;
set $api_upstream http://${BACKEND}:${PORT};
proxy_pass $api_upstream;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
+2 -2
View File
@@ -1,6 +1,6 @@
<!DOCTYPE html>
<!-- GENERATED FILE - do not edit by hand.
Built by scripts/build-api-docs.mjs from api/openapi.yaml (openGym API v1.3.1).
Built by scripts/build-api-docs.mjs from api/openapi.yaml (openGym API v1.3.2).
Regenerate with: node scripts/build-api-docs.mjs -->
<html lang="en">
<head>
@@ -232,7 +232,7 @@ main.api-main .lead { color: var(--fg-2); max-width: 58ch; margin: 14px 0 0; fon
</div>
<p class="api-facts">
<span>OpenAPI 3.1.0</span>
<span>openGym v1.3.1</span>
<span>openGym v1.3.2</span>
<span>28 endpoints</span>
<span>AGPL-3.0-or-later</span>
</p>