Compare commits

...
102 Commits
Author SHA1 Message Date
Duarte Santos 9c7c351345 v1.3.4: effort picker restyled as a menu list, media falls back to the still or a tile instead of a broken image 2026-09-05 15:03:52 +02:00
Duarte Santos 4e015ec74d roadmap: v1.3.3 went to the workout redesign, so the planned milestones move up one patch 2026-09-05 14:38:14 +02:00
Duarte Santos 4e3377f4c3 website: download button says v1.3.3 2026-09-05 14:36:16 +02:00
Duarte Santos 80a8026a79 website: docs for the v1.3.3 workout screen, RIR picker, history, favourites, unit conversion and in-app update 2026-09-05 14:35:15 +02:00
Duarte Santos 3707a215f0 ROADMAP.md: v1.3.2 und v1.3.3 als veroeffentlicht markiert 2026-09-05 14:31:30 +02:00
Duarte Santos 078f091cfb Merge workout-clean: schlanker Workout-Screen, Farb-RIR (!91), Historie im Workout, Favoriten, In-App-Update (!40), Bugfix-Runde — v1.3.3 2026-09-05 14:28:12 +02:00
Duarte Santos 2c7009a9d7 v1.3.3 2026-09-05 14:28:12 +02:00
Duarte Santos 067302fd16 In-App-Update (!40) nachgeschaerft: Zeile nur mit APK-Asset, keine Installation ohne Pruefsumme, ein Release-Check pro App-Sitzung 2026-09-05 14:27:28 +02:00
Duarte Santos f7b664bcda Merge main (CI-Digest-Fix) into workout-clean 2026-09-05 14:26:47 +02:00
Duarte Santos 6422332b4d CI: Digest-Auslese ohne head -1 — pipefail + SIGPIPE (141) liess beide Image-Jobs des v1.3.2-Tags nach dem Push scheitern 2026-09-05 14:26:42 +02:00
Duarte Santos 370b651373 pt-BR-Guard nach den Feature-Merges (626/612) 2026-09-05 14:25:05 +02:00
Duarte Santos d021d9b5f3 Merge feat/favourites: Favoriten-Uebungen (#6)
# Conflicts:
#	frontend/src/lib/pt-br-locale.test.js
2026-09-05 14:24:24 +02:00
Duarte Santos 0797fda152 Merge feat/update-check: !40 In-App-Update auf dem Android-Build (#38, #9)
# Conflicts:
#	frontend/src/lib/pt-br-locale.test.js
2026-09-05 14:24:11 +02:00
Duarte Santos f162505549 Favoriten-Uebungen (#6): Stern im Detail-Sheet, Favoriten zuoberst im Picker, in der Bibliothek und im Muskel-Explorer
Wer eine Routine plant, scrollt sonst jedes Mal durch 1300 Uebungen zu denselben zehn.
Ein Stern im Kopf des Uebungs-Detail-Sheets (aria-label + Toast) merkt sich eine Uebung in
S.favEx — Katalog- oder eigene Ids. Das Feld reist mit dem Profil (Sync/Export), bleibt aber
bewusst aus dem geteilten Plan-Bundle draussen (lib/plan-share.js baut das Bundle nur aus
Routinen/Woche/customEx, dort war nichts zu aendern).

- lib/favourites.js: favIds/isFav/toggleFav/sortFavouritesFirst; alte Profile ohne Feld lesen
  als leer. Die Sortierung ist in beiden Haelften stabil, damit eine nach Name oder Nutzung
  sortierte Liste ihre Ordnung behaelt.
- Picker, Library, MuscleExplorer sortieren erst NACH Suche/Koerperteil/Equipment, also innerhalb
  der aktuellen Trefferliste; Favoriten tragen einen kleinen gelben Stern vor dem Namen. Der
  Akzent-Tag am Zeilenende ("Gewaehlt" = schon in Routine/Log) bleibt unveraendert und ist
  durch Position und Farbe davon unterscheidbar.
- Picker: zusaetzlicher Chip "Favoriten (n)" vor "Gewaehlt", nur sichtbar wenn es welche gibt,
  mit eigenem Leer-Hinweis; die Scope-Abfrage ist jetzt eine kleine inScope-Funktion.
- Eine geloeschte eigene Uebung faellt auch aus favEx.
- ko/ru nannten den alten "Chosen"-Filter bereits "Favoriten" — umbenannt (선택됨 / Выбранные),
  damit die zwei Chips nicht gleich heissen.
- 6 neue Strings in 14 Packs, pt-BR nur der Leer-Hinweis (toque/adicioná-lo); Fingerprint
  in pt-br-locale.test.js nachgezogen.
- Tests: lib/favourites.test.js, sheets.favourites.test.jsx (Stern + Picker-Reihenfolge +
  Chip mit echtem Store), views/Library.test.jsx (Reihenfolge + Koerperteil-Filter).
2026-09-05 14:23:30 +02:00
Duarte Santos 1f47d5015c Merge feat/history: Uebungsverlauf aus dem ⋯-Menue (#43)
# Conflicts:
#	frontend/src/sheets.jsx
2026-09-05 14:23:10 +02:00
Duarte Santos e2a34a2fee Merge !40: feat: add update check in settings
In-app update check for the Android build (closes #38, #9): Settings shows
"openGym vX available" when gitlab.com has a newer release, tapping it
downloads the APK, checks its SHA-256 and hands it to the package installer
through a small local Capacitor plugin.

Brought onto workout-clean by hand:
- Settings.jsx: the branch's switchUnit sheet and Workout-controls sheet stay,
  the MR's update state, DownloadProgress sheet and Data row come on top; the
  row keeps the branch's "Load starter plan" neighbour (starterPlanSheet).
- The row is additionally gated on MOBILE so the web bundle never asks
  gitlab.com; isAndroid() still decides between Android and iOS.
- build.gradle: the MR's `.debug` applicationIdSuffix is dropped — the branch
  already gives the debug build its own id (`.test`, with the label overlay in
  src/debug/res); git had auto-merged both blocks and Gradle silently took
  the last one.
- Locale packs: both sides kept; the progress sheet's '{0} %' / '{0} MB'
  templates now exist in every pack (fr: Mo, ru: МБ, tr: %{0}). pt-BR only
  carries the four strings whose Brazilian wording differs (baixar vs
  transferir); the identical ones inherit from pt.
- pt-br-locale.test.js: branch version, values recomputed (624/603).
- Settings.workoutview.test.jsx mocks isAndroid like the other Settings tests.
- New: update.test.js fixture with the real v1.3.1 release JSON (the checksum
  link is listed before the APK), Settings.update.test.jsx for the gating.
2026-09-05 14:22:48 +02:00
Duarte Santos 9d3178bac9 README: Funktionsliste fuer v1.3.2/v1.3.3 (Workout-Menues, Listenansicht, Farb-RIR, Historie im Workout, Favoriten, Starterplaene, Muskel-Explorer, Einheiten-Umrechnung, In-App-Update), Roadmap zeigt auf ROADMAP.md 2026-09-05 14:21:56 +02:00
Duarte Santos b0735f6cde Merge docs/roadmap into workout-clean 2026-09-05 14:21:55 +02:00
Duarte Santos fbe33600ff Workout: Uebungsverlauf mit Kurve und letzten Einheiten aus dem ⋯-Menue (#43)
Mitten im Training fehlte die Antwort auf "was habe ich hier letztes Mal und
davor gemacht" — die stand nur in Stats, drei Screens weiter weg. Das ⋯-Menue
jeder Uebung hat jetzt "Verlauf": ein Sheet mit der Kurve (bester Satz pro
Einheit, umschaltbar auf gesch. 1RM; Halten in Sekunden, Cardio in Minuten,
nie beladene Uebungen ihre Wdh.) und den letzten zehn Einheiten, neueste
zuerst, mit Saetzen, Volumen, 1RM und einem PR-Marker auf der Einheit, in
der die Bestleistung zuerst fiel. Aus dem Detail-Sheet (Bibliothek) ist es
ueber einen Button erreichbar, sobald es Verlauf gibt.

Die Ableitung liegt als reiner Helfer in lib/exercise-history.js (ein Lauf
ueber das Log, Aufwaermsaetze wie ueberall ausgeschlossen, Backfill nach
Datum sortiert) und wird im Sheet memoisiert, damit der Workout-Screen beim
Tick nicht das ganze Log neu liest und LineChart seinen Hover behaelt.
2026-09-05 14:21:21 +02:00
Duarte Santos 228f758e5e Merge main (v1.3.2) into workout-clean 2026-09-05 14:19:26 +02:00
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 039a280777 Warm-up-Ramp und Prescription snappen auf das Inkrement der Uebung (weightIncrement), nicht auf den Einheiten-Default — in session-start, Add-Exercise, Progression-Sheet und Swap 2026-09-05 14:16:36 +02:00
Duarte Santos 9cd4979219 ROADMAP.md: Versionsnummern nach der Release-Regel (1.3.2 … 1.3.5), Regel erklaert 2026-09-05 14:01:13 +02:00
Duarte Santos b5769b9c38 Bugfix-Runde vom Board: Coach-Speichern auf Android (#42), Baender wie Koerpergewicht (#39), Einheitenwechsel rechnet um (#22), Mitte-Tab im Workout (#29/#21), Kopie-Namen, Geister-Wochentag, Swap-Picker
- #42: "Save and use the Coach" blieb auf Android 16 grau. Der sichere Speicher wird jetzt mit
  4 s Timeout angesprochen (coach-secrets.js withTimeout), die Geraete-Einstellung wird VOR dem
  Schluessel geschrieben, und jeder Fehler landet als Toast statt in einem stummen Promise.
- #39: isBodyweightEq zaehlt 'band'/'resistance band' mit (54 Katalog-Uebungen) — ein Reps-Stepper,
  Progression in Wdh./Saetzen; der Bodyweight-Schalter je Uebung ueberstimmt weiterhin.
- #22: Settings → Gewichtseinheit fragt: Zahlen umrechnen (lib/units.js convertStateUnit ueber
  Saetze, Drops, topW, Ziele, inc, Warm-up-Configs, exWeights, barWeights, Koerpergewicht, Zielgewicht;
  lb auf 0.5, kg auf 0.25 gerundet, Hin- und Rueckweg stabil) oder nur die Beschriftung aendern.
  Fussnote entsprechend, alter Hinweis-String raus. 5 neue Strings in 14 Packs.
- #29/#21: der Mitte-Tab heisst auf dem Workout-Screen "Workout" und leuchtet; sonst "Resume",
  das zum gemerkten Eintrag (S.active.cur) fuehrt, der sich seit !92 nie von selbst bewegt.
- !85: Kopie einer Kopie wird "Name (Copy 2)", nicht "(Copy) (Copy)".
- !94: ein Wochentag, dessen Routine nicht mehr existiert, loest keine Bestaetigung aus.
- !72: das "+" im Swap-Picker uebernimmt sofort mit Standard-Config wie ueberall sonst.
2026-09-05 13:58:07 +02:00
Duarte Santos 3773f65355 Merge !91: feat(workout): colour-coded RIR/RPE quick picker
# Conflicts:
#	frontend/src/lib/pt-br-locale.test.js
#	frontend/src/locales/pt-BR.js
#	frontend/src/sheets.jsx
#	frontend/src/views/Workout.jsx
#	frontend/src/views/Workout.test.jsx
2026-09-05 13:44:02 +02:00
Duarte Santos 0f75e50d3d ROADMAP.md: Versionen ausfuehrlicher, mehr Punkte je Version, Ideen-Sektion erweitert 2026-09-05 13:43:40 +02:00
Duarte Santos 5dcaeed73c ROADMAP.md: v1.4 bis v1.7 als Zusammenfassung der GitLab-Meilensteine, Ideen-Sektion, Ablauf ueber das Board 2026-09-05 13:34:13 +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 edb870a71e Merge mrbatch-0904 (!99) into workout-clean 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
Duarte Santos 00adae77e8 Workout: im Listenmodus bleibt der Kopf (Name, Uhr, Saetze, Abbrechen/Fertig, Fortschritt) oben stehen 2026-09-05 13:28:31 +02:00
Duarte Santos 86d3723b88 Workout: ein Mehr-Menue pro Uebung und ein Menue pro Satz statt Tastenreihen, dazu "Bedienelemente im Training" in den Einstellungen
Vorher standen pro Uebung Notiz/Details, zwei Superset-Tasten, ein Stangen-Chip, unter den
Saetzen drei Tasten und unter der Karte Prev/Next, Hinzufuegen, Hoch/Runter, Tauschen, Entfernen;
pro Satz dazu +Drop/+Burst und bei Warm-ups ein X. Jetzt:

- Uebungskopf: nur noch "⋯" (Notiz, Details, Progression, Stangengewicht, Aufwaermsatz,
  Superset mit vorheriger/naechster, Tauschen, Hoch, Runter, Entfernen). Der Notiz-Stift bleibt
  sichtbar, sobald eine Notiz existiert. Die Aktionen zielen auf GENAU diese Uebung, auch als
  Superset-Mitglied (blockProps traegt idx, moveUnitAt(at, dir) statt moveCurrentUnit).
- Satznummer ist ein Button: Drop-Satz, Rest-Pause-Burst, diesen Satz entfernen (ersetzt die Chips
  und das Warm-up-X). Unter der Karte nur noch "Satz hinzufuegen".
- Stangen-Chip wird eine Textzeile (Bearbeiten ueber das Menue).
- Settings → Waehrend eines Trainings → "Bedienelemente im Training": Plus/Minus-Tasten (aus =
  Zahl antippen und eintippen, .stp.plain), Drop/Burst-Kuerzel an jedem Satz, Superset-Tasten im
  Kopf, Verschieben/Tauschen/Entfernen unter der Uebung. S.wc ueberlagert WC_DEFAULT
  (lib/workout-controls.js), alte Profile lesen als schlankes Layout.
- menuSheet() in sheets.jsx als generisches Aktionsmenue, Icon "more".
- 14 neue Strings in allen 14 Packs (pt-BR mit voce-Formen), pt-BR-Guard 617/592/088bb72a.
- Tests: Menue-Pfade + Schalter neu; Move/Swap/Remove-Tests laufen mit exerciseButtons an.
2026-09-05 13:17:56 +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 2c5678e877 feat(update): gate in-app updater to Android only
The updater downloads an .apk and hands it to the system package
installer, which only exists on Android. Add an isAndroid() flag in
mobile.js and run the update check behind it, so the update row never
appears on iOS or the web build.
2026-09-04 13:01:42 +02:00
Sebastian G 15b95eb434 test: derive update-check versions from __APP_VERSION__ instead of hardcoding
The semver comparison tests hardcoded v1.2.11-relative versions, so they
broke when package.json bumped to 1.2.14. Derive test versions from the
running __APP_VERSION__ so the suite stays correct across version bumps.
2026-09-04 13:01:42 +02:00
Sebastian G 7958d0fcd4 feat: SHA-256 verification, download progress, native installer, i18n
- SHA-256 hash check on downloaded APK (Web Crypto API, no new deps)
- Download progress bar in a locked sheet (stream-based tracking)
- Native Android InstallPlugin (FileProvider + ACTION_VIEW intent)
- REQUEST_INSTALL_PACKAGES permission in AndroidManifest
- applicationIdSuffix .debug for debug builds
- Update row only shown when an update is available
- Label changed to 'openGym v{0} available', icon to 'info'
- All 7 new UI strings translated in 12 locales
- pt-BR snapshot count updated (291 → 298)
2026-09-04 13:01:42 +02:00
Sebastian G 106a3abee0 feat: add update check in settings
Check GitLab releases API on settings open to determine if a newer
version is available. Shows current version (up to date) or the new
version number with download/install action.

- New lib/update.js: checkForUpdate(), downloadAndInstall()
- Settings Data section: update row with auto-check on mount
- Dialog for re-check confirmation when already up to date
- APK download + installer trigger on Android via Capacitor
- Falls back to opening releases page on web
- 16 unit tests for version check logic
2026-09-04 13:00:25 +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
Duarte Santos d6f0db9b4b v1.3.1 2026-09-04 09:51:25 +02:00
Duarte Santos 565311accc Handy: 'Use my self-hosted openGym' erkennt den Coach des gepaarten Servers
Der Mobile-Boot und das Pairing haben /api/config nie geladen, nur die Web-Variante und der
Login-Screen. Auf dem gepaarten Handy stand deshalb im Coach-Setup immer 'Your server has no
Coach enabled' — waehrend der Admin auf einen gruenen Test schaute (Discord-Meldung, 2026-09-04).
Jetzt: refreshConfig() fragt immer, loadConfig() cached nur noch darueber; Boot (remote) und
connectToServer laden die Config, der Setup-Screen fragt beim Oeffnen neu und zeigt bis dahin
'Loading…'. Regressionstest fuer load/refresh.
2026-09-04 09:51:01 +02:00
Duarte Santos 8b7abe5c26 Website: der AI Coach steht auf der Startseite 2026-09-03 23:24:30 +02:00
Duarte Santos 6b3c7d0ed7 v1.3.0 2026-09-03 23:08:45 +02:00
Duarte Santos eead4afd88 assets: Brand-Dateien wieder raus, die 11d5632 versehentlich mitgenommen hat
BMC-Cover, Logo-Varianten und Merch-Vorlagen lagen unversioniert im Arbeitsverzeichnis und
sind mit einem git add -A in den Stats-Commit gerutscht. Sie gehoeren nicht ins oeffentliche
Repo; ab hier sind sie wieder unversioniert (in der Historie bleiben sie, main ist gegen
Force-Push geschuetzt).
2026-09-03 23:05:05 +02:00
Duarte Santos 11d5632156 Stats: die Strength-Liste sagt, wie lange ein Muskel nicht trainiert wurde
Die Zeilen unter der Strength-Karte zeigten die Saetze der letzten 90 Tage — fuer Muskeln,
die genau deshalb in der Liste stehen, weil sie lange nicht trainiert wurden, also fast immer
0, und sonst als ungerundeter Float (1.2000000000000002). Jetzt: Wochen seit dem letzten
Training bzw. 'not trained', gerundete 90-Tage-Saetze nur darueber, wenn es welche gibt.
Balance-Zeilen runden ueber fmtNum.
2026-09-03 23:01:34 +02:00
Duarte Santos 12309f394b Website: APK-Zeile v1.2.16 · 4.8 MB 2026-09-03 22:55:28 +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
Sebastian G ab95bacaa1 improved RIR edit handling 2026-09-03 10:00:53 +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 5e42bd29d6 feat(workout): colour-coded RIR/RPE quick picker 2026-09-02 17:22:02 +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
123 changed files with 8516 additions and 765 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
+397 -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,25 @@ 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.
# sed, not head: the runner's shell has pipefail on, and `head -1` closing the pipe early
# kills the producer with SIGPIPE (exit 141) as soon as the output is more than one write —
# which a multi-arch manifest list is. That failed both image jobs of the v1.3.2 tag.
DIGEST="$(docker buildx imagetools inspect "$REPO:$IMAGE_TAG" --format '{{.Manifest.Digest}}' | grep -oE 'sha256:[0-9a-f]{64}' | sed -n 1p)"
[ -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 +382,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 +398,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 +449,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 +466,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 +480,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 +509,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 +563,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 +586,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 +597,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 +721,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 +737,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 +752,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 +778,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 +813,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 +836,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 +850,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
+167
View File
@@ -1,5 +1,172 @@
# Changelog
## v1.3.4 — 2026-09-05
Two things noticed on the phone right after v1.3.3. Web bundle and APK; the API only carries the
version number.
- 🎨 **The effort picker looks like the rest of the app.** The v1.3.3 sheet was a grid of colour-edged
tiles that matched nothing else on screen. It is now the same list the ⋯ menus use: a tinted
square with the value where the icon sits, the sentence as the row, a tick on the current one, and
an "Exact RIR" row carrying the app's own stepper, tinted like the logged cell. Same six levels, same
colours, same free value.
- 🖼️ **Animations that fail to load fall back instead of breaking.** If the animation cannot be
fetched (dropped connection, CDN hiccup, an instance that gates media behind a session) the still
picture takes its place; if that fails too, a neutral tile does, and a tap tries again. No more
broken-image glyph on a white block.
## v1.3.3 — 2026-09-05
The workout screen gets out of the way, and the bug round from the board. Same day as v1.3.2 on
purpose: that one is the contributors' batch, this one is the redesign and the fixes on top of it.
Self-hosters need the new web bundle and images; the API is unchanged. This is the release to
install on Android — it is the first APK that can update itself.
### The workout screen
- ⋯ **One menu per exercise.** Note, details, progression settings, bar weight, add a warm-up set,
make a superset with the previous or next exercise, swap, move up, move down, remove — all behind
one button next to the exercise name, acting on exactly that exercise, also inside a superset. The
rows of buttons that used to sit in the header, under the sets and under the card are gone; a
pencil still appears once an exercise has a note. (issue #20)
- 🔢 **The set number is the set's menu**: drop set, rest-pause burst, remove this set. No more
"+ Drop / + Burst" chips on every row and no per-row X on warm-ups.
- 📌 **List view keeps the header pinned** — name, clock, set counter, discard and finish stay at the
top while the session scrolls.
- 🎛️ **Settings → During a workout → Workout controls.** Four switches bring any of the old groups
back: weight and reps +/− buttons (off: tap the number and type it), drop/burst shortcuts on every
set, superset buttons in the header, move/swap/remove buttons below the exercise. Existing profiles
read as the lean default.
- 🌈 **Colour-coded RIR / RPE.** An unrated set shows one "RIR" (or "RPE") button; tapping it opens
a picker with six levels, each with a sentence — "Nothing left, went to failure" through "Easy,
warm-up territory" — and a field for an exact value. A logged rating tints its cell by how close
to failure it was, the same colour whether you think in RIR or RPE; the +/− on it follow the
Workout-controls switch. (ErrorUsernameAlreadyTaken, !91 — issue #32)
- 📖 **History without leaving the workout.** ⋯ → History: a line of your best set (or estimated
1RM, longest hold, minutes) over time and the last ten sessions with every set, the volume and a
PR marker. Also reachable from an exercise's details in the library. (issue #43)
- ▶️ On the workout screen the centre tab button reads "Workout" and stays lit instead of an idle
"Resume"; Resume from anywhere else returns to the exercise you marked, which no longer moves on
its own. (issues #29, #21)
### Planning and library
- ⭐ **Favourite exercises.** Star an exercise in its details; favourites sort first in the picker,
the library and the muscle explorer, and the picker gets a Favourites chip. (issue #6)
- ⚖️ **Switching kg ↔ lb converts your numbers** — or keeps them and only changes the label, your
choice in a sheet: logged sets and drops, working weights, routine targets and increments, warm-up
configs, body weight, goal and bar weights; lb rounded to 0.5, kg to 0.25. (issue #22)
- 🪢 **Resistance bands count as bodyweight equipment**: one reps stepper and the reps-then-sets
progression, unless you switch Bodyweight off for that exercise. (issue #39)
- 🔥 Warm-up ramps snap to the exercise's own increment (1.25 kg plates) instead of the unit default.
- 📄 Copying a copy of a routine gives "Name (Copy 2)"; the swap picker's "+" quick-adds like every
other picker; a weekday whose routine no longer exists no longer triggers the starter-plan prompt.
### Android
- 🔄 **In-app update.** Settings → Data shows "openGym vX available" when a newer release exists; one
tap downloads the signed APK, verifies its SHA-256 against the published checksum and opens the
installer. No checksum, no install. Needs the "install unknown apps" permission the first time.
(ErrorUsernameAlreadyTaken, !40 — issues #38, #9)
- 🧠 **Saving the Coach with your own API key** no longer hangs on a greyed-out button: the mode is
written before the key, the secure store gets a timeout, and every failure says what went wrong
in a toast. (issue #42)
- 🔢 The APK carries version code 17 (v1.3.2: 16). Two releases had reused 15; the update check
compares the version name, so nothing changes for you, but Android's own "newer" check is honest again.
## 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
server's `/api/config` after boot or after pairing, so the Coach setup screen told everyone
"your server has no Coach enabled" — while the admin was looking at a passed test. The screen
now asks the server afresh every time it opens, and the boot and pairing paths load the config
like the web app always did. Reported on Discord.
## v1.3.0 — 2026-09-03
The AI Coach gets the version number it deserves. v1.2.16, earlier today, was the release that
got it out of the door; v1.3.0 is the same app with one more fix, and the number that says
"something new is in here" to everyone who reads a changelog. If you are on v1.2.16, this is
a small update. If you are on anything older, read the v1.2.15/v1.2.16 notes below — the Coach,
bar weights, the rest-day line and the rewritten admin dashboard are all new to you.
- 🗺️ **The Strength map's list makes sense again.** Below the map, every detrained muscle
showed its set count of the last 90 days — which, for a muscle that is on that list precisely
because it has not been trained lately, was a column of "0 sets", and where it was not zero it
printed as `1.2000000000000002`. Each row now says how many weeks ago the muscle was last
trained (or "not trained"), with the rounded 90-day sets on top only when there are any.
## v1.2.16 — 2026-09-03
- 🐳 **The web image builds again.** v1.2.15's tag pipeline published the API image and the APK
+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.
+17 -16
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)
@@ -60,9 +62,14 @@ as a home-screen app, passkey sign-in, offline support, sync across your phone a
## Features
- ⚖️ **Body-weight tracking** — interactive chart with a goal line you set, gains/losses colored by whether they move toward it
- 🏋️ **Weekly plan** — a routine per weekday, over a library of **1,324 exercises** (searchable, with animated demos)
- 🏋️ **Weekly plan** — a routine per weekday, over a library of **1,324 exercises** (searchable, with animated demos), browsable **by muscle** on a body map
- ✨ **Four starter plans** — Push/Pull/Legs, Upper/Lower, Full Body, 5×5; loaded as ordinary routines you can edit, and a routine can be copied in one tap
- 🗓️ **Reschedule any day** — sick, missed a session, or fewer gym days this week? Move a workout to another day without touching your weekly plan
- 📅 **Your week starts where you say** — Monday or Sunday, in Settings. The weekly plan, the day strip on Home, the calendar and every "this week" total follow it, so the app reads the way the calendar on your wall does
- 🧭 **A workout screen that gets out of the way** — one ⋯ menu per exercise (note, details, progression, bar weight, warm-up, superset, swap, move, remove), the set number as the set's own menu (drop set, rest-pause burst, remove), and a scrollable **list view** of the whole session with the header pinned. Four switches under Settings → Workout controls bring any of the old button rows back
- 🌈 **Colour-coded RIR / RPE** — one tap logs how hard a set was, with a sentence per level ("one more rep in the tank"); the same colour whether you think in RIR or RPE, a free field for in-between values
- 📖 **History without leaving the workout** — the exercise's last sessions and a progress line, from the ⋯ menu or the exercise details
- ⭐ **Favourite exercises** — star what you use, it sorts first in the picker and the library
- ▶️ **Guided workouts** — it knows what day it is and starts today's session; asks your body weight first, pre-fills your weights from last time, rest timer, PR detection, per-exercise weight tracking. On a rest day it doesn't just say "rest day" — it names when your next session is and what it is
- 🙈 **Animations are your call** — the exercise demos can be full size, small, or hidden entirely during a workout. Hidden collapses the media rather than leaving a gap, for anyone who finds a looping GIF between sets more distracting than useful
- ☀️ **The screen stays awake while you train** — no unlocking the phone and finding your place again between every set. On for as long as a workout is running, released the moment you finish it, and switchable off in Settings
@@ -93,10 +100,10 @@ as a home-screen app, passkey sign-in, offline support, sync across your phone a
- 🎨 **Designed, not assembled** — light/dark themes and 8 accent colors saved to your profile, over a hand-drawn icon set instead of emoji, so it looks the same on every phone
- 🌍 **14 languages** — full UI translation (EN, DE, ES, FR, IT, PT (Portugal), PT (Brazil), PL, TR, RU, ZH, KO, HI, TH, HU); exercise instructions localized in 12 of them and built-in exercise names shown bilingually in PT-BR and HU, all loaded on demand so the app stays fast
- 📥 **Bring your history with you** — import from **FitNotes** (Android and iOS), **Strong** and **Hevy** (CSV or directly with a [Hevy Pro API key](https://hevy.com/settings?developer)), or body weight straight out of an **Apple Health** export. Exercise names are matched against the library and anything unrecognised becomes one of your own exercises, so nothing in the file is dropped
- 📦 **Yours to keep** — one-tap JSON export/import, guest mode, **no telemetry**
- 📦 **Yours to keep** — one-tap JSON export/import, guest mode, **no telemetry**; switching kg ↔ lb offers to convert every stored number
- 🤖 **Ask an AI about your training** (optional) — an [MCP server](mcp/README.md) lets a client like Claude Desktop or Cursor read your history in your own words: *"what did I bench last week?"*. Read-only, spawned locally by the client, nothing leaves your box. Not in the Docker build — if you don't use an AI assistant, it isn't there
- 🧠 **An AI coach that writes your plan** (optional, off by default) — answer a handful of questions and it designs a week of routines; later it reads what you actually logged and proposes changes, each one with the evidence behind it. You approve every change and can undo it. It runs on **your** server under **your** provider account — Anthropic, OpenAI, Gemini or any OpenAI-compatible endpoint (Ollama on your LAN counts) with a pasted API key on the default image, or the Claude Agent SDK / Codex CLI on a separate build. The phone app can use your instance or its own key. See [docs/AI_COACH.md](docs/AI_COACH.md)
- 📱 **Standalone Android app** — the whole tracker as a sideloadable APK: no account, no server, data on the phone, native workout reminders ([download](https://opengym.duarte-santos.ch))
- 📱 **Standalone Android app** — the whole tracker as a sideloadable APK: no account, no server, data on the phone, native workout reminders, and an **in-app update check** that downloads the next signed APK and verifies its checksum ([download](https://opengym.duarte-santos.ch))
## Quick start (self-host)
@@ -202,19 +209,13 @@ host side of that volume, not the variable.
## Roadmap
Rough, community-driven — ideas and PRs welcome:
- [x] Standalone mobile app — Android APK to sideload ([download](https://opengym.duarte-santos.ch)); on iOS as a self-hosted PWA (no store listings planned)
- [x] Automatic progression programs (linear, Greyskull LP, double progression) with stalls and deloads
- [x] Estimated 1RM per exercise
- [x] Optional AI coach — designs a plan and reviews your training, on your own server and your own provider account ([docs](docs/AI_COACH.md))
- [ ] Percentage / training-max programming (5/3/1-style) on top of the progression engine
- [ ] More starter plans (upper/lower, full-body, 5×5)
- [x] Importers from FitNotes / Strong / Hevy (CSV, or Hevy Pro API key — workouts and/or weigh-ins), including the RPE they record, and body weight from Apple Health
- [x] Effort per set — RIR or RPE, whichever scale you think in
- [ ] Body measurements (waist, arms…) alongside weight
- [ ] Per-exercise notes & plate calculator
- [ ] Exercise instructions in German & Portuguese (Portugal); the separately curated Brazilian Portuguese pack is complete
The plan lives in [ROADMAP.md](ROADMAP.md) and on the
[GitLab milestones](https://gitlab.com/DuarteSantos8/opengym/-/milestones): v1.3.4 programmes and
progression (explicit warm-up/work phases, AMRAP driver selection, multi-week programmes, adaptive
1RM), v1.3.5 accounts and sync (password and OIDC login, personal-trainer role, remote MCP), v1.3.6
mobile (timer in the notification bar, widgets, Withings). Ideas and merge requests welcome — the
[board](https://gitlab.com/DuarteSantos8/opengym/-/boards) shows what is planned, in progress and
waiting for a test on the staging instance.
## Tech
+127
View File
@@ -0,0 +1,127 @@
# Roadmap
Where openGym is going, in the order it is likely to land. Each block is a GitLab milestone; the
issues and merge requests attached to it are the plan, this file is the readable summary. The
dates are the order, not a promise: a one-maintainer self-hosted project ships a version when the
branch has been used in a real gym for a while. Blocks are deliberately over-full — whatever is not
done when a version ships rolls into the next one. Version numbers follow the release rule, not the
size of the change: the next release is the last published one plus one patch (1.3.1 → 1.3.2), and a
minor bump is reserved for something that breaks compatibility.
- Board: https://gitlab.com/DuarteSantos8/opengym/-/boards — planned → in progress → in review → closed
- Milestones: https://gitlab.com/DuarteSantos8/opengym/-/milestones
- "In review" means: on a branch and deployed to gym-test.duarte-santos.ch, waiting for a real session.
---
## v1.3.2 and v1.3.3 — Cleaner workout (released 2026-09-05)
**Theme: the workout screen gets out of the way.** Fewer things to tap, the things you tap every set
stay where they are, everything else moves one tap away. Compared with Hevy or Strong the screen was
busy: ~10 buttons under a card and ~8 per set. The new default is one "⋯" per exercise, the set
number as the set's own menu, and an optional list view.
Shipped: v1.3.2 is the contributors' batch, v1.3.3 the redesign and the bug round on top of it.
- Workout view: cards or a scrollable list, with the header pinned in list mode (!96, #28, #44, #50)
- One menu per exercise (note, details, progression, bar weight, warm-up, superset, swap, move,
remove) and one per set (drop set, rest-pause burst, remove) (#20)
- Settings → During a workout → "Workout controls": +/− buttons, drop/burst shortcuts, superset
buttons, move/swap/remove buttons — each switch brings an old button row back
- Colour-coded RIR/RPE picker with a plain-language explanation per level; the empty cell is one
button, a logged rating is tinted by how close to failure it was (!91, #32)
- Automatic working weight, no confirmation prompt, no auto-advance (!92, #18)
- Stepper fixes: one tap = one step in supersets (!97, #41); the +/− uses the exercise's own
increment and progression's rounding, without snapping off-grid values (!84)
- Progression: routines with progression off keep their targets everywhere (!71); a weight change
starts a new stall streak so a deload cannot spiral (!93); the progression sheet cannot save into
the wrong entry (!77)
- Starter plans: Push/Pull/Legs, Upper/Lower, Full Body, 5×5 with a chooser and confirmation (!94)
- Muscle explorer in the library and the exercise picker, honouring the equipment profile (!87)
- Copy routine (!85); the "+" in the exercise picker adds immediately (!72)
- Timer flash blinks the theme; no replay after the app was hidden; a quiet toast on reopen (!89)
- MCP: `preview_session` shows what a routine will really open with; `rest_sec` in `get_routine` (!90, !81, #36)
- Coach: the create schema requires routine ids and a week, and caps the arrays (!99)
- Infrastructure: nginx re-resolves the api container (#16); Renovate config repaired (#37); CI with
JUnit/coverage, stack smoke test, Trivy scan, SBOMs, release preflight, fork-MR pipelines
Also in v1.3.3: exercise history and a progress line from the ⋯ menu (#43), favourite exercises
(#6), the in-app update check for the Android build (!40, #38, #9), the Coach save fix on Android
(#42), bands as bodyweight equipment (#39), kg ↔ lb conversion (#22), the centre tab button on the
workout screen (#29, #21), warm-up ramps on the exercise increment, and the small fixes from the
tester round.
Left over from this block:
- "By muscle" inside the Add-exercise sheet keeps the keyboard-aware search
- A real pause for the workout timers (#29 asked for it)
- Discord announcement (owner)
## v1.3.4 — Programmes & progression (October 2026)
**Theme: training structure beyond one weekly template.** Most of this is the Space-Hermes series.
It changes the training model (per-set roles, explicit phases, normalisation on every persist), so
it goes in one MR at a time, each rebased and tested on gym-test before the next.
- Explicit warm-up / work phases on every row, with legacy rows still readable (!76)
- Per-phase settings during a workout: set count, targets, fixed or percentage loads (!56)
- Choose which set drives AMRAP progression instead of "the last one" (!78)
- Multi-week programmes: 1–52 weeks, normal/deload/rest weeks, several sessions per day,
start/complete lifecycle, off by default (!98, #15)
- Home: several routines on one day with a session chooser; date overrides as ordered lists (!74)
- Per-exercise strength with an adaptive estimated 1RM; one point per workout and exact exercise (!50)
- Import: kg/lb normalised per row to the profile unit, malformed rows reported before confirming;
duration-only rows classified as timed strength or cardio (!53)
- Plan sharing: versioned payload, custom exercises carried across, repeat imports idempotent (!49)
- Resistance bands treated like bodyweight in config and progression (#39)
- Exercise history and a progress chart from inside the workout (#43) — reachable from the ⋯ menu
- Pictures for custom exercises: pick from the catalogue, later upload (#30)
- Percentage / training-max programming (5/3/1 style) on top of the policy interface
- Rest-pause and drop sets configurable in the routine editor, with adjustable rest (#17)
- Catalogue cleanup: exercises that should not carry weight, incline and interval fields for
cardio (#46); timers for planks and outdoor cardio are already there, document them (#45)
## v1.3.5 — Accounts & sync (November 2026)
**Theme: who may sign in, and what else may read or write your data.**
- Optional username + password login next to passkeys, for devices without a passkey (#1)
- OIDC login for people with an existing SSO such as PocketID or Authelia (#40)
- Personal-trainer role: invite students by code, open a student in a read-only context, write
their plan from a template library, assign in one tap (!79, #8)
- Remote MCP over OAuth for hosted AI clients, with per-connection profile and read/write scopes,
and compare-and-swap writes to the profile state (!88)
- MCP write tools: create/update routines, correct a logged set, delete a duplicate session,
manage equipment profiles (#24)
- Switching kg ↔ lb converts stored values instead of relabelling them (#22)
- Offline: saved routines and the active workout usable without the server, sync on return (#23)
- Sync reports still waiting on details: routines created on the web not reaching the phone (#33),
logged sessions lost after editing a routine (#25)
- Admin: per-user export, invite management, audit log filters
## v1.3.6 — Mobile (December 2026)
**Theme: the Android app catches up with the web app.**
- In-app update check against the GitLab releases, APK download with SHA-256 check and install (!40, #38, #9)
- Rest timer as an ongoing notification and on the lock screen, with "next set" from there (#19, #26)
- Home-screen widget for today's session
- Body weight from Withings or the phone's health store (#31)
- External links open in the system browser; Android back gesture across every screen
- Play Store / F-Droid feasibility check (the app stays sideload-first)
## Later — ideas, not scheduled
- Skins alongside the accent colour, default look untouched (#34); background wallpapers (#48)
- Big-screen / kiosk layout for a wall display (#49) and a physical "next" button, keyboard first (#47)
- Native NixOS module (!83) and Azure App Service deployment (!35) — only if someone maintains them
- Arabic and right-to-left layout (!36) — needs a rebase, then a visual round
- Periodisation extras: wave progression, auto-regulation on RPE, training-age based recommendations (#15)
- Watch app / companion for the rest timer
## How things move
An issue goes planned → in progress → in review → closed on the board. Contributor merge requests
from returning contributors get their pipeline started here automatically; a first MR is started
by hand after a look at the diff. Anything in review is on gym-test.duarte-santos.ch. Releases
bundle whatever has passed that test, with a changelog section per contributor.
+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.2.16
version: 1.3.4
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.2.16",
"version": "1.3.4",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "gym-api",
"version": "1.2.16",
"version": "1.3.4",
"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.2.16",
"version": "1.3.4",
"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 18
versionName "1.3.4"
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,13 +27,20 @@
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 -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<!-- Workout-day reminder: lets the local-notifications plugin fire at the exact minute
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>
@@ -0,0 +1,51 @@
package ch.duartesantos.opengym;
import android.content.Intent;
import android.net.Uri;
import androidx.core.content.FileProvider;
import com.getcapacitor.Plugin;
import com.getcapacitor.PluginCall;
import com.getcapacitor.PluginMethod;
import com.getcapacitor.annotation.CapacitorPlugin;
import java.io.File;
/**
* Minimal local Capacitor plugin that opens the Android package installer
* for an APK file stored in the app's cache directory.
*
* Usage from JS:
* import { registerPlugin } from '@capacitor/core';
* const Install = registerPlugin('Install');
* await Install.installApk({ fileName: 'opengym-update.apk' });
*/
@CapacitorPlugin(name = "Install")
public class InstallPlugin extends Plugin {
@PluginMethod
public void installApk(PluginCall call) {
String fileName = call.getString("fileName");
if (fileName == null || fileName.isEmpty()) {
call.reject("fileName is required");
return;
}
File file = new File(getContext().getCacheDir(), fileName);
if (!file.exists()) {
call.reject("APK file not found: " + fileName);
return;
}
Uri uri = FileProvider.getUriForFile(
getContext(),
getContext().getPackageName() + ".fileprovider",
file
);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_GRANT_READ_URI_PERMISSION);
getContext().startActivity(intent);
call.resolve();
}
}
@@ -1,5 +1,12 @@
package ch.duartesantos.opengym;
import android.os.Bundle;
import com.getcapacitor.BridgeActivity;
public class MainActivity extends BridgeActivity {}
public class MainActivity extends BridgeActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
registerPlugin(InstallPlugin.class);
super.onCreate(savedInstanceState);
}
}
@@ -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.2.16",
"version": "1.3.4",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "opengym-frontend",
"version": "1.2.16",
"version": "1.3.4",
"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.2.16",
"version": "1.3.4",
"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>
</>
}
+6
View File
@@ -108,10 +108,16 @@ const P = {
flag: <><path d="M6 20.4V4.2" /><path d="M6.4 5.2h13v9.2h-13" /><path d="M12.9 5.2v9.2M6.4 9.8h13" /></>,
chartLine: <path d="M3.6 20.2V4.4M3.6 20.2h16.8M6.4 16.4l3.9-4.8 3.1 2.7 5.2-6.6" />,
dot: <circle cx="12" cy="12" r="4.2" fill="currentColor" stroke="none" />,
more: <><circle cx="5.5" cy="12" r="1.6" fill="currentColor" stroke="none" /><circle cx="12" cy="12" r="1.6" fill="currentColor" stroke="none" /><circle cx="18.5" cy="12" r="1.6" fill="currentColor" stroke="none" /></>,
history: <><path d="M4.5 12.2a7.6 7.6 0 1 0 2.5-5.6" /><path d="M4.1 4.4v4.3h4.3" /><path d="M12 8.3v4.2l3.1 1.9" /></>,
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" /></>,
}
+17 -3
View File
@@ -13,21 +13,35 @@ import Icon from './Icon.jsx'
// a custom exercise without media. Any other/legacy value behaves as 'full'.
export default function Media({ ex, id, compact, minimizable }) {
const [playing, setPlaying] = useState(true)
// 'gif' → the animation failed, the still is showing; 'all' → the still failed too. Media is
// fetched from wherever the build points (a mount, a CDN): a dropped connection, an expired
// session on a gated instance or a CDN hiccup used to leave the browser's broken-image glyph
// on a white block. Now the still stands in for the animation, a neutral tile stands in for
// both, and a tap tries again — no text, so nothing new to translate.
const [failed, setFailed] = useState(null)
const gifSize = useStore(s => s.S.gifSize)
const update = useStore(s => s.update)
if (!ex.gif) return null
if (minimizable && gifSize === 'off') return null
const mini = minimizable && gifSize === 'mini'
const toggleSize = e => { e.stopPropagation(); update(s => { s.gifSize = mini ? 'full' : 'mini' }) }
const showGif = playing && failed == null
const onError = () => setFailed(showGif ? 'gif' : 'all')
const onTap = () => {
if (failed) { setFailed(null); setPlaying(true); return }
setPlaying(p => !p)
}
return (
<div className={'exmedia' + (compact ? ' compact' : '') + (mini ? ' mini' : '')} id={id} onClick={() => setPlaying(p => !p)}>
<img decoding="async" draggable={false} src={playing ? gifSrc(ex) : imgSrc(ex)} alt={exerciseNameFor(ex)} />
<div className={'exmedia' + (compact ? ' compact' : '') + (mini ? ' mini' : '') + (failed === 'all' ? ' broken' : '')} id={id} onClick={onTap}>
{failed === 'all'
? <div className="exmedia-x"><Icon name="dumbbell" /></div>
: <img decoding="async" draggable={false} src={showGif ? gifSrc(ex) : imgSrc(ex)} alt={exerciseNameFor(ex)} onError={onError} />}
{minimizable && (
<button className="giftoggle" onClick={toggleSize}>
<Icon name={mini ? 'expand' : 'minimize'} />{mini ? t('Expand') : t('Minimize')}
</button>
)}
{!mini && (
{!mini && !failed && (
<span className="gifhint">
<Icon name={playing ? 'pause' : 'play'} />{playing ? t('tap to pause') : t('tap to play')}
</span>
@@ -0,0 +1,99 @@
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'
import { isFav, sortFavouritesFirst } from '../lib/favourites.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 : ''
// Favourites float to the top of whatever the filters left (issue #6), the rest keeps its order.
const exercises = sortFavouritesFirst(eqOn ? base.filter(e => e.eq === eqOn) : base, S)
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">{isFav(S, e.id) && <Icon name="starFill" className="fav-star" />}{exerciseNameFor(e)}</div><div className="ss">{t(primary ? 'Primary target' : 'Also trains')} · <span className="capitalize">{t(e.tg || e.bp)} · {t(e.eq)}</span></div></div>
{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"
/>
)
}
+7 -4
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) {
@@ -32,9 +32,12 @@ export default function TabBar({ onStart }) {
<nav id="tabbar">
<Tab k="home" icon="house" to="/home" label={t('Home')} />
<Tab k="plan" icon="calendar" to="/plan" label={t('Plan')} />
<button className={'start' + (S.active ? ' rec' : '')} onClick={startWorkout}>
<span className="cir"><Icon name={S.active ? 'play' : 'dumbbell'} /></span>
<span>{S.active ? t('Resume') : t('Start')}</span>
{/* On the workout screen itself there is nothing to resume, so the button reads as the
tab it is and stays lit (#29); anywhere else it brings you back to the exercise you
were on — the marker is kept in S.active.cur and never moves on its own (#21). */}
<button className={'start' + (S.active ? ' rec' : '') + (S.active && cur === 'workout' ? ' on' : '')} onClick={startWorkout}>
<span className="cir"><Icon name={S.active ? (cur === 'workout' ? 'dumbbell' : 'play') : 'dumbbell'} /></span>
<span>{S.active ? (cur === 'workout' ? t('Workout') : t('Resume')) : t('Start')}</span>
</button>
<Tab k="stats" icon="chart" to="/stats" label={t('Stats')} />
<Tab k="library" icon="list" to="/library" label={t('Exercises')} />
+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
}
+155 -25
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
@@ -416,6 +416,11 @@ h4.sec{
font-weight:500;text-transform:capitalize;
}
.tag.acc{background:var(--acc-soft);color:var(--acc)}
/* favourite marker (issue #6): a small yellow star glued to the exercise name — distinct from
the accent "chosen" tag at the row's end, which means "already in a routine or the log" */
.fav-star{color:var(--yellow);font-size:12px;display:inline-block;margin-right:5px;vertical-align:-1px}
.fav-btn{margin-top:-4px}
.fav-btn.on{color:var(--yellow)}
/* ---------------------------------------------------------------- chips -- */
.chips{
@@ -438,6 +443,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 ==================================== */
@@ -601,6 +607,21 @@ h4.sec{
.ck.on svg{stroke:var(--on-acc)}
/* ------------------------------------------------------------- workout --- */
/* Workout header. In list mode it is pinned: pulled up over #app's top padding so it sits flush
with the screen edge from the first pixel, and given the page's own ground plus a light blur so
the rows scrolling underneath read as underneath. */
.whdr.stick{
position:sticky;top:0;z-index:20;
margin:calc(-1 * (var(--sat) + 8px)) calc(-1 * var(--pad)) 6px;
padding:calc(var(--sat) + 8px) var(--pad) 0;
background:color-mix(in srgb,var(--bg) 94%,transparent);
-webkit-backdrop-filter:saturate(180%) blur(10px);backdrop-filter:saturate(180%) blur(10px);
}
.whdr.stick .hdr{margin-bottom:12px}
.whdr.stick .wprog{margin-bottom:10px}
@supports not ((backdrop-filter:blur(1px)) or (-webkit-backdrop-filter:blur(1px))){
.whdr.stick{background:var(--bg)}
}
.wprog{height:4px;background:var(--surface-2);border-radius:99px;overflow:hidden;margin-bottom:16px}
.wprog i{display:block;height:100%;background:var(--acc);border-radius:99px;transition:width var(--med) var(--ease)}
.exmedia{position:relative;border-radius:var(--r-lg);overflow:hidden;background:#fff;margin-bottom:12px}
@@ -618,6 +639,12 @@ h4.sec{
at 180px you had to scroll a full screen between two exercises done back-to-back */
.exmedia.compact img{height:120px}
.exmedia.mini img{height:84px}
/* both the animation and the still failed to load: a neutral tile instead of the browser's
broken-image glyph; same heights as the picture so the card does not jump. tap retries. */
.exmedia.broken{background:var(--surface-2)}
.exmedia-x{width:100%;height:320px;display:flex;align-items:center;justify-content:center;color:var(--label-3);font-size:34px}
.exmedia.compact .exmedia-x{height:120px}
.exmedia.mini .exmedia-x{height:84px}
.sethead{
display:flex;align-items:center;gap:8px;padding:0 0 6px;
@@ -638,24 +665,74 @@ h4.sec{
.setrow .n{
width:24px;height:24px;border-radius:50%;background:var(--surface-2);color:var(--label-2);
display:flex;align-items:center;justify-content:center;font-size:12px;font-weight:500;flex:none;
position:relative;padding:0;border:0;font-family:inherit;cursor:pointer;
transition:background var(--fast),color var(--fast);
}
.setrow .stp.w{flex:1.4;min-width:0}
.setrow .stp.r{flex:1;min-width:0}
.setrow .stp.eff{flex:1.1;min-width:0}
.setrow .stp button{width:32px;height:40px}
/* a 3rd stepper (RIR) needs narrower buttons and a tighter row gap to fit next to weight+reps
on narrow phones, same technique as the exercise-config sheet's three-steppers-in-a-row
(.cfgrow below). The buttons stay 28px wide — anything narrower is a miss-prone target —
so the room comes from the smaller glyphs and from the value fields giving up their padding.
The header shares the numbers so its labels stay centred over the steppers they name. */
/* The effort column is a single tap-to-pick button, not a stepper. It is a direct flex child
of the row (like the .stp cells), carrying its own column width via flex. `align-self` and
a fixed height stop the row from stretching it taller than the weight/reps cells; it is NOT
inside `.stp`, so the stepper's 32px fixed button width (which wrapped "RIR") never applies. */
/* flex-basis:0 so the button's width comes from its flex share, not its text, and the column
never jumps between an empty "RIR" and a logged "2". The unrated state uses `.is-empty`, not
the generic `.empty` (which is a full-page empty-state with 44px padding — sharing that name
inflated the cell to ~90px). */
.setrow .effcell,.sethead .eff-sp{flex:.8 1 0;min-width:0}
.effcell{
box-sizing:border-box;height:44px;border-radius:10px;
background:var(--surface-2);border:1.5px solid transparent;
color:var(--label);font-size:15px;font-weight:600;letter-spacing:-.01em;
font-variant-numeric:tabular-nums;white-space:nowrap;line-height:1;
display:flex;align-items:center;justify-content:center;
transition:background var(--fast),transform var(--fast),border-color var(--fast);
}
.effcell:active{transform:scale(.94)}
.effcell.is-empty{color:var(--label-2);font-weight:500;font-size:12px;letter-spacing:.02em}
/* a logged rating becomes a −/value/+ stepper, tinted by its effort band: the band colour
fills the cell at low opacity (set inline via color-mix), borders it, and colours the value.
the +/− buttons step 0.5 on the profile's scale; the value opens the picker. it carries the
same column flex as the plain .effcell so the row does not jump when a rating is added. */
.setrow .effcell-stp,.setrow.eff3 .effcell-stp{
height:44px;border-radius:10px;border:1.5px solid transparent;
transition:background var(--fast),border-color var(--fast);
}
.effcell-stp button{color:inherit}
.effcell-stp>button[aria-label="Decrease"],
.effcell-stp>button[aria-label="Increase"]{width:26px;height:44px;font-size:15px;opacity:.85}
.effcell-stp .val{
flex:1;min-width:0;display:flex;align-items:center;justify-content:center;
font-size:15px;font-weight:600;letter-spacing:-.01em;
font-variant-numeric:tabular-nums;line-height:1;align-self:stretch;color:inherit;
}
.effcell-stp .val:active{background:var(--surface-3)}
/* the effort cell needs less room now (one short value, no +/- buttons), so weight/reps keep
more of the row on narrow phones than they did when three steppers had to share it */
.setrow .effcell-stp,.setrow.eff3 .effcell-stp{flex:.8 1 0;min-width:0}
.setrow.eff3 .effcell-stp{flex:.7 1 0}
.setrow.eff3,.sethead.eff3{gap:6px}
.setrow.eff3 .stp.w,.sethead.eff3 .w-sp{flex:1.2}
.setrow.eff3 .stp.r,.sethead.eff3 .r-sp{flex:1}
.setrow.eff3 .stp.eff,.sethead.eff3 .eff-sp{flex:.85}
.setrow.eff3 .stp button{width:28px;font-size:14px}
.setrow.eff3 .stp.w,.sethead.eff3 .w-sp{flex:1.4}
.setrow.eff3 .stp.r,.sethead.eff3 .r-sp{flex:1.1}
.setrow.eff3 .effcell,.sethead.eff3 .eff-sp{flex:.7 1 0}
.setrow.eff3 .stp.w button,.setrow.eff3 .stp.r button{width:26px}
.setrow.eff3 .stp .num{font-size:14px}
.setrow.eff3 .stp .val{padding:0}
.setrow.eff3 .effcell-stp>button[aria-label="Decrease"],
.setrow.eff3 .effcell-stp>button[aria-label="Increase"]{width:22px}
.setrow.eff3 .effcell-stp .val{font-size:14px}
/* effort quick picker sheet: colour-coded preset buttons, hardest (purple) first */
/* effort picker: the ⋯-menu list with the value in the icon square, tinted per band; the
exact-value row carries the same stepper as the logged cell in the set row. */
.effpick.menu-list .menu-item .effpick-n{
background:var(--bc);color:#fff;font-size:13px;font-weight:700;letter-spacing:-.02em;
font-variant-numeric:tabular-nums;
}
.effpick .menu-item.on{background:color-mix(in srgb,var(--bc) 14%,var(--surface))}
.effpick .menu-on.is-on{color:var(--bc)}
.effpick .effpick-free{padding-right:8px}
.effpick .effpick-free .stp{flex:none;width:148px}
.effpick .effpick-free .stp .num{font-size:17px;font-weight:600}
.effpick .effpick-free .stp .num::placeholder{color:var(--label-3);font-weight:500}
.setrow.done .n{background:var(--acc);color:var(--on-acc)}
.setrow.done{opacity:.45}
/* drop-set drops / rest-pause bursts riding on a work row, editable like the row itself
@@ -666,6 +743,19 @@ h4.sec{
.subrow .stp.mini button{width:26px;height:30px}
.subrow .stp.mini .num{font-size:13px;min-height:30px}
.subrow .iconbtn{width:26px;height:26px;font-size:11px;flex:none}
/* The number is the set's menu (drop / burst / remove); a 24px circle needs a finger-sized hit area. */
.setrow .n::before{content:'';position:absolute;inset:-10px}
/* No +/- buttons: the number field takes the whole cell and is the tap target. */
.stp.plain{grid-template-columns:1fr}
.stp.plain .val{width:100%}
.stp.plain .num{width:100%;text-align:center}
/* --- menu sheet (the workout's "more" menus) --- */
.menu-list .menu-item{min-height:52px;padding:8px 12px}
.menu-list .menu-item .lrow-i{width:32px;height:32px;font-size:16px;background:var(--surface-2);color:var(--label)}
.menu-list .menu-item.danger .tt,.menu-list .menu-item.danger .lrow-i{color:var(--red)}
.menu-list .menu-item.disabled{opacity:.4;pointer-events:none}
.menu-on{color:transparent;font-size:16px;flex:none}
.menu-on.is-on{color:var(--acc)}
.setextra{display:flex;flex-wrap:wrap;gap:6px;margin:2px 0 8px 32px}
.setextra .chip.add{display:inline-flex;align-items:center;gap:4px;color:var(--acc)}
.setextra .chip.add svg{width:13px;height:13px}
@@ -802,19 +892,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 +1087,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 +1146,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;
+12 -3
View File
@@ -20,10 +20,19 @@ function plugin() {
return pluginPromise
}
// A native call that never answers must not hang the setup screen behind a greyed-out button
// (issue #42: "Save and use the Coach" stayed disabled forever on one Android 16 phone). After
// this long the platform store is treated as unavailable and the process-local map takes over.
const NATIVE_TIMEOUT_MS = 4000
export const withTimeout = (promise, ms = NATIVE_TIMEOUT_MS) => new Promise((resolve, reject) => {
const tm = setTimeout(() => reject(new Error('secure storage timed out')), ms)
promise.then(v => { clearTimeout(tm); resolve(v) }, e => { clearTimeout(tm); reject(e) })
})
export async function getApiKey() {
const p = await plugin()
if (p) {
try { const v = await p.get(KEY); return typeof v === 'string' && v ? v : null } catch { /* fall through */ }
try { const v = await withTimeout(p.get(KEY)); return typeof v === 'string' && v ? v : null } catch { /* fall through */ }
}
return memory.get(KEY) || null
}
@@ -32,12 +41,12 @@ export async function setApiKey(value) {
if (!v) return clearApiKey()
const p = await plugin()
if (p) {
try { await p.set(KEY, v); memory.delete(KEY); return } catch { /* fall through */ }
try { await withTimeout(p.set(KEY, v)); memory.delete(KEY); return } catch { /* fall through */ }
}
memory.set(KEY, v)
}
export async function clearApiKey() {
const p = await plugin()
if (p) { try { await p.remove(KEY) } catch { /* nothing to clear */ } }
if (p) { try { await withTimeout(p.remove(KEY)) } catch { /* nothing to clear */ } }
memory.delete(KEY)
}
+40
View File
@@ -132,3 +132,43 @@ export function effortHistogram(S, days) {
/** A set that counts as hard — the filter behind the muscle map's "hard sets" mode. */
export const isHardSet = s => { const r = rirOf(s); return r != null && r <= HARD_RIR }
// ---------------------------------------------------------------- colour bands --
//
// A set's effort read as a colour, so a glance down a workout tells you how hard it ran
// without reading every number. Bands are defined once, in RIR (the internal scale), and
// apply unchanged whether the profile logs RIR or RPE — RPE 8 and RIR 2 are the same set and
// get the same colour. The scale runs from "nothing left" (purple, past red — the far end,
// not just "very hard") through to "easy, warm-up range" (green).
//
// The named buckets are also the quick-pick presets: one tap logs the middle of a band. They
// are deliberately coarse where estimation is coarse — nobody reliably tells 5 RIR from 7, so
// everything from 4 up shares one bucket — and fine near failure, where the difference between
// 0, 0.5 and 1 actually changes the training. A typed value between presets still colours by
// the band it falls in, so the flexibility of a free number is never lost.
export const EFFORT_BANDS = [
{ rir: 0, max: 0.25, color: 'var(--purple)', feel: 'Nothing left — went to failure' },
{ rir: 0.5, max: 0.75, color: 'var(--red)', feel: 'Maybe half a rep left' },
{ rir: 1, max: 1.5, color: 'var(--orange)', feel: 'One more rep in the tank' },
{ rir: 2, max: 2.5, color: 'var(--yellow)', feel: 'Two more reps' },
{ rir: 3, max: 3.5, color: 'var(--green)', feel: 'Three more reps' },
{ rir: 4, max: Infinity, color: 'var(--acc-2)', feel: 'Easy — warm-up territory' }
]
// The presets shown in the picker, hardest first — the order they read on the scale and the
// order the colours run. `tail` is the collapsed top bucket ("4+"): its value is the floor it
// stands for, so a tap logs a concrete 4, not a range nothing downstream could average.
export const EFFORT_PRESETS = EFFORT_BANDS.map((b, i) => ({
rir: b.rir, color: b.color, feel: b.feel, tail: i === EFFORT_BANDS.length - 1
}))
/**
* The colour for one effort value, given in RIR (use rirOf to convert a set first). Picks the
* band the value falls into: an exact preset lands on its own band, a typed in-between value
* (RIR 1.5) takes the band it sits within so it is never left uncoloured. null (unrated) has
* no colour — the caller shows a neutral control, not a green one.
*/
export const effortColor = rir => {
if (rir == null) return null
for (const b of EFFORT_BANDS) if (rir <= b.max) return b.color
return EFFORT_BANDS[EFFORT_BANDS.length - 1].color
}
+77 -1
View File
@@ -1,7 +1,8 @@
import { describe, it, expect } from 'vitest'
import {
rirOf, toScale, displayScale, avgRir, effortSummary, hasEffort, effortWeeks,
effortHistogram, isHardSet, HARD_RIR, MIN_RATED
effortHistogram, isHardSet, HARD_RIR, MIN_RATED,
effortColor, EFFORT_BANDS, EFFORT_PRESETS
} from './effort.js'
import { isoOf } from './format.js'
@@ -184,3 +185,78 @@ describe('isHardSet', () => {
expect(isHardSet({})).toBe(false) // unrated is not hard, and not easy either
})
})
describe('EFFORT_BANDS / EFFORT_PRESETS', () => {
it('runs hardest-first and covers the whole scale with no gap', () => {
// presets are the quick-pick buttons, top of the scale (0 RIR = failure) first
expect(EFFORT_PRESETS.map(p => p.rir)).toEqual([0, 0.5, 1, 2, 3, 4])
// only the last bucket is the collapsed "4+" tail
expect(EFFORT_PRESETS.map(p => p.tail)).toEqual([false, false, false, false, false, true])
// the bands are contiguous: each band's ceiling is below the next band's floor, and the
// last reaches infinity so no rating is ever left without a colour
expect(EFFORT_BANDS[EFFORT_BANDS.length - 1].max).toBe(Infinity)
for (let i = 1; i < EFFORT_BANDS.length; i++) {
expect(EFFORT_BANDS[i].rir).toBeGreaterThan(EFFORT_BANDS[i - 1].max)
}
})
it('every preset carries a colour and a human description', () => {
for (const p of EFFORT_PRESETS) {
expect(p.color).toMatch(/^var\(--/)
expect(typeof p.feel).toBe('string')
expect(p.feel.length).toBeGreaterThan(0)
}
})
})
describe('effortColor', () => {
it('gives each preset value its own band colour', () => {
// hardest to easiest — the colours the picker shows on its buttons
expect(effortColor(0)).toBe('var(--purple)')
expect(effortColor(0.5)).toBe('var(--red)')
expect(effortColor(1)).toBe('var(--orange)')
expect(effortColor(2)).toBe('var(--yellow)')
expect(effortColor(3)).toBe('var(--green)')
expect(effortColor(4)).toBe('var(--acc-2)')
})
it('colours a typed in-between value by the band it falls in, never leaving it blank', () => {
// a half-step belongs to the harder band below it — the band ceilings are inclusive, so
// 1.5 (between "one left" and "two left") reads as the tougher of the two, its band 1 colour
expect(effortColor(1.5)).toBe(effortColor(1)) // orange, not yellow
expect(effortColor(2.5)).toBe(effortColor(2)) // yellow, not green
// 0.25 sits between failure (0) and the half-rep band (0.5); by the same inclusive-ceiling
// rule it reads as the harder one — the failure colour, never uncoloured
expect(effortColor(0.25)).toBe(effortColor(0))
})
it('collapses everything past the top bucket into one colour', () => {
// nobody reliably tells 5 from 7 reps in reserve — they are all "easy"
expect(effortColor(4)).toBe(effortColor(7))
expect(effortColor(4)).toBe(effortColor(10))
})
it('is null for an unrated set — colour means a rating, empty has none', () => {
expect(effortColor(null)).toBe(null)
expect(effortColor(undefined)).toBe(null)
})
it('reads the same colour whether the set was logged as RIR or RPE', () => {
// the picker colours by internal RIR (via rirOf), so 0 RIR and 10 RPE match, 2 and 8 match
expect(effortColor(rirOf({ rir: 0 }))).toBe(effortColor(rirOf({ rpe: 10 })))
expect(effortColor(rirOf({ rir: 2 }))).toBe(effortColor(rirOf({ rpe: 8 })))
expect(effortColor(rirOf({ rir: 0.5 }))).toBe(effortColor(rirOf({ rpe: 9.5 })))
})
})
describe('picker preset labels', () => {
// The picker labels each preset with its value on the active scale — the RIR presets shown
// to an RPE profile read as 10, 9.5, 9, 8, 7, 6. This is what toScale computes per button.
it('labels presets on the RIR scale unchanged', () => {
expect(EFFORT_PRESETS.map(p => toScale('rir', p.rir))).toEqual([0, 0.5, 1, 2, 3, 4])
})
it('labels the same presets as their RPE mirror for an RPE profile', () => {
expect(EFFORT_PRESETS.map(p => toScale('rpe', p.rir))).toEqual([10, 9.5, 9, 8, 7, 6])
})
})
+83
View File
@@ -0,0 +1,83 @@
import { metricModeForEntry, metricRowsForEntry, bestWeightForEntry, modeOf } from './history.js'
import { extraVolumeOf } from './workout-model.js'
import { bestSetOf } from './onerm.js'
// One exercise's past, read back for the history sheet (issue #43): a chart series and the
// last few sessions, derived in a single pass over the log so the sheet can memoise the
// result and never rescan on a re-render.
//
// The chart plots ONE number per session, chosen the way Stats does it:
// reps — the heaviest completed work set (metric 'weight'); an exercise never loaded
// (pull-ups, push-ups) plots its best rep count instead (metric 'reps'), because
// that is the thing improving
// time — the longest completed hold, in seconds (metric 'sec')
// cardio — the minutes logged that session (metric 'min')
// The mode is the one the exercise was logged in most recently; a session logged in another
// mode still appears in the list (its sets are labelled by their own target) but gets no point
// and no value, so the curve never mixes seconds with kilos.
//
// Warm-up rows are excluded from every number here, as everywhere else.
export const HISTORY_SESSIONS = 10
const startOf = w => (Number.isFinite(w.start) ? w.start : new Date(w.d + 'T12:00:00').getTime())
// Volume of the exercise in one session: main set plus its drops/bursts, reps mode only —
// there is no honest tonnage for a hold or a run.
const entryVolume = rows => rows.reduce((v, s) => v + (s.w || 0) * (s.r || 0) + extraVolumeOf(s), 0)
export function exerciseHistory(S, exId, { limit = HISTORY_SESSIONS } = {}) {
const workouts = S?.workouts || []
// Chronological pairs of (workout, entry); the sort covers backfilled sessions, which are
// inserted by date rather than appended.
const logged = []
workouts.forEach(w => {
const en = (w.entries || []).find(e => e.id === exId)
if (!en) return
const mode = metricModeForEntry(en)
if (!mode) return
const rows = metricRowsForEntry(en, mode)
if (rows.length) logged.push({ w, en, mode, rows })
})
logged.sort((a, b) => startOf(a.w) - startOf(b.w))
const empty = { mode: modeOf({ id: exId }), metric: 'weight', best: 0, prId: null, total: 0, sessions: [], points: [], e1rmPoints: [] }
if (!logged.length) return empty
const mode = logged[logged.length - 1].mode
const repsOnly = mode === 'reps' && !logged.some(l => l.mode === 'reps' && bestWeightForEntry(l.en) > 0)
const metric = mode === 'cardio' ? 'min' : mode === 'time' ? 'sec' : repsOnly ? 'reps' : 'weight'
const valueOf = ({ en, rows }) => {
if (metric === 'min') return rows.reduce((a, s) => a + (Number(s.min) || 0), 0)
if (metric === 'sec') return Math.max(0, ...rows.map(s => Number(s.sec) || 0))
if (metric === 'reps') return Math.max(0, ...rows.map(s => Number(s.r) || 0))
return bestWeightForEntry(en)
}
let best = 0, prId = null
const sessions = [], points = [], e1rmPoints = []
logged.forEach(({ w, en, mode: m, rows }) => {
const same = m === mode
const value = same ? valueOf({ en, rows }) : null
const e1rm = m === 'reps' ? (bestSetOf(en)?.est ?? null) : null
const t = startOf(w)
// "PR" goes on the session that first reached the all-time best, not on every session
// that later matched it — one marker says where the record was set.
if (value != null && value > best) { best = value; prId = w.id }
if (value != null && value > 0) points.push({ t, d: w.d, y: value, e1rm })
if (e1rm != null) e1rmPoints.push({ t, d: w.d, y: e1rm })
sessions.push({
id: w.id, d: w.d, t, mode: m, target: en.target || null, sets: rows, value, e1rm,
volume: m === 'reps' ? entryVolume(rows) : null,
})
})
// The "first reached" rule only holds for records above zero: a bodyweight session with
// no weight logged is not a PR of anything.
if (best <= 0) prId = null
return {
mode, metric, best, prId, total: sessions.length,
sessions: sessions.slice(-limit).reverse().map(s => ({ ...s, pr: s.id === prId })),
points, e1rmPoints,
}
}
+112
View File
@@ -0,0 +1,112 @@
import { describe, it, expect } from 'vitest'
import { exerciseHistory, HISTORY_SESSIONS } from './exercise-history.js'
import { estimate1RM } from './onerm.js'
const DAY = 86400000
const T0 = Date.UTC(2026, 0, 5, 10)
const iso = i => new Date(T0 + i * DAY).toISOString().slice(0, 10)
// One workout on day `i` with a single bench entry made of the given rows.
const session = (i, rows, extra = {}) => ({
id: 'w' + i, d: iso(i), start: T0 + i * DAY, entries: [{ id: 'bench', target: { mode: 'reps' }, sets: rows, ...extra }],
})
const work = (w, r, done = true) => ({ w, r, done })
const warm = (w, r) => ({ w, r, done: true, phase: 'warmup' })
describe('exerciseHistory', () => {
it('is empty when the exercise was never logged', () => {
const S = { workouts: [session(0, [work(60, 5)])] }
expect(exerciseHistory(S, 'squat')).toMatchObject({ total: 0, best: 0, prId: null, sessions: [], points: [] })
expect(exerciseHistory({ workouts: [] }, 'bench').total).toBe(0)
expect(exerciseHistory({}, 'bench').total).toBe(0)
})
it('lists sessions newest first with their work sets, value and volume', () => {
const S = { workouts: [session(0, [work(60, 5), work(60, 5)]), session(2, [work(65, 5), work(65, 4)])] }
const h = exerciseHistory(S, 'bench')
expect(h.mode).toBe('reps')
expect(h.metric).toBe('weight')
expect(h.total).toBe(2)
expect(h.sessions.map(s => s.d)).toEqual([iso(2), iso(0)])
expect(h.sessions[0]).toMatchObject({ value: 65, volume: 65 * 9, target: { mode: 'reps' } })
expect(h.sessions[0].sets).toHaveLength(2)
expect(h.sessions[1]).toMatchObject({ value: 60, volume: 600 })
// the chart stays chronological
expect(h.points.map(p => [p.d, p.y])).toEqual([[iso(0), 60], [iso(2), 65]])
})
it('leaves warm-ups and unfinished rows out of every number', () => {
const S = { workouts: [session(0, [warm(40, 8), work(60, 5), work(100, 5, false)])] }
const h = exerciseHistory(S, 'bench')
expect(h.best).toBe(60)
expect(h.sessions[0].sets).toEqual([work(60, 5)])
expect(h.sessions[0].volume).toBe(300)
expect(h.sessions[0].e1rm).toBe(estimate1RM(60, 5))
})
it('marks the PR on the session that first reached the best weight, once', () => {
const S = { workouts: [
session(0, [work(60, 5)]), session(1, [work(70, 5)]), session(2, [work(65, 5)]), session(3, [work(70, 3)]),
] }
const h = exerciseHistory(S, 'bench')
expect(h.best).toBe(70)
expect(h.prId).toBe('w1')
expect(h.sessions.filter(s => s.pr).map(s => s.id)).toEqual(['w1'])
})
it('keeps the last ten sessions in the list but every session on the chart', () => {
const S = { workouts: Array.from({ length: 14 }, (_, i) => session(i, [work(50 + i, 5)])) }
const h = exerciseHistory(S, 'bench')
expect(h.total).toBe(14)
expect(h.sessions).toHaveLength(HISTORY_SESSIONS)
expect(h.sessions[0].d).toBe(iso(13))
expect(h.sessions.at(-1).d).toBe(iso(4))
expect(h.points).toHaveLength(14)
expect(h.e1rmPoints).toHaveLength(14)
// the record lives outside the listed window, so no listed session carries the marker
expect(h.prId).toBe('w13')
expect(exerciseHistory(S, 'bench', { limit: 3 }).sessions).toHaveLength(3)
})
it('orders backfilled sessions by date, not by position in the log', () => {
const S = { workouts: [session(5, [work(60, 5)]), { ...session(1, [work(80, 5)]), start: undefined }] }
const h = exerciseHistory(S, 'bench')
expect(h.points.map(p => p.d)).toEqual([iso(1), iso(5)])
expect(h.sessions.map(s => s.d)).toEqual([iso(5), iso(1)])
expect(h.prId).toBe('w1')
})
it('plots reps for an exercise that was never loaded', () => {
const S = { workouts: [session(0, [work(0, 8)]), session(1, [work(0, 10), work(0, 9)])] }
const h = exerciseHistory(S, 'bench')
expect(h.metric).toBe('reps')
expect(h.points.map(p => p.y)).toEqual([8, 10])
expect(h.best).toBe(10)
expect(h.prId).toBe('w1')
})
it('plots the longest hold for timed work and the minutes for cardio', () => {
const hold = i => ({ id: 'h' + i, d: iso(i), start: T0 + i * DAY, entries: [{ id: 'plank', target: { mode: 'time' }, sets: [{ sec: 40 + i * 10, done: true }, { sec: 30, done: true }] }] })
const run = i => ({ id: 'r' + i, d: iso(i), start: T0 + i * DAY, entries: [{ id: 'run', target: { mode: 'cardio' }, sets: [{ min: 20, speed: 10, done: true }, { min: 5, speed: 12, done: true }] }] })
const S = { workouts: [hold(0), hold(1), run(0)] }
const plank = exerciseHistory(S, 'plank')
expect(plank).toMatchObject({ mode: 'time', metric: 'sec', best: 50, prId: 'h1' })
expect(plank.points.map(p => p.y)).toEqual([40, 50])
expect(plank.sessions[0].volume).toBeNull()
expect(plank.e1rmPoints).toEqual([])
const cardio = exerciseHistory(S, 'run')
expect(cardio).toMatchObject({ mode: 'cardio', metric: 'min', best: 25 })
expect(cardio.points[0].y).toBe(25)
})
it('gives a session logged in another mode no point, but keeps it in the list', () => {
const S = { workouts: [
{ id: 'a', d: iso(0), start: T0, entries: [{ id: 'x', target: { mode: 'time' }, sets: [{ sec: 30, done: true }] }] },
{ id: 'b', d: iso(1), start: T0 + DAY, entries: [{ id: 'x', target: { mode: 'reps' }, sets: [work(20, 10)] }] },
] }
const h = exerciseHistory(S, 'x')
expect(h.mode).toBe('reps')
expect(h.points).toHaveLength(1)
expect(h.sessions.map(s => [s.id, s.value])).toEqual([['b', 20], ['a', null]])
})
})
+5 -1
View File
@@ -142,8 +142,12 @@ export const isCardio = idOrEx => (typeof idOrEx === 'string' ? EXIDX[idOrEx] :
// catalogue. This seeds the `bw` flag on a fresh config so a push-up never asks for a weight
// nobody was going to enter. It is only the default: the flag lives on the config, so a dip
// done with a belt can turn it off and a custom exercise can turn it on.
// Equipment with no meaningful load in kg: your own body, or a band whose "weight" is a colour.
// Both default to the bodyweight model (one reps stepper, progression in reps then sets); the
// per-exercise Bodyweight switch still overrides it either way (issue #39).
const BODYWEIGHT_EQ = new Set(['body weight', 'band', 'resistance band'])
export const isBodyweightEq = idOrEx =>
(typeof idOrEx === 'string' ? EXIDX[idOrEx] : idOrEx)?.eq === 'body weight'
BODYWEIGHT_EQ.has((typeof idOrEx === 'string' ? EXIDX[idOrEx] : idOrEx)?.eq)
// An id that resolves to nothing — a plan file built against a different exercise dataset,
// a custom exercise deleted on another device before the sync arrived — still has to
+29
View File
@@ -0,0 +1,29 @@
// Favourite exercises (issue #6): a personal shortlist that floats to the top of the picker,
// the Library and the muscle explorer so building a routine takes fewer scrolls.
//
// Stored as a flat id list in synced state (S.favEx) — catalogue or custom ids alike. It is
// personal, so it stays out of shared plan bundles (lib/plan-share.js) on purpose. Profiles
// written before the field existed simply have no list, hence every reader tolerates undefined.
export const favIds = S => (Array.isArray(S?.favEx) ? S.favEx : [])
export const isFav = (S, id) => favIds(S).includes(id)
/** Flip one exercise in a state draft. Returns true when it is a favourite afterwards. */
export function toggleFav(s, id) {
const list = favIds(s)
const on = !list.includes(id)
s.favEx = on ? [...list, id] : list.filter(x => x !== id)
return on
}
/**
* Favourites first, everything else after — both halves keep the order they came in, so a
* list that is already sorted by name (or by usage) stays that way within each half.
*/
export function sortFavouritesFirst(list, S) {
const fav = favIds(S)
if (!fav.length) return list
const set = new Set(fav)
return [...list.filter(e => set.has(e.id)), ...list.filter(e => !set.has(e.id))]
}
+33
View File
@@ -0,0 +1,33 @@
import { describe, expect, it } from 'vitest'
import { favIds, isFav, toggleFav, sortFavouritesFirst } from './favourites.js'
const ex = id => ({ id, n: id })
describe('favourites', () => {
it('reads a profile without the field as no favourites', () => {
expect(favIds({})).toEqual([])
expect(favIds({ favEx: null })).toEqual([])
expect(isFav({}, '0001')).toBe(false)
})
it('toggles an id in and out of the list and reports the new state', () => {
const s = {}
expect(toggleFav(s, '0001')).toBe(true)
expect(toggleFav(s, 'c123')).toBe(true)
expect(s.favEx).toEqual(['0001', 'c123'])
expect(isFav(s, '0001')).toBe(true)
expect(toggleFav(s, '0001')).toBe(false)
expect(s.favEx).toEqual(['c123'])
})
it('moves favourites to the front and keeps both halves in their original order', () => {
const list = ['a', 'b', 'c', 'd', 'e'].map(ex)
const S = { favEx: ['d', 'b', 'zzz-not-listed'] }
expect(sortFavouritesFirst(list, S).map(e => e.id)).toEqual(['b', 'd', 'a', 'c', 'e'])
})
it('returns the very same list when there are no favourites', () => {
const list = ['a', 'b'].map(ex)
expect(sortFavouritesFirst(list, {})).toBe(list)
})
})
+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', () => {
+16
View File
@@ -15,6 +15,22 @@ import { effectiveRoutineId } from './history.js'
export const MOBILE = import.meta.env.VITE_MOBILE === '1'
// Some features only make sense on Android. The in-app updater downloads an .apk and hands it
// to the system package installer — there is no equivalent on iOS (App Store only) or on the
// web build. On anything but a native Android shell this must stay off.
//
// @capacitor/core is imported dynamically (like every other Capacitor dependency here) so it
// never lands in the web bundle. Capacitor.getPlatform() returns 'android' | 'ios' | 'web'.
export async function isAndroid() {
if (!MOBILE) return false
try {
const { Capacitor } = await import('@capacitor/core')
return Capacitor.getPlatform() === 'android'
} catch (e) {
return false
}
}
const FILE = 'opengym-state.json'
export async function nativeLoad() {
+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(626)
expect(inherited).toHaveLength(613)
// 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('81d277306b3029090b7a2ba6cc19108ca207ea65d738487155123260b6e9525d')
})
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)
})
})
+15
View File
@@ -0,0 +1,15 @@
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()
// "Push (Copy)" copied again becomes "Push (Copy 2)", not "Push (Copy) (Copy)".
const esc = suffix.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
const m = new RegExp('^(.*) \\(' + esc + '(?: (\\d+))?\\)$').exec(routine.name || '')
copy.name = m ? m[1] + ' (' + suffix + ' ' + ((Number(m[2]) || 1) + 1) + ')' : routine.name + ' (' + suffix + ')'
return copy
}
+90
View File
@@ -0,0 +1,90 @@
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')
})
})
describe('copyRoutine of a copy', () => {
it('numbers the copies instead of stacking suffixes', () => {
const first = copyRoutine({ id: 'r', name: 'Push', ex: [] })
expect(first.name).toBe('Push (Copy)')
const second = copyRoutine(first)
expect(second.name).toBe('Push (Copy 2)')
expect(copyRoutine(second).name).toBe('Push (Copy 3)')
expect(copyRoutine({ id: 'r', name: 'Push (Kopie)', ex: [] }, 'Kopie').name).toBe('Push (Kopie 2)')
})
})
+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()
})
})
+7 -4
View File
@@ -3,8 +3,8 @@
// to identical entries, or the two paths drift apart the first time a prescription rule changes.
// Imports both history.js and progression.js (which itself imports history.js); nothing in
// either imports this file, so there is no cycle.
import { buildSets, applyIntensifierPlan } from './history.js'
import { nextPrescription, applyPrescription, defaultIncrement } from './progression.js'
import { buildSets, applyIntensifierPlan, modeOf } from './history.js'
import { nextPrescription, applyPrescription, defaultIncrement, weightIncrement } from './progression.js'
export function buildSessionEntries(st, r) {
// The prescription is applied as the session is built, so you walk up to the bar with the
@@ -13,8 +13,11 @@ export function buildSessionEntries(st, r) {
const excluded = r?.excludeFromProgression === true
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)
// The warm-up ramp and the prescription snap to the exercise's own increment (1.25 kg
// plates exist), not the unit default; a timed exercise's `inc` is seconds, so it keeps the
// default for its optional load.
const step = modeOf(cfg) === 'reps' ? weightIncrement(cfg, st.unit) : defaultIncrement(cfg.id, st.unit)
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 }
+23
View File
@@ -0,0 +1,23 @@
import { describe, it, expect } from 'vitest'
import { buildSessionEntries } from './session-start.js'
import { isWarmupRow } from './workout-model.js'
// The session builder used by the live start and by "log a past workout".
describe('buildSessionEntries', () => {
const st = { unit: 'kg', workouts: [], exWeights: {}, routines: [] }
it('ramps the warm-ups on the exercise’s own increment, not the unit default', () => {
const r = { id: 'r', prog: 'off', ex: [{ id: '0025', sets: 3, reps: 5, weight: 60, inc: 1.25, warmupSets: 2 }] }
const { entries } = buildSessionEntries(st, r)
const warm = entries[0].sets.filter(isWarmupRow).map(s => s.w)
expect(warm).toHaveLength(2)
for (const w of warm) expect(Math.round(w / 1.25 * 1000) / 1000 % 1).toBe(0) // a multiple of 1.25
expect(entries[0].sets.filter(s => !isWarmupRow(s)).every(s => s.w === 60)).toBe(true)
})
it('keeps the unit default for timed exercises, whose inc is seconds', () => {
const r = { id: 'r', prog: 'off', ex: [{ id: '0025', mode: 'time', sets: 2, sec: 30, inc: 10, weight: 0 }] }
const { entries } = buildSessionEntries(st, r)
expect(entries[0].sets.every(s => s.sec === 30)).toBe(true)
})
})
+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)
})
})
+54
View File
@@ -0,0 +1,54 @@
// Converting a profile between kg and lb. Until now the unit switch only relabelled the numbers
// (60 kg became "60 lb", issue #22); this walks every stored weight once. Rounded to what a gym
// can load: lb to the nearest 0.5, kg to the nearest 0.25 — enough that a value converted there
// and back lands where it started for any plate-loadable number.
const LB_PER_KG = 2.2046226218
export function convertWeight(value, from, to) {
if (from === to || value == null || value === '' || !Number.isFinite(Number(value))) return value
const v = Number(value)
if (to === 'lb') return Math.round(v * LB_PER_KG * 2) / 2
return Math.round(v / LB_PER_KG * 4) / 4
}
const convSet = (set, from, to) => {
if (!set || typeof set !== 'object') return set
const out = { ...set }
if (out.w != null) out.w = convertWeight(out.w, from, to)
if (Array.isArray(out.drops)) out.drops = out.drops.map(d => ({ ...d, w: convertWeight(d.w, from, to) }))
return out
}
const convTarget = (cfg, from, to) => {
if (!cfg || typeof cfg !== 'object') return cfg
const out = { ...cfg }
if (out.weight != null) out.weight = convertWeight(out.weight, from, to)
// A per-exercise increment is a load too — 2.5 kg is 5 lb, not 2.5 lb.
if (out.inc > 0 && (out.mode == null || out.mode === 'reps')) out.inc = convertWeight(out.inc, from, to)
if (Array.isArray(out.warmup)) out.warmup = out.warmup.map(w => (w && w.weight != null ? { ...w, weight: convertWeight(w.weight, from, to) } : w))
return out
}
const convEntry = (e, from, to) => {
if (!e || typeof e !== 'object') return e
return {
...e,
...(e.topW != null ? { topW: convertWeight(e.topW, from, to) } : {}),
...(e.target ? { target: convTarget(e.target, from, to) } : {}),
...(Array.isArray(e.sets) ? { sets: e.sets.map(s => convSet(s, from, to)) } : {}),
}
}
/** A new state object with every weight expressed in `to`, and `unit` set to it. */
export function convertStateUnit(S, to) {
const from = S.unit || 'kg'
if (from === to) return S
const c = v => convertWeight(v, from, to)
const out = { ...S, unit: to }
if (Array.isArray(S.bodyweight)) out.bodyweight = S.bodyweight.map(b => ({ ...b, w: c(b.w) }))
if (S.targetW != null) out.targetW = c(S.targetW)
if (S.exWeights) out.exWeights = Object.fromEntries(Object.entries(S.exWeights).map(([k, v]) => [k, v && typeof v === 'object' ? { ...v, w: c(v.w) } : c(v)]))
if (S.barWeights) out.barWeights = Object.fromEntries(Object.entries(S.barWeights).map(([k, v]) => [k, c(v)]))
if (Array.isArray(S.routines)) out.routines = S.routines.map(r => ({ ...r, ex: (r.ex || []).map(cfg => convTarget(cfg, from, to)) }))
if (Array.isArray(S.workouts)) out.workouts = S.workouts.map(w => ({ ...w, entries: (w.entries || []).map(e => convEntry(e, from, to)) }))
if (S.active) out.active = { ...S.active, entries: (S.active.entries || []).map(e => convEntry(e, from, to)) }
return out
}
+52
View File
@@ -0,0 +1,52 @@
import { describe, it, expect } from 'vitest'
import { convertWeight, convertStateUnit } from './units.js'
describe('convertWeight', () => {
it('rounds lb to a half and kg to a quarter', () => {
expect(convertWeight(60, 'kg', 'lb')).toBe(132.5)
expect(convertWeight(135, 'lb', 'kg')).toBe(61.25)
expect(convertWeight(2.5, 'kg', 'lb')).toBe(5.5)
})
it('leaves the value alone for the same unit, nothing, or garbage', () => {
expect(convertWeight(60, 'kg', 'kg')).toBe(60)
expect(convertWeight(null, 'kg', 'lb')).toBe(null)
expect(convertWeight('', 'kg', 'lb')).toBe('')
expect(convertWeight('abc', 'kg', 'lb')).toBe('abc')
})
it('round-trips plate-loadable numbers', () => {
for (const kg of [20, 42.5, 60, 100, 142.5]) {
expect(convertWeight(convertWeight(kg, 'kg', 'lb'), 'lb', 'kg')).toBe(kg)
}
})
})
describe('convertStateUnit', () => {
const S = {
unit: 'kg', targetW: 80, bodyweight: [{ d: '2026-01-01', w: 82.4, t: 1 }],
exWeights: { '0025': { w: 80, d: '2026-01-01' }, legacy: 100 }, barWeights: { '0025': 20 },
routines: [{ id: 'r', ex: [{ id: '0025', sets: 3, reps: 5, weight: 80, inc: 2.5, warmup: [{ weight: 40, reps: 8 }] }, { id: 'plank', mode: 'time', sec: 30, inc: 5 }] }],
workouts: [{ id: 'w', entries: [{ id: '0025', topW: 80, target: { weight: 80 }, sets: [{ w: 80, r: 5, done: true, drops: [{ w: 60, r: 5 }] }] }] }],
active: { id: 'a', entries: [{ id: '0025', sets: [{ w: 82.5, r: 5, done: false }] }] },
workoutView: 'list',
}
it('converts every stored weight and keeps everything else', () => {
const out = convertStateUnit(S, 'lb')
expect(out.unit).toBe('lb')
expect(out.targetW).toBe(176.5)
expect(out.bodyweight[0]).toEqual({ d: '2026-01-01', w: 181.5, t: 1 })
expect(out.exWeights['0025'].w).toBe(176.5)
expect(out.exWeights.legacy).toBe(220.5)
expect(out.barWeights['0025']).toBe(44)
expect(out.routines[0].ex[0]).toMatchObject({ weight: 176.5, inc: 5.5, warmup: [{ weight: 88, reps: 8 }] })
expect(out.routines[0].ex[1]).toEqual({ id: 'plank', mode: 'time', sec: 30, inc: 5 }) // seconds stay seconds
expect(out.workouts[0].entries[0]).toMatchObject({ topW: 176.5, target: { weight: 176.5 } })
expect(out.workouts[0].entries[0].sets[0]).toMatchObject({ w: 176.5, done: true, drops: [{ w: 132.5, r: 5 }] })
expect(out.active.entries[0].sets[0].w).toBe(182)
expect(out.workoutView).toBe('list')
expect(S.unit).toBe('kg') // the input is not mutated
expect(S.workouts[0].entries[0].sets[0].w).toBe(80)
})
it('is a no-op for the unit already in use', () => {
expect(convertStateUnit(S, 'kg')).toBe(S)
})
})
+148
View File
@@ -0,0 +1,148 @@
// Update check — compares the installed version (__APP_VERSION__) against
// the latest release tag on GitLab and optionally downloads + installs the APK.
//
// The GitLab releases API is public for this project, so no token is needed.
// On Android (Capacitor), the APK asset is downloaded to the cache directory
// and handed to the system installer via a content:// URI.
import { MOBILE } from './mobile.js'
const GITLAB_PROJECT_ID = 'DuarteSantos8%2Fopengym'
const RELEASES_URL = `https://gitlab.com/api/v4/projects/${GITLAB_PROJECT_ID}/releases`
/**
* Compares two semver strings (e.g. "1.2.11" vs "1.3.0").
* Returns 1 if a > b, -1 if a < b, 0 if equal.
*/
function compareSemver(a, b) {
const pa = a.replace(/^v/, '').split('.').map(Number)
const pb = b.replace(/^v/, '').split('.').map(Number)
for (let i = 0; i < 3; i++) {
const diff = (pa[i] || 0) - (pb[i] || 0)
if (diff > 0) return 1
if (diff < 0) return -1
}
return 0
}
/**
* Checks the GitLab releases API for a newer version.
* Returns { hasUpdate, latestVersion, apkUrl, hashUrl } or throws on network failure.
* - hasUpdate: true if the latest release tag is newer than the running build
* - latestVersion: the semver string of the latest release (without "v" prefix)
* - apkUrl: direct download URL of the first .apk asset, or null
* - hashUrl: direct download URL of the .apk.sha256 hash file, or null
*/
// One request per app session: Settings is opened often, gitlab.com does not need to hear
// about it every time. The promise is cached, a failure is not.
let cached = null
export function resetUpdateCheck() { cached = null }
export async function checkForUpdate() {
if (!cached) cached = fetchLatest().catch(e => { cached = null; throw e })
return cached
}
async function fetchLatest() {
const res = await fetch(RELEASES_URL + '?per_page=1')
if (!res.ok) throw new Error(`GitLab API ${res.status}`)
const releases = await res.json()
if (!releases.length) return { hasUpdate: false, latestVersion: __APP_VERSION__, apkUrl: null, hashUrl: null }
const latest = releases[0]
const latestVersion = latest.tag_name.replace(/^v/, '')
const hasUpdate = compareSemver(latestVersion, __APP_VERSION__) > 0
// Find the APK asset among the release links (generic package links) or assets.sources
let apkUrl = null
let hashUrl = null
if (latest.assets?.links?.length) {
const apkLink = latest.assets.links.find(l => /\.apk$/i.test(l.url) || /\.apk$/i.test(l.direct_asset_url))
if (apkLink) apkUrl = apkLink.direct_asset_url || apkLink.url
// Look for a matching .sha256 hash file
const hashLink = latest.assets.links.find(l => /\.apk\.sha256$/i.test(l.url) || /\.apk\.sha256$/i.test(l.direct_asset_url) || /sha256/i.test(l.name))
if (hashLink) hashUrl = hashLink.direct_asset_url || hashLink.url
}
return { hasUpdate, latestVersion, apkUrl, hashUrl }
}
/**
* Computes the SHA-256 hash of an ArrayBuffer using the Web Crypto API.
* Returns the hex-encoded digest string.
*/
export async function sha256(buffer) {
const hash = await crypto.subtle.digest('SHA-256', buffer)
return Array.from(new Uint8Array(hash)).map(b => b.toString(16).padStart(2, '0')).join('')
}
/**
* Downloads the APK from `url`, verifies its SHA-256 hash against `expectedHash`
* (if provided), and triggers the Android installer.
* Only works on the MOBILE (Capacitor) build with Android.
*
* @param {string} url - Direct download URL for the APK
* @param {string|null} expectedHash - Expected SHA-256 hex string (from .sha256 asset), or null to skip verification
* @param {function|null} onProgress - Called with (received, total) bytes during download, or null
*/
export async function downloadAndInstall(url, expectedHash = null, onProgress = null) {
if (!MOBILE) {
// On web, just open the release page
window.open('https://gitlab.com/DuarteSantos8/opengym/-/releases', '_blank', 'noopener')
return
}
const { Filesystem, Directory } = await import('@capacitor/filesystem')
// Download with progress tracking via ReadableStream
const res = await fetch(url)
if (!res.ok) throw new Error(`Download failed: ${res.status}`)
const total = parseInt(res.headers.get('content-length') || '0', 10)
const reader = res.body.getReader()
const chunks = []
let received = 0
for (;;) {
const { done, value } = await reader.read()
if (done) break
chunks.push(value)
received += value.length
if (onProgress) onProgress(received, total)
}
// Reassemble into a single blob
const blob = new Blob(chunks)
// Size check: an APK should be at least 100 KB
if (blob.size < 100_000) {
throw new Error('Downloaded file is too small to be a valid APK (' + blob.size + ' bytes)')
}
// SHA-256 integrity check
if (expectedHash) {
const buffer = await blob.arrayBuffer()
const actualHash = await sha256(buffer)
if (actualHash !== expectedHash.toLowerCase().trim()) {
throw new Error('SHA-256 mismatch — download may be corrupted or tampered with')
}
}
// Convert blob to base64
const base64 = await new Promise((resolve, reject) => {
const reader = new FileReader()
reader.onload = () => resolve(reader.result.split(',')[1])
reader.onerror = reject
reader.readAsDataURL(blob)
})
const fileName = 'opengym-update.apk'
await Filesystem.writeFile({
path: fileName,
directory: Directory.Cache,
data: base64,
})
// Use the local InstallPlugin to trigger the Android package installer
const { registerPlugin } = await import('@capacitor/core')
const Install = registerPlugin('Install')
await Install.installApk({ fileName })
}
+282
View File
@@ -0,0 +1,282 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { checkForUpdate, sha256, resetUpdateCheck } from './update.js'
// __APP_VERSION__ is defined at build time by vite.config.js (reads package.json).
// In the test environment vitest applies the same define, so it's available here.
describe('sha256', () => {
it('computes the correct hash for a known input', async () => {
const input = new TextEncoder().encode('hello world')
const hash = await sha256(input.buffer)
// Well-known SHA-256 of "hello world"
expect(hash).toBe('b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9')
})
it('computes a different hash for different input', async () => {
const a = await sha256(new TextEncoder().encode('aaa').buffer)
const b = await sha256(new TextEncoder().encode('bbb').buffer)
expect(a).not.toBe(b)
})
it('returns a 64-character hex string', async () => {
const hash = await sha256(new TextEncoder().encode('test').buffer)
expect(hash).toHaveLength(64)
expect(hash).toMatch(/^[0-9a-f]{64}$/)
})
})
describe('checkForUpdate', () => {
let originalFetch
beforeEach(() => { originalFetch = globalThis.fetch; resetUpdateCheck() })
afterEach(() => { globalThis.fetch = originalFetch })
function mockFetch(body, status = 200) {
globalThis.fetch = vi.fn(() => Promise.resolve({
ok: status >= 200 && status < 300,
status,
json: () => Promise.resolve(body),
}))
}
it('reports no update when the latest release matches the current version', async () => {
mockFetch([{ tag_name: 'v' + __APP_VERSION__, assets: { links: [] } }])
const result = await checkForUpdate()
expect(result.hasUpdate).toBe(false)
expect(result.latestVersion).toBe(__APP_VERSION__)
expect(result.apkUrl).toBe(null)
expect(result.hashUrl).toBe(null)
})
it('reports no update when the latest release is older than current', async () => {
mockFetch([{ tag_name: 'v0.0.1', assets: { links: [] } }])
const result = await checkForUpdate()
expect(result.hasUpdate).toBe(false)
expect(result.latestVersion).toBe('0.0.1')
})
it('reports an update when the latest release is newer', async () => {
mockFetch([{ tag_name: 'v99.0.0', assets: { links: [] } }])
const result = await checkForUpdate()
expect(result.hasUpdate).toBe(true)
expect(result.latestVersion).toBe('99.0.0')
})
it('strips the v prefix from the tag name', async () => {
mockFetch([{ tag_name: 'v99.1.2', assets: { links: [] } }])
const result = await checkForUpdate()
expect(result.latestVersion).toBe('99.1.2')
})
it('handles tag names without a v prefix', async () => {
mockFetch([{ tag_name: '99.0.0', assets: { links: [] } }])
const result = await checkForUpdate()
expect(result.hasUpdate).toBe(true)
expect(result.latestVersion).toBe('99.0.0')
})
it('finds the APK download URL from release asset links', async () => {
const apkUrl = 'https://gitlab.com/project/-/releases/v2.0.0/downloads/opengym.apk'
mockFetch([{
tag_name: 'v99.0.0',
assets: { links: [{ url: apkUrl, direct_asset_url: apkUrl }] }
}])
const result = await checkForUpdate()
expect(result.apkUrl).toBe(apkUrl)
})
it('prefers direct_asset_url over url for APK links', async () => {
mockFetch([{
tag_name: 'v99.0.0',
assets: {
links: [{
url: 'https://redirect.example/opengym.apk',
direct_asset_url: 'https://direct.example/opengym.apk'
}]
}
}])
const result = await checkForUpdate()
expect(result.apkUrl).toBe('https://direct.example/opengym.apk')
})
it('returns null apkUrl when no .apk link exists', async () => {
mockFetch([{
tag_name: 'v99.0.0',
assets: { links: [{ url: 'https://example.com/changelog.md', direct_asset_url: 'https://example.com/changelog.md' }] }
}])
const result = await checkForUpdate()
expect(result.hasUpdate).toBe(true)
expect(result.apkUrl).toBe(null)
})
it('finds the .sha256 hash URL from release asset links', async () => {
const hashUrl = 'https://gitlab.com/project/-/releases/v2.0.0/downloads/opengym.apk.sha256'
mockFetch([{
tag_name: 'v99.0.0',
assets: {
links: [
{ url: 'https://example.com/opengym.apk', direct_asset_url: 'https://example.com/opengym.apk' },
{ url: hashUrl, direct_asset_url: hashUrl },
]
}
}])
const result = await checkForUpdate()
expect(result.hashUrl).toBe(hashUrl)
})
it('finds hash URL by link name containing sha256', async () => {
mockFetch([{
tag_name: 'v99.0.0',
assets: {
links: [
{ name: 'APK', url: 'https://example.com/opengym.apk', direct_asset_url: 'https://example.com/opengym.apk' },
{ name: 'SHA256 checksum', url: 'https://example.com/checksum.txt', direct_asset_url: 'https://example.com/checksum.txt' },
]
}
}])
const result = await checkForUpdate()
expect(result.hashUrl).toBe('https://example.com/checksum.txt')
})
// The exact JSON gitlab.com returns for GET /projects/85678327/releases?per_page=1 (v1.3.1,
// fetched 2026-09-05, description and commit trimmed). The CI publishes the APK and its
// checksum as generic-package links, and the checksum link is listed BEFORE the APK — the
// detection must not confuse the two.
const REAL_RELEASE = [
{
"tag_name": "v1.3.1",
"name": "openGym v1.3.1",
"assets": {
"count": 7,
"sources": [
{
"format": "zip",
"url": "https://gitlab.com/DuarteSantos8/opengym/-/archive/v1.3.1/opengym-v1.3.1.zip"
},
{
"format": "tar.gz",
"url": "https://gitlab.com/DuarteSantos8/opengym/-/archive/v1.3.1/opengym-v1.3.1.tar.gz"
},
{
"format": "tar.bz2",
"url": "https://gitlab.com/DuarteSantos8/opengym/-/archive/v1.3.1/opengym-v1.3.1.tar.bz2"
},
{
"format": "tar",
"url": "https://gitlab.com/DuarteSantos8/opengym/-/archive/v1.3.1/opengym-v1.3.1.tar"
}
],
"links": [
{
"id": 12790840,
"name": "Container images (api + web)",
"url": "https://gitlab.com/DuarteSantos8/opengym/container_registry",
"direct_asset_url": "https://gitlab.com/DuarteSantos8/opengym/container_registry",
"link_type": "image"
},
{
"id": 12790839,
"name": "openGym-1.3.1.apk.sha256 (checksum)",
"url": "https://gitlab.com/api/v4/projects/85678327/packages/generic/opengym-android/1.3.1/openGym-1.3.1.apk.sha256",
"direct_asset_url": "https://gitlab.com/api/v4/projects/85678327/packages/generic/opengym-android/1.3.1/openGym-1.3.1.apk.sha256",
"link_type": "other"
},
{
"id": 12790838,
"name": "openGym-1.3.1.apk (Android, sideload)",
"url": "https://gitlab.com/api/v4/projects/85678327/packages/generic/opengym-android/1.3.1/openGym-1.3.1.apk",
"direct_asset_url": "https://gitlab.com/api/v4/projects/85678327/packages/generic/opengym-android/1.3.1/openGym-1.3.1.apk",
"link_type": "package"
}
]
}
}
]
it('finds the APK and its checksum in a real gitlab.com release payload', async () => {
mockFetch(REAL_RELEASE)
const result = await checkForUpdate()
expect(result.latestVersion).toBe('1.3.1')
expect(result.apkUrl).toBe('https://gitlab.com/api/v4/projects/85678327/packages/generic/opengym-android/1.3.1/openGym-1.3.1.apk')
expect(result.hashUrl).toBe('https://gitlab.com/api/v4/projects/85678327/packages/generic/opengym-android/1.3.1/openGym-1.3.1.apk.sha256')
})
it('returns null hashUrl when no hash link exists', async () => {
mockFetch([{
tag_name: 'v99.0.0',
assets: { links: [{ url: 'https://example.com/opengym.apk', direct_asset_url: 'https://example.com/opengym.apk' }] }
}])
const result = await checkForUpdate()
expect(result.hashUrl).toBe(null)
})
it('returns no update when the releases array is empty', async () => {
mockFetch([])
const result = await checkForUpdate()
expect(result.hasUpdate).toBe(false)
expect(result.latestVersion).toBe(__APP_VERSION__)
expect(result.hashUrl).toBe(null)
})
it('throws when the API responds with an error status', async () => {
mockFetch(null, 500)
await expect(checkForUpdate()).rejects.toThrow('GitLab API 500')
})
it('throws on network failure', async () => {
globalThis.fetch = vi.fn(() => Promise.reject(new Error('Network error')))
await expect(checkForUpdate()).rejects.toThrow('Network error')
})
})
describe('semver comparison (via checkForUpdate behavior)', () => {
let originalFetch
beforeEach(() => { originalFetch = globalThis.fetch; resetUpdateCheck() })
afterEach(() => { globalThis.fetch = originalFetch })
function mockRelease(tag) {
globalThis.fetch = vi.fn(() => Promise.resolve({
ok: true, status: 200,
json: () => Promise.resolve([{ tag_name: tag, assets: { links: [] } }]),
}))
}
// Versions are derived from the running __APP_VERSION__ so the suite never breaks
// when package.json bumps. bump(2, +1) raises the patch; bump(0, +1) raises the major.
const [MAJ, MIN, PATCH] = __APP_VERSION__.split('.').map(Number)
const bump = (idx, by) => {
const parts = [MAJ, MIN, PATCH]
parts[idx] += by
return 'v' + parts.join('.')
}
it('detects a patch bump as an update', async () => {
mockRelease(bump(2, 1))
expect((await checkForUpdate()).hasUpdate).toBe(true)
})
it('detects a minor bump as an update', async () => {
mockRelease(bump(1, 1))
expect((await checkForUpdate()).hasUpdate).toBe(true)
})
it('detects a major bump as an update', async () => {
mockRelease(bump(0, 1))
expect((await checkForUpdate()).hasUpdate).toBe(true)
})
it('does not flag an older patch as an update', async () => {
// One patch below current (current patch is always >= our test floor)
mockRelease('v' + [MAJ, MIN, Math.max(0, PATCH - 1)].join('.'))
// Only meaningful when we could actually go lower; when patch is 0 this equals current,
// which correctly reports no update either way.
expect((await checkForUpdate()).hasUpdate).toBe(false)
})
it('does not flag an older minor as an update', async () => {
// A version guaranteed lower than any 1.x+ release: same major, minor 0, patch 0,
// minus one on the minor when possible.
mockRelease('v' + [MAJ, Math.max(0, MIN - 1), 0].join('.'))
expect((await checkForUpdate()).hasUpdate).toBe(false)
})
})
+15
View File
@@ -0,0 +1,15 @@
// Which optional control groups the workout screen shows besides the sets themselves
// (Settings → During a workout → Workout controls). The lean default keeps the sets and one
// "more" button per exercise; each flag brings one of the old always-visible groups back.
// Lives in its own module so views can read it without the store — the store's DEF only
// references it.
export const WC_DEFAULT = Object.freeze({
steppers: true, // +/- buttons on every weight/reps/effort field
setShortcuts: false, // "+ Drop" / "+ Burst" chips on every set and the warm-up/remove/add row
pairButtons: false, // "Make superset with previous/next" in the exercise header
exerciseButtons: false, // Move up/down, Swap, Remove exercise below the exercise
})
export function workoutControls(S) {
return { ...WC_DEFAULT, ...((S && S.wc) || {}) }
}
+106 -5
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',
@@ -86,6 +93,12 @@ export default {
'Search {0} exercises…': '{0} Übungen durchsuchen…',
'Chosen': 'Gewählt',
'Nothing chosen yet — add exercises and they’ll show up here.': 'Noch nichts gewählt — füge Übungen hinzu, dann erscheinen sie hier.',
'Add to favourites': 'Zu Favoriten hinzufügen',
'Remove from favourites': 'Aus Favoriten entfernen',
'Added to favourites': 'Zu Favoriten hinzugefügt',
'Removed from favourites': 'Aus Favoriten entfernt',
'Favourites': 'Favoriten',
'No favourites here — tap the star on an exercise to add it.': 'Keine Favoriten hier — tippe bei einer Übung auf den Stern.',
'No match': 'Kein Treffer',
'Show more': 'Mehr anzeigen',
'Intervals': 'Intervalle',
@@ -210,8 +223,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 +265,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 +273,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',
@@ -306,7 +333,6 @@ export default {
'Rest timer': 'Pausen-Timer',
'Sounds': 'Töne',
'Flash screen when timer ends': 'Bildschirm bei Timer-Ende blinken lassen',
'Note: switching units only changes the label — logged numbers are not converted.': 'Hinweis: Der Einheitenwechsel ändert nur die Beschriftung — eingetragene Zahlen werden nicht umgerechnet.',
'Data': 'Daten',
'Export backup (JSON)': 'Backup exportieren (JSON)',
'Import backup': 'Backup importieren',
@@ -412,6 +438,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',
@@ -551,6 +583,11 @@ export default {
// --- v1.2.2: timed sets, progression, estimated 1RM (#16 #17 #18) ---
'Top set': 'Bester Satz',
'Est. 1RM': 'gesch. 1RM',
'No sessions logged yet': 'Noch keine Einheiten eingetragen',
'{0} session': '{0} Einheit',
'{0} sessions': '{0} Einheiten',
'Exercise history': 'Übungsverlauf',
'Last {0} sessions': 'Letzte {0} Einheiten',
'Estimated 1RM': 'Geschätztes 1RM',
'Estimated 1RM per workout': 'Geschätztes 1RM pro Training',
'Best estimate from {0} on {1} — an estimate, not a tested max.': 'Beste Schätzung aus {0} am {1} — eine Schätzung, kein getesteter Max-Wert.',
@@ -617,6 +654,11 @@ export default {
'Two more reps': 'Zwei Wiederholungen übrig',
'Three more reps': 'Drei Wiederholungen übrig',
'Easy — warm-up territory': 'Locker — Aufwärmbereich',
'Maybe half a rep left': 'Vielleicht noch eine halbe Wiederholung',
'How hard was that set?': 'Wie schwer war der Satz?',
'Tap how many reps you had left, or type an exact {0}.': 'Tippe, wie viele Wiederholungen du übrig hattest, oder gib einen genauen {0}-Wert ein.',
'Exact {0}': 'Genauer {0}-Wert',
'Clear rating': 'Bewertung löschen',
'RIR counts the reps you left; RPE reads the same effort off a 10-point scale — so RPE ≈ 10 − RIR. Pick the one you already think in.': 'RIR zählt die Wiederholungen, die du übrig lässt; RPE liest dieselbe Anstrengung auf einer 10er-Skala ab — also RPE ≈ 10 − RIR. Nimm die Skala, in der du ohnehin denkst.',
'The highlighted row is where most working sets land. Sets you have already logged keep their own scale, and nothing else reads the value — progression and estimated 1RM are unaffected.': 'Die hervorgehobene Zeile ist der Bereich, in dem die meisten Arbeitssätze landen. Bereits protokollierte Sätze behalten ihre eigene Skala, und sonst liest den Wert nichts — Progression und geschätztes 1RM bleiben unberührt.',
// --- effort in the stats ---
@@ -1099,4 +1141,63 @@ 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.',
'Add note': 'Notiz hinzufügen',
'Edit note': 'Notiz bearbeiten',
'Progression settings': 'Progressions-Einstellungen',
'Set {0}': 'Satz {0}',
'Drop set': 'Drop-Satz',
'Rest-pause burst': 'Rest-Pause-Burst',
'Remove this set': 'Diesen Satz entfernen',
'Workout controls': 'Bedienelemente im Training',
'Weight and reps buttons': 'Plus/Minus-Tasten für Gewicht und Wdh.',
'Off: tap the number and type it': 'Aus: Zahl antippen und eintippen',
'Drop and burst shortcuts on every set': 'Drop/Burst-Kürzel an jedem Satz',
'Superset buttons in the exercise header': 'Superset-Tasten im Übungskopf',
'Move, swap and remove buttons below the exercise': 'Verschieben/Tauschen/Entfernen-Tasten unter der Übung',
'Everything hidden here stays one tap away: the ⋯ button of an exercise and the number of a set.': 'Alles, was hier ausgeblendet ist, bleibt einen Tipp entfernt: die ⋯-Taste einer Übung und die Nummer eines Satzes.',
'Convert to {0}?': 'In {0} umrechnen?',
'Every stored weight — logged sets, working weights, routine targets, body weight, bar weights — is in {0}. Convert the numbers, or keep them and only change the label?': 'Jedes gespeicherte Gewicht — eingetragene Sätze, Arbeitsgewichte, Routinenziele, Körpergewicht, Stangengewichte — steht in {0}. Zahlen umrechnen, oder behalten und nur die Beschriftung ändern?',
'Convert the numbers': 'Zahlen umrechnen',
'Keep the numbers, change the label': 'Zahlen behalten, nur Beschriftung ändern',
'Switching the unit offers to convert every stored weight.': 'Beim Einheitenwechsel wird angeboten, alle gespeicherten Gewichte umzurechnen.',
'Update to {0}?': 'Auf {0} aktualisieren?',
'The latest version will be downloaded and the installer will open.': 'Die neueste Version wird heruntergeladen und die Installation gestartet.',
'Download & Install': 'Herunterladen & Installieren',
'Update failed: {0}': 'Update fehlgeschlagen: {0}',
'openGym v{0} available': 'openGym v{0} verfügbar',
'Starting download…': 'Download wird gestartet…',
'Downloading update…': 'Update wird heruntergeladen…',
'{0} %': '{0} %',
'{0} MB': '{0} MB',
'Checksum not available — not installing': 'Prüfsumme nicht verfügbar — Installation abgebrochen',
}
+106 -5
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',
@@ -82,6 +89,12 @@ export default {
'Search {0} exercises…': 'Buscar entre {0} ejercicios…',
'Chosen': 'Elegidos',
'Nothing chosen yet — add exercises and they’ll show up here.': 'Nada elegido aún — añade ejercicios y aparecerán aquí.',
'Add to favourites': 'Añadir a favoritos',
'Remove from favourites': 'Quitar de favoritos',
'Added to favourites': 'Añadido a favoritos',
'Removed from favourites': 'Quitado de favoritos',
'Favourites': 'Favoritos',
'No favourites here — tap the star on an exercise to add it.': 'Sin favoritos aquí — toca la estrella de un ejercicio para añadirlo.',
'No match': 'Sin resultados',
'Show more': 'Mostrar más',
'Intervals': 'Intervalos',
@@ -202,8 +215,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 +255,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 +262,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',
@@ -292,7 +319,6 @@ export default {
'Rest timer': 'Temporizador de descanso',
'Sounds': 'Sonidos',
'Flash screen when timer ends': 'Hacer parpadear la pantalla al finalizar el temporizador',
'Note: switching units only changes the label — logged numbers are not converted.': 'Nota: cambiar la unidad solo cambia la etiqueta — los números registrados no se convierten.',
'Data': 'Datos',
'Export backup (JSON)': 'Exportar copia (JSON)',
'Import backup': 'Importar copia',
@@ -394,6 +420,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',
@@ -533,6 +565,11 @@ export default {
// --- v1.2.2: timed sets, progression, estimated 1RM (#16 #17 #18) ---
'Top set': 'Mejor serie',
'Est. 1RM': '1RM est.',
'No sessions logged yet': 'Aún no hay sesiones registradas',
'{0} session': '{0} sesión',
'{0} sessions': '{0} sesiones',
'Exercise history': 'Historial del ejercicio',
'Last {0} sessions': 'Últimas {0} sesiones',
'Estimated 1RM': '1RM estimado',
'Estimated 1RM per workout': '1RM estimado por entrenamiento',
'Best estimate from {0} on {1} — an estimate, not a tested max.': 'Mejor estimación a partir de {0} el {1}: una estimación, no un máximo probado.',
@@ -599,6 +636,11 @@ export default {
'Two more reps': 'Dos repeticiones más',
'Three more reps': 'Tres repeticiones más',
'Easy — warm-up territory': 'Fácil — zona de calentamiento',
'Maybe half a rep left': 'Quizá media repetición más',
'How hard was that set?': '¿Qué tan dura fue la serie?',
'Tap how many reps you had left, or type an exact {0}.': 'Toca cuántas repeticiones te quedaban, o escribe un {0} exacto.',
'Exact {0}': '{0} exacto',
'Clear rating': 'Borrar valoración',
'RIR counts the reps you left; RPE reads the same effort off a 10-point scale — so RPE ≈ 10 − RIR. Pick the one you already think in.': 'El RIR cuenta las repeticiones que dejas; el RPE lee ese mismo esfuerzo en una escala de 10 — así que RPE ≈ 10 − RIR. Elige la que ya usas para pensar.',
'The highlighted row is where most working sets land. Sets you have already logged keep their own scale, and nothing else reads the value — progression and estimated 1RM are unaffected.': 'La fila resaltada es donde cae la mayoría de las series efectivas. Las series ya registradas conservan su escala, y nada más lee el valor: la progresión y el 1RM estimado no cambian.',
// --- effort in the stats ---
@@ -1080,4 +1122,63 @@ 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.',
'Add note': 'Añadir nota',
'Edit note': 'Editar nota',
'Progression settings': 'Ajustes de progresión',
'Set {0}': 'Serie {0}',
'Drop set': 'Serie descendente',
'Rest-pause burst': 'Ráfaga rest-pause',
'Remove this set': 'Quitar esta serie',
'Workout controls': 'Controles del entrenamiento',
'Weight and reps buttons': 'Botones +/− de peso y repeticiones',
'Off: tap the number and type it': 'Desactivado: toca el número y escríbelo',
'Drop and burst shortcuts on every set': 'Atajos de drop y ráfaga en cada serie',
'Superset buttons in the exercise header': 'Botones de superserie en la cabecera del ejercicio',
'Move, swap and remove buttons below the exercise': 'Botones mover, cambiar y quitar debajo del ejercicio',
'Everything hidden here stays one tap away: the ⋯ button of an exercise and the number of a set.': 'Todo lo que ocultes aquí sigue a un toque: el botón ⋯ de un ejercicio y el número de una serie.',
'Convert to {0}?': '¿Convertir a {0}?',
'Every stored weight — logged sets, working weights, routine targets, body weight, bar weights — is in {0}. Convert the numbers, or keep them and only change the label?': 'Todos los pesos guardados — series registradas, pesos de trabajo, objetivos de rutina, peso corporal, pesos de barra — están en {0}. ¿Convertir los números o mantenerlos y cambiar solo la etiqueta?',
'Convert the numbers': 'Convertir los números',
'Keep the numbers, change the label': 'Mantener los números, cambiar la etiqueta',
'Switching the unit offers to convert every stored weight.': 'Al cambiar la unidad se ofrece convertir todos los pesos guardados.',
'Update to {0}?': '¿Actualizar a {0}?',
'The latest version will be downloaded and the installer will open.': 'Se descargará la última versión y se abrirá el instalador.',
'Download & Install': 'Descargar e instalar',
'Update failed: {0}': 'Error en la actualización: {0}',
'openGym v{0} available': 'openGym v{0} disponible',
'Starting download…': 'Iniciando descarga…',
'Downloading update…': 'Descargando actualización…',
'{0} %': '{0} %',
'{0} MB': '{0} MB',
'Checksum not available — not installing': 'Suma de verificación no disponible — no se instala',
}
+106 -5
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',
@@ -82,6 +89,12 @@ export default {
'Search {0} exercises…': 'Rechercher parmi {0} exercices…',
'Chosen': 'Choisis',
'Nothing chosen yet — add exercises and they’ll show up here.': 'Rien de choisi — ajoute des exercices et ils apparaîtront ici.',
'Add to favourites': 'Ajouter aux favoris',
'Remove from favourites': 'Retirer des favoris',
'Added to favourites': 'Ajouté aux favoris',
'Removed from favourites': 'Retiré des favoris',
'Favourites': 'Favoris',
'No favourites here — tap the star on an exercise to add it.': 'Aucun favori ici — touche l’étoile d’un exercice pour l’ajouter.',
'No match': 'Aucun résultat',
'Show more': 'Afficher plus',
'Intervals': 'Intervalles',
@@ -202,8 +215,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 +255,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 +262,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',
@@ -292,7 +319,6 @@ export default {
'Rest timer': 'Minuteur de repos',
'Sounds': 'Sons',
'Flash screen when timer ends': 'Faire clignoter l’écran à la fin du minuteur',
'Note: switching units only changes the label — logged numbers are not converted.': 'Note : changer d’unité ne change que l’étiquette — les nombres enregistrés ne sont pas convertis.',
'Data': 'Données',
'Export backup (JSON)': 'Exporter une sauvegarde (JSON)',
'Import backup': 'Importer une sauvegarde',
@@ -394,6 +420,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',
@@ -533,6 +565,11 @@ export default {
// --- v1.2.2: timed sets, progression, estimated 1RM (#16 #17 #18) ---
'Top set': 'Meilleure série',
'Est. 1RM': '1RM est.',
'No sessions logged yet': 'Aucune séance enregistrée pour l’instant',
'{0} session': '{0} séance',
'{0} sessions': '{0} séances',
'Exercise history': 'Historique de l’exercice',
'Last {0} sessions': '{0} dernières séances',
'Estimated 1RM': '1RM estimé',
'Estimated 1RM per workout': '1RM estimé par séance',
'Best estimate from {0} on {1} — an estimate, not a tested max.': 'Meilleure estimation d’après {0} le {1} — une estimation, pas un max testé.',
@@ -599,6 +636,11 @@ export default {
'Two more reps': 'Encore deux répétitions',
'Three more reps': 'Encore trois répétitions',
'Easy — warm-up territory': 'Facile — zone d’échauffement',
'Maybe half a rep left': 'Peut-être une demi-répétition en réserve',
'How hard was that set?': 'Cette série, c’était dur comment ?',
'Tap how many reps you had left, or type an exact {0}.': 'Touche combien de répétitions il te restait, ou saisis un {0} précis.',
'Exact {0}': '{0} précis',
'Clear rating': 'Effacer l’évaluation',
'RIR counts the reps you left; RPE reads the same effort off a 10-point scale — so RPE ≈ 10 − RIR. Pick the one you already think in.': 'Le RIR compte les répétitions qu’il te restait ; le RPE lit le même effort sur une échelle de 10 — donc RPE ≈ 10 − RIR. Prends celle dans laquelle tu penses déjà.',
'The highlighted row is where most working sets land. Sets you have already logged keep their own scale, and nothing else reads the value — progression and estimated 1RM are unaffected.': 'La ligne mise en avant est celle où tombent la plupart des séries de travail. Les séries déjà enregistrées gardent leur échelle, et rien d’autre ne lit la valeur — la progression et le 1RM estimé ne changent pas.',
// --- effort in the stats ---
@@ -1080,4 +1122,63 @@ 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.',
'Add note': 'Ajouter une note',
'Edit note': 'Modifier la note',
'Progression settings': 'Réglages de progression',
'Set {0}': 'Série {0}',
'Drop set': 'Série dégressive',
'Rest-pause burst': 'Rafale rest-pause',
'Remove this set': 'Supprimer cette série',
'Workout controls': 'Commandes pendant la séance',
'Weight and reps buttons': 'Boutons +/− poids et répétitions',
'Off: tap the number and type it': 'Désactivé : touchez le nombre et saisissez-le',
'Drop and burst shortcuts on every set': 'Raccourcis drop et rafale sur chaque série',
'Superset buttons in the exercise header': 'Boutons superset dans l\'en-tête de l\'exercice',
'Move, swap and remove buttons below the exercise': 'Boutons déplacer, remplacer et retirer sous l\'exercice',
'Everything hidden here stays one tap away: the ⋯ button of an exercise and the number of a set.': 'Tout ce qui est masqué ici reste à un tap : le bouton ⋯ d\'un exercice et le numéro d\'une série.',
'Convert to {0}?': 'Convertir en {0} ?',
'Every stored weight — logged sets, working weights, routine targets, body weight, bar weights — is in {0}. Convert the numbers, or keep them and only change the label?': 'Tous les poids enregistrés — séries, charges de travail, cibles des routines, poids de corps, poids des barres — sont en {0}. Convertir les nombres, ou les garder et ne changer que l’étiquette ?',
'Convert the numbers': 'Convertir les nombres',
'Keep the numbers, change the label': 'Garder les nombres, changer l’étiquette',
'Switching the unit offers to convert every stored weight.': 'Changer d’unité propose de convertir tous les poids enregistrés.',
'Update to {0}?': 'Mettre à jour vers {0} ?',
'The latest version will be downloaded and the installer will open.': 'La dernière version sera téléchargée et l’installateur s’ouvrira.',
'Download & Install': 'Télécharger et installer',
'Update failed: {0}': 'Échec de la mise à jour : {0}',
'openGym v{0} available': 'openGym v{0} disponible',
'Starting download…': 'Démarrage du téléchargement…',
'Downloading update…': 'Téléchargement de la mise à jour…',
'{0} %': '{0} %',
'{0} MB': '{0} Mo',
'Checksum not available — not installing': 'Somme de contrôle indisponible — installation annulée',
}
+106 -5
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': 'फ्रीस्टाइल',
@@ -82,6 +89,12 @@ export default {
'Search {0} exercises…': '{0} व्यायामों में खोजें…',
'Chosen': 'चुने हुए',
'Nothing chosen yet — add exercises and they’ll show up here.': 'अभी कुछ नहीं चुना — व्यायाम जोड़ें तो वे यहाँ दिखेंगे।',
'Add to favourites': 'पसंदीदा में जोड़ें',
'Remove from favourites': 'पसंदीदा से हटाएँ',
'Added to favourites': 'पसंदीदा में जोड़ा गया',
'Removed from favourites': 'पसंदीदा से हटाया गया',
'Favourites': 'पसंदीदा',
'No favourites here — tap the star on an exercise to add it.': 'यहाँ कोई पसंदीदा नहीं — किसी व्यायाम पर तारे को टैप करें।',
'No match': 'कोई परिणाम नहीं',
'Show more': 'और दिखाएँ',
'Intervals': 'इंटरवल',
@@ -202,8 +215,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 +255,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 +262,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': 'प्रोफ़ाइल बनी — डेटा स्थानांतरित',
@@ -292,7 +319,6 @@ export default {
'Rest timer': 'आराम टाइमर',
'Sounds': 'ध्वनियाँ',
'Flash screen when timer ends': 'टाइमर खत्म होने पर स्क्रीन फ्लैश करें',
'Note: switching units only changes the label — logged numbers are not converted.': 'नोट: इकाई बदलने से केवल लेबल बदलता है — दर्ज संख्याएँ परिवर्तित नहीं होतीं।',
'Data': 'डेटा',
'Export backup (JSON)': 'बैकअप निर्यात करें (JSON)',
'Import backup': 'बैकअप आयात करें',
@@ -394,6 +420,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': 'छिपा',
@@ -533,6 +565,11 @@ export default {
// --- v1.2.2: timed sets, progression, estimated 1RM (#16 #17 #18) ---
'Top set': 'सर्वश्रेष्ठ सेट',
'Est. 1RM': 'अनु. 1RM',
'No sessions logged yet': 'अभी तक कोई सत्र दर्ज नहीं',
'{0} session': '{0} सत्र',
'{0} sessions': '{0} सत्र',
'Exercise history': 'व्यायाम इतिहास',
'Last {0} sessions': 'पिछले {0} सत्र',
'Estimated 1RM': 'अनुमानित 1RM',
'Estimated 1RM per workout': 'प्रति वर्कआउट अनुमानित 1RM',
'Best estimate from {0} on {1} — an estimate, not a tested max.': '{1} को {0} से सर्वश्रेष्ठ अनुमान — यह अनुमान है, परखा गया अधिकतम नहीं।',
@@ -599,6 +636,11 @@ export default {
'Two more reps': 'दो रेप और बाकी',
'Three more reps': 'तीन रेप और बाकी',
'Easy — warm-up territory': 'आसान — वॉर्म-अप का दायरा',
'Maybe half a rep left': 'शायद आधा रेप और बाकी',
'How hard was that set?': 'वह सेट कितना मुश्किल था?',
'Tap how many reps you had left, or type an exact {0}.': 'टैप करें कि कितने रेप्स बाकी थे, या सटीक {0} दर्ज करें।',
'Exact {0}': 'सटीक {0}',
'Clear rating': 'रेटिंग साफ़ करें',
'RIR counts the reps you left; RPE reads the same effort off a 10-point scale — so RPE ≈ 10 − RIR. Pick the one you already think in.': 'RIR बचे हुए रेप्स गिनता है; RPE उसी मेहनत को 10 के पैमाने पर पढ़ता है — यानी RPE ≈ 10 − RIR. वही चुनें जिसमें आप पहले से सोचते हैं।',
'The highlighted row is where most working sets land. Sets you have already logged keep their own scale, and nothing else reads the value — progression and estimated 1RM are unaffected.': 'हाइलाइट की गई पंक्ति वह है जहाँ ज़्यादातर वर्किंग सेट आते हैं। पहले दर्ज किए सेट अपना पैमाना बनाए रखते हैं, और इस मान को और कुछ नहीं पढ़ता — प्रोग्रेशन और अनुमानित 1RM अछूते रहते हैं।',
// --- effort in the stats ---
@@ -1080,4 +1122,63 @@ 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.': 'कैमरे की अनुमति नहीं मिली — ब्राउज़र में अनुमति दें और फिर कोशिश करें।',
'Add note': 'नोट जोड़ें',
'Edit note': 'नोट संपादित करें',
'Progression settings': 'प्रगति सेटिंग',
'Set {0}': 'सेट {0}',
'Drop set': 'ड्रॉप सेट',
'Rest-pause burst': 'रेस्ट-पॉज़ बर्स्ट',
'Remove this set': 'यह सेट हटाएँ',
'Workout controls': 'वर्कआउट नियंत्रण',
'Weight and reps buttons': 'वज़न और रेप्स के +/− बटन',
'Off: tap the number and type it': 'बंद: संख्या पर टैप करें और टाइप करें',
'Drop and burst shortcuts on every set': 'हर सेट पर ड्रॉप और बर्स्ट शॉर्टकट',
'Superset buttons in the exercise header': 'व्यायाम शीर्षक में सुपरसेट बटन',
'Move, swap and remove buttons below the exercise': 'व्यायाम के नीचे स्थानांतरित, बदलें और हटाएँ बटन',
'Everything hidden here stays one tap away: the ⋯ button of an exercise and the number of a set.': 'यहाँ छिपाया गया सब कुछ एक टैप दूर रहता है: व्यायाम का ⋯ बटन और सेट की संख्या।',
'Convert to {0}?': '{0} में बदलें?',
'Every stored weight — logged sets, working weights, routine targets, body weight, bar weights — is in {0}. Convert the numbers, or keep them and only change the label?': 'हर सहेजा गया वज़न — दर्ज सेट, कार्य वज़न, रूटीन लक्ष्य, शरीर का वज़न, बार वज़न — {0} में है। संख्याएँ बदलें, या उन्हें रखें और केवल लेबल बदलें?',
'Convert the numbers': 'संख्याएँ बदलें',
'Keep the numbers, change the label': 'संख्याएँ रखें, लेबल बदलें',
'Switching the unit offers to convert every stored weight.': 'इकाई बदलने पर सभी सहेजे गए वज़न बदलने का विकल्प मिलता है।',
'Update to {0}?': '{0} में अपडेट करें?',
'The latest version will be downloaded and the installer will open.': 'नवीनतम संस्करण डाउनलोड होगा और इंस्टॉलर खुलेगा।',
'Download & Install': 'डाउनलोड और इंस्टॉल करें',
'Update failed: {0}': 'अपडेट विफल: {0}',
'openGym v{0} available': 'openGym v{0} उपलब्ध',
'Starting download…': 'डाउनलोड शुरू हो रहा है…',
'Downloading update…': 'अपडेट डाउनलोड हो रहा है…',
'{0} %': '{0}%',
'{0} MB': '{0} MB',
'Checksum not available — not installing': 'चेकसम उपलब्ध नहीं — इंस्टॉल नहीं किया गया',
}
+106 -5
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',
@@ -85,6 +92,12 @@ export default {
'Search {0} exercises…': '{0} gyakorlat keresése…',
'Chosen': 'Kiválasztva',
'Nothing chosen yet — add exercises and they’ll show up here.': 'Még nincs kiválasztva semmi — adj hozzá gyakorlatokat, és itt fognak megjelenni.',
'Add to favourites': 'Kedvencekhez adás',
'Remove from favourites': 'Eltávolítás a kedvencekből',
'Added to favourites': 'Hozzáadva a kedvencekhez',
'Removed from favourites': 'Eltávolítva a kedvencekből',
'Favourites': 'Kedvencek',
'No favourites here — tap the star on an exercise to add it.': 'Itt nincs kedvenc — koppints egy gyakorlat csillagára.',
'No match': 'Nincs találat',
'Show more': 'Több megjelenítése',
'Intervals': 'Intervallumok',
@@ -202,8 +215,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 +258,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 +266,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',
@@ -298,7 +325,6 @@ export default {
'Week starts on': 'A hét kezdőnapja',
'Rest timer': 'Pihenő időzítő',
'Sounds': 'Hangok',
'Note: switching units only changes the label — logged numbers are not converted.': 'Megjegyzés: a mértékegység váltása csak a feliratot módosítja — a rögzített számok nem lesznek átváltva.',
'Data': 'Adatok',
'Export backup (JSON)': 'Biztonsági mentés exportálása (JSON)',
'Import backup': 'Biztonsági mentés importálása',
@@ -404,6 +430,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',
@@ -517,6 +549,11 @@ export default {
// --- v1.2.2: timed sets, progression, estimated 1RM (#16 #17 #18) ---
'Top set': 'Legjobb sorozat',
'Est. 1RM': 'becs. 1RM',
'No sessions logged yet': 'Még nincs rögzített edzés',
'{0} session': '{0} edzés',
'{0} sessions': '{0} edzés',
'Exercise history': 'Gyakorlat előzményei',
'Last {0} sessions': 'Utolsó {0} edzés',
'Estimated 1RM': 'Becsült 1RM',
'Estimated 1RM per workout': 'Becsült 1RM edzésenként',
'Best estimate from {0} on {1} — an estimate, not a tested max.': 'Legjobb becslés innen: {0}, ekkor: {1} — ez egy becslés, nem tesztelt maximum.',
@@ -579,6 +616,11 @@ export default {
'Two more reps': 'Két ismétlés még belefért volna',
'Three more reps': 'Három ismétlés még belefért volna',
'Easy — warm-up territory': 'Könnyű — bemelegítő szint',
'Maybe half a rep left': 'Talán még fél ismétlés belefért volna',
'How hard was that set?': 'Mennyire volt nehéz ez a sorozat?',
'Tap how many reps you had left, or type an exact {0}.': 'Koppints rá, hány ismétlés maradt még, vagy adj meg pontos {0} értéket.',
'Exact {0}': 'Pontos {0}',
'Clear rating': 'Értékelés törlése',
'RIR counts the reps you left; RPE reads the same effort off a 10-point scale — so RPE ≈ 10 − RIR. Pick the one you already think in.': 'A RIR a megmaradt ismétléseket számolja; az RPE ugyanazt a megerőltetést egy 10 pontos skálán olvassa le — tehát RPE ≈ 10 − RIR. Válaszd azt, amelyikben amúgy is gondolkodsz.',
'The highlighted row is where most working sets land. Sets you have already logged keep their own scale, and nothing else reads the value — progression and estimated 1RM are unaffected.': 'A kiemelt sor az, ahova a legtöbb munkasorozat esik. A már rögzített sorozatok megtartják a saját skálájukat, és semmi más nem olvassa ki az értéket — a progressziót és a becsült 1RM-et nem érinti.',
// --- effort in the stats ---
@@ -748,6 +790,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 +1150,38 @@ 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.',
'Add note': 'Jegyzet hozzáadása',
'Edit note': 'Jegyzet szerkesztése',
'Progression settings': 'Progresszió beállításai',
'Set {0}': '{0}. sorozat',
'Drop set': 'Drop szett',
'Rest-pause burst': 'Rest-pause sorozat',
'Remove this set': 'Sorozat eltávolítása',
'Workout controls': 'Vezérlők edzés közben',
'Weight and reps buttons': 'Súly és ismétlés +/− gombok',
'Off: tap the number and type it': 'Ki: koppints a számra és írd be',
'Drop and burst shortcuts on every set': 'Drop és rest-pause gyorsgombok minden sorozatnál',
'Superset buttons in the exercise header': 'Szuperszett gombok a gyakorlat fejlécében',
'Move, swap and remove buttons below the exercise': 'Mozgatás, csere és eltávolítás gombok a gyakorlat alatt',
'Everything hidden here stays one tap away: the ⋯ button of an exercise and the number of a set.': 'Minden, amit itt elrejtesz, egy koppintásra marad: a gyakorlat ⋯ gombja és a sorozat száma.',
'Convert to {0}?': 'Átváltás {0}-ra?',
'Every stored weight — logged sets, working weights, routine targets, body weight, bar weights — is in {0}. Convert the numbers, or keep them and only change the label?': 'Minden tárolt súly — naplózott sorozatok, munkasúlyok, rutincélok, testsúly, rúdsúlyok — {0}-ban van. Átváltsuk a számokat, vagy maradjanak és csak a címke változzon?',
'Convert the numbers': 'Számok átváltása',
'Keep the numbers, change the label': 'Számok maradnak, csak a címke változik',
'Switching the unit offers to convert every stored weight.': 'Mértékegység-váltáskor felajánlja minden tárolt súly átváltását.',
'Update to {0}?': 'Frissítés erre: {0}?',
'The latest version will be downloaded and the installer will open.': 'A legújabb verzió letöltődik, és megnyílik a telepítő.',
'Download & Install': 'Letöltés és telepítés',
'Update failed: {0}': 'A frissítés sikertelen: {0}',
'openGym v{0} available': 'openGym v{0} elérhető',
'Starting download…': 'Letöltés indítása…',
'Downloading update…': 'Frissítés letöltése…',
'{0} %': '{0} %',
'{0} MB': '{0} MB',
'Checksum not available — not installing': 'Ellenőrző összeg nem érhető el — nincs telepítés',
}
+106 -5
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',
@@ -82,6 +89,12 @@ export default {
'Search {0} exercises…': 'Cerca tra {0} esercizi…',
'Chosen': 'Scelti',
'Nothing chosen yet — add exercises and they’ll show up here.': 'Ancora niente — aggiungi esercizi e appariranno qui.',
'Add to favourites': 'Aggiungi ai preferiti',
'Remove from favourites': 'Rimuovi dai preferiti',
'Added to favourites': 'Aggiunto ai preferiti',
'Removed from favourites': 'Rimosso dai preferiti',
'Favourites': 'Preferiti',
'No favourites here — tap the star on an exercise to add it.': 'Nessun preferito qui — tocca la stella di un esercizio per aggiungerlo.',
'No match': 'Nessun risultato',
'Show more': 'Mostra altro',
'Intervals': 'Intervalli',
@@ -202,8 +215,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 +255,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 +262,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',
@@ -292,7 +319,6 @@ export default {
'Rest timer': 'Timer di riposo',
'Sounds': 'Suoni',
'Flash screen when timer ends': 'Fai lampeggiare lo schermo alla fine del timer',
'Note: switching units only changes the label — logged numbers are not converted.': 'Nota: cambiare unità cambia solo l’etichetta — i numeri registrati non vengono convertiti.',
'Data': 'Dati',
'Export backup (JSON)': 'Esporta backup (JSON)',
'Import backup': 'Importa backup',
@@ -394,6 +420,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',
@@ -533,6 +565,11 @@ export default {
// --- v1.2.2: timed sets, progression, estimated 1RM (#16 #17 #18) ---
'Top set': 'Serie migliore',
'Est. 1RM': '1RM stim.',
'No sessions logged yet': 'Nessuna sessione registrata',
'{0} session': '{0} sessione',
'{0} sessions': '{0} sessioni',
'Exercise history': 'Storico dell’esercizio',
'Last {0} sessions': 'Ultime {0} sessioni',
'Estimated 1RM': '1RM stimato',
'Estimated 1RM per workout': '1RM stimato per allenamento',
'Best estimate from {0} on {1} — an estimate, not a tested max.': 'Stima migliore da {0} il {1} — una stima, non un massimale testato.',
@@ -599,6 +636,11 @@ export default {
'Two more reps': 'Altre due ripetizioni',
'Three more reps': 'Altre tre ripetizioni',
'Easy — warm-up territory': 'Facile — zona riscaldamento',
'Maybe half a rep left': 'Forse mezza ripetizione in riserva',
'How hard was that set?': 'Quanto è stata dura la serie?',
'Tap how many reps you had left, or type an exact {0}.': 'Tocca quante ripetizioni ti restavano, oppure inserisci un {0} preciso.',
'Exact {0}': '{0} preciso',
'Clear rating': 'Cancella valutazione',
'RIR counts the reps you left; RPE reads the same effort off a 10-point scale — so RPE ≈ 10 − RIR. Pick the one you already think in.': 'Il RIR conta le ripetizioni che ti restavano; l’RPE legge lo stesso sforzo su una scala da 10 — quindi RPE ≈ 10 − RIR. Scegli quella con cui già ragioni.',
'The highlighted row is where most working sets land. Sets you have already logged keep their own scale, and nothing else reads the value — progression and estimated 1RM are unaffected.': 'La riga evidenziata è dove finisce la maggior parte delle serie di lavoro. Le serie già registrate mantengono la loro scala, e nient’altro legge il valore: progressione e 1RM stimato non cambiano.',
// --- effort in the stats ---
@@ -1080,4 +1122,63 @@ 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.',
'Add note': 'Aggiungi nota',
'Edit note': 'Modifica nota',
'Progression settings': 'Impostazioni di progressione',
'Set {0}': 'Serie {0}',
'Drop set': 'Drop set',
'Rest-pause burst': 'Raffica rest-pause',
'Remove this set': 'Rimuovi questa serie',
'Workout controls': 'Controlli durante l’allenamento',
'Weight and reps buttons': 'Pulsanti +/− di peso e ripetizioni',
'Off: tap the number and type it': 'Disattivato: tocca il numero e digitalo',
'Drop and burst shortcuts on every set': 'Scorciatoie drop e raffica su ogni serie',
'Superset buttons in the exercise header': 'Pulsanti superset nell’intestazione dell’esercizio',
'Move, swap and remove buttons below the exercise': 'Pulsanti sposta, sostituisci e rimuovi sotto l’esercizio',
'Everything hidden here stays one tap away: the ⋯ button of an exercise and the number of a set.': 'Tutto ciò che nascondi qui resta a un tocco: il pulsante ⋯ di un esercizio e il numero di una serie.',
'Convert to {0}?': 'Convertire in {0}?',
'Every stored weight — logged sets, working weights, routine targets, body weight, bar weights — is in {0}. Convert the numbers, or keep them and only change the label?': 'Ogni peso salvato — serie registrate, pesi di lavoro, obiettivi delle routine, peso corporeo, pesi dei bilancieri — è in {0}. Convertire i numeri o tenerli e cambiare solo l’etichetta?',
'Convert the numbers': 'Converti i numeri',
'Keep the numbers, change the label': 'Tieni i numeri, cambia l’etichetta',
'Switching the unit offers to convert every stored weight.': 'Cambiando unità viene proposto di convertire tutti i pesi salvati.',
'Update to {0}?': 'Aggiornare a {0}?',
'The latest version will be downloaded and the installer will open.': 'L’ultima versione verrà scaricata e si aprirà il programma di installazione.',
'Download & Install': 'Scarica e installa',
'Update failed: {0}': 'Aggiornamento fallito: {0}',
'openGym v{0} available': 'openGym v{0} disponibile',
'Starting download…': 'Avvio del download…',
'Downloading update…': 'Download dell’aggiornamento…',
'{0} %': '{0} %',
'{0} MB': '{0} MB',
'Checksum not available — not installing': 'Checksum non disponibile — installazione annullata',
}
+107 -6
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': '자유 운동',
@@ -80,8 +87,14 @@ export default {
'Create one and start with this exercise': '새로 만들어 이 운동으로 시작',
'Add exercise': '운동 추가',
'Search {0} exercises…': '{0}개 운동 검색…',
'Chosen': '즐겨찾기',
'Chosen': '선택됨',
'Nothing chosen yet — add exercises and they’ll show up here.': '아직 없어요 — 운동을 추가하면 여기에 표시됩니다.',
'Add to favourites': '즐겨찾기에 추가',
'Remove from favourites': '즐겨찾기에서 제거',
'Added to favourites': '즐겨찾기에 추가했어요',
'Removed from favourites': '즐겨찾기에서 제거했어요',
'Favourites': '즐겨찾기',
'No favourites here — tap the star on an exercise to add it.': '즐겨찾기가 없어요 — 운동의 별을 눌러 추가하세요.',
'No match': '검색 결과 없음',
'Show more': '더 보기',
'Intervals': '인터벌',
@@ -202,8 +215,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 +255,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 +262,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': '프로필 생성됨 — 데이터 이동됨',
@@ -292,7 +319,6 @@ export default {
'Rest timer': '휴식 타이머',
'Sounds': '소리',
'Flash screen when timer ends': '타이머 종료 시 화면 깜박임',
'Note: switching units only changes the label — logged numbers are not converted.': '참고: 단위 변경은 표기만 바꿉니다 — 기록된 숫자는 환산되지 않아요.',
'Data': '데이터',
'Export backup (JSON)': '백업 내보내기 (JSON)',
'Import backup': '백업 가져오기',
@@ -394,6 +420,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': '숨김',
@@ -533,6 +565,11 @@ export default {
// --- v1.2.2: timed sets, progression, estimated 1RM (#16 #17 #18) ---
'Top set': '최고 세트',
'Est. 1RM': '추정 1RM',
'No sessions logged yet': '기록된 세션이 아직 없습니다',
'{0} session': '세션 {0}회',
'{0} sessions': '세션 {0}회',
'Exercise history': '운동 기록',
'Last {0} sessions': '최근 {0}회 세션',
'Estimated 1RM': '추정 1RM',
'Estimated 1RM per workout': '운동별 추정 1RM',
'Best estimate from {0} on {1} — an estimate, not a tested max.': '{1}의 {0} 기준 최고 추정치 — 실제로 측정한 최대치가 아닌 추정값입니다.',
@@ -599,6 +636,11 @@ export default {
'Two more reps': '두 개 더 남았음',
'Three more reps': '세 개 더 남았음',
'Easy — warm-up territory': '가벼움 — 웜업 구간',
'Maybe half a rep left': '반 개 정도 더 남았을지도',
'How hard was that set?': '이 세트는 얼마나 힘들었나요?',
'Tap how many reps you had left, or type an exact {0}.': '몇 개 더 할 수 있었는지 탭하거나 정확한 {0} 값을 입력하세요.',
'Exact {0}': '정확한 {0}',
'Clear rating': '평가 지우기',
'RIR counts the reps you left; RPE reads the same effort off a 10-point scale — so RPE ≈ 10 − RIR. Pick the one you already think in.': 'RIR은 남긴 횟수를 세고, RPE는 같은 노력을 10점 척도로 읽습니다 — 즉 RPE ≈ 10 − RIR. 평소에 쓰던 쪽을 고르세요.',
'The highlighted row is where most working sets land. Sets you have already logged keep their own scale, and nothing else reads the value — progression and estimated 1RM are unaffected.': '강조된 줄은 대부분의 본세트가 들어가는 구간입니다. 이미 기록한 세트는 원래 척도를 그대로 유지하며, 이 값을 읽는 곳은 없습니다 — 프로그레션과 예상 1RM은 영향을 받지 않습니다.',
// --- effort in the stats ---
@@ -1080,4 +1122,63 @@ 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.': '카메라 접근이 거부되었습니다 — 브라우저에서 허용한 뒤 다시 시도하세요.',
'Add note': '메모 추가',
'Edit note': '메모 편집',
'Progression settings': '진행 설정',
'Set {0}': '{0}세트',
'Drop set': '드롭 세트',
'Rest-pause burst': '레스트 포즈',
'Remove this set': '이 세트 삭제',
'Workout controls': '운동 중 버튼',
'Weight and reps buttons': '무게·횟수 +/− 버튼',
'Off: tap the number and type it': '끄면 숫자를 눌러 직접 입력',
'Drop and burst shortcuts on every set': '모든 세트에 드롭·레스트 포즈 바로가기',
'Superset buttons in the exercise header': '운동 제목의 슈퍼세트 버튼',
'Move, swap and remove buttons below the exercise': '운동 아래의 이동·교체·삭제 버튼',
'Everything hidden here stays one tap away: the ⋯ button of an exercise and the number of a set.': '여기서 숨긴 것은 모두 한 번의 탭으로 열 수 있습니다: 운동의 ⋯ 버튼과 세트 번호.',
'Convert to {0}?': '{0}(으)로 변환할까요?',
'Every stored weight — logged sets, working weights, routine targets, body weight, bar weights — is in {0}. Convert the numbers, or keep them and only change the label?': '저장된 모든 무게(기록된 세트, 작업 무게, 루틴 목표, 체중, 바 무게)는 {0} 단위입니다. 숫자를 변환할까요, 아니면 숫자는 그대로 두고 표시만 바꿀까요?',
'Convert the numbers': '숫자 변환',
'Keep the numbers, change the label': '숫자 유지, 표시만 변경',
'Switching the unit offers to convert every stored weight.': '단위를 바꾸면 저장된 모든 무게를 변환할지 물어봅니다.',
'Update to {0}?': '{0}(으)로 업데이트하시겠습니까?',
'The latest version will be downloaded and the installer will open.': '최신 버전이 다운로드되고 설치 프로그램이 열립니다.',
'Download & Install': '다운로드 및 설치',
'Update failed: {0}': '업데이트 실패: {0}',
'openGym v{0} available': 'openGym v{0} 사용 가능',
'Starting download…': '다운로드 시작 중…',
'Downloading update…': '업데이트 다운로드 중…',
'{0} %': '{0}%',
'{0} MB': '{0} MB',
'Checksum not available — not installing': '체크섬을 확인할 수 없어 설치하지 않습니다',
}
+106 -5
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',
@@ -82,6 +89,12 @@ export default {
'Search {0} exercises…': 'Szukaj wśród {0} ćwiczeń…',
'Chosen': 'Wybrane',
'Nothing chosen yet — add exercises and they’ll show up here.': 'Nic nie wybrano — dodaj ćwiczenia, a pojawią się tutaj.',
'Add to favourites': 'Dodaj do ulubionych',
'Remove from favourites': 'Usuń z ulubionych',
'Added to favourites': 'Dodano do ulubionych',
'Removed from favourites': 'Usunięto z ulubionych',
'Favourites': 'Ulubione',
'No favourites here — tap the star on an exercise to add it.': 'Brak ulubionych — dotknij gwiazdki przy ćwiczeniu, aby je dodać.',
'No match': 'Brak wyników',
'Show more': 'Pokaż więcej',
'Intervals': 'Interwały',
@@ -202,8 +215,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 +255,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 +262,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',
@@ -292,7 +319,6 @@ export default {
'Rest timer': 'Minutnik przerwy',
'Sounds': 'Dźwięki',
'Flash screen when timer ends': 'Migaj ekranem po zakończeniu minutnika',
'Note: switching units only changes the label — logged numbers are not converted.': 'Uwaga: zmiana jednostki zmienia tylko etykietę — zapisane liczby nie są przeliczane.',
'Data': 'Dane',
'Export backup (JSON)': 'Eksportuj kopię (JSON)',
'Import backup': 'Importuj kopię',
@@ -394,6 +420,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',
@@ -533,6 +565,11 @@ export default {
// --- v1.2.2: timed sets, progression, estimated 1RM (#16 #17 #18) ---
'Top set': 'Najlepsza seria',
'Est. 1RM': 'Szac. 1RM',
'No sessions logged yet': 'Brak zapisanych sesji',
'{0} session': '{0} sesja',
'{0} sessions': '{0} sesji',
'Exercise history': 'Historia ćwiczenia',
'Last {0} sessions': 'Ostatnie {0} sesji',
'Estimated 1RM': 'Szacowany 1RM',
'Estimated 1RM per workout': 'Szacowany 1RM na trening',
'Best estimate from {0} on {1} — an estimate, not a tested max.': 'Najlepsze oszacowanie z {0} dnia {1} — to szacunek, a nie zmierzony maks.',
@@ -599,6 +636,11 @@ export default {
'Two more reps': 'Jeszcze dwa powtórzenia',
'Three more reps': 'Jeszcze trzy powtórzenia',
'Easy — warm-up territory': 'Lekko — poziom rozgrzewki',
'Maybe half a rep left': 'Może pół powtórzenia w zapasie',
'How hard was that set?': 'Jak ciężka była ta seria?',
'Tap how many reps you had left, or type an exact {0}.': 'Dotknij, ile powtórzeń zostało w zapasie, lub wpisz dokładną wartość {0}.',
'Exact {0}': 'Dokładne {0}',
'Clear rating': 'Wyczyść ocenę',
'RIR counts the reps you left; RPE reads the same effort off a 10-point scale — so RPE ≈ 10 − RIR. Pick the one you already think in.': 'RIR liczy powtórzenia, które zostały w zapasie; RPE odczytuje ten sam wysiłek w skali 10 — czyli RPE ≈ 10 − RIR. Wybierz tę, w której już myślisz.',
'The highlighted row is where most working sets land. Sets you have already logged keep their own scale, and nothing else reads the value — progression and estimated 1RM are unaffected.': 'Wyróżniony wiersz to miejsce, w które trafia większość serii roboczych. Zapisane wcześniej serie zachowują swoją skalę, a wartości nic więcej nie czyta — progresja i szacowany 1RM pozostają bez zmian.',
// --- effort in the stats ---
@@ -1080,4 +1122,63 @@ 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.',
'Add note': 'Dodaj notatkę',
'Edit note': 'Edytuj notatkę',
'Progression settings': 'Ustawienia progresji',
'Set {0}': 'Seria {0}',
'Drop set': 'Drop set',
'Rest-pause burst': 'Seria rest-pause',
'Remove this set': 'Usuń tę serię',
'Workout controls': 'Przyciski podczas treningu',
'Weight and reps buttons': 'Przyciski +/− ciężaru i powtórzeń',
'Off: tap the number and type it': 'Wyłączone: dotknij liczby i wpisz ją',
'Drop and burst shortcuts on every set': 'Skróty drop i rest-pause przy każdej serii',
'Superset buttons in the exercise header': 'Przyciski superserii w nagłówku ćwiczenia',
'Move, swap and remove buttons below the exercise': 'Przyciski przenieś, zamień i usuń pod ćwiczeniem',
'Everything hidden here stays one tap away: the ⋯ button of an exercise and the number of a set.': 'Wszystko, co tu ukryjesz, jest o jedno dotknięcie: przycisk ⋯ ćwiczenia i numer serii.',
'Convert to {0}?': 'Przeliczyć na {0}?',
'Every stored weight — logged sets, working weights, routine targets, body weight, bar weights — is in {0}. Convert the numbers, or keep them and only change the label?': 'Wszystkie zapisane ciężary — serie, ciężary robocze, cele rutyn, masa ciała, ciężary sztang — są w {0}. Przeliczyć liczby, czy zostawić je i zmienić tylko etykietę?',
'Convert the numbers': 'Przelicz liczby',
'Keep the numbers, change the label': 'Zostaw liczby, zmień etykietę',
'Switching the unit offers to convert every stored weight.': 'Zmiana jednostki proponuje przeliczenie wszystkich zapisanych ciężarów.',
'Update to {0}?': 'Zaktualizować do {0}?',
'The latest version will be downloaded and the installer will open.': 'Najnowsza wersja zostanie pobrana i otworzy się instalator.',
'Download & Install': 'Pobierz i zainstaluj',
'Update failed: {0}': 'Aktualizacja nie powiodła się: {0}',
'openGym v{0} available': 'openGym v{0} dostępna',
'Starting download…': 'Rozpoczynanie pobierania…',
'Downloading update…': 'Pobieranie aktualizacji…',
'{0} %': '{0}%',
'{0} MB': '{0} MB',
'Checksum not available — not installing': 'Suma kontrolna niedostępna — instalacja przerwana',
}
+50 -6
View File
@@ -4,6 +4,7 @@
import pt from './pt.js'
export const PT_BR_OVERRIDES = {
'No sessions logged yet': 'Ainda não há sessões registradas',
'What should change?': 'O que deve mudar?',
'Coach is thinking…': 'O Coach está pensando…',
'Message the Coach…': 'Escreva ao Coach…',
@@ -32,6 +33,7 @@ export const PT_BR_OVERRIDES = {
'Create one and start with this exercise': 'Crie uma e comece com este exercício',
'Search {0} exercises…': 'Buscar entre {0} exercícios…',
'Nothing chosen yet — add exercises and they’ll show up here.': 'Nenhum exercício escolhido — adicione exercícios e eles aparecerão aqui.',
'No favourites here — tap the star on an exercise to add it.': 'Sem favoritos aqui — toque na estrela de um exercício para adicioná-lo.',
'The sets you logged for this exercise in this session will be lost.': 'As séries registradas para este exercício nesta sessão serão perdidas.',
'Swap exercise': 'Trocar exercício',
'Swap exercise?': 'Trocar exercício?',
@@ -62,13 +64,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 +79,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',
@@ -105,7 +109,6 @@ export const PT_BR_OVERRIDES = {
'synced with your profile': 'sincronizado com seu perfil',
'The screen stays on while a workout is running, so you don’t have to unlock your phone between sets.': 'A tela permanece ligada durante o treino, para você não precisar desbloquear o celular entre as séries.',
'Flash screen when timer ends': 'Piscar a tela quando o temporizador terminar',
'Note: switching units only changes the label — logged numbers are not converted.': 'Observação: trocar a unidade altera somente o rótulo — os valores registrados não são convertidos.',
'Export backup (JSON)': 'Exportar backup (JSON)',
'Import backup': 'Importar backup',
'Reset everything?': 'Redefinir tudo?',
@@ -608,7 +611,48 @@ 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',
'Progression settings': 'Configurações de progressão',
'Workout controls': 'Controles durante o treino',
'Off: tap the number and type it': 'Desligado: toque no número e digite',
'Move, swap and remove buttons below the exercise': 'Botões mover, trocar e remover abaixo do exercício',
'Everything hidden here stays one tap away: the ⋯ button of an exercise and the number of a set.': 'Tudo o que você esconde aqui fica a um toque: o botão ⋯ de um exercício e o número de uma série.',
// effort quick picker — pt-PT uses "toca"/"escreve"; Brazilian uses "toque"/"digite"
'Tap how many reps you had left, or type an exact {0}.': 'Toque em quantas repetições você ainda tinha, ou digite um {0} exato.',
'Every stored weight — logged sets, working weights, routine targets, body weight, bar weights — is in {0}. Convert the numbers, or keep them and only change the label?': 'Todos os pesos salvos — séries registradas, pesos de trabalho, alvos das rotinas, peso corporal, pesos das barras — estão em {0}. Converter os números, ou mantê-los e mudar só o rótulo?',
'Keep the numbers, change the label': 'Manter os números, mudar o rótulo',
'Switching the unit offers to convert every stored weight.': 'Ao mudar de unidade é oferecido converter todos os pesos salvos.',
'The latest version will be downloaded and the installer will open.': 'A versão mais recente será baixada e o instalador será aberto.',
'Download & Install': 'Baixar e instalar',
'Starting download…': 'Iniciando download…',
'Downloading update…': 'Baixando atualização…',
}
export default { ...pt, ...PT_BR_OVERRIDES }
+106 -5
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',
@@ -82,6 +89,12 @@ export default {
'Search {0} exercises…': 'Pesquisar {0} exercícios…',
'Chosen': 'Escolhidos',
'Nothing chosen yet — add exercises and they’ll show up here.': 'Ainda nada escolhido — adiciona exercícios e eles aparecem aqui.',
'Add to favourites': 'Adicionar aos favoritos',
'Remove from favourites': 'Remover dos favoritos',
'Added to favourites': 'Adicionado aos favoritos',
'Removed from favourites': 'Removido dos favoritos',
'Favourites': 'Favoritos',
'No favourites here — tap the star on an exercise to add it.': 'Sem favoritos aqui — toca na estrela de um exercício para o adicionar.',
'No match': 'Sem resultados',
'Show more': 'Mostrar mais',
'Intervals': 'Intervalos',
@@ -202,8 +215,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 +255,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 +262,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',
@@ -292,7 +319,6 @@ export default {
'Rest timer': 'Temporizador de descanso',
'Sounds': 'Sons',
'Flash screen when timer ends': 'Piscar o ecrã quando o temporizador terminar',
'Note: switching units only changes the label — logged numbers are not converted.': 'Nota: mudar a unidade só muda o rótulo — os números registados não são convertidos.',
'Data': 'Dados',
'Export backup (JSON)': 'Exportar cópia (JSON)',
'Import backup': 'Importar cópia',
@@ -394,6 +420,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',
@@ -533,6 +565,11 @@ export default {
// --- v1.2.2: timed sets, progression, estimated 1RM (#16 #17 #18) ---
'Top set': 'Melhor série',
'Est. 1RM': '1RM est.',
'No sessions logged yet': 'Ainda não há sessões registadas',
'{0} session': '{0} sessão',
'{0} sessions': '{0} sessões',
'Exercise history': 'Histórico do exercício',
'Last {0} sessions': 'Últimas {0} sessões',
'Estimated 1RM': '1RM estimado',
'Estimated 1RM per workout': '1RM estimado por treino',
'Best estimate from {0} on {1} — an estimate, not a tested max.': 'Melhor estimativa a partir de {0} em {1} — uma estimativa, não um máximo testado.',
@@ -599,6 +636,11 @@ export default {
'Two more reps': 'Mais duas repetições',
'Three more reps': 'Mais três repetições',
'Easy — warm-up territory': 'Fácil — zona de aquecimento',
'Maybe half a rep left': 'Talvez meia repetição em reserva',
'How hard was that set?': 'Quão dura foi a série?',
'Tap how many reps you had left, or type an exact {0}.': 'Toca em quantas repetições te restavam, ou escreve um {0} exato.',
'Exact {0}': '{0} exato',
'Clear rating': 'Limpar avaliação',
'RIR counts the reps you left; RPE reads the same effort off a 10-point scale — so RPE ≈ 10 − RIR. Pick the one you already think in.': 'O RIR conta as repetições que deixaste; o RPE lê o mesmo esforço numa escala de 10 — ou seja, RPE ≈ 10 − RIR. Escolhe aquela em que já pensas.',
'The highlighted row is where most working sets land. Sets you have already logged keep their own scale, and nothing else reads the value — progression and estimated 1RM are unaffected.': 'A linha destacada é onde cai a maioria das séries de trabalho. As séries já registadas mantêm a sua escala, e mais nada lê o valor — a progressão e o 1RM estimado não mudam.',
// --- effort in the stats ---
@@ -1080,4 +1122,63 @@ 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.',
'Add note': 'Adicionar nota',
'Edit note': 'Editar nota',
'Progression settings': 'Definições de progressão',
'Set {0}': 'Série {0}',
'Drop set': 'Drop set',
'Rest-pause burst': 'Rajada rest-pause',
'Remove this set': 'Remover esta série',
'Workout controls': 'Controlos durante o treino',
'Weight and reps buttons': 'Botões +/− de peso e repetições',
'Off: tap the number and type it': 'Desligado: toca no número e escreve-o',
'Drop and burst shortcuts on every set': 'Atalhos de drop e rajada em cada série',
'Superset buttons in the exercise header': 'Botões de superset no cabeçalho do exercício',
'Move, swap and remove buttons below the exercise': 'Botões mover, trocar e remover por baixo do exercício',
'Everything hidden here stays one tap away: the ⋯ button of an exercise and the number of a set.': 'Tudo o que escondes aqui fica a um toque: o botão ⋯ de um exercício e o número de uma série.',
'Convert to {0}?': 'Converter para {0}?',
'Every stored weight — logged sets, working weights, routine targets, body weight, bar weights — is in {0}. Convert the numbers, or keep them and only change the label?': 'Todos os pesos guardados — séries registadas, pesos de trabalho, alvos das rotinas, peso corporal, pesos das barras — estão em {0}. Converter os números, ou mantê-los e mudar só a etiqueta?',
'Convert the numbers': 'Converter os números',
'Keep the numbers, change the label': 'Manter os números, mudar a etiqueta',
'Switching the unit offers to convert every stored weight.': 'Ao mudar de unidade é proposto converter todos os pesos guardados.',
'Update to {0}?': 'Atualizar para {0}?',
'The latest version will be downloaded and the installer will open.': 'A versão mais recente será transferida e o instalador será aberto.',
'Download & Install': 'Transferir e instalar',
'Update failed: {0}': 'Falha na atualização: {0}',
'openGym v{0} available': 'openGym v{0} disponível',
'Starting download…': 'A iniciar transferência…',
'Downloading update…': 'A transferir atualização…',
'{0} %': '{0} %',
'{0} MB': '{0} MB',
'Checksum not available — not installing': 'Soma de verificação indisponível — não instalado',
}
+107 -6
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': 'Свободная',
@@ -80,8 +87,14 @@ export default {
'Create one and start with this exercise': 'Создай новую и начни с этого упражнения',
'Add exercise': 'Добавить упражнение',
'Search {0} exercises…': 'Поиск среди {0} упражнений…',
'Chosen': 'Избранные',
'Chosen': 'Выбранные',
'Nothing chosen yet — add exercises and they’ll show up here.': 'Пока ничего нет — добавляй упражнения, и они появятся здесь.',
'Add to favourites': 'В избранное',
'Remove from favourites': 'Убрать из избранного',
'Added to favourites': 'Добавлено в избранное',
'Removed from favourites': 'Убрано из избранного',
'Favourites': 'Избранное',
'No favourites here — tap the star on an exercise to add it.': 'Здесь нет избранного — нажми на звезду у упражнения.',
'No match': 'Ничего не найдено',
'Show more': 'Показать ещё',
'Intervals': 'Интервалы',
@@ -202,8 +215,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 +255,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 +262,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': 'Профиль создан — данные перенесены',
@@ -292,7 +319,6 @@ export default {
'Rest timer': 'Таймер отдыха',
'Sounds': 'Звуки',
'Flash screen when timer ends': 'Мигать экраном по окончании таймера',
'Note: switching units only changes the label — logged numbers are not converted.': 'Примечание: смена единиц меняет только подпись — записанные числа не пересчитываются.',
'Data': 'Данные',
'Export backup (JSON)': 'Экспорт резервной копии (JSON)',
'Import backup': 'Импорт резервной копии',
@@ -394,6 +420,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': 'Скрыта',
@@ -533,6 +565,11 @@ export default {
// --- v1.2.2: timed sets, progression, estimated 1RM (#16 #17 #18) ---
'Top set': 'Лучший подход',
'Est. 1RM': 'Расч. 1ПМ',
'No sessions logged yet': 'Записанных сессий пока нет',
'{0} session': '{0} сессия',
'{0} sessions': '{0} сессий',
'Exercise history': 'История упражнения',
'Last {0} sessions': 'Последние {0} сессий',
'Estimated 1RM': 'Расчётный 1ПМ',
'Estimated 1RM per workout': 'Расчётный 1ПМ за тренировку',
'Best estimate from {0} on {1} — an estimate, not a tested max.': 'Лучшая оценка по {0} от {1} — это расчёт, а не проверенный максимум.',
@@ -599,6 +636,11 @@ export default {
'Two more reps': 'Ещё два повторения',
'Three more reps': 'Ещё три повторения',
'Easy — warm-up territory': 'Легко — разминочная зона',
'Maybe half a rep left': 'Может, ещё пол-повторения в запасе',
'How hard was that set?': 'Насколько тяжёлым был подход?',
'Tap how many reps you had left, or type an exact {0}.': 'Нажмите, сколько повторений оставалось в запасе, или введите точное значение {0}.',
'Exact {0}': 'Точный {0}',
'Clear rating': 'Сбросить оценку',
'RIR counts the reps you left; RPE reads the same effort off a 10-point scale — so RPE ≈ 10 − RIR. Pick the one you already think in.': 'RIR считает повторения, оставшиеся в запасе; RPE читает то же усилие по 10-балльной шкале — то есть RPE ≈ 10 − RIR. Выберите ту, в которой вы уже думаете.',
'The highlighted row is where most working sets land. Sets you have already logged keep their own scale, and nothing else reads the value — progression and estimated 1RM are unaffected.': 'Выделенная строка — это диапазон, в который попадает большинство рабочих подходов. Уже записанные подходы сохраняют свою шкалу, и больше это значение нигде не используется: прогрессия и расчётный 1ПМ не меняются.',
// --- effort in the stats ---
@@ -1080,4 +1122,63 @@ 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.': 'Доступ к камере запрещён — разрешите его в браузере и попробуйте снова.',
'Add note': 'Добавить заметку',
'Edit note': 'Изменить заметку',
'Progression settings': 'Настройки прогрессии',
'Set {0}': 'Подход {0}',
'Drop set': 'Дроп-сет',
'Rest-pause burst': 'Отдых-пауза',
'Remove this set': 'Удалить этот подход',
'Workout controls': 'Кнопки во время тренировки',
'Weight and reps buttons': 'Кнопки +/− для веса и повторений',
'Off: tap the number and type it': 'Выкл.: нажмите на число и введите его',
'Drop and burst shortcuts on every set': 'Кнопки дроп-сета и отдых-паузы у каждого подхода',
'Superset buttons in the exercise header': 'Кнопки суперсета в заголовке упражнения',
'Move, swap and remove buttons below the exercise': 'Кнопки переместить, заменить и удалить под упражнением',
'Everything hidden here stays one tap away: the ⋯ button of an exercise and the number of a set.': 'Всё скрытое здесь остаётся в одном нажатии: кнопка ⋯ упражнения и номер подхода.',
'Convert to {0}?': 'Перевести в {0}?',
'Every stored weight — logged sets, working weights, routine targets, body weight, bar weights — is in {0}. Convert the numbers, or keep them and only change the label?': 'Все сохранённые веса — подходы, рабочие веса, цели программ, вес тела, вес грифов — записаны в {0}. Пересчитать числа или оставить их и сменить только подпись?',
'Convert the numbers': 'Пересчитать числа',
'Keep the numbers, change the label': 'Оставить числа, сменить подпись',
'Switching the unit offers to convert every stored weight.': 'При смене единицы предлагается пересчитать все сохранённые веса.',
'Update to {0}?': 'Обновить до {0}?',
'The latest version will be downloaded and the installer will open.': 'Последняя версия будет загружена и откроется установщик.',
'Download & Install': 'Скачать и установить',
'Update failed: {0}': 'Ошибка обновления: {0}',
'openGym v{0} available': 'openGym v{0} доступна',
'Starting download…': 'Начало загрузки…',
'Downloading update…': 'Загрузка обновления…',
'{0} %': '{0} %',
'{0} MB': '{0} МБ',
'Checksum not available — not installing': 'Контрольная сумма недоступна — установка отменена',
}
+106 -5
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': 'ฟรีสไตล์',
@@ -85,6 +92,12 @@ export default {
'Search {0} exercises…': 'ค้นหาใน {0} ท่า…',
'Chosen': 'ที่เลือกไว้',
'Nothing chosen yet — add exercises and they’ll show up here.': 'ยังไม่ได้เลือกอะไรเลย — เพิ่มท่าออกกำลังกายแล้วจะโผล่มาที่นี่',
'Add to favourites': 'เพิ่มในรายการโปรด',
'Remove from favourites': 'นำออกจากรายการโปรด',
'Added to favourites': 'เพิ่มในรายการโปรดแล้ว',
'Removed from favourites': 'นำออกจากรายการโปรดแล้ว',
'Favourites': 'รายการโปรด',
'No favourites here — tap the star on an exercise to add it.': 'ยังไม่มีรายการโปรดที่นี่ — แตะดาวที่ท่าออกกำลังกายเพื่อเพิ่ม',
'No match': 'ไม่พบผลลัพธ์',
'Show more': 'แสดงเพิ่ม',
'Intervals': 'อินเทอร์วัล',
@@ -202,8 +215,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 +258,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 +266,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': 'สร้างโปรไฟล์แล้ว — ย้ายข้อมูลจากเครื่องนี้เข้าไปแล้ว',
@@ -298,7 +325,6 @@ export default {
'Week starts on': 'สัปดาห์เริ่มวัน',
'Rest timer': 'ตัวจับเวลาพัก',
'Sounds': 'เสียง',
'Note: switching units only changes the label — logged numbers are not converted.': 'หมายเหตุ: การเปลี่ยนหน่วยจะเปลี่ยนแค่ป้ายกำกับ — ตัวเลขที่บันทึกไว้จะไม่ถูกแปลง',
'Data': 'ข้อมูล',
'Export backup (JSON)': 'ส่งออกข้อมูลสำรอง (JSON)',
'Import backup': 'นำเข้าข้อมูลสำรอง',
@@ -404,6 +430,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': 'ซ่อน',
@@ -517,6 +549,11 @@ export default {
// --- v1.2.2: timed sets, progression, estimated 1RM (#16 #17 #18) ---
'Top set': 'เซ็ตที่หนักที่สุด',
'Est. 1RM': '1RM โดยประมาณ',
'No sessions logged yet': 'ยังไม่มีการบันทึกเซสชัน',
'{0} session': '{0} เซสชัน',
'{0} sessions': '{0} เซสชัน',
'Exercise history': 'ประวัติท่าออกกำลังกาย',
'Last {0} sessions': '{0} เซสชันล่าสุด',
'Estimated 1RM': '1RM โดยประมาณ',
'Estimated 1RM per workout': '1RM โดยประมาณต่อครั้ง',
'Best estimate from {0} on {1} — an estimate, not a tested max.': 'ประมาณการดีที่สุดจาก {0} เมื่อ {1} — เป็นค่าประมาณ ไม่ใช่ค่าที่ทดสอบจริง',
@@ -579,6 +616,11 @@ export default {
'Two more reps': 'ยังเหลืออีกสองครั้ง',
'Three more reps': 'ยังเหลืออีกสามครั้ง',
'Easy — warm-up territory': 'ง่าย — ระดับวอร์มอัป',
'Maybe half a rep left': 'อาจเหลืออีกครึ่งครั้ง',
'How hard was that set?': 'เซ็ตนั้นหนักแค่ไหน?',
'Tap how many reps you had left, or type an exact {0}.': 'แตะเลือกว่าเหลืออีกกี่ครั้ง หรือพิมพ์ค่า {0} ที่แน่นอน',
'Exact {0}': '{0} ที่แน่นอน',
'Clear rating': 'ล้างการประเมิน',
'RIR counts the reps you left; RPE reads the same effort off a 10-point scale — so RPE ≈ 10 − RIR. Pick the one you already think in.': 'RIR นับจำนวนครั้งที่เหลือ ส่วน RPE วัดความหนักเดียวกันบนสเกล 10 ระดับ — ดังนั้น RPE ≈ 10 − RIR เลือกแบบที่คุณคุ้นเคยได้เลย',
'The highlighted row is where most working sets land. Sets you have already logged keep their own scale, and nothing else reads the value — progression and estimated 1RM are unaffected.': 'แถวที่ไฮไลต์คือช่วงที่เซ็ตส่วนใหญ่มักอยู่ เซ็ตที่บันทึกไปแล้วจะคงมาตรวัดเดิมไว้ และไม่มีส่วนอื่นนำค่านี้ไปใช้ — การเพิ่มระดับและ 1RM โดยประมาณจะไม่ได้รับผลกระทบ',
// --- effort in the stats ---
@@ -756,6 +798,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 +1158,38 @@ 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.': 'การเข้าถึงกล้องถูกปฏิเสธ — อนุญาตในเบราว์เซอร์แล้วลองอีกครั้ง',
'Add note': 'เพิ่มโน้ต',
'Edit note': 'แก้ไขโน้ต',
'Progression settings': 'ตั้งค่าการเพิ่มน้ำหนัก',
'Set {0}': 'เซ็ต {0}',
'Drop set': 'ดรอปเซ็ต',
'Rest-pause burst': 'เรสต์พอส',
'Remove this set': 'ลบเซ็ตนี้',
'Workout controls': 'ปุ่มระหว่างออกกำลังกาย',
'Weight and reps buttons': 'ปุ่ม +/− น้ำหนักและจำนวนครั้ง',
'Off: tap the number and type it': 'ปิด: แตะตัวเลขแล้วพิมพ์เอง',
'Drop and burst shortcuts on every set': 'ปุ่มลัดดรอปเซ็ตและเรสต์พอสทุกเซ็ต',
'Superset buttons in the exercise header': 'ปุ่มซูเปอร์เซ็ตในหัวข้อท่า',
'Move, swap and remove buttons below the exercise': 'ปุ่มย้าย สลับ และลบใต้ท่าออกกำลังกาย',
'Everything hidden here stays one tap away: the ⋯ button of an exercise and the number of a set.': 'ทุกอย่างที่ซ่อนไว้ยังอยู่ห่างแค่แตะเดียว: ปุ่ม ⋯ ของท่าและหมายเลขเซ็ต',
'Convert to {0}?': 'แปลงเป็น {0} ไหม?',
'Every stored weight — logged sets, working weights, routine targets, body weight, bar weights — is in {0}. Convert the numbers, or keep them and only change the label?': 'น้ำหนักที่บันทึกไว้ทั้งหมด — เซ็ตที่บันทึก น้ำหนักทำงาน เป้าหมายของรูทีน น้ำหนักตัว น้ำหนักบาร์ — เป็นหน่วย {0} จะแปลงตัวเลข หรือคงตัวเลขไว้และเปลี่ยนแค่ป้ายหน่วย?',
'Convert the numbers': 'แปลงตัวเลข',
'Keep the numbers, change the label': 'คงตัวเลขไว้ เปลี่ยนแค่ป้าย',
'Switching the unit offers to convert every stored weight.': 'เมื่อเปลี่ยนหน่วยจะมีตัวเลือกให้แปลงน้ำหนักที่บันทึกไว้ทั้งหมด',
'Update to {0}?': 'อัปเดตเป็น {0} หรือไม่?',
'The latest version will be downloaded and the installer will open.': 'เวอร์ชันล่าสุดจะถูกดาวน์โหลดและตัวติดตั้งจะเปิดขึ้น',
'Download & Install': 'ดาวน์โหลดและติดตั้ง',
'Update failed: {0}': 'อัปเดตล้มเหลว: {0}',
'openGym v{0} available': 'openGym v{0} พร้อมใช้งาน',
'Starting download…': 'กำลังเริ่มดาวน์โหลด…',
'Downloading update…': 'กำลังดาวน์โหลดอัปเดต…',
'{0} %': '{0}%',
'{0} MB': '{0} MB',
'Checksum not available — not installing': 'ไม่มีค่าตรวจสอบ — ยกเลิกการติดตั้ง',
}
+106 -5
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',
@@ -82,6 +89,12 @@ export default {
'Search {0} exercises…': '{0} egzersiz içinde ara…',
'Chosen': 'Seçilenler',
'Nothing chosen yet — add exercises and they’ll show up here.': 'Henüz seçim yok — egzersiz ekledikçe burada görünecekler.',
'Add to favourites': 'Favorilere ekle',
'Remove from favourites': 'Favorilerden çıkar',
'Added to favourites': 'Favorilere eklendi',
'Removed from favourites': 'Favorilerden çıkarıldı',
'Favourites': 'Favoriler',
'No favourites here — tap the star on an exercise to add it.': 'Burada favori yok — eklemek için bir egzersizin yıldızına dokun.',
'No match': 'Sonuç yok',
'Show more': 'Daha fazla göster',
'Intervals': 'Aralıklar',
@@ -202,8 +215,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 +255,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 +262,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ı',
@@ -292,7 +319,6 @@ export default {
'Rest timer': 'Dinlenme sayacı',
'Sounds': 'Sesler',
'Flash screen when timer ends': 'Zamanlayıcı bitince ekranı yanıp söndür',
'Note: switching units only changes the label — logged numbers are not converted.': 'Not: birim değiştirmek sadece etiketi değiştirir — kayıtlı sayılar dönüştürülmez.',
'Data': 'Veriler',
'Export backup (JSON)': 'Yedeği dışa aktar (JSON)',
'Import backup': 'Yedeği içe aktar',
@@ -394,6 +420,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',
@@ -533,6 +565,11 @@ export default {
// --- v1.2.2: timed sets, progression, estimated 1RM (#16 #17 #18) ---
'Top set': 'En iyi set',
'Est. 1RM': 'Tah. 1RM',
'No sessions logged yet': 'Henüz kayıtlı seans yok',
'{0} session': '{0} seans',
'{0} sessions': '{0} seans',
'Exercise history': 'Egzersiz geçmişi',
'Last {0} sessions': 'Son {0} seans',
'Estimated 1RM': 'Tahmini 1RM',
'Estimated 1RM per workout': 'Antrenman başına tahmini 1RM',
'Best estimate from {0} on {1} — an estimate, not a tested max.': '{1} tarihli {0} setinden en iyi tahmin — test edilmiş bir maksimum değil, tahmin.',
@@ -599,6 +636,11 @@ export default {
'Two more reps': 'İki tekrar daha vardı',
'Three more reps': 'Üç tekrar daha vardı',
'Easy — warm-up territory': 'Kolay — ısınma bölgesi',
'Maybe half a rep left': 'Belki yarım tekrar kalmıştı',
'How hard was that set?': 'O set ne kadar zordu?',
'Tap how many reps you had left, or type an exact {0}.': 'Kaç tekrar kaldığına dokun ya da tam bir {0} değeri gir.',
'Exact {0}': 'Tam {0}',
'Clear rating': 'Değerlendirmeyi temizle',
'RIR counts the reps you left; RPE reads the same effort off a 10-point scale — so RPE ≈ 10 − RIR. Pick the one you already think in.': 'RIR yedekte bıraktığın tekrarları sayar; RPE aynı eforu 10’luk ölçekte okur — yani RPE ≈ 10 − RIR. Zaten hangisiyle düşünüyorsan onu seç.',
'The highlighted row is where most working sets land. Sets you have already logged keep their own scale, and nothing else reads the value — progression and estimated 1RM are unaffected.': 'Vurgulanan satır, çalışma setlerinin çoğunun denk geldiği yerdir. Daha önce kaydettiğin setler kendi ölçeğini korur ve bu değeri başka hiçbir şey okumaz — ilerleme ve tahmini 1RM etkilenmez.',
// --- effort in the stats ---
@@ -1080,4 +1122,63 @@ 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.',
'Add note': 'Not ekle',
'Edit note': 'Notu düzenle',
'Progression settings': 'İlerleme ayarları',
'Set {0}': 'Set {0}',
'Drop set': 'Drop set',
'Rest-pause burst': 'Rest-pause patlaması',
'Remove this set': 'Bu seti kaldır',
'Workout controls': 'Antrenman kontrolleri',
'Weight and reps buttons': 'Ağırlık ve tekrar +/− düğmeleri',
'Off: tap the number and type it': 'Kapalı: sayıya dokunup yazın',
'Drop and burst shortcuts on every set': 'Her sette drop ve patlama kısayolları',
'Superset buttons in the exercise header': 'Egzersiz başlığında süperset düğmeleri',
'Move, swap and remove buttons below the exercise': 'Egzersizin altında taşı, değiştir ve kaldır düğmeleri',
'Everything hidden here stays one tap away: the ⋯ button of an exercise and the number of a set.': 'Burada gizlenen her şey bir dokunuş uzakta kalır: egzersizin ⋯ düğmesi ve setin numarası.',
'Convert to {0}?': '{0} birimine çevrilsin mi?',
'Every stored weight — logged sets, working weights, routine targets, body weight, bar weights — is in {0}. Convert the numbers, or keep them and only change the label?': 'Kayıtlı tüm ağırlıklar — setler, çalışma ağırlıkları, rutin hedefleri, vücut ağırlığı, bar ağırlıkları — {0} cinsinden. Sayılar çevrilsin mi, yoksa sayılar kalıp yalnızca etiket mi değişsin?',
'Convert the numbers': 'Sayıları çevir',
'Keep the numbers, change the label': 'Sayıları koru, etiketi değiştir',
'Switching the unit offers to convert every stored weight.': 'Birim değiştirilince tüm kayıtlı ağırlıkları çevirme seçeneği sunulur.',
'Update to {0}?': '{0} sürümüne güncellensin mi?',
'The latest version will be downloaded and the installer will open.': 'En son sürüm indirilecek ve yükleyici açılacak.',
'Download & Install': 'İndir ve Kur',
'Update failed: {0}': 'Güncelleme başarısız: {0}',
'openGym v{0} available': 'openGym v{0} mevcut',
'Starting download…': 'İndirme başlatılıyor…',
'Downloading update…': 'Güncelleme indiriliyor…',
'{0} %': '%{0}',
'{0} MB': '{0} MB',
'Checksum not available — not installing': 'Sağlama toplamı yok — yüklenmedi',
}
+106 -5
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': '自由训练',
@@ -82,6 +89,12 @@ export default {
'Search {0} exercises…': '搜索 {0} 个动作…',
'Chosen': '常用',
'Nothing chosen yet — add exercises and they’ll show up here.': '还没有常用动作——添加后会显示在这里。',
'Add to favourites': '加入收藏',
'Remove from favourites': '取消收藏',
'Added to favourites': '已加入收藏',
'Removed from favourites': '已取消收藏',
'Favourites': '收藏',
'No favourites here — tap the star on an exercise to add it.': '这里还没有收藏——点动作旁的星标即可加入。',
'No match': '没有匹配',
'Show more': '显示更多',
'Intervals': '间歇数',
@@ -202,8 +215,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 +255,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 +262,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': '档案已创建——数据已转入',
@@ -292,7 +319,6 @@ export default {
'Rest timer': '休息计时',
'Sounds': '声音',
'Flash screen when timer ends': '计时结束时闪烁屏幕',
'Note: switching units only changes the label — logged numbers are not converted.': '注意:切换单位只改变标签——已记录的数字不会换算。',
'Data': '数据',
'Export backup (JSON)': '导出备份(JSON)',
'Import backup': '导入备份',
@@ -394,6 +420,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': '隐藏',
@@ -533,6 +565,11 @@ export default {
// --- v1.2.2: timed sets, progression, estimated 1RM (#16 #17 #18) ---
'Top set': '最佳组',
'Est. 1RM': '预估 1RM',
'No sessions logged yet': '尚未记录任何训练',
'{0} session': '{0} 次训练',
'{0} sessions': '{0} 次训练',
'Exercise history': '动作历史',
'Last {0} sessions': '最近 {0} 次训练',
'Estimated 1RM': '预估 1RM',
'Estimated 1RM per workout': '每次训练的预估 1RM',
'Best estimate from {0} on {1} — an estimate, not a tested max.': '基于 {1} 的 {0} 得出的最佳预估——这是推算值,不是实测极限。',
@@ -599,6 +636,11 @@ export default {
'Two more reps': '还能再做两次',
'Three more reps': '还能再做三次',
'Easy — warm-up territory': '轻松——热身区间',
'Maybe half a rep left': '也许还能再做半次',
'How hard was that set?': '这组有多吃力?',
'Tap how many reps you had left, or type an exact {0}.': '点选你还能再做几次,或直接输入准确的 {0}。',
'Exact {0}': '准确的 {0}',
'Clear rating': '清除评分',
'RIR counts the reps you left; RPE reads the same effort off a 10-point scale — so RPE ≈ 10 − RIR. Pick the one you already think in.': 'RIR 数的是你还留了几次;RPE 把同样的吃力程度换成 10 分制来读——所以 RPE ≈ 10 − RIR。选你习惯的那一种。',
'The highlighted row is where most working sets land. Sets you have already logged keep their own scale, and nothing else reads the value — progression and estimated 1RM are unaffected.': '高亮那一行是大多数正式组落在的位置。已经记录的组保留原来的标度,而且这个值不会被别处读取——进阶计划和预估 1RM 都不受影响。',
// --- effort in the stats ---
@@ -1080,4 +1122,63 @@ 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.': '摄像头访问被拒绝 — 请在浏览器中允许后重试。',
'Add note': '添加备注',
'Edit note': '编辑备注',
'Progression settings': '渐进设置',
'Set {0}': '第 {0} 组',
'Drop set': '递减组',
'Rest-pause burst': '休息暂停组',
'Remove this set': '删除这一组',
'Workout controls': '训练中的按钮',
'Weight and reps buttons': '重量和次数的 +/− 按钮',
'Off: tap the number and type it': '关闭:点按数字直接输入',
'Drop and burst shortcuts on every set': '每组显示递减/休息暂停快捷按钮',
'Superset buttons in the exercise header': '动作标题中的超级组按钮',
'Move, swap and remove buttons below the exercise': '动作下方的移动、替换和删除按钮',
'Everything hidden here stays one tap away: the ⋯ button of an exercise and the number of a set.': '这里隐藏的一切都只需一次点按:动作的 ⋯ 按钮和组号。',
'Convert to {0}?': '换算为 {0}?',
'Every stored weight — logged sets, working weights, routine targets, body weight, bar weights — is in {0}. Convert the numbers, or keep them and only change the label?': '所有已保存的重量(记录的组、工作重量、计划目标、体重、杠铃杆重量)目前以 {0} 计。是换算数值,还是保留数值只更改单位标签?',
'Convert the numbers': '换算数值',
'Keep the numbers, change the label': '保留数值,只改标签',
'Switching the unit offers to convert every stored weight.': '切换单位时会提示换算所有已保存的重量。',
'Update to {0}?': '更新到 {0}?',
'The latest version will be downloaded and the installer will open.': '将下载最新版本并打开安装程序。',
'Download & Install': '下载并安装',
'Update failed: {0}': '更新失败:{0}',
'openGym v{0} available': 'openGym v{0} 可用',
'Starting download…': '正在开始下载…',
'Downloading update…': '正在下载更新…',
'{0} %': '{0}%',
'{0} MB': '{0} MB',
'Checksum not available — not installing': '校验和不可用,已取消安装',
}
+96
View File
@@ -0,0 +1,96 @@
// @vitest-environment happy-dom
// Favourites (issue #6): the detail sheet's star writes S.favEx, and the picker floats
// favourites to the top of its list without disturbing the order of everything else.
import React, { act } from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { createRoot } from 'react-dom/client'
import { EXDB } from './lib/exercises.js'
import { DEF, useStore } from './store/useStore.js'
import { useUI } from './store/useUI.js'
import { exerciseDetailSheet, exercisePicker } from './sheets.jsx'
const mounted = []
const S = () => useStore.getState().S
// Renders whatever sheet is on top and returns its host element.
function renderTop() {
const sheet = useUI.getState().sheets.at(-1)
const host = document.createElement('div')
document.body.appendChild(host)
const root = createRoot(host)
mounted.push(root)
act(() => root.render(sheet.render(() => useUI.getState().closeSheet(sheet.id))))
return host
}
const names = host => [...host.querySelectorAll('.item .tt')].map(el => el.textContent)
const starOf = host => host.querySelector('.fav-btn')
beforeEach(() => {
globalThis.IS_REACT_ACT_ENVIRONMENT = true
useUI.setState({ sheets: [], toastMsg: '' })
useStore.setState({ S: structuredClone(DEF), user: null })
document.body.innerHTML = ''
})
afterEach(() => {
act(() => { mounted.splice(0).forEach(root => root.unmount()) })
})
describe('exercise detail star', () => {
it('adds and removes the exercise from favourites with a toast', () => {
const ex = EXDB[0]
exerciseDetailSheet(ex)
const host = renderTop()
expect(starOf(host).getAttribute('aria-label')).toBe('Add to favourites')
act(() => starOf(host).click())
expect(S().favEx).toEqual([ex.id])
expect(useUI.getState().toastMsg).toBe('Added to favourites')
expect(starOf(host).getAttribute('aria-label')).toBe('Remove from favourites')
expect(starOf(host).getAttribute('aria-pressed')).toBe('true')
act(() => starOf(host).click())
expect(S().favEx).toEqual([])
expect(useUI.getState().toastMsg).toBe('Removed from favourites')
})
it('tolerates a profile written before the field existed', () => {
useStore.setState(s => { const next = { ...s.S }; delete next.favEx; return { S: next } })
exerciseDetailSheet(EXDB[0])
const host = renderTop()
act(() => starOf(host).click())
expect(S().favEx).toEqual([EXDB[0].id])
})
})
describe('exercise picker', () => {
it('lists favourites first and marks them, keeping the rest in catalogue order', () => {
const plain = names((exercisePicker(vi.fn()), renderTop())).slice(1) // drop "Create your own"
useUI.setState({ sheets: [] })
const fav = [plain[7], plain[3]]
const favIds = fav.map(n => EXDB.find(e => e.n === n).id)
useStore.setState(s => ({ S: { ...s.S, favEx: favIds } }))
exercisePicker(vi.fn())
const host = renderTop()
const shown = names(host).slice(1)
// Favourites keep the list's own order among themselves — not the order they were starred in.
expect(shown.slice(0, 2)).toEqual(plain.filter(n => fav.includes(n)))
expect(shown.slice(2)).toEqual(plain.filter(n => !fav.includes(n)))
const rows = [...host.querySelectorAll('.item')].slice(1)
expect(rows.slice(0, 2).every(r => r.querySelector('.tt .fav-star'))).toBe(true)
expect(rows[2].querySelector('.tt .fav-star')).toBeNull()
})
it('offers a Favourites chip only when there are favourites, and it filters to them', () => {
exercisePicker(vi.fn())
let host = renderTop()
const chip = h => [...h.querySelectorAll('.chips .chip')].find(b => b.textContent.startsWith('Favourites'))
expect(chip(host)).toBeUndefined()
useUI.setState({ sheets: [] })
useStore.setState(s => ({ S: { ...s.S, favEx: [EXDB[5].id, EXDB[9].id] } }))
exercisePicker(vi.fn())
host = renderTop()
expect(chip(host).textContent).toBe('Favourites (2)')
act(() => chip(host).click())
expect(names(host)).toEqual([EXDB[5].n, EXDB[9].n])
})
})
+91
View File
@@ -0,0 +1,91 @@
// @vitest-environment happy-dom
// The history sheet (issue #43) is the one place the workout screen answers "what did I do
// on this last time, and the time before" — worth pinning that it reads the log newest
// first, labels sets the way the rest of the app does, and does not pretend an exercise
// with no sessions has a curve.
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 { exerciseHistorySheet, exerciseDetailSheet } from './sheets.jsx'
import { EXIDX } from './lib/exercises.js'
const mounted = []
function renderTop() {
const sheet = useUI.getState().sheets.at(-1)
const host = document.createElement('div')
document.body.appendChild(host)
const root = createRoot(host)
mounted.push(root)
act(() => root.render(sheet.render(() => useUI.getState().closeSheet(sheet.id))))
return host
}
const EX = Object.keys(EXIDX).find(id => (EXIDX[id].bp || '') !== 'cardio' && !EXIDX[id].custom)
const DAY = 86400000
const T0 = Date.UTC(2026, 2, 2, 9)
const iso = i => new Date(T0 + i * DAY).toISOString().slice(0, 10)
const session = (i, rows) => ({
id: 'w' + i, d: iso(i), start: T0 + i * DAY, end: T0 + i * DAY + 3600000, name: 'Push', vol: 0,
entries: [{ id: EX, target: { mode: 'reps', bodyweight: false }, sets: rows }],
})
beforeEach(() => {
globalThis.IS_REACT_ACT_ENVIRONMENT = true
useUI.setState({ sheets: [], toastMsg: '' })
useStore.setState(s => ({ S: { ...s.S, unit: 'kg', workouts: [], active: null } }))
document.body.innerHTML = ''
})
afterEach(() => {
act(() => { mounted.splice(0).forEach(root => root.unmount()) })
})
describe('exercise history sheet', () => {
it('shows an empty state instead of a chart when nothing was logged', () => {
exerciseHistorySheet(EX)
const host = renderTop()
expect(host.querySelector('.empty').textContent).toContain('No sessions logged yet')
expect(host.querySelector('.chart')).toBeNull()
})
it('lists sessions newest first with labelled sets, volume and one PR marker', () => {
useStore.setState(s => ({ S: { ...s.S, workouts: [
session(0, [{ w: 40, r: 8, done: true, phase: 'warmup' }, { w: 60, r: 5, done: true }, { w: 60, r: 5, done: true }]),
session(2, [{ w: 70, r: 5, done: true }]),
session(4, [{ w: 70, r: 3, done: true }, { w: 90, r: 1, done: false }]),
] } }))
exerciseHistorySheet(EX)
const host = renderTop()
const rows = [...host.querySelectorAll('.list .item')]
expect(rows).toHaveLength(3)
// newest first, oldest last; the warm-up and the unfinished set never show up
expect(rows[0].querySelector('.ss').textContent).toBe('70×3')
expect(rows[2].querySelector('.ss').textContent).toBe('60×5 · 60×5')
expect(rows[2].textContent).toContain('Volume 600 kg')
// the record was set in the middle session and only that one carries the badge
expect(rows.map(r => !!r.querySelector('.pr'))).toEqual([false, true, false])
expect(host.querySelector('.chart svg')).toBeTruthy()
expect(host.textContent).toContain('Best:')
expect(host.textContent).toContain('70 kg')
})
it('is reachable from the exercise detail sheet once there is history', () => {
exerciseDetailSheet(EXIDX[EX])
const before = renderTop()
expect([...before.querySelectorAll('button')].some(b => b.textContent === 'History')).toBe(false)
useStore.setState(s => ({ S: { ...s.S, workouts: [session(0, [{ w: 60, r: 5, done: true }])] } }))
useUI.setState({ sheets: [] })
exerciseDetailSheet(EXIDX[EX])
const host = renderTop()
const btn = [...host.querySelectorAll('button')].find(b => b.textContent === 'History')
expect(btn).toBeTruthy()
act(() => { btn.click() })
expect(useUI.getState().sheets).toHaveLength(2)
const top = renderTop()
expect(top.querySelectorAll('.list .item')).toHaveLength(1)
})
})
+260 -28
View File
@@ -1,27 +1,31 @@
import { useEffect, useRef, useState } from 'react'
import { useEffect, useMemo, useRef, useState } from 'react'
import { useStore } from './store/useStore.js'
import { useUI } from './store/useUI.js'
import { EXDB, EXIDX, BODYPARTS, isCardio, isBodyweightEq, allExercises, equipmentOf, smOf, matchExercise, exOr } from './lib/exercises.js'
import { 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, EFFORT, capEffort, stepEffort, isBw, isPerSide, sideReps, workSetsDone, applyIntensifierPlan, MAX_PLANNED_WARMUPS, NOTE_MAX } from './lib/history.js'
import { usesBar, barWeightFor, defaultBarWeight, hasBarOverride } from './lib/bar.js'
import { toScale, rirOf, EFFORT_PRESETS, effortColor } from './lib/effort.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 LineChart from './components/LineChart.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 { Button, Slider, Switch, Segmented, SelectRow, Row, TextField, NumberField, 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'
import { buildPlanBundle, parsePlan, mergePlan, printPlan } from './lib/plan-share.js'
import { estimate1RM, best1RM, is1RMRecord, REP_CAP } from './lib/onerm.js'
import { nextPrescription, applyPrescription, policyFor, defaultIncrement, POLICIES_FOR, POLICY_NAME, POLICY_DESC, MAX_BW_SETS } from './lib/progression.js'
import { exerciseHistory } from './lib/exercise-history.js'
import { nextPrescription, applyPrescription, policyFor, defaultIncrement, POLICIES_FOR, POLICY_NAME, POLICY_DESC, MAX_BW_SETS, weightIncrement } from './lib/progression.js'
import { normalizeRepRange } from './lib/rep-range.js'
import { MOBILE, shareExport } from './lib/mobile.js'
import { buildCompletedWorkout } from './lib/finish-workout.js'
@@ -29,6 +33,7 @@ import { isWarmupRow } from './lib/workout-model.js'
import { nextUnfinishedUnit } from './lib/supersetFlow.js'
import { swapActiveExercise } from './lib/active-exercise-swap.js'
import { useSheetKeyboard, useRevealActiveChip, tappable } from './lib/use-sheet-keyboard.js'
import { isFav, toggleFav, sortFavouritesFirst } from './lib/favourites.js'
import { buildSessionEntries } from './lib/session-start.js'
import { workoutsOn, backfillStart, backfillEnd, completeBackfill } from './lib/backfill.js'
@@ -48,21 +53,99 @@ function ConfirmDialog({ title, message, confirmText, cancelText, danger, onConf
<Button variant="ghost" className="dim" onClick={close}>{cancelText || t('Cancel')}</Button>
</div>
}
/* ============================ menu sheet ============================ */
// A list of actions, one per row, closing on tap. This is where the workout screen parks
// everything that is not a set you are about to log: the point of a single "more" button is
// that the ten things you do once a session stop competing with the two you do every set.
// items: [{ icon, label, sub, onClick, danger, disabled, on }] — `on` draws a check for toggles.
function MenuSheet({ title, subtitle, items, close }) {
return <>
{title && <h3 style={{ marginBottom: subtitle ? 2 : 10 }}>{title}</h3>}
{subtitle && <div className="muted small" style={{ marginBottom: 10 }}>{subtitle}</div>}
<div className="list menu-list">
{items.filter(Boolean).map((it, i) => <div key={i}
className={'item menu-item' + (it.danger ? ' danger' : '') + (it.disabled ? ' disabled' : '')}
aria-disabled={it.disabled || undefined}
{...tappable(it.disabled ? null : () => { close(); it.onClick && it.onClick() })}>
{it.icon && <span className="lrow-i"><Icon name={it.icon} /></span>}
<div className="grow"><div className="tt">{it.label}</div>{it.sub && <div className="ss">{it.sub}</div>}</div>
{it.on != null && <span className={'menu-on' + (it.on ? ' is-on' : '')}><Icon name="check" /></span>}
</div>)}
</div>
</>
}
export function menuSheet(opts) {
ui().openSheet(close => <MenuSheet {...opts} close={close} />)
}
// Themed replacement for window.confirm — callback-based (no blocking).
export function confirmSheet(opts) {
ui().openSheet(close => <ConfirmDialog {...opts} close={close} />, { kind: 'center' })
}
/* ============================ 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 routines = useStore(s => s.S.routines)
const choose = (id, name) => {
const days = starterPlanDays(id)
close()
// A confirmation is only worth showing when one of those days is actually occupied — by a
// routine that still exists, not by a stale id the Plan already shows as "Rest".
const taken = day => week[day] && routines.some(r => r.id === week[day])
if (!days.some(taken)) { 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
@@ -542,8 +625,20 @@ function ExerciseDetail({ ex, close }) {
const st = useStore(s => s.S)
const last = lastEntryFor(st, ex.id)
const best = bestWeightFor(st, ex.id)
const fav = isFav(st, ex.id)
const flipFav = () => {
let on = false
update(s => { on = toggleFav(s, ex.id) })
toast(on ? t('Added to favourites') : t('Removed from favourites'))
}
return <>
<h3 className="capitalize">{exerciseNameFor(ex)}</h3>
<div className="row between" style={{ gap: 8, alignItems: 'flex-start' }}>
<h3 className="capitalize">{exerciseNameFor(ex)}</h3>
<button className={'iconbtn fav-btn' + (fav ? ' on' : '')} aria-pressed={fav}
aria-label={fav ? t('Remove from favourites') : t('Add to favourites')} onClick={flipFav}>
<Icon name={fav ? 'starFill' : 'star'} />
</button>
</div>
<Media ex={ex} />
<div className="row" style={{ gap: 6, flexWrap: 'wrap', margin: '10px 0' }}>
<span className="tag acc">{t(ex.bp)}</span>
@@ -554,6 +649,7 @@ function ExerciseDetail({ ex, close }) {
{ex.desc && <div className="exnote">{ex.desc}</div>}
{best > 0 && <div className="small row" style={{ marginBottom: 6, gap: 5 }}><Icon name="trophy" style={{ fontSize: 14, color: 'var(--yellow)' }} />{t('Best:')} <b className="accent">{fmtNum(best)} {st.unit}</b>{last ? ` · ${t('last')} ${fmtDate(last.d)}: ${last.sets.map(s => setLabel(ex.id, s, last.target)).join(', ')}` : ''}</div>}
<Button variant="primary" icon="plus" style={{ margin: '10px 0 4px' }} onClick={() => addToRoutineSheet(ex)}>{t('Add to my plan')}</Button>
{last && <Button icon="history" style={{ marginTop: 4 }} onClick={() => exerciseHistorySheet(ex.id)}>{t('History')}</Button>}
{ex.custom && <div className="row" style={{ gap: 8, marginTop: 8 }}>
<Button icon="pencil" style={{ flex: 1 }} onClick={() => { close(); customExSheet(ex) }}>{t('Edit')}</Button>
<Button variant="danger" icon="trash" style={{ flex: 1 }} onClick={() => deleteCustomEx(ex, close)}>{t('Delete')}</Button>
@@ -568,6 +664,56 @@ function ExerciseDetail({ ex, close }) {
}
export const exerciseDetailSheet = ex => ui().openSheet(close => <ExerciseDetail ex={ex} close={close} />)
/* ============================ exercise history ============================ */
// What you did on this exercise before, reachable mid-workout (issue #43): the curve first,
// then the last sessions set by set, so the question "what did I do last month" is answered
// without leaving the workout for Stats. Derived once per log change — the sheet re-renders on
// every store tick while a session runs, and LineChart drops its hover whenever `points`
// changes identity, so a series rebuilt per render would lose the tooltip under your finger.
function ExerciseHistory({ exId }) {
const st = useStore(s => s.S)
const ex = exOr(exId)
const h = useMemo(() => exerciseHistory(st, exId), [st.workouts, exId])
const [curve, setCurve] = useState('top')
const onE1 = curve === 'e1rm' && h.e1rmPoints.length > 0
const unit = h.metric === 'weight' ? st.unit : h.metric === 'reps' ? t('reps') : h.metric === 'sec' ? 's' : t('min')
const e1Best = useMemo(() => Math.max(0, ...h.e1rmPoints.map(p => p.y)), [h])
if (!h.total) return <>
<h3 className="capitalize">{exerciseNameFor(ex)}</h3>
<div className="empty"><div className="ico"><Icon name="history" /></div>{t('No sessions logged yet')}</div>
</>
const tail = s => [
s.volume > 0 && t('Volume') + ' ' + fmtVol(s.volume, st.unit),
s.e1rm != null && t('Est. 1RM') + ' ' + fmtNum(s.e1rm) + ' ' + st.unit,
].filter(Boolean).join(' · ')
return <>
<h3 className="capitalize" style={{ marginBottom: 2 }}>{exerciseNameFor(ex)}</h3>
<div className="muted small" style={{ marginBottom: 10 }}>{t('Exercise history')} · {t(h.total === 1 ? '{0} session' : '{0} sessions', h.total)}</div>
{/* Only reps work with a load produces an estimate, so the toggle is absent for the rest. */}
{h.e1rmPoints.length > 0 && h.metric === 'weight' && <Segmented className="seg-range" value={curve} onChange={setCurve}
options={[{ value: 'top', label: t('Top set') }, { value: 'e1rm', label: t('Est. 1RM') }]} />}
<div className="chart" style={{ marginTop: 8 }}>
<LineChart points={onE1 ? h.e1rmPoints : h.points} h={140} unit={onE1 ? st.unit : unit} color="var(--blue)" />
</div>
<div className="small row" style={{ margin: '6px 0 4px', gap: 5 }}>
<Icon name="trophy" style={{ fontSize: 14, color: 'var(--yellow)' }} />
{t('Best:')} <b className="accent">{fmtNum(onE1 ? e1Best : h.best)} {onE1 ? st.unit : unit}</b>
</div>
<h4 className="sec">{h.sessions.length < h.total ? t('Last {0} sessions', h.sessions.length) : t('Sessions')}</h4>
<div className="list">
{h.sessions.map(s => <div key={s.id} className="item" style={{ alignItems: 'flex-start' }}>
<div className="grow">
<div className="tt">{fmtDate(s.d, true)} {s.pr && <span className="pr"><Icon name="trophy" />PR</span>}</div>
<div className="ss">{s.sets.map(x => setLabel(exId, x, s.target)).join(' · ')}</div>
{tail(s) && <div className="small dim" style={{ marginTop: 3 }}>{tail(s)}</div>}
</div>
{s.value != null && s.value > 0 && <b className="accent nocap" style={{ whiteSpace: 'nowrap' }}>{fmtNum(s.value)} {unit}</b>}
</div>)}
</div>
</>
}
export const exerciseHistorySheet = exId => ui().openSheet(close => <ExerciseHistory exId={exId} close={close} />)
/* ============================ add to routine ============================ */
function AddToRoutine({ ex, close }) {
const st = useStore(s => s.S)
@@ -689,6 +835,7 @@ export function deleteCustomEx(ex, afterDelete) {
s.customEx = (s.customEx || []).filter(x => x.id !== ex.id)
s.routines.forEach(r => { r.ex = r.ex.filter(e => e.id !== ex.id); cleanupSg(r.ex) })
delete s.exWeights[ex.id]
s.favEx = (s.favEx || []).filter(id => id !== ex.id)
})
toast(t('Exercise deleted'))
afterDelete && afterDelete()
@@ -708,29 +855,41 @@ function ExercisePicker({ onPick, close }) {
const st = useStore(s => s.S)
const usage = usageMap(st)
const [q, setQ] = useState('')
const [bp, setBp] = useState('') // '' = all, '★' = chosen, else a body part
const [bp, setBp] = useState('') // '' = all, '★' = chosen, '☆' = favourites, else a body part
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)
const all = allExercises(st)
const profile = activeProfile(st)
let base = all.filter(e =>
(bp === '★' ? usage[e.id] : (!bp || e.bp === bp)) &&
matchExercise(e, q))
const inScope = e => bp === '★' ? usage[e.id] : bp === '☆' ? isFav(st, e.id) : (!bp || e.bp === bp)
let base = all.filter(e => inScope(e) && matchExercise(e, q))
if (bp === '★') base = [...base].sort((a, b) => (usage[b.id] - usage[a.id]) || exerciseNameFor(a).localeCompare(exerciseNameFor(b)))
const eqFiltered = (profile && !showAll) ? base.filter(e => exAvailable(st, e)) : base
const eqOpts = equipmentOf(eqFiltered)
// Drop the equipment filter if the search narrowed it away, so you never hit a dead end.
const eqOn = eqOpts.includes(eq) ? eq : ''
const f = eqOn ? eqFiltered.filter(e => e.eq === eqOn) : eqFiltered
// Favourites float to the top of whatever the filters left (issue #6), the rest keeps its order.
const f = sortFavouritesFirst(eqOn ? eqFiltered.filter(e => e.eq === eqOn) : eqFiltered, st)
const chosenCount = Object.keys(usage).length
const favCount = (st.favEx || []).length
const special = bp === '★' || bp === '☆'
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>
@@ -743,6 +902,7 @@ function ExercisePicker({ onPick, close }) {
</button>
</div>}
<div className="chips" ref={bpStrip} style={{ margin: eqOpts.length > 1 ? '10px 0 6px' : '10px 0' }}>
{favCount > 0 && <button className={'chip' + (bp === '☆' ? ' on' : '')} onClick={() => { setBp('☆'); setEq(''); setShown(50) }}><Icon name="starFill" className="fav-star" />{t('Favourites')} ({favCount})</button>}
{chosenCount > 0 && <button className={'chip' + (bp === '★' ? ' on' : '')} onClick={() => { setBp('★'); setEq(''); setShown(50) }}><Icon name="starFill" style={{ fontSize: 12, display: 'inline-block', marginRight: 4, verticalAlign: '-1px' }} />{t('Chosen')} ({chosenCount})</button>}
<button className={'chip nocap' + (!bp ? ' on' : '')} onClick={() => { setBp(''); setEq(''); setShown(50) }}>{t('All')}</button>
{BODYPARTS.map(b => <button key={b} className={'chip' + (bp === b ? ' on' : '')} onClick={() => { setBp(b); setEq(''); setShown(50) }}>{t(b)}</button>)}
@@ -752,15 +912,24 @@ function ExercisePicker({ onPick, close }) {
{eqOpts.map(x => <button key={x} className={'chip' + (eqOn === x ? ' on' : '')} onClick={() => { setEq(x); setShown(50) }}>{t(x)}</button>)}
</div>}
<div className="list">
{bp !== '★' && <div className="item" {...tappable(() => customExSheet(null, ex => onPick(ex), q.trim()))}>
{!special && <div className="item" {...tappable(() => customExSheet(null, ex => onPick(ex), q.trim()))}>
<div className="thumb thumb-x"><Icon name="sparkles" /></div>
<div className="grow"><div className="tt">{t('Create your own exercise')}</div><div className="ss">{t('name + body part, no animation')}</div></div><Icon name="plus" className="chev" />
</div>}
{f.slice(0, shown).map(e => <div key={e.id} className="item" {...tappable(() => onPick(e))}>
<Thumb ex={e} /><div className="grow"><div className="tt capitalize">{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" />
<Thumb ex={e} /><div className="grow"><div className="tt capitalize">{isFav(st, e.id) && <Icon name="starFill" className="fav-star" />}{exerciseNameFor(e)}</div><div className="ss capitalize">{t(e.tg || e.bp)} · {t(e.eq)}</div></div>
{/* Accent tag = already in a routine/log ("Chosen"); the yellow star by the name = favourite. */}
{usage[e.id] && <span className="tag acc"><Icon name="starFill" /></span>}
{/* A "+" glyph reads as "add this now" — it used to just open the same detail sheet as
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>}
{f.length === 0 && bp === '☆' && <div className="empty">{t('No favourites here — tap the star on an exercise to add it.')}</div>}
</div>
{f.length > shown && <><div style={{ height: 8 }} /><Button onClick={() => setShown(s => s + 50)}>{t('Show more')}</Button></>}
</>
@@ -772,7 +941,10 @@ export function swapActiveWorkoutExercise(index) {
const active = S().active
if (!active?.entries?.[index]) return
const picker = exercisePicker(ex => exConfigSheet(ex, null, cfg => {
// The "+" on a picker row commits with the default config, exactly as it does in the add
// flows; tapping the row still opens the config sheet first.
const picker = exercisePicker((ex, quick) => quick ? swapTo(ex, defaultConfig(ex.id)) : exConfigSheet(ex, null, cfg => swapTo(ex, cfg), null, null))
function swapTo(ex, cfg) {
// The picker is a chooser here, not a stack you keep adding from: one swap, then back to
// the workout. (The add flow deliberately leaves it open.)
picker.close()
@@ -781,9 +953,9 @@ export function swapActiveWorkoutExercise(index) {
// Same rows the add flow builds: last time's loads and, in a planned session, the
// prescription — swapping barbell for dumbbell bench must not start you at an empty bar.
const freestyle = !st.active?.routineId
const step = defaultIncrement(ex.id, st.unit)
const step = modeOf(full) === 'reps' ? weightIncrement(full, st.unit) : 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 },
@@ -826,7 +998,7 @@ export function swapActiveWorkoutExercise(index) {
confirmText: t('Continue'),
onConfirm: () => apply({ loggedConfirmed: true })
})
}))
}
}
/* ============================ equipment profiles ============================ */
@@ -1189,6 +1361,66 @@ export const glyphPicker = (current, onPick) => {
</>)
}
/* ============================ effort quick picker (RIR / RPE) ============================ */
// Rating a set used to mean walking a +/- stepper up the scale — eleven taps to log "5 reps
// left". This is the one-tap replacement: a colour-coded button per preset, plus a free field
// for the value between two presets. Presets are stored in RIR internally; a profile that logs
// RPE sees the same buttons labelled on its own scale (toScale), coloured identically — the
// colour is the effort, not the number, so 0 RIR and 10 RPE are both the "went to failure" end.
function EffortPicker({ kind, value, onPick, close }) {
// Local mirror so the ticked preset and the exact field track typing live; the store is
// written on every change through onPick, the same as the stepper did.
const [v, setV] = useState(value ?? null)
const set = nv => { setV(nv); onPick(nv) }
// `v` is in the profile's own scale (whatever sits on the set: s.rir or s.rpe). Compare in
// RIR so the tick lands on the right preset on either scale, and so a typed RPE colours the
// same as the RIR it equals.
const curRir = rirOf(kind === 'rpe' ? { rpe: v } : { rir: v })
const curColor = effortColor(curRir)
const commit = nv => { close(); onPick(nv) }
const pick = rir => commit(toScale(kind, rir))
const hd = EFFORT[kind].hd
// Same list the ⋯ menus use: a tinted square with the value where the icon goes, the sentence
// as the row title, a tick on the current one. The exact field is the app's own stepper,
// tinted like the logged cell in the set row, so the sheet and the row read as one thing.
return <>
<h3 style={{ marginBottom: 2 }}>{t('How hard was that set?')}</h3>
<div className="muted small" style={{ marginBottom: 10 }}>{t('Tap how many reps you had left, or type an exact {0}.', hd)}</div>
<div className="list menu-list effpick">
{EFFORT_PRESETS.map(p => {
const label = fmtNum(toScale(kind, p.rir)) + (p.tail ? '+' : '')
const on = curRir != null && curRir === p.rir
return <div key={p.rir} className={'item menu-item' + (on ? ' on' : '')} style={{ '--bc': p.color }}
{...tappable(() => pick(p.rir))}>
<span className="lrow-i effpick-n">{label}</span>
<div className="grow"><div className="tt">{t(p.feel)}</div></div>
<span className={'menu-on' + (on ? ' is-on' : '')}><Icon name="check" /></span>
</div>
})}
<div className="item menu-item effpick-free">
<div className="grow"><div className="tt">{t('Exact {0}', hd)}</div></div>
<div className="stp effcell-stp"
style={curColor ? { color: curColor, background: `color-mix(in srgb, ${curColor} 20%, var(--surface-2))` } : undefined}>
<button aria-label="Decrease" onClick={() => set(stepEffort(kind, v, -1))}><Icon name="minus" /></button>
<span className="val"><NumberField decimal nullable value={v ?? ''} placeholder="–"
onChange={nv => set(capEffort(kind, nv))} /></span>
<button aria-label="Increase" onClick={() => set(stepEffort(kind, v, 1))}><Icon name="plus" /></button>
</div>
</div>
</div>
{v != null && <>
<div style={{ height: 10 }} />
<Button variant="ghost" className="dim" icon="xmark" onClick={() => commit(null)}>{t('Clear rating')}</Button>
</>}
<div style={{ height: 4 }} />
</>
}
// kind is 'rir' | 'rpe'; value is the set's current rating on that scale (or null); onPick
// receives the new value on that same scale (null to clear). The caller stores it exactly as
// weight/reps are stored — a null drops the key rather than writing a zero.
export const effortPickerSheet = (kind, value, onPick) =>
ui().openSheet(close => <EffortPicker kind={kind} value={value} onPick={onPick} close={close} />)
/* ============================ share / print / import a plan ============================ */
export const planToolsSheet = () => ui().openSheet(close => <PlanTools close={close} />)
@@ -1740,7 +1972,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,43 @@
// @vitest-environment happy-dom
// /api/config is what tells a client whether the server offers the Coach (and guest mode).
// loadConfig() caches it for a boot; refreshConfig() always asks — the Coach setup screen on a
// paired phone relies on that, because the admin may have switched the Coach on since boot.
// The bug this pins: the phone never fetched it at all, and said "your server has no Coach
// enabled" to a server whose admin was looking at a green test.
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
vi.mock('../lib/api.js', () => ({ api: vi.fn() }))
import { api } from '../lib/api.js'
import { useStore } from './useStore.js'
beforeEach(() => { api.mockReset(); useStore.setState({ config: null }) })
afterEach(() => { useStore.setState({ config: null }) })
describe('server config', () => {
it('loadConfig fetches once and then answers from the cache', async () => {
api.mockResolvedValue({ invite_only: true, allow_guest: false, coach: { enabled: true } })
expect(await useStore.getState().loadConfig()).toEqual({ invite_only: true, allow_guest: false, coach: { enabled: true } })
expect(await useStore.getState().loadConfig()).toMatchObject({ coach: { enabled: true } })
expect(api).toHaveBeenCalledTimes(1)
expect(api).toHaveBeenCalledWith('/api/config')
})
it('refreshConfig always asks the server, so a Coach switched on after boot is seen', async () => {
api.mockResolvedValueOnce({ invite_only: true, allow_guest: false })
await useStore.getState().loadConfig()
expect(useStore.getState().config.coach).toBeUndefined()
api.mockResolvedValueOnce({ invite_only: true, allow_guest: false, coach: { enabled: true, provider: 'anthropic' } })
await useStore.getState().refreshConfig()
expect(useStore.getState().config.coach.enabled).toBe(true)
expect(api).toHaveBeenCalledTimes(2)
})
it('an unreachable server leaves the cached config alone', async () => {
useStore.setState({ config: { coach: { enabled: true } } })
api.mockRejectedValueOnce(new Error('offline'))
expect(await useStore.getState().refreshConfig()).toBeNull()
expect(useStore.getState().config.coach.enabled).toBe(true)
})
})
@@ -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)
})
})
+35
View File
@@ -8,12 +8,22 @@ import { MOBILE, initReminderSync, nativeLoad, nativeSave, syncReminder, writeAu
import { loadRemote, chooseLocal, forgetRemote, connect } from '../lib/remote.js'
import { loadCoachDevice, saveCoachDevice, coachDeviceSettings } from '../lib/coach-device.js'
import { WC_DEFAULT } from '../lib/workout-controls.js'
const KEY = 'gym_state_v1'
export const DEF = {
unit: 'kg', restSec: 90, restPauseSec: 15, sound: true, timerFlash: false, keepAwake: true, lang: 'en',
theme: 'dark', accent: 'lime', body: 'male', targetW: null,
bodyweight: [], routines: [], week: {}, dayPlan: {},
exWeights: {}, workouts: [], active: null, customEx: [], gifSize: 'full',
// 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',
// Which controls the workout screen shows besides the sets themselves. The default is the
// lean layout: one "more" button per exercise and a menu on each set number. Every switch
// brings one of the old always-visible button groups back (Settings → During a workout).
wc: { ...WC_DEFAULT },
// 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
@@ -26,6 +36,9 @@ export const DEF = {
// every time you do the movement ("seat 4, pin 7"). Distinct from a routine's `note`, which
// belongs to one exercise in one plan, and from a session note, which belongs to one day.
exNotes: {},
// Favourite exercise ids (issue #6) — sorted to the top of the picker/Library. Personal, so
// it syncs with the profile but is never part of a shared plan bundle (lib/favourites.js).
favEx: [],
// First day of the week as a getDay() index — 1 Monday, 0 Sunday. Monday is the default so
// every profile written before this setting existed keeps the week it has been looking at.
// See lib/format.js: nothing reads this field directly, everything goes through the helpers.
@@ -34,6 +47,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))
@@ -152,6 +177,11 @@ export const useStore = create((set, get) => {
config: null,
async loadConfig() {
if (get().config) return get().config
return get().refreshConfig()
},
// Always asks. The cached copy is right for one boot, but an admin can switch the Coach on
// while a paired phone sits on the setup screen — that screen wants today's answer.
async refreshConfig() {
try { const c = await api('/api/config'); set({ config: c }); return c }
catch { return null }
},
@@ -197,6 +227,7 @@ export const useStore = create((set, get) => {
async connectToServer(url, code) {
const user = await connect(url, code) // throws on a bad URL/expired code — caller shows it
get().setUser(user)
await get().refreshConfig() // what this server offers (the Coach, guest mode) — see boot()
await get().pullState()
syncReminder(get().S)
set({ needsMobileOnboarding: false })
@@ -243,6 +274,10 @@ export const useStore = create((set, get) => {
try {
const me = await api('/api/me') // also catches a token revoked elsewhere (sign out everywhere)
get().setUser(me.user)
// The paired server's /api/config, the same one the web boot reads: without it the
// phone never learned whether the server offers the Coach and told everyone "your
// server has no Coach enabled" — with the admin looking at a green test.
await get().loadConfig()
await get().pullState()
} catch (e) {
if (e.status === 401) { await forgetRemote(); get().setGuest(true) }
+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')
}
+10 -2
View File
@@ -31,6 +31,7 @@ export default function CoachSetup() {
const config = useStore(s => s.config)
const coachLocal = useStore(s => s.coachLocal)
const setCoachLocal = useStore(s => s.setCoachLocal)
const refreshConfig = useStore(s => s.refreshConfig)
const toast = useUI(s => s.toast)
const openSheet = useUI(s => s.openSheet)
@@ -46,6 +47,8 @@ export default function CoachSetup() {
useEffect(() => { if (!MOBILE) nav('/settings', { replace: true }) }, [])
useEffect(() => { getApiKey().then(k => setHasKey(!!k)) }, [])
// Ask the paired server afresh: the admin may have switched the Coach on since this phone booted.
useEffect(() => { if (user) refreshConfig() }, [user])
useEffect(() => { setModels(null); setModel(coachLocal?.provider === provider ? (coachLocal?.model || '') : '') }, [provider])
const meta = HTTP_PROVIDERS[provider] || {}
@@ -84,10 +87,15 @@ export default function CoachSetup() {
if (!chosen) return toast(t('Pick a model'))
setBusy(true)
try {
if (key.trim()) { await setApiKey(key.trim()); setHasKey(true); setKey('') }
// The mode first, the key second: the settings file is the cheap, reliable write, the
// key goes through the platform's secure store, which is the step that can misbehave.
// Either way the user hears what happened instead of watching a greyed-out button (#42).
await setCoachLocal({ mode: 'byok', provider, model: chosen, baseUrl: meta.baseUrl ? (validateBaseUrl(baseUrl).value || null) : null })
if (key.trim()) { await setApiKey(key.trim()); setHasKey(true); setKey('') }
toast(t('The Coach is on'))
nav('/coach')
} catch (e) {
toast(e?.message || t('Could not connect'))
} finally { setBusy(false) }
}
@@ -112,7 +120,7 @@ export default function CoachSetup() {
<Section title={t('How should the Coach run?')} footer={current}>
<Row icon="rocket" iconTint="var(--indigo)" title={t('Use my self-hosted openGym')}
subtitle={user ? (serverHasCoach ? t('Your server runs the Coach with whatever provider its admin set up. Nothing new leaves this phone beyond what already syncs.') : t('Your server has no Coach enabled — ask its admin, or bring your own key below.')) : t('Connect to my server')}
subtitle={user ? (serverHasCoach ? t('Your server runs the Coach with whatever provider its admin set up. Nothing new leaves this phone beyond what already syncs.') : config == null ? t('Loading…') : t('Your server has no Coach enabled — ask its admin, or bring your own key below.')) : t('Connect to my server')}
accessory="chevron" onClick={() => { if (!user || serverHasCoach) useServer(); else setChoice('server') }} />
<Row icon="key" iconTint="var(--acc)" title={t('Bring my own API key')}
subtitle={t('This phone calls the provider directly with your key. Every request is charged to your account.')}
+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>
)}
+9 -3
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'
@@ -10,8 +11,10 @@ import { exerciseDetailSheet, addToRoutineSheet, customExSheet } from '../sheets
import Icon from '../components/Icon.jsx'
import { Button } from '../components/ui.jsx'
import { tappable, useRevealActiveChip } from '../lib/use-sheet-keyboard.js'
import { isFav, sortFavouritesFirst } from '../lib/favourites.js'
export default function Library() {
const nav = useNavigate()
const S = useStore(s => s.S)
const [q, setQ] = useState('')
const [bp, setBp] = useState('')
@@ -25,12 +28,15 @@ export default function Library() {
const eqOpts = equipmentOf(eqFiltered)
// Drop the equipment filter if the search narrowed it away, so you never hit a dead end.
const eqOn = eqOpts.includes(eq) ? eq : ''
const f = eqOn ? eqFiltered.filter(e => e.eq === eqOn) : eqFiltered
// Favourites float to the top of whatever the filters left (issue #6), the rest keeps its order.
const f = sortFavouritesFirst(eqOn ? eqFiltered.filter(e => e.eq === eqOn) : eqFiltered, S)
useRevealActiveChip(bpStrip, bp)
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' }}>
@@ -57,7 +63,7 @@ export default function Library() {
const best = bestWeightFor(S, e.id)
return <div key={e.id} className="item" {...tappable(() => exerciseDetailSheet(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>
<div className="grow"><div className="tt capitalize">{isFav(S, e.id) && <Icon name="starFill" className="fav-star" />}{exerciseNameFor(e)}</div><div className="ss capitalize">{t(e.tg || e.bp)} · {t(e.eq)}</div></div>
{best > 0 && <span className="tag acc">{fmtNum(best)}</span>}
<Button size="sm" variant="tinted" icon="plus" onClick={ev => { ev.stopPropagation(); addToRoutineSheet(e) }}>{t('Plan')}</Button>
</div>
+68
View File
@@ -0,0 +1,68 @@
// @vitest-environment happy-dom
// Favourites (issue #6): the Library floats starred exercises to the top of the current
// result list — after the search and body-part filters, without reordering the rest.
import React, { act } from 'react'
import { createRoot } from 'react-dom/client'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import Library from './Library.jsx'
import { EXDB } from '../lib/exercises.js'
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 } })
return state
})
vi.mock('../store/useStore.js', () => {
const useStore = selector => selector ? selector(mocks.snapshot()) : mocks.snapshot()
useStore.getState = mocks.snapshot
return { useStore }
})
vi.mock('react-router-dom', () => ({ useNavigate: () => () => {} }))
vi.mock('../sheets.jsx', () => ({ exerciseDetailSheet: vi.fn(), addToRoutineSheet: vi.fn(), customExSheet: vi.fn() }))
const mounted = []
function render() {
const host = document.createElement('div')
document.body.appendChild(host)
const root = createRoot(host)
mounted.push(root)
act(() => root.render(<Library />))
return host
}
const names = host => [...host.querySelectorAll('.item .tt')].map(el => el.textContent).slice(1) // drop "Create your own"
beforeEach(() => {
mocks.S = { unit: 'kg', lang: 'en', routines: [], workouts: [], customEx: [], exWeights: {}, equipProfiles: [], activeEquipId: null, equipFilterOn: false }
document.body.innerHTML = ''
})
afterEach(() => { act(() => { mounted.splice(0).forEach(root => root.unmount()) }) })
describe('Library favourites', () => {
it('puts favourites first, marked with a star, and leaves the rest in catalogue order', () => {
const plain = names(render())
act(() => { mounted.splice(0).forEach(root => root.unmount()) })
const fav = [plain[6], plain[2]]
mocks.S.favEx = fav.map(n => EXDB.find(e => e.n === n).id)
const host = render()
const shown = names(host)
expect(shown.slice(0, 2)).toEqual(plain.filter(n => fav.includes(n)))
expect(shown.slice(2)).toEqual(plain.filter(n => !fav.includes(n)))
const rows = [...host.querySelectorAll('.item')].slice(1)
expect(rows[0].querySelector('.fav-star')).not.toBeNull()
expect(rows[2].querySelector('.fav-star')).toBeNull()
})
it('keeps a favourite on top inside a body-part filter, but never pulls one in from elsewhere', () => {
const chest = EXDB.filter(e => e.bp === 'chest')
const legs = EXDB.find(e => e.bp !== 'chest')
mocks.S.favEx = [chest[4].id, legs.id]
const host = render()
const chip = [...host.querySelectorAll('.chips .chip')].find(b => b.textContent === 'chest')
act(() => chip.click())
const shown = names(host)
expect(shown[0]).toBe(chest[4].n)
expect(shown).not.toContain(legs.n)
})
})
+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,
+2 -2
View File
@@ -38,10 +38,10 @@ vi.mock('../lib/api.js', () => ({
}))
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('../lib/mobile.js', () => ({ MOBILE: false, isAndroid: () => Promise.resolve(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(),
}))
Loaded 100 of 123 files, more files were not shown because too many files have changed in this diff. Show more