Compare commits

...
71 Commits
Author SHA1 Message Date
Duarte Santos aac9f377d5 v1.2.14: twenty community MRs, past-workout logging, Hevy API import, touch polish 2026-08-30 22:49:57 +02:00
Duarte Santos 60df0cf0dd Touch and scroll polish: chip rows own the horizontal axis, sheets lock an axis before following the finger and close on a flick, the slider drags relative to the knob, steppers repeat on hold, back-navigation restores the scroll position, a dropped row is tappable at once, the picker search stays above the keyboard, tappable rows work from the keyboard, bigger hit areas in the set row 2026-08-30 20:18:50 +02:00
Duarte Santos e1fadadadb curated2: past-workout strings in all 14 languages; pt-BR guard re-fingerprinted 2026-08-30 14:28:12 +02:00
Duarte Santos 95f8346124 curated2: log a past workout — History entry point, date/time/duration/routine sheet, replace-or-add prompt, workout screen without clock or rest timers, no PRs or confirmed weights on finish 2026-08-30 14:28:12 +02:00
Duarte Santos 346e1110c7 curated2: backfill helpers — a past workout is filed by date, the session entries are built by one shared function 2026-08-30 14:28:12 +02:00
Duarte Santos cc878dd353 curated2: review fixes — touch drag (!45), deload seeds (!28), rep-range typing (!69), rebuilt rows on config change (!54), swap keeps history (!43), Hevy retry/dedup/aliases (!30), HTTPS doc (!67), locale gaps 2026-08-30 14:18:09 +02:00
Duarte Santos 148ef9fbbb curated2: !69; Thai/Hungarian get the swap strings; pt-BR guard re-fingerprinted 2026-08-30 13:40:58 +02:00
Duarte Santos adc655ebd3 curated2: !34 2026-08-30 13:38:54 +02:00
Duarte Santos 41286db244 curated2: !54 2026-08-30 13:37:54 +02:00
Duarte Santos 0e3b8fa74b curated2: !43 2026-08-30 13:36:31 +02:00
Duarte Santos 250b164d2d curated2: !41 (a move re-points the rest countdown instead of cancelling it) 2026-08-30 13:35:47 +02:00
Duarte Santos d36fa68a61 curated2: !48 (code only; its test file predates the current mock setup) 2026-08-30 13:34:56 +02:00
Duarte Santos fcfe7c4757 curated2: !52 2026-08-30 13:34:14 +02:00
Duarte Santos f3d65ffb10 curated2: Thai and Hungarian get the move-control labels; !27's test file declares its DOM environment 2026-08-30 13:33:04 +02:00
Duarte Santos f0777e362a curated2: !68 (Thai and Hungarian both land: 14 languages) 2026-08-30 13:31:30 +02:00
Duarte Santos 63ca5fdab2 curated2: !66 without the unrelated exNotes default (nothing reads it) 2026-08-30 13:31:19 +02:00
Duarte Santos 8a20a94d4b curated2: !64 2026-08-30 13:31:08 +02:00
Duarte Santos f5e0a33924 curated2: !67 2026-08-30 13:31:08 +02:00
Duarte Santos e0241b804e curated2: !30 2026-08-30 13:30:59 +02:00
Duarte Santos 77996ec167 curated2: !45 2026-08-30 13:30:59 +02:00
Duarte Santos de3e8e549e curated2: !27 2026-08-30 13:30:38 +02:00
Duarte Santos 67871fe66d curated2: !29 2026-08-30 13:30:38 +02:00
Duarte Santos a65287de0f curated2: !28 2026-08-30 13:30:38 +02:00
Duarte Santos 44fcd7ead6 curated2: !47 2026-08-30 13:30:16 +02:00
Duarte Santos 8e7320d400 curated2: !46 2026-08-30 13:30:16 +02:00
Duarte Santos 81f5c96d84 curated2: !66 2026-08-30 13:30:16 +02:00
Duarte Santos c2d7146eff curated2: !65 2026-08-30 13:30:16 +02:00
Duarte Santos d49e0439ee curated2: !38 2026-08-30 13:30:16 +02:00
Duarte Santos 37bbaeaee2 changelog: v1.2.13 section; the v1.2.12 text describes v1.2.12 again 2026-08-30 13:18:17 +02:00
Manuel 5e6c4d1a75 fix: preserve per-side double progression reps 2026-08-30 01:37:14 +02:00
Manuel a62c75d160 test: update pt-BR locale snapshot 2026-08-30 01:30:14 +02:00
Manuel c71cb09515 feat: expose the double progression rep range 2026-08-30 01:23:20 +02:00
Zoltan K 41df6cb139 i18n: Add Hungarian (hu) — UI, exercise instructions, and exercise names
Rebased onto the Brazilian-Portuguese localization that landed while this was
in progress — that MR introduced EXERCISE_NAME_LANGS/exerciseNameFor()/
exerciseNameSearchText() in lib/i18n-core.js and a generated-pack convention
(scripts/exercise-name-sources/<lang>.json → scripts/build-<lang>-exercise-
names.mjs → frontend/src/exercise-names/<lang>.js), which is exactly the
mechanism this MR originally invented independently as NAME_LANGS/nameFor().
Dropped that duplicate plumbing entirely and reused theirs instead:

- frontend/src/locales/hu.js — full UI translation, 740/740 keys (654 from
  the original translation pass, 86 more added to cover the drop-set/rest-
  pause, equipment-profile, server-pairing and session-note strings that
  landed in the same window).
- frontend/src/instr/hu.js — unchanged mechanism, all 1,324 exercises' step-
  by-step instructions. The upstream exercise dataset (hasaneyldrm/exercises-
  dataset) still has no hu field, so this stays hand-maintained here.
- scripts/exercise-name-sources/hu.json + scripts/build-hu-exercise-
  names.mjs (mirrors the pt-BR ones) → frontend/src/exercise-names/hu.js —
  all 1,324 exercise names, added to EXERCISE_NAME_LANGS. Exercise names
  now render the same bilingual way pt-BR's do: the translated name alone
  when it's the same loanword as English (e.g. "burpee"), otherwise
  "translated (english)".
- One small generalization to exerciseNameFor(): its loanword-casing
  comparison was hardcoded to `.toLocaleLowerCase('pt-BR')`. Changed to the
  active language instead, so it is correct for hu (and any language after
  it) rather than only for pt-BR. No behavior change for pt-BR itself.
- Workout.remove.test.jsx's locale-coverage test hardcoded an expected pack
  count; already fixed once for the 12th language, re-applied here since hu
  is now the 14th — derives the count from LANGS so this stops recurring.

Translated in bulk with AI assistance and validated programmatically (id
coverage against the 1,324-exercise catalogue, key-set parity across all 13
locales via check-locales.mjs, duplicate/collision and encoding checks) —
not yet proofread line-by-line by a fluent human reviewer, same disclosure
standard scripts/exercise-name-sources/README.md and instruction-sources/
README.md already hold the pt-BR translations to.

node frontend/scripts/check-locales.mjs: 13 locales, 740 keys each, in sync.
Full frontend test suite: 39 files / 533 tests passing.
2026-08-29 23:04:10 +02:00
andi242 d65b7cb9a4 add explanations [ci skip] 2026-08-29 20:45:25 +02:00
andi242 4171220067 indent [ci skip] 2026-08-29 19:08:54 +02:00
andi242 28b10fbd1b add info 2026-08-29 19:07:41 +02:00
andi242 39ffb44332 doc links 2026-08-29 18:15:27 +02:00
andi242 2ddcee00e0 finalize 2026-08-29 18:08:01 +02:00
andi242 c1b8ef3190 save progress 2026-08-29 17:57:02 +02:00
andi242 118205bc75 save progress 2026-08-29 17:17:35 +02:00
Julius Haring 6585ad5711 test: make pt-PT test work with hevy import 2026-08-29 17:02:41 +02:00
Julius Haring 687ef2562e feat: add hevy map import to csv import 2026-08-29 17:02:41 +02:00
Julius Haring 45f7541508 feat: add hevy pro api import 2026-08-29 17:02:28 +02:00
andi242 dc8fcec4be test mermaid shape 2026-08-29 16:42:00 +02:00
andi242 36f7558cc3 graph 2026-08-29 16:34:11 +02:00
andi242 c71791eea6 init 2026-08-29 16:32:51 +02:00
mflova 090f615e8b fix: reschedule native workout reminders by date 2026-08-29 14:32:22 +00:00
Suthep ce0e5d4aef Fill in th.js missing keys and fix a mismatched key
- check-locales.mjs was failing: th.js had 628/741 keys. One key
  ('...rest after both') didn't match the source string used in code
  ('...rest when done'), and 112 keys were missing outright — most of
  them the whole tail block (equipment profiles, mobile-app pairing,
  session notes) that never made it into th.js.
- Renamed the mismatched key and added Thai translations for the 112
  missing keys, preserving {n} placeholders and section comments to
  match the other locale files.
- Workout.remove.test.jsx hardcoded 12 locale packs; bumped to 13 now
  that th.js is a complete pack.

npm test / npm run build / node scripts/check-locales.mjs all pass now.
2026-08-29 19:12:49 +07:00
Space_Hermes 2199564593 test(sync): codify saved workout state restore contract 2026-08-29 13:57:39 +02:00
tomzt 241b036fe4 Add Thai (th) translation 2026-08-29 17:32:05 +07:00
Space_Hermes 23b1b719a8 fix(workout): open progression settings from guidance 2026-08-28 13:47:38 +02:00
Space_Hermes 221e365ee8 fix(workout): label progression guidance 2026-08-28 08:04:59 +02:00
Space_Hermes 84274b48d2 Fix disabled routine move control hit targets 2026-08-27 20:06:19 +02:00
Space_Hermes 80b0027bf5 test(workout): cover swipe capture and scroll ownership 2026-08-27 19:55:58 +02:00
Space_Hermes 7422925235 fix(workout): center the actionable superset set 2026-08-27 19:41:34 +02:00
Space_Hermes 933891ee99 Fix routine move controls for grouped exercises 2026-08-27 19:40:49 +02:00
Space_Hermes da161613cf fix(routines): preserve drop click suppression 2026-08-27 19:33:59 +02:00
Space_Hermes 194d62ace3 fix: harden muscle balance stats semantics 2026-08-27 18:34:06 +02:00
Space_Hermes e44d9e7007 fix(routines): harden reorder gesture lifecycle 2026-08-27 18:02:17 +02:00
Space_Hermes 85ecf3563e feat(workout): swipe between active units 2026-08-27 16:50:59 +02:00
Space_Hermes 5770f3bc04 feat(routines): add long-press reorder 2026-08-27 16:46:25 +02:00
Space_Hermes d5e40db774 feat(workout): add active unit move controls 2026-08-27 12:32:52 +02:00
Space_Hermes cf1e99ac95 feat(workout): safely swap active exercise 2026-08-27 12:07:21 +02:00
TheophileDiot 19a8be2c38 MCP: warm-ups do not become personal records 2026-08-27 10:07:26 +02:00
TheophileDiot 5c93a7d8a1 MCP: the read tools resolve customs, prog policies and rep ranges 2026-08-26 16:57:21 +02:00
Alexby 0b4a224c95 workout: optional per-exercise rest for normal sets
An exercise can now carry its own restSec: the workout timer prefers it
over the global default, a superset rests the longest resolved rest in
the group after each round, and the field travels with shared plans —
normalised on import like every other prescribed number. An explicit
restSec still times its rest when the global timer is turned off; only
the default is silenced. Closes #10.
2026-08-26 16:03:27 +02:00
tkyouw 26579e4261 feat: isolate planned deloads from progression 2026-08-26 09:54:24 +02:00
mzspicoli 1aef1d882b feat(timer): add opt-in visual completion flash 2026-08-26 07:28:01 +02:00
doby-llm 4422e4c387 fix(ui): keep picker results above mobile keyboard 2026-08-26 06:39:23 +02:00
doby-llm 40df469fd6 fix(stats): harden historical exercise search fallback 2026-08-26 06:39:23 +02:00
doby-llm 283d897762 feat: add Stats exercise progress picker search 2026-08-26 06:39:23 +02:00
99 changed files with 9610 additions and 297 deletions

No files matched your search

+7
View File
@@ -125,3 +125,10 @@ RP_NAME=openGym
# fine; set a mailto: if you would rather they mailed you:
#
# VAPID_SUBJECT=mailto:you@example.com
# ── Hevy map regeneration (developers only) ────────────────────────────────
# Not used by the running app. End users paste their own key in Settings →
# Import from Hevy. Set this only to regenerate frontend/src/lib/hevy-id-map.js:
#
# HEVY_API_KEY=
# node scripts/build-hevy-id-map.mjs
+89 -3
View File
@@ -1,5 +1,92 @@
# Changelog
## v1.2.14 — 2026-08-30
The largest community release so far: twenty merge requests from ten contributors, read and
tried one by one on a staging instance, plus two features of our own and a pass over how the
app feels under a thumb. Nothing changes on the server — a self-hosted instance only needs the
new web bundle; the APK carries the new reminder scheduling.
### New
- 📝 **Log a past workout.** History → "Log a past workout": pick date, start time, duration
and a routine (or freestyle), then log it on the normal workout screen — weights, reps,
RIR/RPE, timed sets, everything. A day that already has a workout asks: replace it, add a
second one, or cancel. Backfilled sessions are filed in chronological order, claim no PRs
against later history, and don't touch the weights your next session starts from.
- 📥 **Import straight from Hevy.** Settings → Import from Hevy with a Hevy Pro API key pulls
workouts, routines and weigh-ins directly — no CSV export needed. The key is used for the
one import and never stored; importing again updates the routines it created instead of
duplicating them. (JuliusHaring, !30)
- ⏲️ **Rest per exercise.** Any exercise can carry its own rest time; a superset rests once,
with the longest of the group. The global timer stays the default, and "Off" is overridden
only by an explicit per-exercise rest. Shared plans carry it. (trapy, !34 — issue #10)
- 🧘 **Planned deloads.** A routine can be excluded from automatic progression: its sessions
open on the routine's own targets, stay in history and statistics, and are skipped when the
next regular session computes its prescription — reps and durations included.
(tokyo_underworld, !28)
- 📳 **Timer flash.** Opt-in screen flash when a rest or work timer ends — for loud gyms and
headphones. (mzspicoli, !29)
- 🌍 **Thai and Hungarian.** Full UI translation in both; Hungarian also localizes all 1,326
exercise names and instructions. That makes 14 languages. (tomzt, !64 · kecskemethy, !68)
### Active workout
- ➕ Adding an exercise mid-session now also **moves and swaps** cleanly: move the current
exercise or superset up/down (the rest countdown follows it), or swap it for another —
logged sets stay with the original, the replacement arrives with your usual weights, and a
grouped exercise asks whether the replacement stays in the group. (Space-Hermes, !41, !43)
- 👉 **Swipe between exercises** on the workout card — left/right moves through the session,
buttons and inputs stay untouched. (Space-Hermes, !48)
- 🎯 **Supersets keep the next set centered** on screen, not just in view. (Space-Hermes, !52)
- 📖 **The progression line is now a button**: tap "Linear · +2.5 kg…" mid-workout to open the
exercise's settings; changed rules rebuild the open rows and keep everything you already
logged. (Space-Hermes, !54)
### Routines and progression
- ✋ **Reorder by long-press.** Hold a routine row and drag it; superset groups move as one
block. The arrow buttons stay, now group-aware and disabled at the ends.
(Space-Hermes, !45, !47)
- 🔢 **The double-progression rep range is visible**: "Reps from" and "Reps up to" side by
side, per-side exercises stepping in twos — and a progression step of zero can no longer be
saved by accident. (mflova, !69 and !60 follow-up)
### Stats and the rest
- 🔍 **The Stats exercise picker is searchable**, and the results stay above the mobile
keyboard. (mflova, !27)
- 🗺️ **The muscle map works from the keyboard** and ranks ties in body order. (Space-Hermes, !46)
- 🔕 **Android reminders follow the calendar**: scheduled per date instead of per weekday, so
a rescheduled day reminds you and a day you already trained stays quiet. (mflova, !66)
- 🤖 **The MCP coach reads what the app shows**: custom exercises resolve in every tool,
warm-ups no longer count as PRs, and progression policies report the value the UI uses.
(TheophileDiot, !38)
- 📚 **A self-hosting HTTPS guide** for valid certificates on a LAN-only address — wildcard
cert via DNS challenge, Caddy in front, no ports opened. (andi242, !67)
### Feel
A pass over touch, scroll and tap across the whole app: chip rows keep a slightly diagonal
swipe instead of handing it to the page; sheets decide an axis before following the finger,
snap back cleanly and close on a quick flick; the body-weight slider drags relative to the
knob instead of jumping to it; steppers repeat while held; going back restores your scroll
position; a just-dropped routine row is tappable immediately; the exercise picker's search
stays above the keyboard; set-row inputs, checkboxes and small icon buttons all got bigger
touch targets; and rows everywhere can be driven from a keyboard.
With thanks to Space-Hermes, mflova, JuliusHaring, trapy, tokyo_underworld, mzspicoli,
TheophileDiot, tomzt, kecskemethy and andi242 — ten contributors in one release.
## v1.2.13 — 2026-08-30
One follow-up that arrived on !60 minutes after v1.2.12 was tagged, and belongs with it.
- 🔢 **An empty or zero progression step can no longer be saved.** With a progression rule on,
leaving the step field empty or at `0` marks it red, explains why, and holds the save — a step
that cannot progress anything is no longer stored by accident. Nothing else changed; a
self-hosted instance only needs the new web bundle. (mflova, !60)
## v1.2.12 — 2026-08-30
Six small fixes from the community, each read and tried on staging before it went in. All of
@@ -26,9 +113,8 @@ self-hosted instance only needs the new web bundle.
### Exercise settings
- 🔢 **Progression steps below one can be typed.** Entering `0.5` used to snap back to the
default halfway through, because the field rejected the intermediate `0`. Leaving the field
empty or at `0` with a progression rule on now marks it red and holds the save, so a step that
cannot progress anything can no longer be stored by accident. (mflova, !60)
default halfway through, because the field rejected the intermediate `0`. A cleared field
still means "use the default". (mflova, !60)
- 📐 **Long values in routine rows no longer squash the title.** The value column is capped
instead of reserving space, so a "3 × 12 @ 102.5 kg" row keeps its exercise name readable on a
narrow phone. (MokshManral, !37)
+9 -5
View File
@@ -68,11 +68,14 @@ as a home-screen app, passkey sign-in, offline support, sync across your phone a
- 🔥 **Warm-up sets** — mark the ramp-up rows as warm-ups and they stay out of the numbers that should not see them: no effect on your estimated 1RM, your progression, or the fatigue map, while still being there in the session where you need them. A weight change cascades down the rows that share their phase, not across the divide
- ➖ **Change your mind mid-session** — add an exercise you decided to do, or remove one you didn't, without ending the workout. Removing a member of a superset asks which one
- ⏱️ **Timed exercises** — planks, hangs, wall sits and loaded carries are logged by time, not reps, with a work timer that counts the set itself (separate from the rest timer) and logs the time you actually held. They can carry weight too
- 📈 **Progression that follows a rule** — pick one per routine, override it per exercise: linear, **Greyskull LP** (AMRAP top set, double jumps, 10 % resets), double progression through a rep range, or adding time. Your weights are already right when the session opens, and every target says *why* it's that number. Missed reps never advance the load, stalls trigger a deload, and bodyweight exercises progress in reps instead
- ⏲️ **Rest per exercise** — heavy triples and curls don't want the same break: give any exercise its own rest time and it overrides the global timer for that exercise (a superset rests once, taking the longest). Travels with shared plans
- 🧘 **Planned deloads** — flag a routine as excluded from automatic progression: its sessions open with the routine's own target weights, stay in your history and statistics, and never become the baseline your next regular session progresses from
- 📈 **Progression that follows a rule** — pick one per routine, override it per exercise: linear, **Greyskull LP** (AMRAP top set, double jumps, 10 % resets), double progression through a **visible rep range** (both bounds editable, per-side exercises step in twos), or adding time. Your weights are already right when the session opens, and every target says *why* it's that number. Missed reps never advance the load, stalls trigger a deload, and bodyweight exercises progress in reps instead
- 💪 **Estimated 1RM** — per exercise, from your best eligible set (it names which one), with its own progress curve and a calculator for sets you haven't done. Won't guess above 12 reps
- 🎯 **Effort per set, in your scale** — an optional third column rating how hard a set was, as **RIR** (reps left in the tank) or **RPE** (the same judgement on a 10-point scale). Off by default; each set keeps the scale it was logged with, and nothing else reads the value — your progression and 1RM are unaffected
- 💪 **Bodyweight exercises, logged as bodyweight** — push-ups, pull-ups, dips and 300-odd others arrive knowing they carry no load, so there's no weight column and no working-weight prompt: one stepper, log the reps. Add a dip belt and it reads as an addition, and progression goes back to following the weight. Without one, reps climb — and past a ceiling you set, a set is added instead of a rep, up to the point where the honest advice is load or a harder variation
- ↔️ **Reps per side** — for lunges, single-arm rows and the rest. You log the total, the app shows the split ("8 per side"), and the target steps in twos so it never lands on a number one side can't have
- 📝 **Log a past workout** — forgot your phone, trained on paper, or switched apps? Add a session after the fact from History: date, start time, duration, routine or freestyle, then the normal workout screen — weights, reps, RIR/RPE, timed sets and all. If that day already has a workout you choose: replace it, keep both, or cancel. Backfilled sessions never claim PRs against workouts that came later
- 🎲 **Freestyle sessions** — train without a plan and pick exercises as you go. Each one arrives prefilled from the last time you did it — same sets, same reps and weight by position — so an unplanned session doesn't start by asking you to retype last week
- 🏃 **Cardio** — log time + speed, not just weight × reps
- 📤 **Share a plan** — send someone your routines and week schedule as a small file (no workouts, no weigh-ins), or print it as a clean PDF. Importing merges, so their plan is never overwritten
@@ -80,12 +83,13 @@ as a home-screen app, passkey sign-in, offline support, sync across your phone a
- ✨ **Your own exercises** — a name and a body part is enough; they behave like built-in ones everywhere, with an optional description instead of an animation
- 🟩 **Activity heatmap** — a GitHub-style year view, shaded by time spent training
- 💪 **Muscle map, three ways** — a front-and-back body diagram you can read as **Balance** (where the volume went, over a week, a month or all time — naming the muscles you *haven't* trained), **Fatigue** (what is still recovering, weighted by how close each set was to your maximum, decaying smoothly rather than expiring at a window edge) or **Strength** (how long since you trained each muscle, and behind every one the exercises that built it with their estimated 1RM). It previews what a routine hits while you build it, and shows what you just trained when you finish. Male or female figure, your pick
- 🔔 **Push notifications** — rest-timer alerts even with the app closed, plus an optional reminder on days you have a workout planned but haven't logged one. Opt in per profile; keys are generated on first run, nothing to configure
- 📳 **See the timer end, not just hear it** — an opt-in screen flash when a rest or work timer finishes, for loud gyms and headphones
- 🔔 **Push notifications** — rest-timer alerts even with the app closed, plus an optional reminder on days you have a workout planned but haven't logged one — on the Android app scheduled per calendar date, so a day you already trained or rescheduled stays quiet. Opt in per profile; keys are generated on first run, nothing to configure
- 🔑 **Passkeys, not passwords** — Face ID / Touch ID / fingerprint login; each profile keeps its own data, synced across devices. Sign-ins last 90 days by default (configurable), and “sign out everywhere” in Settings ends every session on every device at once
- 🛠️ **Admin dashboard** (optional) — for whoever runs the instance: who's training right now, per-user history, disable accounts, invite-only signup, and an **activity log** of sign-ins, failed attempts and admin actions. Off by default, so a fresh instance stays open with no admin
- 🎨 **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
- 🌍 **13 languages** — full UI translation (EN, DE, ES, FR, IT, PT (Portugal), PT (Brazil), PL, TR, RU, ZH, KO, HI); exercise instructions localized in 11 of them and built-in exercise names shown bilingually in PT-BR, all loaded on demand so the app stays fast
- 📥 **Bring your history with you** — import from **FitNotes** (Android and iOS), **Strong** and **Hevy**, 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
- 🌍 **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**
- 🤖 **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
- 📱 **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))
@@ -197,7 +201,7 @@ Rough, community-driven — ideas and PRs welcome:
- [x] Estimated 1RM per exercise
- [ ] 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 (including the RPE they record), and body weight from Apple Health
- [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
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "gym-api",
"version": "1.2.13",
"version": "1.2.14",
"private": true,
"type": "module",
"main": "server.js",
+18 -1
View File
@@ -36,7 +36,24 @@ These apps have been tested to work without adjustments to the column names:
| **FitNotes 2 (iOS)** | Export workouts as CSV; also manual/auto iCloud backups |
| **Strong** | Settings → Export Data |
| **Gravl** | Profile → Export Data |
| **Hevy** | Profile → Settings → Export & Import Data (Workouts or Measurements) |
| **Hevy** | Profile → Settings → Export & Import Data (Workouts or Measurements), **or** Settings → Import from Hevy with a Pro API key |
### Hevy API (direct)
If you have **Hevy Pro**, you can skip the CSV and import straight from Hevy:
1. Open [Hevy → Settings → Developer](https://hevy.com/settings?developer) and create an API key
2. In openGym: **Settings → Import from Hevy**
3. Paste the key (used only for that import — it is not saved)
4. Choose whether to bring **workouts**, **routines**, **weigh-ins**, or any mix, then confirm
Both the API import and a detected **Hevy CSV** resolve exercises through the same generated
lookup (`frontend/src/lib/hevy-id-map.js`): template id for the API, English title for the CSV.
To regenerate (developers): set `HEVY_API_KEY` in the environment or `.env`, then run
`node scripts/build-hevy-id-map.mjs`. Unmapped lifts become your own exercises. Workout days
that already have data here are left alone; routines are always added as **new** plans
(nothing you already have is overwritten). Localized CSV titles (non-English) still fall back
to name matching.
You can also create your own `CSV` file:
+2
View File
@@ -59,6 +59,8 @@ you're poking at the API directly:
## 3. Expose it over HTTPS on your own domain
> Want HTTPS **without** exposing anything to the internet — a valid certificate on a LAN-only address? See [SELF_HOSTING_HTTPS.md](./SELF_HOSTING_HTTPS.md) (wildcard cert via a DNS challenge, Caddy in front).
Put openGym behind something that terminates TLS for a hostname you control, then point it at
the `web` container. Pick whichever you already run:
+168
View File
@@ -0,0 +1,168 @@
# Selfhosting with HTTPS
This is a rather complex topic of its own, so it lives apart from the [SELF_HOSTING.md](./SELF_HOSTING.md) which focuses on how to run openGym.
This document takes a more general approach on how to achieve "https at home", it is not necessarily focused on openGym and applies to self hosting in general.
When self-hosting it is often assumed that one needs to expose their services to the internet, this is not necessarily the case.
We can have https certificates without having to expose our precious hosts to the world. You can still do that if you want to access your applications from the internet without any VPN, but it's not necessary to take the risk.
Since VPN is a beast of its own we'll only handle the certificates for now and grant https traffic to our local network hosts.
This guide assumes that you are running a Linux host, everything else is not covered.
## Components
Given we have the following setup:
- a little server (e.g. a Raspberry Pi or mini PC) that runs our applications.
- a client (your PC, mobile, tablet, etc.)
- your router (the thing that provides internet access, wifi, etc.)
```mermaid
graph TD
A@{ shape: cloud, label: "Internet"}
A <--> B[Router]
B <-->C[PC]
B <-->E[Mobile]
B <-->D[homelab]
```
### DNS
In most cases the router also provides DNS for the local network and forwards all requests to the internet provider DNS.
(If you set up your own DNS server on your homelab, you probably know what you're doing.)
The clients (PC, mobile phone, ...) will ask the local DNS for address translation and if the local DNS can't provide the target address, it will forward the request.
Usually the DNS servers out there translate DNS names to public IP addresses.
Since we do not own a public DNS server, we need a DNS provider that does this for us.
You probably heard of dyndns, duckdns and the like. This is what they do: provide a public DNS for us.
In order to make the public DNS servers out there resolve the local IP address of our homelab we will set up the DNS provider.
It is strongly advised to check which DNS providers are supported by the tools you choose (we'll get to that later).
### Let's encrypt!
Let's encrypt is free to use, they provide certificates for everyone to make the internet safer. Read [here](https://letsencrypt.org/docs/why-all-https/) for more information.
They provide tools to automatically create certificates with a challenge to ensure your request is valid.
Therefore the tool needs to have access to the DNS provider to generate temporary TXT entries on the DNS entry.
If all is checked, the certificate authority of Let's Encrypt signs the certificate and it can be used.
We will make use of a wildcard certificate, so we can serve all our services with one certificate.
### proxy
A proxy is optional but desirable. It acts as sort of a gateway to our service and can be a single entrypoint to multiple services on our homelab.
Let's say we have three services running on our instance. Since a TCP port can be used only once on a host we would have three ports that access our individual services.
It would not be very nice to have to remember all the ports when we address our services, so we let the proxy do it.
Port 443 (https) can only be used once so we would let our proxy answer to that port.
We configure the proxy to forward requests to our individual services like so:
```mermaid
graph TD
A[proxy]
A <-->B[openGym :8080]
A <-->C[openGym-api :3000]
A <-->D[Nextcloud :8081]
```
Now we have a nice URL and can forget about the ports. The proxy reads the URL request and forwards it to the target service/host.
## How?!
So how does it all come together?
1. DNS provider translates name to the local IP of homelab (e.g.: `https://opengym.myhomelab.dedyn.io -> http://192.168.0.100:8080`)
1. the proxy listens to the local IP and provides HTTPS
1. Let's encrypt provides certificates with certbot
### Tools
- DNS provider: https://desec.io/ free and supports IPv6 and a certbot plugin
- let's encrypt client: certbot, officially supported by LE
- reverse proxy: caddy, lightweight and hackable.
These are the tools I picked and know to work, your choice may be different and the setup is different as well.
But the main tasks are the same, so you can adapt to your choice.
Additional info:
- homelab host: 192.168.0.100
running services:
- opengym on port 8080
- nextcloud on port 8081
1. register with desec.io and choose a name (we take `myhomelab` as example)
1. create a new A record that points to your service, e.g.: `*.myhomelab.dedyn.io` (Wildcard!) - 192.168.0.100 (the ip of your homelab/mini PC/Raspberry Pi running the proxy)
2. A wildcard certificate handles all certificates for that given host. e.g.: `opengym.myhomelab.dedyn.io` and `nextcloud.myhomelab.dedyn.io` can share the same certificates.
3. create an API token for the certbot plugin. It only needs to write records inside your domain — leave `Can create domains` and `Can delete domains` **off**; a leaked token should not be able to take your domain apart. Note the token, it is only displayed once.
2. install certbot on your host
1. most linux distributions provide the packages for this, e.g. debian: `apt install certbot python3-certbot-dns-desec` check the [docs](https://desec.readthedocs.io/en/latest/integrations/lets-encrypt.html)
2. create a config file in `/etc/letsencrypt`: `desec.ini` containing `dns_desec_token = YOUR_TOKEN`, and `chmod 600` it
3. run certbot to register
```bash
certbot certonly \
--authenticator dns-desec \
--dns-desec-credentials /etc/letsencrypt/desec.ini \
-m YOUR_EMAIL@HOST.TLD \
--agree-tos \
--no-eff-email \
-d "*.myhomelab.dedyn.io"
```
4. certbot also installs a systemd timer that renews the certificate automatically. Caddy only re-reads the files when told to, so add a deploy hook once: `certbot renew --deploy-hook "systemctl reload caddy"` (or drop that line into `/etc/letsencrypt/renewal-hooks/deploy/`).
5. certbot writes `privkey.pem` readable by root only, while caddy runs as its own user. Either `chgrp caddy /etc/letsencrypt/live /etc/letsencrypt/archive && chmod g+rx` those directories (and `g+r` on the key), or copy the files in the deploy hook — otherwise caddy starts, but every TLS handshake fails.
3. install caddy
1. most linux distributions provide the packages for this, e.g. debian: `apt install caddy` check the [docs](https://caddyserver.com/docs/install)
2. create the caddy config, this is an example that should work:
```jsonc
:443 {
header Content-Type text/html
respond <<HTML
<html>
<head><title>caddy</title></head>
<body><h2>caddy works.</h2></body>
</html>
HTML 200
}
# define desec configuration
(desec) {
tls /etc/letsencrypt/live/myhomelab.dedyn.io/fullchain.pem /etc/letsencrypt/live/myhomelab.dedyn.io/privkey.pem {
protocols tls1.3
}
}
# reverse proxy config for opengym
opengym.myhomelab.dedyn.io {
import desec
reverse_proxy http://192.168.0.100:8080
}
# config for some other service
nextcloud.myhomelab.dedyn.io {
import desec
reverse_proxy http://192.168.0.100:8081
}
```
And that's about it. Now you should be able to access your opengym instance from your local network via https with working passkeys.
Be sure to update the openGym config accordingly (`RP_ID=opengym.myhomelab.dedyn.io`, `ORIGIN=https://opengym.myhomelab.dedyn.io` — see [SELF_HOSTING.md](./SELF_HOSTING.md#2-understand-the-passkey-requirement-important)).
**If the name does not resolve on your phone:** many home routers (Fritz!Box, some ISP boxes) have *DNS rebind protection* and silently drop public names that resolve to a private IP. Add `myhomelab.dedyn.io` to the router's rebind exception list, or run your own resolver.
usable URLs in this example:
- `https://opengym.myhomelab.dedyn.io -> http://192.168.0.100:8080`
- `https://nextcloud.myhomelab.dedyn.io -> http://192.168.0.100:8081`
Note that the SSL/HTTPS termination is only at the proxy, the service does not have any certificates whatsoever.
### Alternatives
- DNS providers: [certbot provider list](https://certbot.eff.org/hosting_providers) so many options...
- Let's encrypt clients: see [here](https://letsencrypt.org/docs/client-options/)
- reverse proxy: nginx proxymanager, easier with web GUI
## Conclusion
We created a local-network-only access to our services with HTTPS using Let's encrypt, certbot and caddy.
If something does not work, please check the corresponding documentation:
- [desec](https://desec.readthedocs.io/en/latest/index.html)
- [caddy](https://caddyserver.com/docs/)
- [Let's encrypt](https://letsencrypt.org/docs/)
- [certbot](https://certbot.eff.org/)
Reaching the services from outside your network (WireGuard plus a dynamic-DNS updater) is out of scope here.
+2 -2
View File
@@ -7,8 +7,8 @@ android {
applicationId "ch.duartesantos.opengym"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 14
versionName "1.2.13"
versionCode 15
versionName "1.2.14"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
aaptOptions {
// Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps.
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "opengym-frontend",
"version": "1.2.13",
"version": "1.2.14",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "opengym-frontend",
"version": "1.2.13",
"version": "1.2.14",
"license": "AGPL-3.0-or-later",
"dependencies": {
"@capacitor/app": "^7.1.2",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "opengym-frontend",
"private": true,
"version": "1.2.13",
"version": "1.2.14",
"type": "module",
"scripts": {
"dev": "vite",
+29 -4
View File
@@ -1,5 +1,5 @@
import { useEffect } from 'react'
import { HashRouter, Routes, Route, Navigate, useNavigate, useLocation } from 'react-router-dom'
import { useEffect, useLayoutEffect, useRef } from 'react'
import { HashRouter, Routes, Route, Navigate, useNavigate, useLocation, useNavigationType } from 'react-router-dom'
import { useStore } from './store/useStore.js'
import { useUI } from './store/useUI.js'
import { bindUI } from './components/ui.jsx'
@@ -15,6 +15,7 @@ import ErrorBoundary from './components/ErrorBoundary.jsx'
import Modals from './components/Modals.jsx'
import Toast from './components/Toast.jsx'
import RestTimer from './components/RestTimer.jsx'
import TimerFlash from './components/TimerFlash.jsx'
import Login from './views/Login.jsx'
import MobileOnboarding from './views/MobileOnboarding.jsx'
import Home from './views/Home.jsx'
@@ -27,6 +28,9 @@ import Library from './views/Library.jsx'
import Settings from './views/Settings.jsx'
import Admin from './views/Admin.jsx'
// last known scrollY per route, so back-navigation can put the page where it was
const scrollPositions = new Map()
bindUI(useUI) // lets the shared controls open sheets without importing the store at module scope
// theme === 'system' follows the OS/browser preference instead of a fixed choice.
@@ -45,6 +49,7 @@ function applyPrefs(theme, accent) {
function Shell() {
const navigate = useNavigate()
const loc = useLocation()
const navType = useNavigationType()
const { S, user, ready } = useStore()
const isGuest = useStore(s => s.isGuest())
const needsMobileOnboarding = useStore(s => s.needsMobileOnboarding)
@@ -63,8 +68,27 @@ function Shell() {
}, [S.theme, S.accent])
useEffect(() => { setLang(S.lang || 'en') }, [S.lang])
useEffect(() => { document.documentElement.lang = S.lang || 'en' }, [langV, S.lang])
// every tab/route change starts at the top of the page
useEffect(() => { window.scrollTo(0, 0) }, [loc.pathname])
// Forward navigation starts at the top; going back lands where you left off.
// The position is recorded from scroll events rather than read at route
// change, because by then a shorter page may already have clamped it.
const pathRef = useRef(loc.pathname)
useEffect(() => {
const onScroll = () => {
// Modals pins the body while a sheet is open; scrollY is 0 then, not a position.
if (document.body.style.position === 'fixed') return
scrollPositions.set(pathRef.current, window.scrollY)
}
window.addEventListener('scroll', onScroll, { passive: true })
return () => window.removeEventListener('scroll', onScroll)
}, [])
useLayoutEffect(() => {
pathRef.current = loc.pathname
if (navType !== 'POP') { window.scrollTo(0, 0); return }
const y = scrollPositions.get(loc.pathname) || 0
// the restored view needs a layout pass before it is tall enough to scroll to y
const frame = window.requestAnimationFrame(() => window.scrollTo(0, y))
return () => window.cancelAnimationFrame(frame)
}, [loc.pathname, navType])
// bound to the workout, not to the route — checking Stats mid-session keeps the screen on
useWakeLock(!!S.active && S.keepAwake !== false)
@@ -103,6 +127,7 @@ function Shell() {
<RestTimer />
<Modals />
<Toast />
<TimerFlash />
</>
)
}
+12 -2
View File
@@ -27,8 +27,13 @@ function useBodyPaths() {
}
function View({ view, levels, onMuscle, selected }) {
const activate = (event, slug) => {
if (event.key !== 'Enter' && event.key !== ' ') return
if (event.key === ' ') event.preventDefault()
onMuscle(slug)
}
return (
<svg className="bm-v" viewBox={view.vb} role="img">
<svg className="bm-v" viewBox={view.vb} role={onMuscle ? 'group' : 'img'}>
{INERT.map(slug => (view.p[slug] || []).map((d, i) =>
<path key={slug + i} className="bm-sil" d={d} />))}
{MUSCLES.map(slug => (view.p[slug] || []).map((d, i) =>
@@ -37,6 +42,11 @@ function View({ view, levels, onMuscle, selected }) {
className={'bm-m l' + (levels[slug] || 0) + (selected === slug ? ' sel' : '')}
d={d}
onClick={onMuscle ? () => onMuscle(slug) : undefined}
onKeyDown={onMuscle ? event => activate(event, slug) : undefined}
role={onMuscle ? 'button' : undefined}
tabIndex={onMuscle ? 0 : undefined}
aria-label={onMuscle ? t(MUSCLE_NAME[slug]) : undefined}
aria-pressed={onMuscle ? selected === slug : undefined}
>
<title>{t(MUSCLE_NAME[slug])}</title>
</path>))}
@@ -66,7 +76,7 @@ export default function BodyMap({ load = {}, thresholds, body = 'male', onMuscle
}
export function BodyMapLegend() {
return <div className="hm-legend">
return <div className="hm-legend" aria-label={`${t('Less')} ${t('More')}`}>
{t('Less')} <div className="hm-c l0" /><div className="hm-c l1" /><div className="hm-c l2" />
<div className="hm-c l3" /><div className="hm-c l4" /> {t('More')}
</div>
+62
View File
@@ -0,0 +1,62 @@
// @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 BodyMap, { BodyMapLegend } from './BodyMap.jsx'
globalThis.IS_REACT_ACT_ENVIRONMENT = true
let container
let root
beforeEach(() => {
container = document.createElement('div')
document.body.appendChild(container)
root = createRoot(container)
})
afterEach(() => {
act(() => root.unmount())
container.remove()
})
async function renderMap(props = {}) {
await act(async () => {
root.render(<BodyMap load={{ chest: 2 }} {...props} />)
})
await vi.waitFor(() => expect(container.querySelectorAll('.bm-v')).toHaveLength(2))
return container.querySelector('.bm-m[aria-label="Chest"]')
}
describe('BodyMap interaction semantics', () => {
it('keeps noninteractive maps as images without focusable muscle controls', async () => {
await renderMap()
expect(container.querySelectorAll('svg[role="img"]')).toHaveLength(2)
expect(container.querySelector('[role="button"]')).toBeNull()
})
it('exposes interactive muscles as translated pressed buttons inside groups', async () => {
const path = await renderMap({ selected: 'chest', onMuscle: vi.fn() })
expect(container.querySelectorAll('svg[role="group"]')).toHaveLength(2)
expect(path).toBeTruthy()
expect(path.tabIndex).toBe(0)
expect(path.getAttribute('aria-pressed')).toBe('true')
})
it.each(['Enter', ' '])('activates a muscle once with %s', async key => {
const onMuscle = vi.fn()
const path = await renderMap({ onMuscle })
const event = new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true })
act(() => path.dispatchEvent(event))
expect(onMuscle).toHaveBeenCalledTimes(1)
expect(onMuscle).toHaveBeenCalledWith('chest')
expect(event.defaultPrevented).toBe(key === ' ')
})
it('labels the existing legend direction for assistive technology', () => {
act(() => root.render(<BodyMapLegend />))
expect(container.querySelector('.hm-legend').getAttribute('aria-label')).toBe('Less More')
})
})
+2 -1
View File
@@ -1,6 +1,7 @@
import { useEffect, useRef } from 'react'
import { fmtVol, isoOf, todayISO, MONTHS } from '../lib/format.js'
import { t } from '../lib/i18n.js'
import { tappable } from '../lib/use-sheet-keyboard.js'
// GitHub-style activity heatmap, shaded by time trained per day.
export default function Heatmap({ S, onDay }) {
@@ -38,7 +39,7 @@ export default function Heatmap({ S, onDay }) {
const cls = 'hm-c l' + level(a) + (key === todayISO() ? ' today' : '') + (day > today ? ' future' : '')
cells.push(<div key={d} className={cls}
title={key + (a ? ` · ${t(a.n === 1 ? '{0} workout' : '{0} workouts', a.n)} · ${a.min} min · ${fmtVol(a.vol, S.unit)}` : '')}
onClick={a ? () => onDay(key) : undefined} />)
{...tappable(a ? () => onDay(key) : undefined)} />)
}
cols.push(<div key={wk} className="hm-col">{cells}</div>)
}
+2 -2
View File
@@ -18,7 +18,7 @@ export default function Media({ ex, id, compact, minimizable }) {
const toggleSize = e => { e.stopPropagation(); update(s => { s.gifSize = mini ? 'full' : 'mini' }) }
return (
<div className={'exmedia' + (compact ? ' compact' : '') + (mini ? ' mini' : '')} id={id} onClick={() => setPlaying(p => !p)}>
<img decoding="async" src={playing ? gifSrc(ex) : imgSrc(ex)} alt={exerciseNameFor(ex)} />
<img decoding="async" draggable={false} src={playing ? gifSrc(ex) : imgSrc(ex)} alt={exerciseNameFor(ex)} />
{minimizable && (
<button className="giftoggle" onClick={toggleSize}>
<Icon name={mini ? 'expand' : 'minimize'} />{mini ? t('Expand') : t('Minimize')}
@@ -35,5 +35,5 @@ export default function Media({ ex, id, compact, minimizable }) {
export function Thumb({ ex }) {
if (!ex.img) return <div className="thumb thumb-x"><Icon name="dumbbell" /></div>
return <img className="thumb" loading="lazy" decoding="async" src={imgSrc(ex)} alt="" />
return <img className="thumb" loading="lazy" decoding="async" draggable={false} src={imgSrc(ex)} alt="" />
}
+44 -35
View File
@@ -5,56 +5,65 @@ import { useUI } from '../store/useUI.js'
function Sheet({ sheet }) {
const { closeSheet } = useUI()
const ref = useRef(null)
const drag = useRef({ startY: null, delta: 0 })
// startY null = no gesture. axis stays null until the finger has travelled far enough to
// tell a vertical pull from a sideways scroll; 'x' hands the gesture to whatever scrolls
// horizontally under it (chip strips, heatmap) and the sheet stays put.
const idle = () => ({ startX: null, startY: null, axis: null, delta: 0, vy: 0, lastY: 0, lastT: 0 })
const drag = useRef(idle())
const onTouchStart = e => {
// a gesture that begins on a slider (or opted-out control) belongs to that control, not to
// the sheet's swipe-to-dismiss — so it keeps working while you drag. Horizontal strips are
// opted out too: a sideways scroll must never wobble or pull down the sheet.
const NODRAG = 'input[type=range], [data-nodrag], .chips, .hm-wrap'
const begin = (target, x, y) => {
const el = ref.current
// a gesture that begins on a slider (or opted-out control) belongs to that control,
// not to the sheet's swipe-to-dismiss — so it keeps working while you drag
if (e.target.closest && e.target.closest('input[type=range], [data-nodrag]')) {
drag.current = { startY: null, delta: 0 }
return
}
drag.current = { startY: el.scrollTop <= 0 ? e.touches[0].clientY : null, delta: 0 }
if (target.closest && target.closest(NODRAG)) { drag.current = idle(); return }
if (el.scrollTop > 0) { drag.current = idle(); return }
drag.current = { ...idle(), startX: x, startY: y, lastY: y, lastT: performance.now() }
}
const onTouchMove = e => {
const move = (e, x, y) => {
const el = ref.current, d = drag.current
if (d.startY === null) return
d.delta = e.touches[0].clientY - d.startY
if (d.delta > 0 && el.scrollTop <= 0) {
// synthetic events (tests) may carry no x at all: treat that as straight down
const dx = Number.isFinite(x) ? x - d.startX : 0, dy = y - d.startY
if (d.axis === null) {
// axis lock after ~8px: clearly-more-vertical wins the sheet, anything else is a scroll
if (Math.abs(dx) < 8 && Math.abs(dy) < 8) return
d.axis = Math.abs(dy) > Math.abs(dx) * 1.2 ? 'y' : 'x'
if (d.axis === 'x') return
}
if (d.axis === 'x') return
const now = performance.now()
// velocity from the last move, so a fast short flick can still be told from a slow drag
if (now > d.lastT) { d.vy = (y - d.lastY) / (now - d.lastT); d.lastY = y; d.lastT = now }
if (dy > 0 && el.scrollTop <= 0) {
e.preventDefault()
d.delta = dy
el.style.transition = 'none'
el.style.transform = `translateY(${d.delta}px)`
} else d.delta = 0
el.style.transform = `translateY(${dy}px)`
} else if (d.delta > 0) {
// the pull reversed above the start: snap back before the sheet is allowed to scroll,
// otherwise it scrolls while still hanging below its resting place
e.preventDefault()
d.delta = 0
el.style.transform = 'translateY(0px)'
}
}
const onTouchStart = e => begin(e.target, e.touches[0].clientX, e.touches[0].clientY)
const onTouchMove = e => move(e, e.touches[0].clientX, e.touches[0].clientY)
const onTouchEnd = () => {
const el = ref.current, d = drag.current
if (d.startY === null) return
el.style.transition = 'transform .2s'
if (d.delta > 90 && !sheet.locked) { el.style.transform = 'translateY(110%)'; setTimeout(() => closeSheet(sheet.id), 180) }
// a long pull, or a short but fast flick, dismisses
const flick = d.delta > 30 && d.vy > 0.6
if ((d.delta > 90 || flick) && !sheet.locked) { el.style.transform = 'translateY(110%)'; setTimeout(() => closeSheet(sheet.id), 180) }
else el.style.transform = ''
d.startY = null
drag.current = idle()
}
// Mouse drag (desktop testing / trackpads): same swipe-to-dismiss behaviour.
const onMouseDown = e => {
if (e.button !== 0) return
if (e.target.closest && e.target.closest('input[type=range], [data-nodrag]')) {
drag.current = { startY: null, delta: 0 }
return
}
const el = ref.current
drag.current = { startY: el.scrollTop <= 0 ? e.clientY : null, delta: 0 }
}
const onMouseMove = e => {
const el = ref.current, d = drag.current
if (d.startY === null) return
d.delta = e.clientY - d.startY
if (d.delta > 0 && el.scrollTop <= 0) {
e.preventDefault()
el.style.transition = 'none'
el.style.transform = `translateY(${d.delta}px)`
} else d.delta = 0
}
const onMouseDown = e => { if (e.button === 0) begin(e.target, e.clientX, e.clientY) }
const onMouseMove = e => move(e, e.clientX, e.clientY)
const onMouseUp = () => onTouchEnd()
// non-passive touchmove so preventDefault works (bottom sheets only; centered dialogs have no ref)
+95 -2
View File
@@ -74,10 +74,11 @@ async function popstate() {
await act(async () => { window.dispatchEvent(new dom.Event('popstate')) })
}
function mouse(target, type, clientY) {
function mouse(target, type, clientY, clientX = 0) {
const event = new dom.Event(type, { bubbles: true })
Object.defineProperties(event, {
button: { value: 0 },
clientX: { value: clientX },
clientY: { value: clientY },
})
target.dispatchEvent(event)
@@ -181,13 +182,16 @@ describe('Modals mouse dragging', () => {
})
it('releases a drag when mouseup occurs outside the sheet', async () => {
// a slow pull: synthetic events fire in the same tick, which would read as a flick
let now = 0
vi.spyOn(performance, 'now').mockImplementation(() => now)
await setSheets([sheet('drag')])
const sheetEl = container.querySelector('.sheet')
sheetEl.scrollTop = 0
await act(async () => {
mouse(sheetEl, 'mousedown', 10)
mouse(sheetEl, 'mousemove', 60)
now = 300; mouse(sheetEl, 'mousemove', 60)
})
expect(sheetEl.style.transform).toBe('translateY(50px)')
@@ -199,3 +203,92 @@ describe('Modals mouse dragging', () => {
expect(mocks.state.sheets).toHaveLength(1)
})
})
describe('Modals drag axis lock and dismiss', () => {
it('ignores a sideways gesture instead of wobbling the sheet', async () => {
await setSheets([sheet('x')])
const sheetEl = container.querySelector('.sheet')
sheetEl.scrollTop = 0
await act(async () => {
mouse(sheetEl, 'mousedown', 10, 10)
mouse(sheetEl, 'mousemove', 20, 60)
// once locked to x, even a clearly downward move stays with the horizontal gesture
mouse(sheetEl, 'mousemove', 120, 70)
window.dispatchEvent(new dom.Event('mouseup'))
})
expect(sheetEl.style.transform).toBe('')
expect(mocks.state.sheets).toHaveLength(1)
})
it('leaves horizontal chip strips to their own scrolling', async () => {
await setSheets([sheet('chips', {
render: () => React.createElement('div', { className: 'chips' }, React.createElement('button', { className: 'chip' }, 'a')),
})])
const sheetEl = container.querySelector('.sheet')
sheetEl.scrollTop = 0
await act(async () => {
mouse(container.querySelector('.chip'), 'mousedown', 10)
mouse(sheetEl, 'mousemove', 150)
window.dispatchEvent(new dom.Event('mouseup'))
})
expect(sheetEl.style.transform).toBe('')
expect(mocks.state.sheets).toHaveLength(1)
})
it('snaps back to zero when the pull reverses instead of scrolling while offset', async () => {
await setSheets([sheet('rev')])
const sheetEl = container.querySelector('.sheet')
sheetEl.scrollTop = 0
await act(async () => {
mouse(sheetEl, 'mousedown', 10)
mouse(sheetEl, 'mousemove', 110)
})
expect(sheetEl.style.transform).toBe('translateY(100px)')
await act(async () => { mouse(sheetEl, 'mousemove', 5) })
expect(sheetEl.style.transform).toBe('translateY(0px)')
await act(async () => { window.dispatchEvent(new dom.Event('mouseup')) })
expect(sheetEl.style.transform).toBe('')
expect(mocks.state.sheets).toHaveLength(1)
})
it('dismisses on a short but fast flick', async () => {
vi.useFakeTimers()
let now = 0
vi.spyOn(performance, 'now').mockImplementation(() => now)
await setSheets([sheet('flick')])
const sheetEl = container.querySelector('.sheet')
sheetEl.scrollTop = 0
await act(async () => {
mouse(sheetEl, 'mousedown', 10)
now = 20; mouse(sheetEl, 'mousemove', 40)
now = 60; mouse(sheetEl, 'mousemove', 80) // 70px in 60ms: ~1 px/ms
window.dispatchEvent(new dom.Event('mouseup'))
})
expect(sheetEl.style.transform).toBe('translateY(110%)')
await act(async () => { vi.advanceTimersByTime(200) })
expect(mocks.state.sheets).toHaveLength(0)
vi.useRealTimers()
})
it('keeps a short slow pull open', async () => {
let now = 0
vi.spyOn(performance, 'now').mockImplementation(() => now)
await setSheets([sheet('slow')])
const sheetEl = container.querySelector('.sheet')
sheetEl.scrollTop = 0
await act(async () => {
mouse(sheetEl, 'mousedown', 10)
now = 400; mouse(sheetEl, 'mousemove', 80)
window.dispatchEvent(new dom.Event('mouseup'))
})
expect(sheetEl.style.transform).toBe('')
expect(mocks.state.sheets).toHaveLength(1)
})
})
+8
View File
@@ -0,0 +1,8 @@
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.
export default function TimerFlash() {
const id = useUI(s => s.timerFlashId)
return id ? <div key={id} className="timer-flash" aria-hidden="true" /> : null
}
+146 -23
View File
@@ -60,11 +60,11 @@ export function TextArea({ className = '', ...rest }) {
return <textarea className={'field area ' + className} {...rest} />
}
export function SearchField({ value, onChange, onClear, ...rest }) {
export const SearchField = forwardRef(function SearchField({ value, onChange, onClear, ...rest }, ref) {
return (
<div className="searchf">
<Icon name="magnifier" className="lead" />
<input className="field" value={value} onChange={onChange} {...rest} />
<input ref={ref} className="field" value={value} onChange={onChange} {...rest} />
{!!value && (
<button className="clear" onClick={onClear} aria-label="Clear">
<Icon name="xmark" />
@@ -72,7 +72,7 @@ export function SearchField({ value, onChange, onClear, ...rest }) {
)}
</div>
)
}
})
/* ============================ switch ============================ */
@@ -117,14 +117,50 @@ export function Segmented({ options, value, onChange, className = '' }) {
export function Stepper({ value, step = 1, onChange, decimal = true, className = '', label, unit, invalid = false }) {
const set = v => onChange(Math.max(0, Math.round((v || 0) * 100) / 100))
// Holding a button repeats the step; the latest value/step live in a ref so
// the interval doesn't keep stepping from the value it was started with.
const live = useRef({ value, step, set })
live.current = { value, step, set }
const hold = useRef({ delay: null, tick: null, count: 0, repeated: false })
const bump = dir => { const { value, step, set } = live.current; set((+value || 0) + dir * step) }
const stopHold = () => {
const h = hold.current
window.clearTimeout(h.delay); window.clearInterval(h.tick)
h.delay = h.tick = null
}
const startHold = dir => {
stopHold()
const h = hold.current
h.repeated = false; h.count = 0
h.delay = window.setTimeout(() => {
const run = () => {
h.repeated = true; h.count++
bump(dir)
// modest acceleration after a bit of holding so a long hold covers ground
if (h.count === 15) { window.clearInterval(h.tick); h.tick = window.setInterval(run, 40) }
}
h.tick = window.setInterval(run, 80)
}, 400)
}
// The click that follows pointerup must not add a step once the hold repeated.
const click = dir => {
if (hold.current.repeated) { hold.current.repeated = false; return }
bump(dir)
}
useEffect(() => stopHold, [])
const holdProps = dir => ({
onPointerDown: e => { if (e.button === 0 || e.button == null) startHold(dir) },
onPointerUp: stopHold, onPointerCancel: stopHold, onPointerLeave: stopHold, onBlur: stopHold,
onClick: () => click(dir),
})
const inner = (
<div className={'stp ' + className}>
<button onClick={() => set((+value || 0) - step)} aria-label="Decrease"><Icon name="minus" /></button>
<button {...holdProps(-1)} aria-label="Decrease"><Icon name="minus" /></button>
<span className="val">
<NumberField value={value} decimal={decimal} onChange={onChange} aria-invalid={invalid ? 'true' : undefined} />
{unit && <i>{unit}</i>}
</span>
<button onClick={() => set((+value || 0) + step)} aria-label="Increase"><Icon name="plus" /></button>
<button {...holdProps(1)} aria-label="Increase"><Icon name="plus" /></button>
</div>
)
if (!label) return inner
@@ -136,9 +172,13 @@ export function Stepper({ value, step = 1, onChange, decimal = true, className =
// Pointer-driven so the fill, track and thumb are all ours — no ::-webkit-*
// pseudo-elements, which is the only way the control looks identical on every
// platform and can pick up the accent colour.
export const SLIDER_GRAB_PX = 22
export function Slider({ value, min = 0, max = 100, step = 1, onChange, className = '' }) {
const ref = useRef(null)
const [drag, setDrag] = useState(false)
// Grabbing the knob drags it relative to where the finger landed; a finger
// is ~22px wide, so a touch that far off still means "the knob", not "jump".
const offset = useRef(0)
const pct = Math.min(100, Math.max(0, ((value - min) / (max - min)) * 100))
const posToValue = useCallback(clientX => {
@@ -156,7 +196,7 @@ export function Slider({ value, min = 0, max = 100, step = 1, onChange, classNam
if (!drag) return
const move = e => {
e.preventDefault()
onChange(posToValue(e.touches ? e.touches[0].clientX : e.clientX))
onChange(posToValue((e.touches ? e.touches[0].clientX : e.clientX) - offset.current))
}
const up = () => setDrag(false)
window.addEventListener('pointermove', move)
@@ -186,7 +226,15 @@ export function Slider({ value, min = 0, max = 100, step = 1, onChange, classNam
aria-valuenow={value} aria-valuemin={min} aria-valuemax={max}
data-nodrag /* keeps the sheet from swipe-dismissing */
onKeyDown={key}
onPointerDown={e => { e.currentTarget.setPointerCapture?.(e.pointerId); setDrag(true); onChange(posToValue(e.clientX)) }}
onPointerDown={e => {
e.currentTarget.setPointerCapture?.(e.pointerId)
const r = e.currentTarget.getBoundingClientRect()
const knobX = r.left + (pct / 100) * r.width
const d = e.clientX - knobX
offset.current = Math.abs(d) <= SLIDER_GRAB_PX ? d : 0
setDrag(true)
if (!offset.current) onChange(posToValue(e.clientX))
}}
>
<span className="sld-track"><span className="sld-fill" style={{ width: pct + '%' }} /></span>
<span className="sld-knob" style={{ left: pct + '%' }} />
@@ -248,25 +296,12 @@ export function Row({ icon, iconTint, title, subtitle, value, accessory = 'none'
// theme entirely — on dark mode it flashes a white sheet — and can't show more
// than a bare label per option. This opens our own sheet with a checkmark on the
// current value, which is also how iOS itself handles a long option list.
export function SelectRow({ icon, iconTint, title, value, options, onChange, sheetTitle, stackedValue = false }) {
export function SelectRow({ icon, iconTint, title, value, options, onChange, sheetTitle, stackedValue = false, search }) {
const cur = options.find(o => o.value === value)
const open = () => {
const { openSheet } = require_ui()
const h = openSheet(close => (
<>
<h3>{sheetTitle || title}</h3>
<div className="sect-b">
{options.map(o => (
<button key={o.value} className="lrow tap" onClick={() => { close(); onChange(o.value) }}>
<span className="lrow-m"><span className="lrow-t">{o.label}</span>
{o.subtitle && <span className="lrow-s">{o.subtitle}</span>}</span>
{o.value === value && <Icon name="check" className="lrow-k" />}
</button>
))}
</div>
<div style={{ height: 8 }} />
</>
))
const h = openSheet(close => <SelectSheet title={sheetTitle || title} value={value} options={options}
onChange={onChange} search={search} close={close} />)
return h
}
return (
@@ -275,6 +310,94 @@ export function SelectRow({ icon, iconTint, title, value, options, onChange, she
)
}
function SelectSheet({ title, value, options, onChange, search, close }) {
const [query, setQuery] = useState('')
const inputRef = useRef(null)
const firstVisibleRef = useRef(null)
const syncPickerViewport = useCallback(() => {
const input = inputRef.current
const sheet = input?.closest('.sheet')
const viewport = window.visualViewport
if (!sheet || !viewport) return
const visualHeight = Math.max(0, viewport.height || window.innerHeight)
const visualBottom = (viewport.offsetTop || 0) + visualHeight
const bottomInset = Math.max(0, window.innerHeight - visualBottom)
sheet.style.setProperty('--picker-keyboard-bottom', `${bottomInset}px`)
sheet.style.setProperty('--picker-visual-height', `${visualHeight}px`)
}, [])
const matcher = typeof search === 'function' ? search : search?.match
const visible = matcher ? options.filter(o => matcher(o, query)) : options
useEffect(() => {
if (!search) return
const viewport = window.visualViewport
if (!viewport) return
const sync = () => syncPickerViewport()
sync()
viewport.addEventListener('resize', sync)
viewport.addEventListener('scroll', sync)
return () => {
viewport.removeEventListener('resize', sync)
viewport.removeEventListener('scroll', sync)
const sheet = inputRef.current?.closest('.sheet')
sheet?.style.removeProperty('--picker-keyboard-bottom')
sheet?.style.removeProperty('--picker-visual-height')
}
}, [search, syncPickerViewport])
// Filtering can leave the first result underneath the mobile keyboard. Keep the
// correction local to the sheet instead of letting focus/scrollIntoView move the page.
useEffect(() => {
if (!query.trim() || !visible.length) return
const input = inputRef.current
if (!input || document.activeElement !== input) return
const schedule = callback => window.requestAnimationFrame
? window.requestAnimationFrame(callback)
: window.setTimeout(callback, 0)
const cancel = frame => window.cancelAnimationFrame
? window.cancelAnimationFrame(frame)
: window.clearTimeout(frame)
const frame = schedule(() => {
if (document.activeElement !== input) return
const option = firstVisibleRef.current
const sheet = option?.closest('.sheet')
if (!option || !sheet) return
const viewport = window.visualViewport
const visualBottom = viewport ? (viewport.offsetTop || 0) + viewport.height : window.innerHeight
const sheetBottom = sheet.getBoundingClientRect().bottom || visualBottom
const hiddenBy = option.getBoundingClientRect().bottom - Math.min(visualBottom, sheetBottom) + 8
if (hiddenBy <= 0) return
const maxScroll = Math.max(0, sheet.scrollHeight - sheet.clientHeight)
const nextScroll = Math.min(maxScroll, Math.max(0, sheet.scrollTop + hiddenBy))
if (nextScroll !== sheet.scrollTop) sheet.scrollTop = nextScroll
})
return () => cancel(frame)
}, [query, visible.length])
return (
<>
<h3>{title}</h3>
{search && <div className="picker-search">
<SearchField value={query} onChange={e => setQuery(e.target.value)} onInput={e => setQuery(e.target.value)}
onClear={() => setQuery('')} onFocus={syncPickerViewport} ref={inputRef} placeholder={search.placeholder} aria-label={search.label || search.placeholder} />
</div>}
<div className="sect-b">
{visible.map((o, index) => (
<button key={o.value} ref={index === 0 ? firstVisibleRef : undefined} className="lrow tap" onClick={() => { close(); onChange(o.value) }}>
<span className="lrow-m"><span className="lrow-t">{o.label}</span>
{o.subtitle && <span className="lrow-s">{o.subtitle}</span>}</span>
{o.value === value && <Icon name="check" className="lrow-k" />}
</button>
))}
{!visible.length && search && <div className="empty">
<div className="ico"><Icon name="magnifier" /></div>{search.emptyLabel}
</div>}
</div>
<div style={{ height: 8 }} />
</>
)
}
/** Multi-select row for additive exercise metadata. The sheet mirrors selection locally so
* each tap updates its checkmark immediately while the caller persists the value. */
export function MultiSelectRow({ icon, iconTint, title, values, options, onToggle, sheetTitle, noneLabel, doneLabel }) {
+108
View File
@@ -0,0 +1,108 @@
// @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 { Slider, Stepper, SLIDER_GRAB_PX } from './ui.jsx'
globalThis.IS_REACT_ACT_ENVIRONMENT = true
let host, root
beforeEach(() => {
vi.useFakeTimers()
host = document.createElement('div')
document.body.appendChild(host)
root = createRoot(host)
})
afterEach(() => {
act(() => root.unmount())
host.remove()
vi.useRealTimers()
})
function pointer(target, type, { x = 0, y = 0, button = 0 } = {}) {
const event = new Event(type, { bubbles: true, cancelable: true })
for (const [k, v] of Object.entries({ pointerId: 1, pointerType: 'touch', isPrimary: true, button, clientX: x, clientY: y })) {
Object.defineProperty(event, k, { configurable: true, value: v })
}
act(() => target.dispatchEvent(event))
return event
}
describe('Slider', () => {
// 300px track from x=100 to x=400 over 0..300 so 1px == 1 unit
const mountSlider = (value, onChange) => {
act(() => root.render(<Slider value={value} min={0} max={300} step={1} onChange={onChange} />))
const el = host.querySelector('.sld')
vi.spyOn(el, 'getBoundingClientRect').mockReturnValue({ left: 100, right: 400, width: 300, top: 0, bottom: 20, height: 20, x: 100, y: 0 })
return el
}
it('drags relative to the grab point when the touch lands on the knob', () => {
const onChange = vi.fn()
const el = mountSlider(80, onChange) // knob at x=180
pointer(el, 'pointerdown', { x: 180 + SLIDER_GRAB_PX - 2 })
expect(onChange).not.toHaveBeenCalled() // grabbing must not jump
pointer(window, 'pointermove', { x: 180 + SLIDER_GRAB_PX - 2 + 60 })
expect(onChange).toHaveBeenLastCalledWith(140) // moved by 60, not to the finger
pointer(window, 'pointerup')
})
it('still jumps to the touched position away from the knob', () => {
const onChange = vi.fn()
const el = mountSlider(80, onChange)
pointer(el, 'pointerdown', { x: 350 })
expect(onChange).toHaveBeenLastCalledWith(250)
pointer(window, 'pointermove', { x: 360 })
expect(onChange).toHaveBeenLastCalledWith(260)
pointer(window, 'pointerup')
})
})
describe('Stepper', () => {
// controlled like every real caller: the parent re-renders with the new value
function Host({ initial, onChange, step }) {
const [v, setV] = React.useState(initial)
return <Stepper value={v} step={step} onChange={n => { setV(n); onChange(n) }} />
}
const mountStepper = (value, onChange, step = 1) => {
act(() => root.render(<Host initial={value} step={step} onChange={onChange} />))
return host.querySelector('button[aria-label="Increase"]')
}
it('steps once for a short tap (pointerdown, pointerup, click)', () => {
const onChange = vi.fn()
const plus = mountStepper(10, onChange)
pointer(plus, 'pointerdown'); pointer(plus, 'pointerup')
act(() => plus.click())
expect(onChange).toHaveBeenCalledTimes(1)
expect(onChange).toHaveBeenCalledWith(11)
})
it('repeats while held and swallows the trailing click', () => {
let value = 10
const onChange = vi.fn(v => { value = v })
const plus = mountStepper(value, onChange)
pointer(plus, 'pointerdown')
act(() => vi.advanceTimersByTime(399))
expect(onChange).not.toHaveBeenCalled()
// one act per tick: in the browser every interval callback is its own task
act(() => vi.advanceTimersByTime(1 + 80))
act(() => vi.advanceTimersByTime(80))
act(() => vi.advanceTimersByTime(80))
expect(onChange).toHaveBeenCalledTimes(3)
// each repeat builds on the latest value, not the one the hold started with
expect(onChange).toHaveBeenLastCalledWith(13)
pointer(plus, 'pointerup')
act(() => plus.click())
expect(onChange).toHaveBeenCalledTimes(3)
act(() => vi.advanceTimersByTime(1000))
expect(onChange).toHaveBeenCalledTimes(3) // nothing keeps ticking after release
})
it('keeps working from the keyboard (click without a pointer)', () => {
const onChange = vi.fn()
const plus = mountStepper(10, onChange)
act(() => plus.click())
expect(onChange).toHaveBeenCalledWith(11)
})
})
+2
View File
@@ -0,0 +1,2 @@
// generated by scripts/build-hu-exercise-names.mjs — edit scripts/exercise-name-sources/hu.json
export default {"1000":"gumiszalagos egylábas fordított vádliemelés","1001":"gumiszalagos egylábas terpeszguggolás","1002":"gumiszalagos fekvő nyújtott lábemelés","1003":"gumiszalagos guggoló evezés","1004":"gumiszalagos guggolás","1005":"gumiszalagos álló hasprés","1007":"gumiszalagos álló csavart hasprés","1008":"gumiszalagos fellépés","1009":"gumiszalagos feszes lábú felhúzás","1010":"gumiszalagos nyújtott lábú felhúzás","1011":"gumiszalagos ülő csavarás","1012":"gumiszalagos csavart fejnyomás","1013":"gumiszalagos alsó fogású lehúzás","1014":"gumiszalagos v-felülés","1015":"gumiszalagos függőleges pallof-nyomás","1016":"gumiszalagos csuklóhajlítás","1017":"gumiszalagos y-emelés","1018":"gumiszalagos vállvonás","1022":"gumiszalagos álló hátsó váll evezés","1023":"gumiszalagos egyenes hátú, feszes lábú felhúzás","1160":"burpee","1167":"dinamikus mellizom-nyújtás","1201":"súlyzós burpee","1253":"emelőkaros szamár vádliemelés","1254":"gumiszalagos fekvenyomás","1255":"lejtős pullover rúddal","1256":"fordított fogású lejtős fekvenyomás rúddal","1257":"fordított fogású ferde fekvenyomás rúddal","1258":"rúd széles fordított fogású fekvenyomás","1259":"mellizom nyújtás fej mögött","1260":"kábel lejtős egykaros nyomás","1261":"kábel lejtős nyomás","1262":"kábel egykaros lejtős mellizom repülés","1263":"kábel egykaros repülés fitneszlabdán","1264":"kábel egykaros ferde repülés fitneszlabdán","1265":"kábel egykaros ferde nyomás","1266":"kábel egykaros ferde nyomás fitneszlabdán","1267":"kábel egykaros nyomás fitneszlabdán","1268":"kábel nyomás fitneszlabdán","1269":"kábel álló egyenes törzsű keresztezés","1270":"kábel felső mellizom keresztezés","1271":"mell és elülső váll nyújtás","1272":"mellizom nyújtás fitneszlabdával","1273":"tapsos fekvőtámasz","1274":"mély fekvőtámasz súlyzóval","1275":"leejtős fekvőtámasz","1276":"súlyzós egykaros lejtős pados repülés","1277":"súlyzós repülés fitneszlabdán","1278":"súlyzós ferde pados repülés fitneszlabdán","1279":"súlyzós ferde pados egykaros repülés","1280":"súlyzós ferde pados egykaros repülés fitneszlabdán","1281":"súlyzós ferde pados egykaros nyomás","1282":"súlyzós ferde pados egykaros nyomás fitneszlabdán","1283":"súlyzós ferde pados nyomás fitneszlabdán","1284":"súlyzós fekvő pullover fitneszlabdán","1285":"súlyzós egykaros pados repülés","1286":"súlyzós egykaros mellizom repülés fitneszlabdán","1287":"súlyzós egykaros lejtős pados mellnyomás","1288":"súlyzós egykaros repülés fitneszlabdán","1289":"súlyzós egykaros ferde pados mellnyomás","1290":"súlyzós egykaros nyomás fitneszlabdán","1291":"súlyzós egykaros pullover fitneszlabdán","1292":"súlyzós egylábas repülés fitneszlabdán","1293":"súlyzós nyomás fitneszlabdán","1294":"súlyzós pullover csípőnyújtással fitneszlabdán","1295":"súlyzós pullover fitneszlabdán","1296":"fitneszlabdás pike fekvőtámasz","1297":"izometrikus mellizom-összenyomás","1298":"kettlebell egykaros fekvő nyomás","1299":"emelőkaros ferde mellnyomás","1300":"emelőkaros lejtős mellnyomás","1301":"gépi belső mellnyomás","1302":"medicinlabda mellpassz","1303":"medicinlabda melltolás hárompontos állásból","1304":"medicinlabda melltolás sorozatban","1305":"medicinlabda melltolás egyszer","1306":"plyometrikus fekvőtámasz","1307":"fekvőtámasz bosu labdán","1308":"széles fogású fekvenyomás Smith-gépen","1309":"széles fogású negatív fekvenyomás Smith-gépen","1310":"súlyozott ejtő fekvőtámasz","1311":"széles tenyérállású fekvőtámasz","1312":"medicinlabda melltolás nekifutásból","1313":"emelőkaros egyoldali evezés","1314":"törzsemelés fitneszlabdán","1316":"hajlított karú pullover rúddal","1317":"fordított fogású ferde evezés rúddal","1318":"kábel ferde padon evezés","1319":"kábel csuklóforgatásos evezés","1320":"kábel köteles keresztezett ülő evezés","1321":"kábel köteles emelt ülő evezés","1322":"kábel köteles ferde padon evezés nyújtással","1323":"kábel köteles ülő evezés","1324":"kábel felső evezés","1325":"kábel széles fogású tarkó mögötti lehúzás","1326":"húzódzkodás alulfogással","1327":"szűk fogású húzódzkodás alulfogással","1328":"súlyzós fekvő hátsó delta evezés","1329":"súlyzós forgó fogású döntött törzsű evezés","1330":"súlyzós fordított fogású ferde pados egykaros evezés","1331":"súlyzós fordított fogású ferde pados kétkaros evezés","1332":"fitneszlabdás váltott karemelés","1333":"fitneszlabdás hátfeszítés nyújtott karral","1334":"fitneszlabdás hátfeszítés tarkóra tett kézzel","1335":"fitneszlabdás hátfeszítés talajtól elemelt térddel","1336":"fitneszlabdás hátfeszítés csavarással","1338":"fitneszlabda-ölelés","1339":"fitneszlabdás széles hLine truncated
+70 -9
View File
@@ -183,7 +183,15 @@ body.resting #app{padding-bottom:calc(250px + var(--sab))}
transition:background var(--fast),transform var(--fast);
}
.iconbtn:active{background:var(--surface-2);transform:scale(.92)}
/* invisible hit-area extension: these look right at their size but fall short of a
finger-sized target, so the pseudo element widens what the tap lands on without
changing the painted box. Segmented buttons sit flush against each other, so they
only grow vertically or the neighbour would steal the edge of the tap. */
.iconbtn,.chip,.seg button,.helpbtn{position:relative}
.iconbtn::before,.chip::before,.seg button::before,.helpbtn::before{content:'';position:absolute;inset:-6px}
.seg button::before{inset:-6px 0}
.iconbtn.on-ss{background:var(--acc-soft);color:var(--acc)}
.iconbtn:disabled{opacity:.32}
h4.sec{
font-size:13px;font-weight:400;letter-spacing:-.004em;color:var(--label-2);
@@ -380,7 +388,20 @@ h4.sec{
transition:background var(--fast);text-align:left;width:100%;
}
.item:active{background:var(--surface-2)}
.routine-list{position:relative}
.routine-drag-row{touch-action:pan-y;-webkit-touch-callout:none;position:relative;transition:transform var(--fast) var(--ease)}
.routine-list.is-reordering{user-select:none;-webkit-user-select:none}
.routine-list.is-reordering .routine-drag-row{transition:none}
.routine-drag-row.is-dragging{z-index:2;pointer-events:none}
.routine-drag-row.is-dragging .item{box-shadow:0 10px 28px rgba(0,0,0,.22);background:var(--surface-2)}
.routine-drop-indicator{
position:absolute;left:6px;right:6px;height:3px;border-radius:99px;
background:var(--acc);transform:translateY(-50%);pointer-events:none;z-index:3;
}
.thumb{width:50px;height:50px;border-radius:9px;object-fit:cover;background:#fff;flex:none}
/* exercise pictures are decoration inside tappable rows/cards: no save-image callout on
a long press and no drag ghost when a scroll starts on the picture */
.thumb,.exmedia img{-webkit-touch-callout:none;-webkit-user-drag:none;user-select:none;-webkit-user-select:none}
.thumb-x{
display:flex;align-items:center;justify-content:center;font-size:21px;
background:var(--surface-2);color:var(--label-2);
@@ -402,6 +423,14 @@ h4.sec{
scrollbar-width:none;-webkit-overflow-scrolling:touch;
}
.chips::-webkit-scrollbar{display:none}
/* horizontal strips: keep a sideways overscroll from chaining to the page and leave a
margin when a chip is scrolled into view. The chip row also claims the horizontal axis
(touch-action:pan-x): on a phone a slightly diagonal swipe along the chips used to hand
the gesture to the page, which scrolled down instead. The row is 32px tall, so losing a
vertical scroll that happens to start on it costs nothing; the ~130px heatmap wrap keeps
both axes, there the trade-off goes the other way. */
.chips,.hm-wrap{overscroll-behavior-x:contain;scroll-padding-inline:16px}
.chips{touch-action:pan-x}
.chip{
flex:none;padding:6px 13px;border-radius:99px;background:var(--surface);
font-size:14px;font-weight:400;color:var(--label);text-transform:capitalize;
@@ -522,12 +551,16 @@ h4.sec{
.stp button:active{background:var(--surface-3)}
.stp .val{
flex:1;min-width:0;display:flex;align-items:baseline;justify-content:center;gap:3px;padding:0 2px;
align-self:stretch;
}
.stp .val i{font-style:normal;font-size:12px;color:var(--label-2);flex:none}
.stp .num{
width:100%;min-width:0;text-align:center;background:none;border:none;outline:none;
font-size:17px;font-weight:500;letter-spacing:-.012em;padding:0;
-moz-appearance:textfield;appearance:textfield;
/* the field is the whole height of the stepper, not just its 18px text line, so a tap
anywhere between the two buttons focuses it */
height:100%;min-height:40px;cursor:text;
}
.stp .num::-webkit-inner-spin-button{display:none}
.stp.invalid{box-shadow:inset 0 0 0 1px var(--red)}
@@ -549,12 +582,15 @@ h4.sec{
/* --- checkbox --- */
.chk,.ck{
width:30px;height:30px;border-radius:50%;flex:none;
width:30px;height:30px;border-radius:50%;flex:none;position:relative;
display:flex;align-items:center;justify-content:center;
background:none;box-shadow:inset 0 0 0 1.8px var(--label-4);color:transparent;
transition:background var(--fast),box-shadow var(--fast),color var(--fast),transform var(--fast);
}
.chk .icn{font-size:16px;--icon-stroke:2.6}
/* 30px is the right look next to a stepper but a poor target: extend the tap area to 44px
without painting it; the left side stays shorter so the stepper's + button keeps its edge */
.chk::before,.ck::before{content:'';position:absolute;inset:-7px -7px -7px -4px}
.chk.on{background:var(--acc);box-shadow:none;color:var(--on-acc)}
.chk:active,.ck:active{transform:scale(.9)}
.ck svg{
@@ -610,16 +646,16 @@ h4.sec{
.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) — RIR's own value is short ("1.5") so its buttons shrink the most, weight/reps
just enough to make room since their values ("82.5", "12") need more of what's left.
(.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. */
.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:23px}
.setrow.eff3 .stp.eff button{width:20px}
.setrow.eff3 .stp button{width:28px;font-size:14px}
.setrow.eff3 .stp .num{font-size:14px}
.setrow.eff3 .stp .val{padding:0}
.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
@@ -628,7 +664,7 @@ h4.sec{
.subrow .subn{font-size:11px;color:var(--label-3);flex:none;width:46px}
.subrow .stp.mini{flex:1;min-width:0}
.subrow .stp.mini button{width:26px;height:30px}
.subrow .stp.mini .num{font-size:13px}
.subrow .stp.mini .num{font-size:13px;min-height:30px}
.subrow .iconbtn{width:26px;height:26px;font-size:11px;flex:none}
.setextra{display:flex;flex-wrap:wrap;gap:6px;margin:2px 0 8px 32px}
.setextra .chip.add{display:inline-flex;align-items:center;gap:4px;color:var(--acc)}
@@ -636,8 +672,8 @@ h4.sec{
.setextra .chip.add:disabled{opacity:.35}
/* why the next target is what it is (issue #17) */
.progline{
display:flex;align-items:flex-start;gap:7px;margin:6px 0 2px;
font-size:13px;line-height:1.38;color:var(--acc);
width:100%;display:flex;align-items:flex-start;gap:7px;margin:6px 0 2px;padding:0;
text-align:left;font-size:13px;line-height:1.38;color:var(--acc);
}
.progline.warn{color:var(--yellow)}
.progline svg{flex:none;margin-top:2px}
@@ -703,14 +739,24 @@ h4.sec{
position:absolute;left:0;right:0;bottom:0;background:var(--bg-el);
border-radius:var(--r-xl) var(--r-xl) 0 0;
padding:8px 18px calc(20px + var(--sab));
max-height:90vh;overflow-y:auto;-webkit-overflow-scrolling:touch;
max-height:90vh;max-height:min(90vh,calc(100dvh - 8px));
overflow-y:auto;-webkit-overflow-scrolling:touch;scroll-padding-bottom:calc(20px + var(--sab));
animation:sheetup .34s var(--ease);
overscroll-behavior:contain;touch-action:pan-y;will-change:transform;
}
.sheet:has(.picker-search){
bottom:var(--picker-keyboard-bottom,0px);
max-height:min(90vh,calc(100dvh - 8px),calc(var(--picker-visual-height,100vh) - 8px));
}
:root[data-theme="light"] .sheet{background:var(--bg)}
@keyframes sheetup{from{transform:translateY(100%)}to{transform:none}}
.sheet .grab{width:36px;height:5px;border-radius:99px;background:var(--label-4);margin:6px auto 14px}
.sheet h3{font-size:20px;font-weight:600;letter-spacing:-.021em;margin-bottom:14px}
.picker-search{
position:sticky;top:0;z-index:2;margin-bottom:0;padding-bottom:10px;
background:var(--bg-el);
}
:root[data-theme="light"] .picker-search{background:var(--bg)}
.center{
position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);
width:min(84vw,300px);background:var(--bg-el);border-radius:var(--r-lg);padding:20px;
@@ -756,6 +802,19 @@ 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{
@@ -843,6 +902,7 @@ h4.sec{
.bm-m.sel{stroke:var(--label);stroke-width:7}
.bodymap.tappable .bm-m{cursor:pointer}
.bodymap.tappable .bm-m:focus-visible{outline:none;stroke:var(--label);stroke-width:7;filter:drop-shadow(0 0 2px var(--surface))}
/* A hairline in the surface colour separates neighbouring muscles; the artwork has no
outline path of its own, so without this the body reads as one flat blob. */
.bm-v path{stroke:var(--surface);stroke-width:2.5;stroke-linejoin:round}
@@ -935,6 +995,7 @@ h4.sec{
border-radius:var(--r-lg);padding:14px;
background:var(--surface);box-shadow:inset 0 0 0 1.5px var(--acc-line);
}
.workout-swipe-surface{touch-action:pan-y}
/* A superset nests a card inside the page's own gutter, so its inset is paid twice. On a
narrow phone that left the weight and reps steppers too tight to show a three-digit
number — reported as "the reps textbox becomes too small when superset on mobile". The
+5
View File
@@ -0,0 +1,5 @@
// Hungarian exercise instructions, translated from the upstream English dataset
// (github.com/hasaneyldrm/exercises-dataset). Not produced by scripts/build-instructions.mjs —
// that dataset has no hu field upstream yet, so this pack is maintained here until an hu
// contribution lands there. See docs/SELF_HOSTING.md or the project notes for details.
export default {"1000":["Állj úgy, hogy a lábaid csípőszélességben legyenek, és helyezd a gumiszalagot a lábfejed párnás része köré.","Kapaszkodj meg egy stabil tárgyban az egyensúly megtartásához.","Lassan emeld fel a sarkadat a talajról, a testsúlyodat a lábujjaid párnájára helyezve.","Tarts egy rövid szünetet a mozdulat tetején, majd lassan engedd vissza a sarkadat a kiindulási helyzetbe.","Ismételd a kívánt ismétlésszámban, majd válts a másik lábra."],"1001":["Állj úgy, hogy a lábaid csípőszélességben legyenek, és helyezz egy ellenállószalagot a bokáid köré.","Tegyél egy nagy lépést előre a jobb lábaddal, és egy kisebb lépést hátra a bal lábaddal.","Hajlítsd be a térdeidet, és ereszkedj addig, amíg a jobb combod párhuzamos nem lesz a talajjal, közben tartsd a bal térdedet kicsivel a talaj fölött.","A jobb sarkadon átnyomva térj vissza a kiindulási helyzetbe.","Ismételd a másik oldalon."],"1002":["Feküdj a hátadra úgy, hogy a lábaid egyenesen legyenek, a lábfejeidet pedig tartsd össze.","Helyezd a gumiszalagot a lábfejed boltozata köré, és fogd meg a szalag végeit a kezeiddel.","A hasadat megfeszítve emeld fel mindkét lábadat a talajról, amíg merőlegesek nem lesznek rá.","Tarts egy rövid szünetet a mozdulat tetején, majd lassan engedd vissza a lábaidat a kiindulási helyzetbe.","Ismételd a kívánt ismétlésszámban."],"1003":["Rögzítsd a gumiszalagot egy stabil ponthoz derékmagasságban.","Állj szemben a rögzítési ponttal, a lábaid vállszélességben legyenek.","Tartsd a gumiszalag fogantyúit úgy, hogy a tenyered egymással szemben nézzen, a karjaid pedig magad előtt nyújtva legyenek.","Hajlítsd be a térdeidet, és ereszkedj guggolásba, közben tartsd egyenesen a hátad és emelt helyzetben a mellkasodat.","A guggolásból húzd a gumiszalag fogantyúit magad felé, összezárva a lapockáidat.","Tarts egy rövid szünetet a mozdulat tetején, majd lassan engedd fel a feszülést, és térj vissza a kiindulási helyzetbe.","Ismételd a kívánt ismétlésszámban."],"1004":["Állj úgy, hogy a lábaid vállszélességben legyenek, a gumiszalagot pedig helyezd közvetlenül a térded fölé.","Tartsd emelt helyzetben a mellkasodat és feszítsd meg a törzsedet, told hátra a csípődet, és hajlítsd be a térdeidet, hogy guggolásba ereszkedj.","Ügyelj arra, hogy a térdeid a lábujjaid vonalában maradjanak, és a súlyod a sarkadon legyen.","Tarts egy rövid szünetet lent, majd a sarkadon átnyomva térj vissza a kiindulási helyzetbe.","Ismételd a kívánt ismétlésszámban."],"1005":["Rögzítsd a gumiszalagot egy stabil ponthoz derékmagasságban.","Állj háttal a rögzítési pontnak, a lábaid vállszélességben legyenek.","Fogd meg a gumiszalagot mindkét kezeddel, és húzd a mellkasodhoz, közben tartsd a könyöködet behajlítva és a törzsedhez közel.","Feszítsd meg a hasadat, és lassan hajolj előre, közelítve a mellkasodat a térdeidhez.","Tarts egy rövid szünetet a felhajlítás tetején, majd lassan térj vissza a kiindulási helyzetbe.","Ismételd a kívánt ismétlésszámban."],"1007":["Állj úgy, hogy a lábaid vállszélességben legyenek, és helyezd a gumiszalagot a felső hátad köré, keresztezve a mellkasod előtt.","Fogd meg a gumiszalag végeit a kezeiddel, közben tartsd a könyöködet behajlítva és a törzsedhez közel.","Feszítsd meg a hasadat, és csavard a törzsedet az egyik oldalra, közben húzd a könyöködet az ellentétes térded felé.","Tarts egy rövid szünetet, majd térj vissza a kiindulási helyzetbe.","Ismételd a másik oldalon.","Folytasd az oldalak váltogatását a kívánt ismétlésszámban."],"1008":["Helyezz egy gumiszalagot a combjaid köré, közvetlenül a térded fölé.","Állj egy lépcsővel vagy platformmal szemben, a lábaid csípőszélességben legyenek.","Lépj fel a platformra a jobb lábaddal, a sarkadon átnyomva.","Nyújtsd hátra a bal lábadat, közben tartsd egyenesen.","Engedd vissza a bal lábadat a talajra.","Ismételd úgy, hogy a bal lábaddal lépsz fel a platformra.","Folytasd a lábak váltogatását a kívánt ismétlésszámban."],"1009":["Állj úgy, hogy a lábaid vállszélességben legyenek, és helyezd a gumiszalagot a bokáid köré.","Fogd meg a gumiszalagot mindkét kezeddel a combjaid előtt, a tenyered magad felé nézzen.","Tartsd egyenesen a hátad és feszítsd meg a törzsedet, miközben előredőlsz a csípődből, és lassan engeded a felsőtested a talaj felé.","Miközben ereszkedsz, told hátra a csípődet, és engedd, hogy a térdeid enyhén behajoljanak.","Engedd a gumiszalagot a talaj felé, közben érezd a nyújtást a combhajlítóidban.","Tarts egy rövid szünetet lent, majd feszítsd meg a farizmaidat és a combhajlítóidat, hogy visszaemeld a felsőtested a kiindulási helyzetbe.","Ismételd a kívánt ismétlésszámban."],"1010":["Állj úgy, hogy a lLine truncated
+44
View File
@@ -0,0 +1,44 @@
import { supersetUnits, unitOf } from './history.js'
function hasLoggedSet(entry) {
return Array.isArray(entry?.sets) && entry.sets.some(set => set?.done === true)
}
/**
* Swap one exact active-workout occurrence.
*
* Unlogged occurrences are replaced in place. Logged results are never relabelled: after explicit
* confirmation, the replacement is inserted beside the original. A logged group member also
* requires an explicit choice to keep the replacement in the group or detach it after the group.
*/
export function swapActiveExercise(active, index, replacement, {
loggedConfirmed = false,
groupDisposition
} = {}) {
if (!active || !Array.isArray(active.entries) || !replacement || index < 0 || index >= active.entries.length) return null
const current = active.entries[index]
if (!hasLoggedSet(current)) {
const metadata = Object.fromEntries(Object.entries(current).filter(([key]) => (
!['id', 'target', 'plan', 'sets', 'sg'].includes(key)
)))
active.entries[index] = { ...metadata, ...replacement, ...(current.sg ? { sg: current.sg } : {}) }
active.cur = index
return { inserted: false, index }
}
if (!loggedConfirmed) return { needsConfirmation: true, grouped: !!current.sg, index }
if (current.sg && !['keep', 'detach'].includes(groupDisposition)) {
return { needsConfirmation: true, grouped: true, index }
}
const unit = unitOf(supersetUnits(active.entries), index)
const keepGroup = current.sg && groupDisposition === 'keep'
const insertAt = keepGroup ? index + 1 : (unit.length > 1 ? unit.at(-1) + 1 : index + 1)
active.entries.splice(insertAt, 0, {
...replacement,
...(keepGroup ? { sg: current.sg } : {})
})
active.cur = insertAt
return { inserted: true, index: insertAt }
}
@@ -0,0 +1,88 @@
import { describe, expect, it } from 'vitest'
import { swapActiveExercise } from './active-exercise-swap.js'
const entry = (id, { sg, done = false, target, sets } = {}) => ({
id,
...(sg ? { sg } : {}),
target: target || { mode: 'reps', sets: 1, reps: 5, weight: 40 },
sets: sets || [{ w: 40, r: 5, done }]
})
const replacement = () => entry('incline', {
target: { mode: 'reps', sets: 2, reps: 8, weight: 32.5, note: 'Keep elbows tucked.', intensifier: { type: 'dropset', count: 1, pct: 20 } },
sets: [{ w: 32.5, r: 8, done: false }, { w: 32.5, r: 8, done: false }]
})
describe('safe active exercise swap', () => {
it('replaces only the selected duplicate occurrence and preserves its group and replacement metadata', () => {
const first = entry('bench', { sg: 'pair' })
const selected = entry('bench', { sg: 'pair' })
selected.occurrenceId = 'bench#2'
selected.provenance = { routineIndex: 4 }
const unrelated = entry('row')
const active = { cur: 1, entries: [first, selected, unrelated] }
const next = replacement()
expect(swapActiveExercise(active, 1, next)).toEqual({ inserted: false, index: 1 })
expect(active.entries.map(value => value.id)).toEqual(['bench', 'incline', 'row'])
expect(active.entries[0]).toBe(first)
expect(active.entries[2]).toBe(unrelated)
expect(active.entries[1]).toEqual({
...next,
occurrenceId: 'bench#2',
provenance: { routineIndex: 4 },
sg: 'pair'
})
expect(active.cur).toBe(1)
})
it('fails closed before a logged standalone occurrence is explicitly confirmed', () => {
const logged = entry('bench', { sets: [{ w: 42.5, r: 7, done: true, rir: 1 }] })
const active = { cur: 0, entries: [logged, entry('row')] }
expect(swapActiveExercise(active, 0, replacement())).toEqual({ needsConfirmation: true, grouped: false, index: 0 })
expect(active.entries).toEqual([logged, active.entries[1]])
expect(active.cur).toBe(0)
})
it('preserves a confirmed logged occurrence and inserts the replacement after it', () => {
const logged = entry('bench', { sets: [{ w: 42.5, r: 7, done: true, rir: 1 }] })
const unrelated = entry('row')
const active = { cur: 0, entries: [logged, unrelated] }
expect(swapActiveExercise(active, 0, replacement(), { loggedConfirmed: true })).toEqual({ inserted: true, index: 1 })
expect(active.entries[0]).toBe(logged)
expect(active.entries[0].sets[0]).toEqual({ w: 42.5, r: 7, done: true, rir: 1 })
expect(active.entries[1].id).toBe('incline')
expect(active.entries[2]).toBe(unrelated)
expect(active.cur).toBe(1)
})
it('requires an explicit grouped disposition before changing a logged group member', () => {
const active = { cur: 0, entries: [entry('bench', { sg: 'pair', done: true }), entry('row', { sg: 'pair' }), entry('curl')] }
const before = [...active.entries]
expect(swapActiveExercise(active, 0, replacement(), { loggedConfirmed: true }))
.toEqual({ needsConfirmation: true, grouped: true, index: 0 })
expect(active.entries).toEqual(before)
})
it.each([
['keep', ['bench', 'incline', 'row', 'curl'], ['pair', 'pair', 'pair', undefined], 1],
['detach', ['bench', 'row', 'incline', 'curl'], ['pair', 'pair', undefined, undefined], 2]
])('%s confirmation preserves logged group data and unrelated entries', (groupDisposition, ids, groups, cursor) => {
const logged = entry('bench', { sg: 'pair', sets: [{ w: 45, r: 6, done: true }] })
const partner = entry('row', { sg: 'pair' })
const unrelated = entry('curl')
const active = { cur: 0, entries: [logged, partner, unrelated] }
expect(swapActiveExercise(active, 0, replacement(), { loggedConfirmed: true, groupDisposition }))
.toEqual({ inserted: true, index: cursor })
expect(active.entries.map(value => value.id)).toEqual(ids)
expect(active.entries.map(value => value.sg)).toEqual(groups)
expect(active.entries[0]).toBe(logged)
expect(active.entries.includes(partner)).toBe(true)
expect(active.entries.at(-1)).toBe(unrelated)
expect(active.cur).toBe(cursor)
})
})
+31
View File
@@ -0,0 +1,31 @@
import { supersetUnits } from './history.js'
function moveTarget(active, index, direction) {
if (!active || !Array.isArray(active.entries) || (direction !== -1 && direction !== 1)) return null
const units = supersetUnits(active.entries)
const source = units.findIndex(unit => unit.includes(index))
const target = source + direction
if (source < 0 || target < 0 || target >= units.length) return null
return { units, source, target }
}
export function canMoveActiveWorkoutUnit(active, index, direction) {
return moveTarget(active, index, direction) !== null
}
export function moveActiveWorkoutUnit(active, index, direction) {
const move = moveTarget(active, index, direction)
if (!move) return null
const selected = active.entries[index]
const reorderedUnits = [...move.units]
const sourceUnit = reorderedUnits[move.source]
reorderedUnits[move.source] = reorderedUnits[move.target]
reorderedUnits[move.target] = sourceUnit
const indices = reorderedUnits.flat()
const reorderedEntries = indices.map(entryIndex => active.entries[entryIndex])
active.entries.splice(0, active.entries.length, ...reorderedEntries)
active.cur = active.entries.indexOf(selected)
return { indices }
}
@@ -0,0 +1,87 @@
import { describe, expect, it } from 'vitest'
import { canMoveActiveWorkoutUnit, moveActiveWorkoutUnit } from './active-workout-order.js'
import { LANGS } from './i18n-core.js'
import { PT_BR_OVERRIDES } from '../locales/pt-BR.js'
const entry = (id, extra = {}) => ({
id,
target: { sets: 1, reps: 5 },
sets: [{ w: 0, r: 5, done: false }],
...extra,
})
describe('active workout whole-unit order', () => {
it('moves one standalone occurrence without conflating duplicate exercise ids', () => {
const duplicateA = entry('duplicate', { occurrenceId: 'duplicate#1' })
const selected = entry('duplicate', {
occurrenceId: 'duplicate#2',
target: { sets: 2, reps: 7, weight: 82.5, notes: 'Keep this target' },
sets: [{ w: 77.5, r: 6, done: true, rir: 2 }],
})
const active = { cur: 2, entries: [duplicateA, entry('middle'), selected] }
expect(moveActiveWorkoutUnit(active, active.cur, -1)?.indices).toEqual([0, 2, 1])
expect(active.entries.map(item => item.occurrenceId || item.id)).toEqual(['duplicate#1', 'duplicate#2', 'middle'])
expect(active.entries[0]).toBe(duplicateA)
expect(active.entries[1]).toBe(selected)
expect(active.entries[1].target).toBe(selected.target)
expect(active.entries[1].sets).toBe(selected.sets)
expect(active.cur).toBe(1)
})
it('moves a complete contiguous group one unit and preserves the selected member identity', () => {
const first = entry('group-a', { sg: 'pair', occurrenceId: 'group-a#1' })
const selected = entry('group-b', { sg: 'pair', occurrenceId: 'group-b#1' })
const groupMeta = { pair: { kind: 'complex', label: 'Carry pair', cues: 'Stay braced.' } }
const active = { cur: 2, entries: [entry('before'), first, selected, entry('after')], groupMeta }
expect(moveActiveWorkoutUnit(active, active.cur, -1)?.indices).toEqual([1, 2, 0, 3])
expect(active.entries.map(item => item.id)).toEqual(['group-a', 'group-b', 'before', 'after'])
expect(active.entries.slice(0, 2)).toEqual([first, selected])
expect(active.entries.map(item => item.sg)).toEqual(['pair', 'pair', undefined, undefined])
expect(active.groupMeta).toBe(groupMeta)
expect(active.entries[active.cur]).toBe(selected)
})
it('moves a group down by exactly one neighbouring unit', () => {
const first = entry('group-a', { sg: 'pair' })
const selected = entry('group-b', { sg: 'pair' })
const active = { cur: 1, entries: [first, selected, entry('middle'), entry('last')] }
expect(moveActiveWorkoutUnit(active, active.cur, 1)?.indices).toEqual([2, 0, 1, 3])
expect(active.entries.map(item => item.id)).toEqual(['middle', 'group-a', 'group-b', 'last'])
expect(active.entries[active.cur]).toBe(selected)
})
it('rejects boundaries and invalid directions without mutating the active workout', () => {
const active = { cur: 0, entries: [entry('first'), entry('last')] }
const entries = [...active.entries]
expect(canMoveActiveWorkoutUnit(active, 0, -1)).toBe(false)
expect(canMoveActiveWorkoutUnit(active, 1, 1)).toBe(false)
expect(moveActiveWorkoutUnit(active, 0, 0)).toBeNull()
expect(moveActiveWorkoutUnit(active, 0, -1)).toBeNull()
expect(active.entries).toEqual(entries)
expect(active.cur).toBe(0)
})
})
describe('active workout move locale coverage', () => {
const packs = import.meta.glob('../locales/*.js', { eager: true, import: 'default' })
const localeCodes = Object.keys(LANGS).filter(code => code !== 'en')
it('defines both visible move labels in every current locale pack', () => {
expect(Object.keys(packs)).toHaveLength(localeCodes.length)
for (const code of localeCodes) {
const pack = packs[`../locales/${code}.js`]
expect(pack, `${code} locale pack is missing`).toBeTruthy()
for (const key of ['Move up', 'Move down']) {
expect(Object.hasOwn(pack, key), `${code} is missing ${key}`).toBe(true)
expect(pack[key], `${code} has a blank ${key}`).toEqual(expect.any(String))
expect(pack[key].trim(), `${code} has a blank ${key}`).not.toBe('')
}
}
expect(Object.hasOwn(PT_BR_OVERRIDES, 'Move up')).toBe(true)
expect(Object.hasOwn(PT_BR_OVERRIDES, 'Move down')).toBe(true)
})
})
+39
View File
@@ -0,0 +1,39 @@
// Logging a workout after the fact. The session itself is the ordinary active workout with a
// `backfill` field on it; these helpers are the parts that differ from a live session, kept
// pure so the date arithmetic and the history surgery can be tested without the UI.
export const workoutsOn = (S, iso) => (S.workouts || []).filter(w => w.d === iso)
// Epoch of `iso` at the given wall-clock time, in the browser's zone — the same zone
// todayISO() and isoOf() use, so `d` and `start` agree the way they do for a live session.
export const backfillStart = (iso, time = '18:00') => {
const [h, m] = String(time || '18:00').split(':').map(Number)
const d = new Date(iso + 'T12:00:00')
d.setHours(h || 0, m || 0, 0, 0)
return d.getTime()
}
// A live session ends when you tap finish; a logged one ends when you said it did.
export const backfillEnd = active => active.start + Math.max(1, active.backfill?.durationMin || 60) * 60000
// The workouts array is chronological (History reverses it), so a past workout cannot just be
// pushed — it goes where its date and start time put it, after anything from the same moment.
export function insertChronological(workouts, w) {
const key = x => [x.d || '', x.start || 0]
const [d, s] = key(w)
let i = workouts.length
while (i > 0) {
const [pd, ps] = key(workouts[i - 1])
if (pd < d || (pd === d && ps <= s)) break
i--
}
return [...workouts.slice(0, i), w, ...workouts.slice(i)]
}
// The history after a backfilled session is filed: the workout it replaces (if any) is gone
// and the new one sits in date order. Returns a new array; the caller stores it.
export function completeBackfill(workouts, active, w) {
const replaceId = active.backfill?.replaceId
const kept = replaceId ? workouts.filter(x => x.id !== replaceId) : workouts
return insertChronological(kept, w)
}
+59
View File
@@ -0,0 +1,59 @@
import { describe, expect, it } from 'vitest'
import { workoutsOn, backfillStart, backfillEnd, insertChronological, completeBackfill } from './backfill.js'
const w = (id, d, start = 0) => ({ id, d, start })
describe('workoutsOn', () => {
it('returns every workout of that day and nothing else', () => {
const S = { workouts: [w('a', '2026-01-01'), w('b', '2026-01-02'), w('c', '2026-01-02')] }
expect(workoutsOn(S, '2026-01-02').map(x => x.id)).toEqual(['b', 'c'])
expect(workoutsOn(S, '2026-01-03')).toEqual([])
expect(workoutsOn({}, '2026-01-03')).toEqual([])
})
})
describe('backfillStart / backfillEnd', () => {
it('lands on the chosen day at the chosen time in local zone', () => {
const t = new Date(backfillStart('2026-03-10', '07:45'))
expect([t.getFullYear(), t.getMonth() + 1, t.getDate(), t.getHours(), t.getMinutes()]).toEqual([2026, 3, 10, 7, 45])
})
it('defaults to 18:00 and ends after the given duration', () => {
const start = backfillStart('2026-03-10')
expect(new Date(start).getHours()).toBe(18)
expect(backfillEnd({ start, backfill: { durationMin: 45 } })).toBe(start + 45 * 60000)
expect(backfillEnd({ start, backfill: {} })).toBe(start + 60 * 60000)
expect(backfillEnd({ start, backfill: { durationMin: 0 } })).toBe(start + 60 * 60000)
})
})
describe('insertChronological', () => {
const list = [w('a', '2026-01-01', 10), w('b', '2026-01-05', 10), w('c', '2026-01-05', 20), w('d', '2026-01-09', 10)]
it('places by date, then by start time, after equal keys', () => {
expect(insertChronological(list, w('x', '2026-01-03')).map(x => x.id)).toEqual(['a', 'x', 'b', 'c', 'd'])
expect(insertChronological(list, w('x', '2026-01-05', 15)).map(x => x.id)).toEqual(['a', 'b', 'x', 'c', 'd'])
expect(insertChronological(list, w('x', '2026-01-05', 20)).map(x => x.id)).toEqual(['a', 'b', 'c', 'x', 'd'])
})
it('appends at the end and inserts at the front', () => {
expect(insertChronological(list, w('x', '2026-02-01')).at(-1).id).toBe('x')
expect(insertChronological(list, w('x', '2025-12-31'))[0].id).toBe('x')
expect(insertChronological([], w('x', '2026-01-01')).map(x => x.id)).toEqual(['x'])
})
it('does not mutate the input', () => {
const copy = [...list]
insertChronological(list, w('x', '2026-01-03'))
expect(list).toEqual(copy)
})
})
describe('completeBackfill', () => {
const list = [w('a', '2026-01-01', 10), w('b', '2026-01-05', 10), w('d', '2026-01-09', 10)]
it('adds a second workout on a day in order', () => {
const out = completeBackfill(list, { backfill: { durationMin: 60, replaceId: null } }, w('x', '2026-01-05', 5))
expect(out.map(x => x.id)).toEqual(['a', 'x', 'b', 'd'])
})
it('replaces the chosen workout', () => {
const out = completeBackfill(list, { backfill: { durationMin: 60, replaceId: 'b' } }, w('x', '2026-01-05', 30))
expect(out.map(x => x.id)).toEqual(['a', 'x', 'd'])
expect(list).toHaveLength(3)
})
})
+1
View File
@@ -35,6 +35,7 @@ export function buildCompletedWorkout(active, { end = Date.now(), prs = [], snap
bw: active.bw,
entries,
prs,
...(active.excludeFromProgression === true ? { excludeFromProgression: true } : {}),
...(sessionNote ? { note: sessionNote } : {}),
}
}
+12
View File
@@ -15,6 +15,18 @@ describe('completed workout boundary', () => {
})
})
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,
excludeFromProgression: true,
entries: [{ id: '0025', sets: [{ done: true, w: 30, r: 8 }], target: { sets: 1, reps: 8 } }],
}
expect(buildCompletedWorkout(active, { end: 2000 }).excludeFromProgression).toBe(true)
const { excludeFromProgression, ...regular } = active
expect(buildCompletedWorkout(regular, { end: 2000 })).not.toHaveProperty('excludeFromProgression')
})
it('persists a muscle snapshot only when the caller supplies one', () => {
const active = {
id: 'active-1', d: '2026-08-08', start: 1000,
+576
View File
@@ -0,0 +1,576 @@
// AUTO-GENERATED by scripts/build-hevy-id-map.mjs — do not edit by hand.
// Hevy exercise_template id → openGym catalogue id, plus English title → id for CSV exports
// (Hevy CSV has titles, not template ids). Regenerated from the Hevy templates API +
// verified title aliases. Five title aliases whose catalogue match was wrong (crunch → weighted
// crunch, side plank → hip adduction, machine squat → barbell squat, cable triceps extension and
// cable reverse fly → lever machines) are left out; those titles import as custom exercises.
// 283 mapped · 168 left unmatched (import as custom).
// Source templates: 451 (built-in only).
export const HEVY_ID_MAP = {
"018ADC12": "3017",
"01A35BF9": "2404",
"023943F1": "0572",
"026FD047": "0407",
"0393F233": "0218",
"040BA2E3": "2612",
"046E25A2": "0673",
"0482DA98": "0826",
"05293BCA": "3142",
"059E835D": "0603",
"062AB91A": "0594",
"06745E58": "1372",
"073032BB": "1457",
"07B38369": "0314",
"084A67CA": "0128",
"08590920": "0472",
"08A2974E": "0606",
"091737FA": "0573",
"09C9F635": "0865",
"0B4C1902": "0294",
"0B841777": "0095",
"0B9B92BA": "0085",
"0EB695C9": "2611",
"0F24286A": "0099",
"0FBF7195": "0748",
"1006DF48": "0401",
"10313AFD": "0550",
"10347BAC": "0591",
"10D76E8F": "1273",
"112FC6B7": "0080",
"11A123F3": "0586",
"12017185": "0308",
"123EE239": "0439",
"1283BBA6": "0043",
"150E076B": "3655",
"18487FA7": "0301",
"19372ABC": "0662",
"19A38071": "0604",
"1B2B1E7C": "0652",
"1B89CA1B": "0521",
"1D4B3D6B": "0313",
"1DF4A847": "1350",
"1E42FD5F": "0743",
"1E9A6B8E": "0592",
"20870ED5": "0752",
"20C1A3CB": "0809",
"21310F5F": "0607",
"218DA87C": "0803",
"22578A94": "0168",
"234897AB": "0165",
"23A48484": "0175",
"23E92538": "0292",
"243710DE": "3666",
"286C1D0B": "0246",
"28BB4A95": "0591",
"29083183": "1326",
"29472BE1": "0251",
"2982AA23": "0687",
"2A48E443": "0116",
"2B4B7310": "0085",
"2C37EC5E": "0017",
"2CFED196": "0069",
"2F8D3067": "0607",
"2FA77B28": "0459",
"3092FADD": "0607",
"32B0B590": "0507",
"32C4D4A2": "0298",
"32HKJ34K": "1460",
"3303376C": "2141",
"33EDD7DB": "1460",
"35B51B87": "0030",
"3601968B": "0289",
"36E8F14E": "0165",
"3765684D": "0607",
"37FCC2BB": "0294",
"392887AA": "0662",
"39C99849": "0493",
"3A6FA3D1": "0757",
"3D0C7C75": "1760",
"3F5F8D40": "3142",
"3FF6A22E": "0544",
"40C6A9FC": "0127",
"4180C405": "0044",
"422B08F1": "0334",
"425805F4": "0499",
"43573BB8": "0003",
"4377A52B": "2311",
"4377A52C": "2311",
"473CF5B8": "0673",
"47B036EF": "0978",
"49C922A1": "1409",
"4B4BF8C2": "0019",
"4E5257DE": "2616",
"4F5866F8": "0573",
"4F942934": "0070",
"5046D0A9": "0042",
"50C613D0": "2133",
"50DFDFAB": "0047",
"5122E7D9": "1451",
"51A0EDAA": "0677",
"542F3CD5": "1700",
"55E6546F": "0027",
"56808FD2": "0970",
"582ADA23": "1636",
"5E10D0E6": "3142",
"5E1A7777": "0054",
"5F4E6DD3": "0300",
"5F8903BF": "0551",
"6120CAAB": "0795",
"6182EE83": "0607",
"651F844C": "1269",
"6575F52D": "0283",
"6622E5A0": "3142",
"67280085": "0375",
"68B83EE0": "3193",
"68F8A292": "0060",
"6A6C31A5": "2330",
"6AC96645": "0405",
"6DA40660": "0417",
"6E6EE645": "0054",
"6FCD7755": "0251",
"70D4EBBF": "0514",
"72297E8C": "5201",
"724CDE60": "0297",
"729237D1": "0652",
"72CFFAD5": "1459",
"74103F24": "0052",
"742E5BD5": "0767",
"75A4F6C4": "0585",
"78683336": "0596",
"7952B5CD": "0872",
"796E8E2C": "0834",
"797F0782": "0437",
"79D0BB3A": "0025",
"7AB9A362": "0120",
"7B8D84E8": "0091",
"7C0028C3": "0593",
"7C50F118": "1429",
"7E3BC8B6": "0312",
"7EB3F7C3": "0577",
"818BA121": "0078",
"8293E554": "0310",
"875F585F": "0060",
"878CD1D0": "0405",
"89304423": "0529",
"8A2E6481": "0180",
"8BAB2735": "0318",
"8BEBFED6": "0598",
"8C331CD8": "0196",
"8C9D2928": "1494",
"90427D4A": "1675",
"90B04F96": "0471",
"90E506D5": "3305",
"91237BDD": "2289",
"914F3A96": "0327",
"91AF29E0": "0091",
"9237BAD1": "0603",
"923874CA": "0562",
"9273BA17": "0237",
"9283BABA": "0858",
"92D858EA": "0243",
"9372FFAA": "0396",
"93A552C6": "0241",
"947DAC23": "0259",
"95F2E076": "1426",
"9694DA61": "3543",
"98237BA2": "0826",
"991833C2": "3220",
"9930DF71": "0091",
"99507114": "0032",
"99B49684": "3663",
"99C1F2AD": "0151",
"99D5F10E": "0857",
"9B13BA4B": "0548",
"9DCE2D64": "0596",
"9F48F858": "0206",
"9F9C164B": "0631",
"A01BE509": "0443",
"A05C064D": "0573",
"A0D8FA1B": "2271",
"A127DA73": "0534",
"A2D838BD": "0243",
"A41C7261": "0972",
"A57D38D5": "0815",
"A5AC6449": "0031",
"A69FF221": "2137",
"A733CC5B": "1460",
"A8814C06": "1003",
"AA1EB7D8": "0571",
"AA52E8D2": "0773",
"ABB00838": "0028",
"ABEC557F": "0406",
"AC5A4C58": "0046",
"ADA8623C": "0868",
"AF328E3D": "0575",
"B05C2C29": "0605",
"B09A1304": "0766",
"B123DD01": "2285",
"B2398CD1": "0277",
"B3B1D947": "3360",
"B537D09F": "0336",
"B582299E": "0383",
"B5D3A742": "0410",
"B5EFBF9C": "0194",
"B74A95BB": "3211",
"B8127AD1": "0586",
"B82D6418": "0043",
"B923B230": "0811",
"BB792A36": "1160",
"BB83BDDE": "0687",
"BC10A922": "0277",
"BD4E7E53": "0535",
"BD86EFD5": "0041",
"BE289E45": "0178",
"BE640BA0": "0203",
"BF6ECE89": "0431",
"C315DC2A": "0602",
"C43825EA": "0279",
"C469EA70": "0597",
"C6272009": "0032",
"C628D768": "0648",
"C6C9B8A0": "2135",
"C7973E0E": "0739",
"C7AE420A": "0688",
"C8706C80": "0624",
"CC35A01F": "0043",
"CC55119B": "0979",
"CD6DC8E5": "0830",
"D04AC939": "0043",
"D20D7BBE": "0117",
"D23C609B": "0572",
"D2FE7B2E": "2330",
"D3095577": "0028",
"D3E2AB55": "0319",
"D4A2FE7E": "2143",
"D53F2886": "0065",
"D5D0354D": "0584",
"D8281C62": "0602",
"D82EA543": "0983",
"D8460FA6": "0385",
"D8911FC4": "0276",
"D8F7F851": "2331",
"D928C232": "0832",
"D950429E": "0038",
"DA0F0470": "0033",
"DBB91A3C": "0162",
"DBE341AA": "1495",
"DBF9273A": "0310",
"DCF3B31B": "0832",
"DCFF3E9F": "0413",
"DDCC3821": "0770",
"DE68C825": "0192",
"DF200976": "0977",
"E05C2C38": "0605",
"E3EDA509": "1775",
"E53CCBE5": "1372",
"E5988A0A": "0383",
"E644F828": "1258",
"E9E4089F": "0009",
"EA820646": "0027",
"EAC7D9C5": "3124",
"EB43ADD4": "1452",
"EB813C91": "1359",
"F1258206": "1004",
"F1D60854": "0218",
"F1E57334": "0292",
"F2A37357": "1410",
"F30A4F01": "1460",
"F3717B0E": "3888",
"F49E31D6": "0630",
"F4B4C6EE": "0597",
"F5DEF1EB": "1489",
"F8356514": "0472",
"F8A0FCCA": "0549",
"F99C211D": "0535",
"FAB6EB2F": "0372",
"FAF31231": "0033",
"FB09C938": "0067",
"FBF92739": "1299",
"FE389074": "0074",
"FFABC123": "0220",
"FFC106CB": "0753",
"FFDA283B": "0381",
}
/** Lowercased Hevy English title → catalogue id (CSV / name path). */
export const HEVY_TITLE_MAP = {
"ab wheel": "0857",
"air bike": "0003",
"arnold press (dumbbell)": "2137",
"around the world": "2143",
"back extension (hyperextension)": "0573",
"back extension (machine)": "0573",
"back extension (weighted hyperextension)": "0573",
"battle ropes": "0128",
"bear crawl": "3360",
"bench dip": "0830",
"bench press (barbell)": "0025",
"bench press (cable)": "0151",
"bench press (dumbbell)": "0289",
"bench press (smith machine)": "0748",
"bench press - close grip (barbell)": "0030",
"bench press - wide grip (barbell)": "1258",
"bent over row (band)": "0027",
"bent over row (barbell)": "0027",
"bent over row (dumbbell)": "0292",
"bent over row (smith machine)": "1359",
"bicep curl (barbell)": "0031",
"bicep curl (cable)": "0868",
"bicep curl (dumbbell)": "0294",
"bicep curl (machine)": "0575",
"bicep curl (suspension)": "0294",
"bicycle crunch": "0972",
"boxing": "2271",
"bulgarian split squat (barbell)": "0099",
"bulgarian split squat (dumbbell)": "0410",
"burpee": "1160",
"butterfly (pec deck)": "0596",
"cable core pallof press": "0979",
"cable crunch": "0175",
"cable fly crossovers": "1269",
"cable pull through": "0196",
"cable twist (down to up)": "0243",
"cable twist (up to down)": "0243",
"calf press (machine)": "2289",
"chest dip": "0251",
"chest dip (assisted)": "0009",
"chest dip (weighted)": "0251",
"chest fly (dumbbell)": "0308",
"chest fly (machine)": "0596",
"chest press (band)": "3124",
"chest press (machine)": "0577",
"chest supported incline row (dumbbell)": "0327",
"chest supported reverse fly (dumbbell)": "0383",
"chin up": "1326",
"chin up (assisted)": "0572",
"chin up (weighted)": "0572",
"clap push ups": "1273",
"clean": "0028",
"clean and press": "0028",
"concentration curl": "0297",
"cross body hammer curl": "0298",
"crunch (machine)": "1452",
"crunch (weighted)": "0832",
"cycling": "2331",
"dead bug": "0276",
"deadlift (band)": "0032",
"deadlift (barbell)": "0032",
"deadlift (dumbbell)": "0300",
"deadlift (smith machine)": "0752",
"deadlift (trap bar)": "0811",
"decline bench press (barbell)": "0033",
"decline bench press (dumbbell)": "0301",
"decline bench press (machine)": "0033",
"decline bench press (smith machine)": "0753",
"decline crunch": "0277",
"decline crunch (weighted)": "0277",
"decline push up": "0279",
"diamond push up": "0283",
"drag curl": "0038",
"dumbbell row": "0292",
"dumbbell snatch": "3888",
"dumbbell step up": "0431",
"elbow to knee": "0443",
"elliptical trainer": "2141",
"ez bar biceps curl": "2404",
"face pull": "0203",
"farmers walk": "2133",
"floor press (barbell)": "0065",
"floor triceps dip": "0815",
"flutter kicks": "0459",
"front raise (band)": "0978",
"front raise (barbell)": "0041",
"front raise (cable)": "0162",
"front raise (dumbbell)": "0310",
"front raise (suspension)": "0834",
"front squat": "0042",
"full squat": "0043",
"glute bridge (barbell)": "1409",
"glute ham raise": "3193",
"goblet squat": "1760",
"good morning (barbell)": "0044",
"hack squat": "0046",
"hack squat (machine)": "0743",
"hammer curl (band)": "0313",
"hammer curl (cable)": "0165",
"hammer curl (dumbbell)": "0312",
"handstand push up": "0471",
"hang clean": "0535",
"hanging knee raise": "0472",
"hanging leg raise": "0472",
"high knees": "3655",
"hip abduction (cable)": "0597",
"hip abduction (machine)": "0597",
"hip adduction (cable)": "0168",
"hip adduction (machine)": "0598",
"incline bench press (barbell)": "0047",
"incline bench press (dumbbell)": "0314",
"incline bench press (smith machine)": "0757",
"incline chest fly (dumbbell)": "0319",
"incline chest press (machine)": "1299",
"incline push ups": "0493",
"inverted row": "0499",
"iso-lateral row (machine)": "0571",
"jackknife sit up": "0507",
"jm press (barbell)": "0052",
"jump rope": "2612",
"jump squat": "0514",
"jumping jack": "3220",
"kettlebell clean": "0535",
"kettlebell goblet squat": "0534",
"kettlebell high pull": "0548",
"kettlebell snatch": "0529",
"kettlebell swing": "0549",
"kettlebell turkish get up": "0551",
"knee raise parallel bars": "0826",
"kneeling pulldown (band)": "0983",
"kneeling push up": "3211",
"landmine 180": "0562",
"lat pulldown (band)": "2330",
"lat pulldown (cable)": "2330",
"lat pulldown (machine)": "0673",
"lat pulldown - close grip (cable)": "2616",
"lateral lunge": "1410",
"lateral raise (band)": "0977",
"lateral raise (cable)": "0178",
"lateral raise (dumbbell)": "0334",
"lateral raise (machine)": "0584",
"leg extension (machine)": "0585",
"leg press (machine)": "0739",
"leg press horizontal (machine)": "2611",
"leg raise parallel bars": "0826",
"low row (suspension)": "0180",
"lunge": "0054",
"lunge (barbell)": "0054",
"lunge (dumbbell)": "0336",
"lying leg curl (machine)": "0586",
"lying leg raise": "0865",
"mountain climber": "0630",
"muscle up": "0631",
"oblique crunch": "1495",
"overhead curl (cable)": "1636",
"overhead press (barbell)": "0091",
"overhead press (dumbbell)": "0405",
"overhead press (smith machine)": "0766",
"overhead squat": "0069",
"overhead triceps extension (cable)": "0194",
"pendlay row (barbell)": "3017",
"pistol squat": "0544",
"plank": "2135",
"plate front raise": "0310",
"power clean": "0648",
"preacher curl (barbell)": "0070",
"preacher curl (dumbbell)": "0372",
"preacher curl (machine)": "0592",
"pull up": "0652",
"pull up (assisted)": "0017",
"pull up (band)": "0970",
"pull up (weighted)": "0652",
"pullover (dumbbell)": "0375",
"pullover (machine)": "2285",
"push press": "1700",
"push up": "0662",
"push up (weighted)": "0662",
"push up - close grip": "0259",
"rack pull": "0074",
"rear delt reverse fly (dumbbell)": "0383",
"rear delt reverse fly (machine)": "0602",
"renegade row (dumbbell)": "0521",
"reverse crunch": "0872",
"reverse curl (barbell)": "0080",
"reverse curl (cable)": "0206",
"reverse grip lat pulldown (cable)": "0673",
"reverse hyperextension": "0593",
"reverse lunge (barbell)": "0078",
"reverse lunge (dumbbell)": "0381",
"reverse plank": "3663",
"reverse wrist curl (dumbbell)": "0385",
"ring dips": "0677",
"romanian deadlift (barbell)": "0085",
"romanian deadlift (dumbbell)": "1459",
"romanian deadlift (smith machine)": "0085",
"rope cable curl": "0165",
"rope straight arm pulldown": "0237",
"russian twist (bodyweight)": "0687",
"russian twist (weighted)": "0687",
"scapular pull ups": "0688",
"seated cable row - bar grip": "0218",
"seated cable row - v grip (cable)": "0218",
"seated calf raise": "0594",
"seated dip machine": "1451",
"seated incline curl (dumbbell)": "0318",
"seated lateral raise (dumbbell)": "0396",
"seated leg curl (machine)": "0586",
"seated overhead press (barbell)": "0091",
"seated overhead press (dumbbell)": "0091",
"seated palms up wrist curl": "0401",
"seated row (machine)": "1350",
"seated shoulder press (machine)": "0603",
"seated wrist curl (barbell)": "1426",
"shoulder press (dumbbell)": "0405",
"shoulder press (machine plates)": "0603",
"shrug (barbell)": "0095",
"shrug (cable)": "0220",
"shrug (dumbbell)": "0406",
"shrug (machine)": "0604",
"shrug (smith machine)": "0767",
"side bend (dumbbell)": "0407",
"single arm lateral raise (cable)": "0192",
"single leg standing calf raise (machine)": "0605",
"sissy squat (weighted)": "1489",
"skullcrusher (barbell)": "0060",
"skullcrusher (dumbbell)": "0060",
"snatch": "0067",
"spider curl (dumbbell)": "1675",
"split squat (dumbbell)": "0809",
"sprints": "0858",
"squat (band)": "1004",
"squat (barbell)": "0043",
"squat (bodyweight)": "3543",
"squat (dumbbell)": "0413",
"squat (smith machine)": "0770",
"squat (suspension)": "0043",
"squat row": "1003",
"stair machine (floors)": "2311",
"stair machine (steps)": "2311",
"standing calf raise": "1372",
"standing calf raise (barbell)": "1372",
"standing calf raise (dumbbell)": "0417",
"standing calf raise (machine)": "0605",
"standing calf raise (smith)": "0773",
"standing leg curls": "0795",
"standing military press (barbell)": "1457",
"straight leg deadlift": "0116",
"sumo deadlift": "0117",
"sumo squat": "3142",
"sumo squat (barbell)": "3142",
"sumo squat (dumbbell)": "3142",
"sumo squat (kettlebell)": "3142",
"superman": "0803",
"t bar row": "0606",
"thruster (barbell)": "3305",
"thruster (kettlebell)": "0550",
"treadmill": "3666",
"triceps dip": "0591",
"triceps dip (assisted)": "0019",
"triceps dip (weighted)": "0591",
"triceps extension (barbell)": "0607",
"triceps extension (dumbbell)": "0607",
"triceps extension (machine)": "0607",
"triceps extension (suspension)": "0607",
"triceps pushdown": "0241",
"upright row (barbell)": "0120",
"upright row (cable)": "0246",
"upright row (dumbbell)": "0437",
"waiter curl (dumbbell)": "5201",
"walking": "1460",
"walking lunge": "1460",
"walking lunge (dumbbell)": "1460",
"walking lunge (sandbag)": "1460",
"wall sit": "0624",
"wide pull up": "1429",
"yoga": "1494",
"zercher squat": "0127",
"zottman curl (dumbbell)": "0439",
}
+34 -5
View File
@@ -308,13 +308,21 @@ export function buildSets(S, cfg, options = {}) {
export const MAX_PLANNED_WARMUPS = 5
function buildWorkSets(S, cfg, options = {}) {
const last = lastEntryFor(S, cfg.id)
const preferLast = !!options.preferLast
const useTarget = !!options.useTarget
// A workout flagged excludeFromProgression (a planned deload) is not "last time" for the
// next regular session either: its reps and durations must not seed the rows any more than
// its weight seeds the prescription. The deload session itself reads the routine's own target.
const regular = (S.workouts || []).some(w => w.excludeFromProgression === true)
? { ...S, workouts: S.workouts.filter(w => w.excludeFromProgression !== true) }
: S
const last = lastEntryFor(regular, cfg.id)
const n = Math.max(1, cfg.sets || 1)
const mode = modeOf(cfg)
const preferLast = !!options.preferLast
const sets = []
// Last time's set at the same position, falling back to its final set when the plan grew.
const prevAt = i => (last ? (last.sets[i] || last.sets[last.sets.length - 1]) : null)
// A deload routine must use its own prescription instead of carrying regular-session values
// into the workout. Other planned sessions keep the existing history-first behaviour.
const prevAt = i => (!useTarget && last ? (last.sets[i] || last.sets[last.sets.length - 1]) : null)
if (mode === 'cardio') {
for (let i = 0; i < n; i++) {
@@ -339,7 +347,12 @@ function buildWorkSets(S, cfg, options = {}) {
const usable = prev && prev.r > 0 ? prev : null
// Planned sessions may use the confirmed working weight, while freestyle should reproduce
// the load of each matching set when that option is requested.
const w = preferLast && usable ? usable.w : (conf && conf.w > 0 ? conf.w : (usable ? usable.w : cfg.weight))
// A deload uses the routine's target weight; a routine that never set one (weight 0) falls
// back to the last regular load rather than prescribing an empty bar.
const lastRegular = last ? (last.sets[i] || last.sets[last.sets.length - 1]) : null
const w = useTarget
? (cfg.weight > 0 ? cfg.weight : (lastRegular && lastRegular.r > 0 ? lastRegular.w : cfg.weight))
: preferLast && usable ? usable.w : (conf && conf.w > 0 ? conf.w : (usable ? usable.w : cfg.weight))
sets.push({ w, r: usable ? usable.r : cfg.reps, done: false })
}
return sets
@@ -421,6 +434,22 @@ export function supersetUnits(items) {
})
return units
}
// Move the selected occurrence's complete display unit by one neighbouring unit. Returning a
// new array keeps this helper pure; the caller decides how to persist it. Index identity matters
// here because the same exercise id may appear more than once with different setup.
export function moveSupersetUnit(items, index, direction) {
if (!Array.isArray(items) || (direction !== -1 && direction !== 1)) return null
const units = supersetUnits(items)
const source = units.findIndex(unit => unit.includes(index))
const target = source + direction
if (source < 0 || target < 0 || target >= units.length) return null
const reordered = [...units]
const selected = reordered[source]
reordered[source] = reordered[target]
reordered[target] = selected
return reordered.flat().map(i => items[i])
}
export function unitOf(units, idx) { return units.find(u => u.includes(idx)) || [idx] }
export function streakWeeks(S) {
+8
View File
@@ -493,6 +493,14 @@ describe('buildSets', () => {
.toEqual([{ w: 60, r: 10, done: false }, { w: 62.5, r: 8, done: false }])
})
it('can use a deload target without carrying regular-session values into it', () => {
const S = { exWeights: { [LIFT]: { w: 75 } }, workouts: [{ d: '2026-01-01', entries: [{ id: LIFT, sets: [
{ w: 75, r: 10, done: true }, { w: 75, r: 9, done: true }
] }] }] }
expect(buildSets(S, { id: LIFT, sets: 2, reps: 12, weight: 40 }, { useTarget: true }))
.toEqual([{ w: 40, r: 12, done: false }, { w: 40, r: 12, done: false }])
})
})
describe('applyIntensifierPlan', () => {
+10 -7
View File
@@ -7,13 +7,13 @@ export const LANGS = {
en: 'English', de: 'Deutsch', es: 'Español', fr: 'Français', it: 'Italiano',
pt: 'Português (Portugal)', 'pt-BR': 'Português (Brasil)', pl: 'Polski',
tr: 'Türkçe', ru: 'Русский', zh: '中文',
ko: '한국어', hi: 'हिन्दी'
ko: '한국어', hi: 'हिन्दी', th: 'ไทย', hu: 'Magyar'
}
export const INSTR_LANGS = ['en', 'es', 'fr', 'it', 'tr', 'ru', 'zh', 'hi', 'pl', 'ko', 'pt-BR']
export const EXERCISE_NAME_LANGS = ['pt-BR']
export const INSTR_LANGS = ['en', 'es', 'fr', 'it', 'tr', 'ru', 'zh', 'hi', 'pl', 'ko', 'pt-BR', 'hu']
export const EXERCISE_NAME_LANGS = ['pt-BR', 'hu']
export const DATE_LOCALES = {
en: 'en-GB', de: 'de-DE', es: 'es-ES', fr: 'fr-FR', it: 'it-IT', pt: 'pt-PT', 'pt-BR': 'pt-BR',
pl: 'pl-PL', tr: 'tr-TR', ru: 'ru-RU', zh: 'zh-CN', ko: 'ko-KR', hi: 'hi-IN'
pl: 'pl-PL', tr: 'tr-TR', ru: 'ru-RU', zh: 'zh-CN', ko: 'ko-KR', hi: 'hi-IN', th: 'th-TH', hu: 'hu-HU'
}
let lang = 'en' // set only by _setLangState, called from i18n.js setLang
@@ -41,9 +41,12 @@ export const instrFor = ex => (instr && instr[ex.id]) || ex.st || []
export const exerciseNameFor = ex => {
const translated = exerciseNames && ex && exerciseNames[ex.id]
if (!translated) return ex?.n || ''
// Some names (Burpee, Pilates, brand/model terms) are the established pt-BR term too.
// Repeating an identical loanword in parentheses adds noise rather than context.
return translated.toLocaleLowerCase('pt-BR') === ex.n.toLocaleLowerCase('en')
// Some names (Burpee, Pilates, brand/model terms) are the established term in the target
// language too. Repeating an identical loanword in parentheses adds noise rather than
// context. Compared in the active language's own casing rules, not hardcoded to one —
// this only ever differs from ordinary casing for languages with locale-specific rules
// (e.g. Turkish dotless i), which does not include any language shipped here today.
return translated.toLocaleLowerCase(lang) === ex.n.toLocaleLowerCase('en')
? translated
: `${translated} (${ex.n})`
}
+17 -1
View File
@@ -21,6 +21,7 @@
import { EXDB, EXIDX } from './exercises.js'
import { uid } from './format.js'
import { isWarmupRow } from './workout-model.js'
import { HEVY_TITLE_MAP } from './hevy-id-map.js'
/* ----------------------------------------------------------------- CSV ---- */
@@ -251,6 +252,16 @@ export function matchExercise(name) {
return ties === 1 ? best : null
}
/**
* Exact Hevy English title → catalogue id (from the generated title map).
* Used when a CSV is detected as Hevy: same deterministic table as the API import,
* keyed by title because Hevy's CSV has no template id column.
*/
export function matchHevyTitle(name) {
const id = HEVY_TITLE_MAP[String(name || '').trim().toLowerCase()]
return id && EXIDX[id] ? id : null
}
// Hevy exports no category column, so every invented exercise fell through to the
// 'upper legs' default and a third of an imported history was attributed to the legs in
// the muscle map. When there is no category, read the body part off the name instead.
@@ -389,7 +400,12 @@ export function parseWorkoutCSV(text, { unit = 'kg' } = {}) {
const key = keyOf(name)
let id = resolved.get(key)
if (id === undefined) { id = matchExercise(name); resolved.set(key, id) }
if (id === undefined) {
// Hevy CSV: prefer the generated English-title map (same table as the API import).
// Localized titles still fall through to the word-bag matcher.
id = (source === 'Hevy' ? matchHevyTitle(name) : null) || matchExercise(name)
resolved.set(key, id)
}
if (id) matched++
else {
let c = created.get(key)
+448
View File
@@ -0,0 +1,448 @@
// Import a Hevy account through the public API (https://api.hevyapp.com/docs/).
//
// Exercise identity is Hevy's `exercise_template_id`, looked up in the generated
// `hevy-id-map.js` table — never the localized title on a set. Regenerate the map
// with `node scripts/build-hevy-id-map.mjs`. The API key never leaves this module's
// callers: nothing here stores it.
import { EXIDX } from './exercises.js'
import { uid } from './format.js'
import { isWarmupRow } from './workout-model.js'
import { HEVY_ID_MAP, HEVY_TITLE_MAP } from './hevy-id-map.js'
export { HEVY_ID_MAP, HEVY_TITLE_MAP }
export const HEVY_API = 'https://api.hevyapp.com'
export const HEVY_DEV_SETTINGS = 'https://hevy.com/settings?developer'
const LB_TO_KG = 0.45359237
/* --------------------------------------------------------------- auth/fetch -- */
class HevyApiError extends Error {
constructor(status, message) {
super(message || `Hevy API error ${status}`)
this.name = 'HevyApiError'
this.status = status
}
}
async function hevyGet(path, apiKey, params = {}) {
const url = new URL(path, HEVY_API)
for (const [k, v] of Object.entries(params)) {
if (v != null && v !== '') url.searchParams.set(k, String(v))
}
// Hevy publishes no rate limit, but a large account is 100+ sequential page requests; a 429
// gets a short back-off and one more try before it surfaces as its own error kind.
for (let attempt = 0; ; attempt++) {
const res = await fetch(url, { headers: { 'api-key': apiKey } })
if (res.status === 401 || res.status === 403) {
throw new HevyApiError(res.status, 'auth')
}
if (res.status === 429 && attempt < 2) {
const after = Number(res.headers?.get?.('retry-after'))
await new Promise(r => setTimeout(r, (after > 0 && after <= 30 ? after : 2 * (attempt + 1)) * 1000))
continue
}
if (res.status === 429) throw new HevyApiError(res.status, 'rate-limit')
if (!res.ok) throw new HevyApiError(res.status, `http ${res.status}`)
return res.json()
}
}
/** Page through a Hevy list endpoint. `pageSize` caps differ per resource. */
export async function fetchHevyPages(path, apiKey, {
resultKey,
pageSize = 10,
onProgress,
} = {}) {
const items = []
let page = 1
let pageCount = 1
while (page <= pageCount) {
const data = await hevyGet(path, apiKey, { page, pageSize })
pageCount = Math.max(1, data.page_count || 1)
const batch = data[resultKey] || []
items.push(...batch)
onProgress && onProgress({ page, pageCount, loaded: items.length, resultKey })
if (!batch.length) break
page++
}
return items
}
export async function fetchHevyAccount(apiKey, { onProgress } = {}) {
const key = String(apiKey || '').trim()
if (!key) throw new HevyApiError(0, 'empty')
const templates = await fetchHevyPages('/v1/exercise_templates', key, {
resultKey: 'exercise_templates', pageSize: 100,
onProgress: p => onProgress && onProgress({ stage: 'templates', ...p }),
})
const workouts = await fetchHevyPages('/v1/workouts', key, {
resultKey: 'workouts', pageSize: 10,
onProgress: p => onProgress && onProgress({ stage: 'workouts', ...p }),
})
const routines = await fetchHevyPages('/v1/routines', key, {
resultKey: 'routines', pageSize: 10,
onProgress: p => onProgress && onProgress({ stage: 'routines', ...p }),
})
let bodyMeasurements = []
try {
bodyMeasurements = await fetchHevyPages('/v1/body_measurements', key, {
resultKey: 'body_measurements', pageSize: 10,
onProgress: p => onProgress && onProgress({ stage: 'body', ...p }),
})
} catch (e) {
// Older keys / accounts may lack measurements — workouts still import.
if (!(e instanceof HevyApiError) || e.message === 'auth') throw e
}
return { templates, workouts, routines, bodyMeasurements }
}
/* ---------------------------------------------------------- template → id -- */
// Hevy primary_muscle_group → openGym body-part for exercises we invent.
const HEVY_BP = {
biceps: 'upper arms', triceps: 'upper arms', forearms: 'lower arms',
chest: 'chest', lats: 'back', upper_back: 'back', lower_back: 'back',
traps: 'back', shoulders: 'shoulders',
abdominals: 'waist', abs: 'waist', obliques: 'waist',
quadriceps: 'upper legs', hamstrings: 'upper legs', glutes: 'upper legs',
abductors: 'upper legs', adductors: 'upper legs', calves: 'lower legs',
cardio: 'cardio', full_body: 'upper legs', other: 'upper legs', neck: 'neck',
}
/**
* Resolve a Hevy exercise template to a catalogue id.
*
* Deterministic: only `HEVY_ID_MAP` (generated by scripts/build-hevy-id-map.mjs).
* No runtime name guessing — unmatched templates become custom exercises.
*/
export function matchHevyTemplate(template) {
if (!template?.id) return null
const id = HEVY_ID_MAP[template.id]
return id && EXIDX[id] ? id : null
}
/** Build templateId → catalogue id (or null) from a templates list. */
export function buildHevyExerciseMap(templates) {
const map = new Map()
for (const t of templates || []) {
if (!t?.id) continue
map.set(t.id, matchHevyTemplate(t))
}
return map
}
/* --------------------------------------------------------------- parse ---- */
const p2 = n => String(n).padStart(2, '0')
/** Hevy ISO timestamps → local calendar date + ms-since-midnight (matches CSV import). */
export function localWhen(iso) {
const d = new Date(iso)
if (isNaN(d.getTime())) return null
const day = `${d.getFullYear()}-${p2(d.getMonth() + 1)}-${p2(d.getDate())}`
const t = d.getHours() * 3600000 + d.getMinutes() * 60000 + d.getSeconds() * 1000
return { d: day, t }
}
function bpOfTemplate(t) {
const g = String(t?.primary_muscle_group || '').toLowerCase()
return HEVY_BP[g] || 'upper legs'
}
/** Shared resolver: HEVY_ID_MAP hit, else one custom exercise per Hevy template id. */
function makeResolver(templates) {
const byId = new Map((templates || []).map(t => [t.id, t]))
const created = new Map()
const unmatched = new Set()
const matchedIds = new Set()
const resolve = (templateId, fallbackTitle) => {
const pinned = templateId && HEVY_ID_MAP[templateId]
if (pinned && EXIDX[pinned]) {
matchedIds.add(pinned)
return pinned
}
const key = templateId || String(fallbackTitle || '').toLowerCase()
if (!key) return null
let c = created.get(key)
if (!c) {
const t = templateId ? byId.get(templateId) : null
const name = (t?.title || fallbackTitle || 'exercise').toLowerCase()
c = {
id: 'im' + uid(), n: name, custom: true, eq: 'custom', tg: '', desc: '',
bp: bpOfTemplate(t) || (t?.type === 'distance_duration' || t?.type === 'duration' ? 'cardio' : null)
|| 'upper legs',
}
created.set(key, c)
unmatched.add(t?.title || fallbackTitle || name)
}
return c.id
}
return {
resolve,
byId,
customEx: () => [...created.values()],
unmatchedNames: () => [...unmatched].sort(),
matchedCount: () => matchedIds.size,
createdCount: () => created.size,
}
}
const toProfileWeight = (wKg, unit) => {
if (wKg == null || !isFinite(wKg)) return 0
if (unit === 'lb') return Math.round(wKg / LB_TO_KG * 10) / 10
return Math.round(wKg * 10) / 10
}
/**
* Turn Hevy API workouts into the same shape `mergeImport` already understands.
* Mapping is by `exercise_template_id` through `HEVY_ID_MAP` only — localized
* titles on each set are never used to pick a catalogue entry.
*/
export function parseHevyWorkouts(workouts, templates, { unit = 'kg' } = {}) {
const R = makeResolver(templates)
const byDate = new Map()
let sets = 0, skipped = 0, matched = 0, warmups = 0, rpeSets = 0
for (const w of workouts || []) {
const start = localWhen(w.start_time)
const end = localWhen(w.end_time)
if (!start) { skipped++; continue }
let day = byDate.get(start.d)
if (!day) {
day = { ex: new Map(), name: w.title || '', start: start.t, end: end?.t ?? null }
byDate.set(start.d, day)
} else if (!day.name && w.title) day.name = w.title
if (end?.t != null) day.end = end.t
for (const ex of w.exercises || []) {
const id = R.resolve(ex.exercise_template_id, ex.title)
if (!id) { skipped++; continue }
if (EXIDX[id] && !String(id).startsWith('im')) matched++
if (!day.ex.has(id)) day.ex.set(id, [])
const list = day.ex.get(id)
for (const s of ex.sets || []) {
const warmup = /warm/i.test(String(s.type || ''))
if (warmup) warmups++
const reps = s.reps != null ? Math.round(s.reps) : 0
const wgt = toProfileWeight(s.weight_kg, unit)
const secs = s.duration_seconds != null ? Number(s.duration_seconds) : 0
const km = s.distance_meters != null ? Number(s.distance_meters) / 1000 : 0
if (!wgt && !reps && !secs && !km) { skipped++; continue }
const isCardio = (km > 0 || secs > 0) && !reps
const mins = secs > 0 ? Math.round(secs / 60 * 10) / 10 : 0
const set = isCardio
? { min: mins, speed: mins > 0 ? Math.round(km / (mins / 60) * 10) / 10 : 0, done: true, ...(warmup ? { phase: 'warmup' } : {}) }
: { w: wgt, r: reps || 0, done: true, ...(warmup ? { phase: 'warmup' } : {}) }
if (!isCardio && s.rpe != null && isFinite(Number(s.rpe)) && Number(s.rpe) > 0) {
set.rpe = Math.min(10, Math.round(Number(s.rpe) * 100) / 100)
rpeSets++
}
list.push(set)
sets++
}
}
}
const dates = [...byDate.keys()].sort()
const outWorkouts = dates.map(d => {
const day = byDate.get(d)
const entries = [...day.ex.entries()].map(([id, ss]) => {
const mx = Math.max(0, ...ss.filter(s => !isWarmupRow(s)).map(s => s.w || 0))
return { id, sets: ss, topW: mx || null }
})
const base = new Date(d + 'T00:00:00').getTime()
const startMs = base + (day.start ?? 18 * 3600000)
const endMs = day.end != null ? base + day.end : startMs
const workout = {
id: 'iw' + uid(), d, start: startMs, end: endMs > startMs ? endMs : startMs,
routineId: null, name: day.name || 'Imported', entries, prs: [],
}
workout.vol = entries.reduce((a, e) => a + e.sets.reduce((b, s) => b + (s.w || 0) * (s.r || 0), 0), 0)
return workout
})
return {
kind: 'workouts',
source: 'Hevy',
workouts: outWorkouts,
customEx: R.customEx(),
matched: R.matchedCount(),
matchedSets: matched,
created: R.createdCount(),
unmatchedNames: R.unmatchedNames(),
sets, skipped, warmups,
fileUnit: 'kg',
mixedUnits: false,
converted: unit === 'lb',
rpeSets, rirSets: 0,
from: dates[0] || null,
to: dates[dates.length - 1] || null,
}
}
/**
* Hevy routine → openGym routine config.
* Work sets become `sets`×`reps`/`weight`; warm-ups become `warmupSets`;
* supersets keep adjacency via `sg`. Always imported as *new* routines.
*/
export function parseHevyRoutines(routines, templates, { unit = 'kg' } = {}) {
const R = makeResolver(templates)
const out = []
for (const r of routines || []) {
const ex = []
const sgMap = new Map() // Hevy superset_id → openGym sg token
for (const he of r.exercises || []) {
const id = R.resolve(he.exercise_template_id, he.title)
if (!id) continue
const allSets = he.sets || []
const warm = allSets.filter(s => /warm/i.test(String(s.type || ''))).length
const work = allSets.filter(s => !/warm/i.test(String(s.type || '')))
if (!work.length && !warm) continue
const sample = work[0] || allSets[0]
const reps = sample?.reps != null ? Math.round(sample.reps) : 0
const secs = sample?.duration_seconds != null ? Number(sample.duration_seconds) : 0
const km = sample?.distance_meters != null ? Number(sample.distance_meters) / 1000 : 0
const wgt = toProfileWeight(sample?.weight_kg, unit)
const nWork = Math.max(1, work.length)
let cfg
if (km > 0 && !reps) {
const mins = secs > 0 ? Math.round(secs / 60 * 10) / 10 : 20
cfg = {
id, sets: nWork, min: mins || 20,
speed: mins > 0 ? Math.round(km / (mins / 60) * 10) / 10 : 0,
}
} else if (secs > 0 && !reps && !wgt) {
cfg = { id, sets: nWork, sec: Math.round(secs), weight: 0, mode: 'time' }
} else {
cfg = { id, sets: nWork, reps: reps || 10, weight: wgt || 0, mode: 'reps' }
}
if (warm > 0) cfg.warmupSets = Math.min(5, warm)
if (he.notes) cfg.note = String(he.notes).slice(0, 280)
if (he.superset_id != null && he.superset_id !== '') {
const key = String(he.superset_id)
if (!sgMap.has(key)) sgMap.set(key, 'hs' + uid())
cfg.sg = sgMap.get(key)
}
ex.push(cfg)
}
if (!ex.length) continue
// Drop singleton supersets (partner missing after drops).
ex.forEach((e, i) => {
if (e.sg && !(ex[i - 1]?.sg === e.sg || ex[i + 1]?.sg === e.sg)) delete e.sg
})
out.push({
id: 'hr' + uid(),
name: (r.title || 'Imported').trim() || 'Imported',
emoji: 'figureStrength',
hevyId: r.id || null,
ex,
})
}
return {
kind: 'routines',
source: 'Hevy',
routines: out,
customEx: R.customEx(),
matched: R.matchedCount(),
created: R.createdCount(),
unmatchedNames: R.unmatchedNames(),
exerciseCount: out.reduce((n, r) => n + r.ex.length, 0),
converted: unit === 'lb',
}
}
/** Merge Hevy routines into state — always added as new routines (fresh ids). */
export function mergeHevyRoutines(S, parsed) {
S.customEx = S.customEx || []
S.routines = S.routines || []
const exIdMap = {}
;(parsed.customEx || []).forEach(c => {
const same = S.customEx.find(x => (x.n || '').toLowerCase() === (c.n || '').toLowerCase() && x.bp === c.bp)
if (same) { exIdMap[c.id] = same.id; return }
// Keep the pre-assigned id from parse so routine configs already point at it.
if (!S.customEx.some(x => x.id === c.id)) S.customEx.push(c)
})
// A second import must not double every plan: a routine that already carries the same Hevy
// id is replaced in place (its exercises re-read from Hevy), everything else is appended.
let added = 0, updated = 0
for (const r of parsed.routines || []) {
const ex = (r.ex || []).map(e => ({ ...e, id: exIdMap[e.id] || e.id }))
const existing = r.hevyId ? S.routines.find(x => x.hevyId === r.hevyId) : null
if (existing) {
existing.name = r.name
existing.ex = ex
updated++
continue
}
S.routines.push({
id: uid(),
name: r.name,
emoji: r.emoji || 'figureStrength',
...(r.hevyId ? { hevyId: r.hevyId } : {}),
ex,
})
added++
}
return { added, updated }
}
/** Body measurements from the Hevy API → `mergeImport` bodyweight shape. */
export function parseHevyBodyweight(measurements, { unit = 'kg' } = {}) {
const out = new Map()
for (const m of measurements || []) {
const d = String(m.date || '').slice(0, 10)
if (!/^\d{4}-\d{2}-\d{2}$/.test(d)) continue
let w = Number(m.weight_kg)
if (!isFinite(w) || w <= 0) continue
if (unit === 'lb') w = Math.round(w / LB_TO_KG * 10) / 10
else w = Math.round(w * 10) / 10
const t = m.created_at ? new Date(m.created_at).getTime() : new Date(d + 'T12:00:00').getTime()
out.set(d, { d, w, t: isFinite(t) ? t : new Date(d + 'T12:00:00').getTime() })
}
const dates = [...out.keys()].sort()
return {
kind: 'bodyweight',
source: 'Hevy',
bodyweight: dates.map(d => out.get(d)),
fileUnit: 'kg',
converted: unit === 'lb',
from: dates[0] || null,
to: dates[dates.length - 1] || null,
}
}
/**
* Fetch + parse. Returns `{ workouts, routines, bodyweight }` ready to merge,
* or throws `HevyApiError`. The apiKey is only read here — never written.
*/
export async function importHevyData(apiKey, { unit = 'kg', onProgress } = {}) {
const { templates, workouts, routines, bodyMeasurements } = await fetchHevyAccount(apiKey, { onProgress })
onProgress && onProgress({ stage: 'parse' })
return {
workouts: parseHevyWorkouts(workouts, templates, { unit }),
routines: parseHevyRoutines(routines, templates, { unit }),
bodyweight: parseHevyBodyweight(bodyMeasurements, { unit }),
templateCount: templates.length,
}
}
export { HevyApiError }
+302
View File
@@ -0,0 +1,302 @@
import { describe, expect, it, vi, afterEach } from 'vitest'
import {
matchHevyTemplate, buildHevyExerciseMap, parseHevyWorkouts, parseHevyBodyweight,
parseHevyRoutines, mergeHevyRoutines, localWhen, importHevyData, HevyApiError, HEVY_ID_MAP,
} from './import-hevy.js'
import { EXIDX } from './exercises.js'
import { mergeImport } from './import-csv.js'
const TEMPLATES = [
{
id: '3303376C', title: 'Elliptical Trainer', type: 'distance_duration',
primary_muscle_group: 'cardio', secondary_muscle_groups: [], equipment: 'machine', is_custom: false,
},
{
id: '4E5257DE', title: 'Lat Pulldown - Close Grip (Cable)', type: 'weight_reps',
primary_muscle_group: 'lats', secondary_muscle_groups: [], equipment: 'machine', is_custom: false,
},
{
id: 'DEADBEEF', title: 'My Invented Landmine Twist', type: 'weight_reps',
primary_muscle_group: 'abdominals', secondary_muscle_groups: [], equipment: 'other', is_custom: true,
},
{
id: '99D5F10E', title: 'Ab Wheel', type: 'reps_only',
primary_muscle_group: 'abdominals', secondary_muscle_groups: [], equipment: 'other', is_custom: false,
},
]
const WORKOUT = {
id: 'w1',
title: 'Oberkörper 2',
start_time: '2026-08-25T10:10:24+00:00',
end_time: '2026-08-25T11:10:08+00:00',
exercises: [
{
index: 0,
title: 'Crosstrainer', // localized — must NOT drive the match
exercise_template_id: '3303376C',
sets: [{
index: 0, type: 'normal', weight_kg: null, reps: null,
distance_meters: 480, duration_seconds: 180, rpe: null,
}],
},
{
index: 1,
title: 'Latzug - Enger Griff (Kabel)',
exercise_template_id: '4E5257DE',
sets: [
{ index: 0, type: 'warmup', weight_kg: 25, reps: 15, distance_meters: null, duration_seconds: null, rpe: null },
{ index: 1, type: 'normal', weight_kg: 52, reps: 15, distance_meters: null, duration_seconds: null, rpe: 8 },
{ index: 2, type: 'normal', weight_kg: 52, reps: 10, distance_meters: null, duration_seconds: null, rpe: null },
],
},
{
index: 2,
title: 'Meine Eigenkreation',
exercise_template_id: 'DEADBEEF',
sets: [
{ index: 0, type: 'normal', weight_kg: 20, reps: 12, distance_meters: null, duration_seconds: null, rpe: null },
],
},
],
}
describe('HEVY_ID_MAP', () => {
it('only points at real catalogue ids', () => {
for (const id of Object.values(HEVY_ID_MAP)) {
expect(EXIDX[id], `catalogue missing ${id}`).toBeTruthy()
}
})
// Real import leftovers: same lifts under Hevy's naming. Map lookup is the
// only resolution path — titles are never guessed at runtime.
const PINNED = {
B5D3A742: '0410', // Bulgarian Split Squat (Dumbbell)
'914F3A96': '0327', // Chest Supported Incline Row (Dumbbell)
'98237BA2': '0826', // Knee Raise Parallel Bars
'4E5257DE': '2616', // Lat Pulldown - Close Grip (Cable)
C315DC2A: '0602', // Rear Delt Reverse Fly (Cable)
FFDA283B: '0381', // Reverse Lunge (Dumbbell)
'8BAB2735': '0318', // Seated Incline Curl (Dumbbell)
'9237BAD1': '0603', // Seated Shoulder Press (Machine)
B05C2C29: '0605', // Single Leg Standing Calf Raise (Machine)
'3303376C': '2141', // Elliptical Trainer
'99D5F10E': '0857', // Ab Wheel
}
for (const [hid, want] of Object.entries(PINNED)) {
it(`maps ${hid} → ${want} (${EXIDX[want]?.n})`, () => {
expect(HEVY_ID_MAP[hid]).toBe(want)
expect(matchHevyTemplate({ id: hid, title: 'ignored localized name' })).toBe(want)
})
}
it('leaves catalogue gaps unmapped (import as custom)', () => {
for (const id of ['68CE0B9B', '0222DB42', 'D1CD146F']) {
expect(HEVY_ID_MAP[id]).toBeUndefined()
expect(matchHevyTemplate({ id, title: 'whatever' })).toBeNull()
}
})
})
describe('matchHevyTemplate', () => {
it('is map-only — title never overrides the id', () => {
expect(matchHevyTemplate({ id: '3303376C', title: 'Totally Wrong Name' })).toBe('2141')
expect(matchHevyTemplate({ id: 'DEADBEEF', title: 'Bench Press' })).toBeNull()
})
})
describe('parseHevyWorkouts', () => {
it('maps by template id, not the localized workout title', () => {
const parsed = parseHevyWorkouts([WORKOUT], TEMPLATES, { unit: 'kg' })
expect(parsed.error).toBeUndefined()
expect(parsed.source).toBe('Hevy')
expect(parsed.workouts).toHaveLength(1)
const entries = parsed.workouts[0].entries
const elliptical = entries.find(e => e.id === '2141')
expect(elliptical).toBeTruthy()
expect(elliptical.sets[0]).toMatchObject({ min: 3, done: true })
const pulldown = entries.find(e => e.id === '2616')
expect(pulldown).toBeTruthy()
expect(pulldown.sets[0]).toMatchObject({ w: 25, r: 15, phase: 'warmup' })
expect(pulldown.sets[1]).toMatchObject({ w: 52, r: 15, rpe: 8 })
expect(pulldown.topW).toBe(52)
expect(parsed.warmups).toBe(1)
expect(parsed.rpeSets).toBe(1)
const custom = entries.find(e => String(e.id).startsWith('im'))
expect(custom).toBeTruthy()
expect(parsed.customEx.some(c => c.id === custom.id && c.n === 'my invented landmine twist')).toBe(true)
expect(parsed.customEx.find(c => c.id === custom.id).bp).toBe('waist')
expect(parsed.unmatchedNames).toContain('My Invented Landmine Twist')
})
it('converts kg weights into a lb profile', () => {
const parsed = parseHevyWorkouts([WORKOUT], TEMPLATES, { unit: 'lb' })
const pulldown = parsed.workouts[0].entries.find(e => e.id === '2616')
expect(pulldown.sets.find(s => s.r === 15 && !s.phase).w).toBeCloseTo(114.6, 0)
expect(parsed.converted).toBe(true)
})
it('merges two Hevy sessions on the same local day', () => {
const a = { ...WORKOUT, id: 'a', title: 'AM', exercises: [WORKOUT.exercises[0]] }
const b = {
...WORKOUT, id: 'b', title: 'PM',
start_time: '2026-08-25T18:00:00+00:00',
end_time: '2026-08-25T19:00:00+00:00',
exercises: [WORKOUT.exercises[1]],
}
const parsed = parseHevyWorkouts([a, b], TEMPLATES, { unit: 'kg' })
expect(parsed.workouts).toHaveLength(1)
expect(parsed.workouts[0].entries.length).toBeGreaterThanOrEqual(2)
})
})
describe('parseHevyBodyweight', () => {
it('reads weigh-ins in the profile unit', () => {
const parsed = parseHevyBodyweight([
{ id: 1, date: '2026-08-23', weight_kg: 83.2, created_at: '2026-08-23T18:22:48.070Z' },
], { unit: 'kg' })
expect(parsed.bodyweight).toEqual([{ d: '2026-08-23', w: 83.2, t: expect.any(Number) }])
})
})
describe('mergeImport with Hevy payloads', () => {
it('adds workouts and skips days that already exist', () => {
const parsed = parseHevyWorkouts([WORKOUT], TEMPLATES, { unit: 'kg' })
const S = { workouts: [], customEx: [], exWeights: {}, bodyweight: [] }
const first = mergeImport(S, parsed)
expect(first.added).toBe(1)
expect(S.customEx.length).toBe(1)
const second = mergeImport(S, parsed)
expect(second.added).toBe(0)
expect(S.workouts).toHaveLength(1)
})
})
describe('localWhen', () => {
it('parses an ISO timestamp into a local calendar day', () => {
const w = localWhen('2026-08-25T10:10:24+00:00')
expect(w.d).toMatch(/^\d{4}-\d{2}-\d{2}$/)
expect(w.t).toBeGreaterThanOrEqual(0)
})
})
describe('importHevyData', () => {
afterEach(() => { vi.unstubAllGlobals(); vi.restoreAllMocks() })
it('pages templates and workouts, never persists the key', async () => {
const calls = []
vi.stubGlobal('fetch', vi.fn(async (url, opts) => {
calls.push({ url: String(url), key: opts.headers['api-key'] })
const u = String(url)
if (u.includes('/exercise_templates')) {
return { ok: true, status: 200, json: async () => ({ page: 1, page_count: 1, exercise_templates: TEMPLATES }) }
}
if (u.includes('/workouts')) {
return { ok: true, status: 200, json: async () => ({ page: 1, page_count: 1, workouts: [WORKOUT] }) }
}
if (u.includes('/routines')) {
return { ok: true, status: 200, json: async () => ({ page: 1, page_count: 1, routines: [] }) }
}
if (u.includes('/body_measurements')) {
return { ok: true, status: 200, json: async () => ({ page: 1, page_count: 1, body_measurements: [] }) }
}
return { ok: false, status: 404, json: async () => ({}) }
}))
const result = await importHevyData('test-key-not-stored', { unit: 'kg' })
expect(result.workouts.workouts).toHaveLength(1)
expect(result.routines.routines).toHaveLength(0)
expect(result.bodyweight.bodyweight).toHaveLength(0)
expect(calls.every(c => c.key === 'test-key-not-stored')).toBe(true)
})
it('surfaces a refused key as HevyApiError auth', async () => {
vi.stubGlobal('fetch', vi.fn(async () => ({ ok: false, status: 401, json: async () => ({}) })))
await expect(importHevyData('bad')).rejects.toMatchObject({ name: 'HevyApiError', message: 'auth' })
})
})
describe('parseHevyRoutines', () => {
const ROUTINE = {
id: 'r1',
title: 'Oberkörper 2',
exercises: [
{
title: 'Crosstrainer',
exercise_template_id: '3303376C',
superset_id: null,
sets: [{ type: 'normal', weight_kg: null, reps: null, distance_meters: 480, duration_seconds: 180 }],
},
{
title: 'Latzug',
exercise_template_id: '4E5257DE',
superset_id: 1,
sets: [
{ type: 'warmup', weight_kg: 25, reps: 15 },
{ type: 'normal', weight_kg: 52, reps: 15 },
{ type: 'normal', weight_kg: 52, reps: 12 },
{ type: 'normal', weight_kg: 52, reps: 10 },
],
},
{
title: 'Row partner',
exercise_template_id: '914F3A96', // chest supported incline row → 0327
superset_id: 1,
sets: [
{ type: 'normal', weight_kg: 20, reps: 12 },
{ type: 'normal', weight_kg: 20, reps: 12 },
],
},
],
}
it('builds openGym routine configs from Hevy sets', () => {
const parsed = parseHevyRoutines([ROUTINE], TEMPLATES, { unit: 'kg' })
expect(parsed.routines).toHaveLength(1)
expect(parsed.routines[0].name).toBe('Oberkörper 2')
expect(parsed.exerciseCount).toBe(3)
const [cardio, pull, row] = parsed.routines[0].ex
expect(cardio.id).toBe('2141')
expect(cardio).toMatchObject({ sets: 1, min: 3 })
expect(pull.id).toBe('2616')
expect(pull).toMatchObject({ sets: 3, reps: 15, weight: 52, warmupSets: 1 })
expect(row.id).toBe('0327')
expect(pull.sg).toBeTruthy()
expect(pull.sg).toBe(row.sg)
})
it('mergeHevyRoutines replaces a routine it imported before instead of duplicating it', () => {
const parsed = parseHevyRoutines([ROUTINE], TEMPLATES, { unit: 'kg' })
const S = { routines: [], customEx: [] }
expect(mergeHevyRoutines(S, parsed)).toEqual({ added: 1, updated: 0 })
expect(S.routines).toHaveLength(1)
expect(S.routines[0].hevyId).toBe(ROUTINE.id)
const firstId = S.routines[0].id
S.routines[0].name = 'renamed locally'
expect(mergeHevyRoutines(S, parsed)).toEqual({ added: 0, updated: 1 })
expect(S.routines).toHaveLength(1)
expect(S.routines[0].id).toBe(firstId)
expect(S.routines[0].name).toBe(ROUTINE.title)
})
it('mergeHevyRoutines still adds a routine that carries no Hevy id', () => {
const parsed = parseHevyRoutines([{ ...ROUTINE, id: undefined }], TEMPLATES, { unit: 'kg' })
const S = { routines: [], customEx: [] }
mergeHevyRoutines(S, parsed); mergeHevyRoutines(S, parsed)
expect(S.routines).toHaveLength(2)
})
})
describe('buildHevyExerciseMap', () => {
it('indexes every template id from the static map', () => {
const map = buildHevyExerciseMap(TEMPLATES)
expect(map.get('3303376C')).toBe('2141')
expect(map.get('4E5257DE')).toBe('2616')
expect(map.get('DEADBEEF')).toBeNull()
expect(map.size).toBe(TEMPLATES.length)
})
})
+34 -1
View File
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest'
import { matchExercise, parseWorkoutCSV } from './import-csv.js'
import { matchExercise, matchHevyTitle, parseWorkoutCSV, detectSource } from './import-csv.js'
import { EXIDX } from './exercises.js'
// The names other apps actually export, and the catalogue entry each has to land on.
@@ -109,3 +109,36 @@ describe('invented exercises get a body part from their name', () => {
expect(r.customEx[0].bp).toBe('shoulders')
})
})
describe('Hevy CSV uses the generated title map', () => {
const HEVY_CSV = [
'title,start_time,end_time,description,exercise_title,superset_id,exercise_notes,set_index,set_type,weight_kg,reps,distance_km,duration_seconds,rpe',
'Push,2026-08-01 10:00:00,2026-08-01 11:00:00,,Bulgarian Split Squat (Dumbbell),,,0,normal,40,10,0,,',
'Push,2026-08-01 10:00:00,2026-08-01 11:00:00,,Lat Pulldown - Close Grip (Cable),,,0,warmup,25,15,0,,',
'Push,2026-08-01 10:00:00,2026-08-01 11:00:00,,Lat Pulldown - Close Grip (Cable),,,1,normal,52,12,0,,8',
'Push,2026-08-01 10:00:00,2026-08-01 11:00:00,,Reverse Lunge (Dumbbell),,,0,normal,20,10,0,,',
].join('\n')
it('detects the Hevy export dialect', () => {
expect(detectSource(HEVY_CSV.split('\n')[0].split(','))).toBe('Hevy')
})
it('resolves English Hevy titles through HEVY_TITLE_MAP before the word-bag', () => {
expect(matchHevyTitle('Bulgarian Split Squat (Dumbbell)')).toBe('0410')
expect(matchHevyTitle('Lat Pulldown - Close Grip (Cable)')).toBe('2616')
expect(matchHevyTitle('Reverse Lunge (Dumbbell)')).toBe('0381')
// Word-bag alone still misses these — the title map is what makes CSV work.
expect(matchExercise('Bulgarian Split Squat (Dumbbell)')).toBeNull()
})
it('imports a Hevy CSV onto catalogue ids, not customs', () => {
const parsed = parseWorkoutCSV(HEVY_CSV, { unit: 'kg' })
expect(parsed.source).toBe('Hevy')
expect(parsed.created).toBe(0)
const ids = parsed.workouts[0].entries.map(e => e.id).sort()
expect(ids).toEqual(['0410', '0381', '2616'].sort())
const pull = parsed.workouts[0].entries.find(e => e.id === '2616')
expect(pull.sets[0]).toMatchObject({ w: 25, r: 15, phase: 'warmup' })
expect(pull.sets[1]).toMatchObject({ w: 52, r: 12, rpe: 8 })
})
})
+69 -19
View File
@@ -4,13 +4,14 @@
// mode in a browser, this is the user's only copy of their training log, so it can't depend
// on WebView localStorage alone (iOS evicts that under storage pressure). Every persist()
// therefore also lands in a JSON file in the app's private data directory, and boot()
// restores from it. The workout reminder uses native local notifications scheduled per
// planned weekday — no server involved, unlike Web Push in the self-hosted version.
// restores from it. The workout reminder uses native local notifications scheduled per future
// calendar date — no server involved, unlike Web Push in the self-hosted version.
//
// Like the demo build, MOBILE is replaced at build time, so all of this folds away in
// web bundles; the Capacitor plugins are only ever imported behind it.
import { t } from './i18n-core.js'
import { todayISO } from './format.js'
import { isoOf, todayISO } from './format.js'
import { effectiveRoutineId } from './history.js'
export const MOBILE = import.meta.env.VITE_MOBILE === '1'
@@ -52,34 +53,83 @@ export async function saveRemoteFile(data) {
} catch (e) { /* worst case: onboarding asks again next launch */ }
}
// (Re)schedule the workout-day reminder: one repeating notification per weekday that has a
// routine in the weekly plan. Cheap enough to run after any state change — the plan or the
// reminder time may just have been edited. `interactive` gates the OS permission prompt to
// the Settings toggle; a background resync never pops a dialog.
// Keep enough dates queued to cover normal app use between foregrounds without creating an
// unbounded notification list. The next sync cancels and replaces this whole window.
export const REMINDER_WINDOW_DAYS = 60
const REMINDER_ID_BASE = 1000
const LEGACY_REMINDER_IDS = Array.from({ length: 7 }, (_, d) => ({ id: 100 + d }))
// Pure date expansion for the native reminder. `now` is injectable so the calendar boundary,
// completed-day suppression, and today's past-time rule stay deterministic in tests.
export function buildReminderNotifications(S, now = new Date()) {
const r = S?.reminder
if (!r?.on) return []
const routines = Array.isArray(S.routines) ? S.routines : []
const completed = new Set((S.workouts || []).map(w => w.d))
const state = { ...S, routines, week: S.week || {}, dayPlan: S.dayPlan || {} }
const [hour, minute] = (r.time || '08:00').split(':').map(Number)
if (!Number.isInteger(hour) || !Number.isInteger(minute)) return []
const date = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 12)
const notifications = []
for (let offset = 0; offset < REMINDER_WINDOW_DAYS; offset++) {
const day = new Date(date)
day.setDate(date.getDate() + offset)
const iso = isoOf(day)
if (completed.has(iso)) continue
const rid = effectiveRoutineId(state, iso)
const routine = routines.find(x => x.id === rid)
if (!routine) continue
const at = new Date(day)
at.setHours(hour, minute, 0, 0)
if (at <= now) continue
notifications.push({
id: REMINDER_ID_BASE + offset,
title: t('Workout day'),
body: t('{0} is on the plan today — let’s go!', routine.name),
schedule: { at, allowWhileIdle: true },
})
}
return notifications
}
// (Re)schedule the workout-day reminder: one one-off notification per future calendar date in
// the bounded window. Cheap enough to run after any state change — the plan or the reminder time
// may just have been edited. `interactive` gates the OS permission prompt to the Settings toggle;
// a background resync never pops a dialog.
export async function syncReminder(S, interactive = false) {
try {
const { LocalNotifications } = await import('@capacitor/local-notifications')
await LocalNotifications.cancel({ notifications: [0, 1, 2, 3, 4, 5, 6].map(d => ({ id: 100 + d })) }).catch(() => {})
await LocalNotifications.cancel({ notifications: [
...LEGACY_REMINDER_IDS,
...Array.from({ length: REMINDER_WINDOW_DAYS }, (_, d) => ({ id: REMINDER_ID_BASE + d })),
] }).catch(() => {})
const r = S.reminder
if (!r?.on) return true
let perm = await LocalNotifications.checkPermissions()
if (perm.display !== 'granted' && interactive) perm = await LocalNotifications.requestPermissions()
if (perm.display !== 'granted') return false
const [hour, minute] = (r.time || '08:00').split(':').map(Number)
const notifications = Object.entries(S.week || {})
.filter(([, rid]) => rid && (S.routines || []).some(x => x.id === rid))
.map(([day, rid]) => ({
id: 100 + Number(day),
title: t('Workout day'),
body: t('{0} is on the plan today — let’s go!', S.routines.find(x => x.id === rid).name),
// Capacitor weekdays are 1 (Sunday) … 7 (Saturday); S.week uses getDay() 0…6.
schedule: { on: { weekday: Number(day) + 1, hour, minute }, allowWhileIdle: true },
}))
const notifications = buildReminderNotifications(S)
if (notifications.length) await LocalNotifications.schedule({ notifications })
return true
} catch (e) { return false }
}
// Capacitor emits appStateChange when the native shell returns to the foreground. The visibility
// listener also covers WebView/browser transitions, and both are harmless on a non-mobile build.
let reminderSyncStarted = false
export function initReminderSync(getState) {
if (!MOBILE || reminderSyncStarted) return
reminderSyncStarted = true
const resync = () => {
if (document.visibilityState === 'hidden') return
syncReminder(getState()).catch(() => {})
}
document.addEventListener('visibilitychange', resync)
import('@capacitor/app').then(({ App }) => {
App.addListener('appStateChange', ({ isActive }) => { if (isActive) resync() })
}).catch(() => {})
}
// WKWebView can't do blob-URL downloads, so the backup goes out through the OS share sheet
// (Files, AirDrop, mail, …) from a temp file instead.
export async function shareExport(json, filename) {
@@ -104,4 +154,4 @@ export async function writeAutoBackup(state) {
recursive: true,
})
} catch (e) { /* best effort — the private mirror in Directory.Data still has the data */ }
}
}
+62
View File
@@ -0,0 +1,62 @@
import { describe, expect, it } from 'vitest'
import { isoOf } from './format.js'
import { buildReminderNotifications } from './mobile.js'
const push = { id: 'push', name: 'Push' }
const pull = { id: 'pull', name: 'Pull' }
const legs = { id: 'legs', name: 'Legs' }
const state = (patch = {}) => ({
routines: [push, pull, legs], week: {}, dayPlan: {}, workouts: [],
reminder: { on: true, time: '08:00' }, ...patch,
})
const iso = d => isoOf(d)
describe('buildReminderNotifications', () => {
it('expands the weekly baseline into future dated notifications', () => {
const now = new Date(2026, 5, 1, 7, 0) // Monday
const notifications = buildReminderNotifications(state({ week: { 1: 'push', 3: 'pull' } }), now)
expect(notifications.slice(0, 2).map(n => iso(n.schedule.at))).toEqual([
iso(now), iso(new Date(2026, 5, 3)),
])
expect(notifications[0].body).toContain('Push')
expect(notifications[0].schedule.allowWhileIdle).toBe(true)
})
it('uses rest today and a routine override tomorrow when rescheduling', () => {
const now = new Date(2026, 5, 1, 7, 0) // Monday
const today = iso(now), tomorrow = iso(new Date(2026, 5, 2))
const notifications = buildReminderNotifications(state({
week: { 1: 'push' }, dayPlan: { [today]: 'rest', [tomorrow]: 'pull' },
}), now)
expect(notifications.slice(0, 1).map(n => [iso(n.schedule.at), n.body])).toEqual([
[tomorrow, expect.stringContaining('Pull')],
])
})
it('schedules a valid override on a weekly rest day', () => {
const now = new Date(2026, 5, 1, 7, 0) // Monday
const wednesday = new Date(2026, 5, 3)
const notifications = buildReminderNotifications(state({ dayPlan: { [iso(wednesday)]: 'legs' } }), now)
expect(notifications.some(n => iso(n.schedule.at) === iso(wednesday) && n.body.includes('Legs'))).toBe(true)
})
it('suppresses dates that already have a completed workout', () => {
const now = new Date(2026, 5, 1, 7, 0) // Monday
const notifications = buildReminderNotifications(state({
week: { 1: 'push' }, workouts: [{ d: iso(now) }],
}), now)
expect(notifications.some(n => iso(n.schedule.at) === iso(now))).toBe(false)
})
it("skips today's reminder after the configured local time has passed", () => {
const now = new Date(2026, 5, 1, 9, 0) // Monday
const notifications = buildReminderNotifications(state({ week: { 1: 'push' } }), now)
expect(notifications.some(n => iso(n.schedule.at) === iso(now))).toBe(false)
expect(notifications.some(n => iso(n.schedule.at) === iso(new Date(2026, 5, 8)))).toBe(true)
})
})
+13 -2
View File
@@ -9,6 +9,7 @@
import { isWarmupRow } from './workout-model.js'
import { EXIDX, smOf } from './exercises.js'
import { todayISO, weekKey } from './format.js'
// The muscles a map can shade, in head-to-toe order — also the order of any list
// built from them, so "what am I neglecting" reads top-down like a body.
@@ -160,7 +161,7 @@ export function muscleGroupsOf(entry) {
? [...parts.primary, ...parts.secondary]
: explicit || [ex?.tg, ex?.mg, ...arrayOf(smOf(ex))]
const out = canonicalUnique(source)
if (!out.length && !useParts && explicit == null) {
if (!out.length && !useParts) {
canonicalUnique(Object.keys(BY_BODYPART[ex?.bp] || {})).forEach(slug => out.push(slug))
}
return out
@@ -259,6 +260,15 @@ export const loadOfWorkouts = (workouts, pick) =>
loadOf((workouts || []).flatMap(w =>
(w.entries || []).map(e => ({ id: e.id, ex: e.exercise || e, sets: (e.sets || []).filter(s => s.done && !isWarmupRow(s) && (!pick || pick(s))).length }))))
/** Workouts in one existing Muscle balance range, with time injected for deterministic tests. */
export function muscleBalanceWindow(workouts, win, now = Date.now(), today = todayISO()) {
return (workouts || []).filter(workout => win === 0
? true
: win === 7
? weekKey(workout.d) === weekKey(today)
: (workout.start || new Date(workout.d).getTime()) > now - win * 86400000)
}
/** Load a routine *would* produce, from its planned set counts. */
export const loadOfRoutine = routine =>
loadOf((routine?.ex || []).map(c => ({ id: c.id, ex: c, sets: c.sets || 1 })))
@@ -304,7 +314,8 @@ export function levelsOf(load, thresholds) {
/** Muscles sorted hardest-worked first; untrained ones last, in body order. */
export function rankOf(load) {
const worked = MUSCLES.filter(m => (load[m] || 0) > 0).sort((a, b) => load[b] - load[a])
const worked = MUSCLES.filter(m => (load[m] || 0) > 0)
.sort((a, b) => load[b] - load[a] || MUSCLES.indexOf(a) - MUSCLES.indexOf(b))
const missed = MUSCLES.filter(m => !(load[m] > 0))
return { worked, missed }
}
+39 -1
View File
@@ -1,6 +1,9 @@
import { describe, it, expect } from 'vitest'
import { EXIDX, EXDB, smOf } from './exercises.js'
import { MUSCLE_NAME, exerciseMuscleSnapshot, hasExplicitMuscleMetadata, loadOf, loadOfWorkouts, matchesMuscleGroups, muscleGroupsOf, musclesOf } from './muscles.js'
import {
MUSCLE_NAME, exerciseMuscleSnapshot, hasExplicitMuscleMetadata, levelsOf, loadOf,
loadOfWorkouts, matchesMuscleGroups, muscleBalanceWindow, muscleGroupsOf, musclesOf, rankOf
} from './muscles.js'
describe('multi-muscle exercise metadata', () => {
it('normalizes legacy primary/secondary fields and removes duplicate groups', () => {
@@ -20,6 +23,12 @@ describe('multi-muscle exercise metadata', () => {
expect(matchesMuscleGroups({ bp: 'back', muscleGroups: [] }, ['lower-back'])).toBe(true)
})
it('falls back consistently when explicit groups contain only unknown names', () => {
const ex = { bp: 'back', muscleGroups: ['not-a-drawable-name'] }
expect(muscleGroupsOf(ex)).toEqual(['upper-back', 'lower-back'])
expect(musclesOf(ex)).toEqual({ 'upper-back': 0.75, 'lower-back': 0.25 })
})
it('matches an exercise when any requested muscle group matches', () => {
const ex = { muscleGroups: ['chest', 'triceps'] }
expect(matchesMuscleGroups(ex, ['hamstring', 'triceps'])).toBe(true)
@@ -172,3 +181,32 @@ describe('warm-up boundary', () => {
}
})
})
describe('muscle balance windows and ranking', () => {
const now = new Date('2026-08-27T12:00:00').getTime()
const workouts = [
{ id: 'monday', d: '2026-08-24', start: new Date('2026-08-24T12:00:00').getTime() },
{ id: 'sunday', d: '2026-08-23', start: new Date('2026-08-23T12:00:00').getTime() },
{ id: 'boundary', d: '2026-07-28', start: now - 30 * 86400000 },
{ id: 'inside', d: '2026-07-29', start: now - 29 * 86400000 },
]
it('preserves calendar-week, strict trailing-day, and all-history semantics', () => {
expect(muscleBalanceWindow(workouts, 7, now, '2026-08-27').map(w => w.id)).toEqual(['monday'])
expect(muscleBalanceWindow(workouts, 30, now, '2026-08-27').map(w => w.id)).toEqual(['monday', 'sunday', 'inside'])
expect(muscleBalanceWindow(workouts, 0, now, '2026-08-27')).toEqual(workouts)
})
it('uses relative levels and canonical order to break load ties', () => {
const load = { chest: 2, deltoids: 2, biceps: 1 }
expect(rankOf(load).worked).toEqual(['deltoids', 'chest', 'biceps'])
expect(levelsOf(load)).toMatchObject({ deltoids: 4, chest: 4, biceps: 2, abs: 0 })
})
it('keeps catalogue precedence and deleted-custom snapshot weights', () => {
const known = { id: '0025', muscleGroups: ['quadriceps'], sets: [{ done: true }] }
const deleted = { id: 'deleted', muscleSnapshot: { muscleWeights: { chest: 1 } }, sets: [{ done: true }] }
expect(loadOfWorkouts([{ entries: [known] }])).toEqual({ chest: 1, triceps: 0.4, deltoids: 0.4, biceps: 0.4 })
expect(loadOfWorkouts([{ entries: [deleted] }])).toEqual({ chest: 1 })
})
})
+20 -4
View File
@@ -44,6 +44,10 @@ function cleanEx(e) {
if (e.inc > 0) o.inc = e.inc
if (e.repsMin != null) o.repsMin = e.repsMin
if (e.repsMax != null) o.repsMax = e.repsMax
// The exercise's own rest (issue #10) is part of how it is prescribed, so it travels too —
// only when set, so a plan that never asked for one leaves the recipient's own default
// timer in charge. parsePlan and mergePlan carry it through by spread.
if (e.restSec > 0) o.restSec = e.restSec
if (e.sg) o.sg = e.sg
if (e.note) o.note = e.note
const warm = cleanWarmupSets(e.warmupSets)
@@ -63,6 +67,13 @@ function cleanWarmupSets(v) {
return n > 0 ? Math.min(MAX_PLANNED_WARMUPS, n) : 0
}
/** A positive whole number of seconds or nothing — the same gate cleanEx applies on the way
* out, so a hand-edited plan file can't hand the rest timer a string or a negative. */
function cleanRestSec(v) {
const n = Math.round(Number(v)) || 0
return n > 0 ? n : 0
}
/** Keep the floors the config sheet and applyIntensifierPlan already enforce, and nothing else:
* a plan file is someone else's data, so anything unrecognised is dropped rather than trusted. */
function cleanIntensifier(x) {
@@ -79,7 +90,10 @@ function cleanIntensifier(x) {
/** Build the shareable bundle: every routine, the week schedule, referenced customs. */
export function buildPlanBundle(S, name) {
const routines = (S.routines || []).map(r => ({
id: r.id, name: r.name, emoji: r.emoji, ...(r.prog ? { prog: r.prog } : {}), ex: (r.ex || []).map(cleanEx)
id: r.id, name: r.name, emoji: r.emoji,
...(r.prog ? { prog: r.prog } : {}),
...(r.excludeFromProgression === true ? { excludeFromProgression: true } : {}),
ex: (r.ex || []).map(cleanEx)
}))
const usedIds = new Set(routines.flatMap(r => r.ex.map(e => e.id)))
const customEx = (S.customEx || [])
@@ -114,12 +128,13 @@ export function parsePlan(raw) {
if (!ok) dropped++
return ok
}).map(e => {
// The exercises pass through as written, so the two fields that carry numbers into the
// The exercises pass through as written, so the fields that carry numbers into the
// planner get the same clamps on the way in that they get on the way out.
const warm = cleanWarmupSets(e.warmupSets)
const intens = cleanIntensifier(e.intensifier)
const { warmupSets, intensifier, ...rest } = e
return { ...rest, ...(warm ? { warmupSets: warm } : {}), ...(intens ? { intensifier: intens } : {}) }
const rest = cleanRestSec(e.restSec)
const { warmupSets, intensifier, restSec, ...passthrough } = e
return { ...passthrough, ...(warm ? { warmupSets: warm } : {}), ...(intens ? { intensifier: intens } : {}), ...(rest ? { restSec: rest } : {}) }
})
}))
return {
@@ -160,6 +175,7 @@ export function mergePlan(s, bundle, { schedule } = {}) {
name: r.name || t('Shared routine'),
emoji: r.emoji,
...(r.prog ? { prog: r.prog } : {}),
...(r.excludeFromProgression === true ? { excludeFromProgression: true } : {}),
ex: (r.ex || []).map(e => ({ ...e, id: exIdMap[e.id] || e.id }))
})
})
+42 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest'
import { buildPlanBundle, parsePlan } from './plan-share.js'
import { buildPlanBundle, mergePlan, parsePlan } from './plan-share.js'
// There was no test file for plan sharing at all, which is how a whole prescription field
// went missing without anyone noticing.
@@ -24,6 +24,37 @@ describe('what survives a shared plan', () => {
expect(roundTrip({ warmupSets: 3 }).warmupSets).toBe(3)
})
it('carries progression exclusion on a routine through export and merge', () => {
const source = stateWith({})
source.routines[0].excludeFromProgression = true
const bundle = parsePlan(buildPlanBundle(source, 'Plan'))
const target = { routines: [], week: {}, customEx: [] }
expect(bundle.routines[0].excludeFromProgression).toBe(true)
mergePlan(target, bundle)
expect(target.routines[0].excludeFromProgression).toBe(true)
})
// Issue #10: the rest an exercise prescribes is part of the prescription. A shared 5x5 whose
// rests arrive as the recipient's 60 s default is a different session than the one written.
it('carries a per-exercise rest', () => {
expect(roundTrip({ restSec: 180 }).restSec).toBe(180)
})
// The absence has to survive too: writing a 0 would pin the recipient's timer to "off"
// instead of letting the exercise keep inheriting whatever their own default is.
it('leaves an exercise that set no rest free of the field', () => {
expect('restSec' in roundTrip({})).toBe(false)
expect('restSec' in roundTrip({ restSec: 0 })).toBe(false)
})
it('carries the rest onto the routine mergePlan adds', () => {
const bundle = parsePlan(JSON.stringify(buildPlanBundle(stateWith({ restSec: 180 }), 'Plan')))
const s = { routines: [], customEx: [], week: {} }
mergePlan(s, bundle, { schedule: false })
expect(s.routines[0].ex[0].restSec).toBe(180)
})
it('drops an intensifier it does not recognise rather than passing it on', () => {
expect(roundTrip({ intensifier: { type: 'nonsense', count: 3 } }).intensifier).toBeUndefined()
})
@@ -33,6 +64,16 @@ describe('what survives a shared plan', () => {
expect(parsePlan(bundle).routines[0].ex[0].warmupSets).toBe(5)
})
// A plan file is someone else's data: a rest that arrives as a string would reach the timer's
// arithmetic as one, and a negative or garbage one has no meaning to keep.
it('normalises a hand-edited rest to a positive whole number or drops it', () => {
const withRest = restSec => ({ opengym_plan: 1, name: 'x', routines: [{ id: 'r', name: 'R', ex: [{ id: '0025', sets: 3, reps: 5, restSec }] }], week: {}, customEx: [] })
expect(parsePlan(withRest('120')).routines[0].ex[0].restSec).toBe(120)
expect(parsePlan(withRest(90.6)).routines[0].ex[0].restSec).toBe(91)
expect('restSec' in parsePlan(withRest(-30)).routines[0].ex[0]).toBe(false)
expect('restSec' in parsePlan(withRest('abc')).routines[0].ex[0]).toBe(false)
})
// The floors are the config sheet's own (count >= 1, pct >= 5); a value that is present but
// out of range is pulled up to the floor, while a missing one falls back to the default.
it('clamps out-of-range intensifier numbers to the floors the app enforces', () => {
+13
View File
@@ -0,0 +1,13 @@
import { POLICY_NAME } from './progression.js'
/**
* Presentation-only view of a progression result. The engine remains the source of truth for
* both the outcome and its explanation; this helper only makes the policy behind that result
* explicit in the workout guidance.
*/
export function progressionGuidance(plan) {
if (!plan?.why || plan.kind === 'off' || plan.policy === 'off') return null
const policyLabel = POLICY_NAME[plan.policy]
if (!policyLabel) return null
return { policyLabel, why: plan.why }
}
+30
View File
@@ -0,0 +1,30 @@
import { describe, expect, it } from 'vitest'
import { progressionGuidance } from './progression-copy.js'
describe('policy-labelled progression guidance', () => {
it('keeps the calculated outcome and identifies the policy that produced it', () => {
const why = ['Every rep last time — {0} {1} more.', 2.5, 'kg']
expect(progressionGuidance({ policy: 'linear', kind: 'up', weight: 62.5, why }))
.toEqual({ policyLabel: 'Linear progression', why })
})
it('labels hold and deload outcomes without changing their calculated reasons', () => {
const hold = ['Missed reps last time — same weight again ({0} of {1} to go).', 2, 3]
const deload = ['Missed reps — reset to {0} {1} and work back up.', 55, 'kg']
expect(progressionGuidance({ policy: 'double', kind: 'hold', why: hold }))
.toEqual({ policyLabel: 'Double progression', why: hold })
expect(progressionGuidance({ policy: 'greyskull', kind: 'deload', why: deload }))
.toEqual({ policyLabel: 'Greyskull LP', why: deload })
})
it('labels a baseline outcome and omits policies with no visible outcome', () => {
const baseline = ['Nothing logged yet — this session sets the baseline.']
expect(progressionGuidance({ policy: 'linear', kind: 'first', why: baseline }))
.toEqual({ policyLabel: 'Linear progression', why: baseline })
expect(progressionGuidance({ policy: 'off', kind: 'off' })).toBeNull()
expect(progressionGuidance({ policy: 'linear', kind: 'first' })).toBeNull()
expect(progressionGuidance(null)).toBeNull()
})
})
+8 -2
View File
@@ -19,6 +19,7 @@
import { modeOf, repStep, rerampWarmups } from './history.js'
import { EXIDX } from './exercises.js'
import { isWarmupRow } from './workout-model.js'
import { normalizeRepRange } from './rep-range.js'
export const POLICIES = ['off', 'linear', 'greyskull', 'double', 'time']
@@ -134,6 +135,10 @@ export function readSession(entry, fallback) {
export function sessionsFor(S, exId, fallback) {
const out = []
;(S.workouts || []).forEach(w => {
// A planned deload remains a real workout for history and statistics, but it cannot become
// the baseline for the next regular prescription. The routine flag is copied onto the
// active session, then onto this completed workout, so later routine edits do not rewrite it.
if (w.excludeFromProgression === true) return
const entry = w.entries.find(e => e.id === exId)
if (entry && entry.sets.some(s => s.done && !isWarmupRow(s))) out.push({ d: w.d, ...readSession(entry, fallback) })
})
@@ -210,8 +215,9 @@ export function nextPrescription(S, cfg, routine) {
return { policy, kind: 'up', weight: 0, reps: next, why: ['Bodyweight — every rep last time, so go for {0} this time.', next] }
}
if (policy === 'double') {
const top = cfg.reps || last.goal || 10
const bottom = Math.min(cfg.repsMin || Math.max(1, top - 2), top)
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 (stalls >= deloadAt) {
const dw = deloadTo(w, inc)
+26
View File
@@ -311,6 +311,13 @@ describe('double progression', () => {
expect(p.reps).toBe(8)
expect(p.weight).toBe(35) // 40 × 0.9 = 36 → nearest loadable 2.5 step
})
it('normalizes persisted per-side bounds before prescribing', () => {
const perSide = { ...cfg, reps: 13, repsMin: 7, side: true }
const p = nextPrescription(hist(LIFT, [[40, 12, 12, 12]], { sets: 3, reps: 13 }), perSide)
expect(p.kind).toBe('hold')
expect(p.reps).toBe(14)
})
})
describe('timed progression', () => {
@@ -374,6 +381,25 @@ describe('sessionsFor', () => {
expect(sessionsFor(S, LIFT).map(s => s.d)).toEqual(['2026-01-01'])
})
it('ignores marked deload workouts when it calculates the next regular target', () => {
const target = { sets: 3, reps: 5, weight: 60 }
const entry = (weight, reps) => ({
id: LIFT,
target: { ...target, weight },
sets: reps.map(r => ({ w: weight, r, done: true }))
})
const S = {
unit: 'kg',
workouts: [
{ d: '2026-01-01', entries: [entry(60, [5, 5, 5])] },
{ d: '2026-01-08', excludeFromProgression: true, entries: [entry(30, [8, 8])] }
]
}
expect(sessionsFor(S, LIFT).map(s => s.d)).toEqual(['2026-01-01'])
expect(nextPrescription(S, { id: LIFT, ...target, prog: 'linear' }).weight).toBe(62.5)
})
it('reads a legacy entry that has no target without crashing', () => {
const S = { unit: 'kg', workouts: [{ d: '2026-01-01', entries: [{ id: LIFT, sets: [{ w: 60, r: 5, done: true }] }] }] }
expect(sessionsFor(S, LIFT)).toHaveLength(1)
+3 -3
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(291)
expect(inherited).toHaveLength(449)
expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(338)
expect(inherited).toHaveLength(454)
// 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('09c4fa5e04c8d3ea21916a6c07f074a35013b33d5d945ecfc13cd54cc8b7d41d')
expect(fingerprint, 'pt-PT inheritance changed; review the inherited pt-BR wording').toBe('549332a72036a9fda6e3c3b129ea57ae9863a6e87099135bc3ae638d2bd31a58')
})
test('does not leak European Portuguese UI terms', () => {
+19
View File
@@ -0,0 +1,19 @@
// Normalize the two bounds used by double progression.
// `reps` is the upper bound and `repsMin` is the lower bound in persisted configs.
export function normalizeRepRange(reps, repsMin, stride = 1) {
const step = Number.isInteger(stride) && stride > 0 ? stride : 1
const upper = align(positiveInt(reps, 10), step)
const lower = align(positiveInt(repsMin, Math.max(1, upper - 2)), step)
return lower >= upper
? { reps: lower + step, repsMin: lower }
: { reps: upper, repsMin: lower }
}
function align(value, stride) {
return Math.max(stride, Math.ceil(value / stride) * stride)
}
function positiveInt(value, fallback) {
const n = Number(value)
return Number.isFinite(n) && n > 0 ? Math.max(1, Math.round(n)) : fallback
}
+38
View File
@@ -0,0 +1,38 @@
import { describe, expect, it } from 'vitest'
import { normalizeRepRange } from './rep-range.js'
describe('normalizeRepRange', () => {
it('keeps valid positive integer bounds unchanged', () => {
expect(normalizeRepRange(12, 8)).toEqual({ reps: 12, repsMin: 8 })
})
it('rounds bounds to positive integers', () => {
expect(normalizeRepRange(12.4, 7.6)).toEqual({ reps: 12, repsMin: 8 })
expect(normalizeRepRange(0, -2)).toEqual({ reps: 10, repsMin: 8 })
})
it('raises the upper bound when the lower bound reaches it', () => {
expect(normalizeRepRange(8, 8)).toEqual({ reps: 9, repsMin: 8 })
})
it('raises the upper bound when the lower bound exceeds it', () => {
expect(normalizeRepRange(8, 12)).toEqual({ reps: 13, repsMin: 12 })
})
it('keeps the lower bound at least one below a lowered upper bound', () => {
expect(normalizeRepRange(6, 8)).toEqual({ reps: 9, repsMin: 8 })
})
it('supplies a usable default lower bound for a small upper bound', () => {
expect(normalizeRepRange(1, undefined)).toEqual({ reps: 2, repsMin: 1 })
})
it('aligns both bounds to an even stride', () => {
expect(normalizeRepRange(13, 7, 2)).toEqual({ reps: 14, repsMin: 8 })
})
it('keeps a valid gap when per-side bounds are invalid', () => {
expect(normalizeRepRange(8, 9, 2)).toEqual({ reps: 12, repsMin: 10 })
expect(normalizeRepRange(0, -2, 2)).toEqual({ reps: 10, repsMin: 8 })
})
})
+21
View File
@@ -0,0 +1,21 @@
// How a session's exercise entries are built from a routine. Shared by the live start and by
// "log a past workout", which is the same screen pointed at another day — both must walk up
// 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'
export function buildSessionEntries(st, r) {
// The prescription is applied as the session is built, so you walk up to the bar with the
// right weight already on the screen instead of being told about it afterwards. `plan` is
// kept on the entry purely so the workout can explain the number it chose.
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)
return { id: cfg.id, sg: cfg.sg, target: { ...cfg }, plan, sets }
})
return { entries, excluded }
}
+26
View File
@@ -63,6 +63,32 @@ export function restOnRecheck({ timerRunning, unitDone, lastUnit }) {
return !timerRunning && restAfterSet({ unitDone, lastUnit })
}
/**
* How long the rest after a completed set should run, in seconds.
*
* An exercise may carry its own `restSec` in its target (issue #10) — a heavy triple and a set
* of curls do not want the same break. One that carries none inherits `defaultRestSec`, the
* global rest timer, which is what every routine did before the field existed.
*
* `unit` is the superset group the set belongs to, as entry indices — a plain exercise is a
* group of one. A group rests once, after the round, so it takes the LONGEST rest any of its
* members asked for: the shortest would send you back to the bar before the member that needs
* the most recovery is ready.
*
* `defaultRestSec` of 0 is the rest timer turned off (v1.2.11). That silences the members that
* have no rest of their own, but an exercise that explicitly asks for one still gets it — the
* setting is a default, and this field overrides the default.
*/
export function restSecFor(entries, unit, defaultRestSec) {
const fallback = defaultRestSec > 0 ? defaultRestSec : 0
const idxs = Array.isArray(unit) && unit.length ? unit : []
if (!idxs.length) return fallback
return idxs.reduce((longest, idx) => {
const own = entries?.[idx]?.target?.restSec
return Math.max(longest, own > 0 ? own : fallback)
}, 0)
}
// Decide where a newly completed superset set goes next. Spent members are skipped, including
// across the wrap. A round ends when no later member in display order has work left; this makes
// the last *active* member the boundary rather than blindly using the group's last array index.
+46 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest'
import { insertionIndexAfterCurrentUnit, nextUnfinishedUnit, setProgressHighWater, supersetFlowStep, restAfterSet, restOnRecheck } from './supersetFlow.js'
import { insertionIndexAfterCurrentUnit, nextUnfinishedUnit, setProgressHighWater, supersetFlowStep, restAfterSet, restOnRecheck, restSecFor } from './supersetFlow.js'
const entry = done => ({ sets: done.map(value => ({ done: value })) })
@@ -92,3 +92,48 @@ describe('rest on a re-check', () => {
expect(restOnRecheck({ timerRunning: false, unitDone: true, lastUnit: false })).toBe(true)
})
})
// Issue #10: a routine can give an exercise its own rest, and the global timer stops being the
// only answer. The resolution is the whole feature — the UI just writes the number down.
describe('restSecFor', () => {
// 0: no rest of its own, 1: 180 s, 2: 45 s — a heavy pull, a light accessory, a plain one.
const entries = [
{ id: 'a', target: { mode: 'reps' } },
{ id: 'b', target: { mode: 'reps', restSec: 180 } },
{ id: 'c', target: { mode: 'reps', restSec: 45 } },
]
it('prefers the exercise’s own rest over the global default', () => {
expect(restSecFor(entries, [1], 90)).toBe(180)
expect(restSecFor(entries, [2], 90)).toBe(45)
})
it('falls back to the global default when the exercise sets none', () => {
expect(restSecFor(entries, [0], 90)).toBe(90)
})
it('gives a superset the longest rest its members asked for', () => {
// Not the member that closed the round, and not the shortest: the group rests once, and
// the 180 s exercise is the one still recovering when the 45 s one is ready to go again.
expect(restSecFor(entries, [1, 2], 90)).toBe(180)
// A member with no rest of its own pulls in the global, which can be the longest of all.
expect(restSecFor(entries, [0, 2], 90)).toBe(90)
})
it('honours an explicit rest even with the global timer switched off', () => {
expect(restSecFor(entries, [1], 0)).toBe(180)
expect(restSecFor(entries, [0, 1], 0)).toBe(180)
})
it('stays off when the timer is off and nothing asked for a rest', () => {
expect(restSecFor(entries, [0], 0)).toBe(0)
expect(restSecFor(entries, [0, 0], 0)).toBe(0)
})
it('survives a missing unit or entry rather than timing NaN', () => {
expect(restSecFor(entries, null, 90)).toBe(90)
expect(restSecFor(entries, [], 90)).toBe(90)
expect(restSecFor(entries, [7], 90)).toBe(90)
expect(restSecFor(undefined, [0], undefined)).toBe(0)
})
})
+78
View File
@@ -0,0 +1,78 @@
import { useCallback, useEffect } from 'react'
/* Keyboard-aware sheets. When the mobile keyboard comes up the layout viewport keeps its
size, only the visual viewport shrinks — so a bottom sheet with a text input near its
foot ends up half under the keys. index.css reads two custom properties on the sheet
(--picker-keyboard-bottom / --picker-visual-height) to lift and cap it. SelectSheet in
components/ui.jsx does exactly this sync inline; the exercise picker, the custom-exercise
form and the note sheets need the same thing, hence this hook. The logic is deliberately
duplicated rather than imported so ui.jsx keeps no public surface for it.
`inputRef` points at the text input (or textarea) whose closest `.sheet` gets the vars.
`enabled` lets a caller switch the sync off (e.g. a picker without a search box). */
export function useSheetKeyboard(inputRef, enabled = true) {
const sync = useCallback(() => {
const input = inputRef.current
const sheet = input?.closest?.('.sheet')
const viewport = typeof window !== 'undefined' ? window.visualViewport : null
if (!sheet || !viewport) return
const visualHeight = Math.max(0, viewport.height || window.innerHeight)
const visualBottom = (viewport.offsetTop || 0) + visualHeight
const bottomInset = Math.max(0, window.innerHeight - visualBottom)
sheet.style.setProperty('--picker-keyboard-bottom', `${bottomInset}px`)
sheet.style.setProperty('--picker-visual-height', `${visualHeight}px`)
}, [inputRef])
useEffect(() => {
if (!enabled) return
const viewport = typeof window !== 'undefined' ? window.visualViewport : null
if (!viewport) return
sync()
viewport.addEventListener('resize', sync)
viewport.addEventListener('scroll', sync)
return () => {
viewport.removeEventListener('resize', sync)
viewport.removeEventListener('scroll', sync)
// The sheet element outlives this input when the sheet swaps content, so leave it
// the way we found it rather than pinning a stale keyboard inset on it.
const sheet = inputRef.current?.closest?.('.sheet')
sheet?.style.removeProperty('--picker-keyboard-bottom')
sheet?.style.removeProperty('--picker-visual-height')
}
}, [enabled, sync, inputRef])
// Hand back as onFocus so the first measurement happens as the keyboard opens, before
// the visualViewport events land (on iOS they can arrive a frame late).
return sync
}
/* Chip strips scroll sideways, and a filter set from code ("★ Chosen", a reset) can land the
active chip off-screen. Pull it into view along the strip only — block:'nearest' never moves
the page when the strip is already visible, which is the case for every strip we have. */
export function useRevealActiveChip(stripRef, active) {
useEffect(() => {
const strip = stripRef.current
const chip = strip?.querySelector?.('.chip.on')
if (!chip || typeof chip.scrollIntoView !== 'function') return
chip.scrollIntoView({ inline: 'nearest', block: 'nearest' })
}, [stripRef, active])
}
/* Props that make a clickable <div> behave like a button for keyboard and screen-reader
users. Kept as a div because some rows nest a real <Button> (Library), and a button inside
a button is invalid HTML. Space is swallowed so the page does not scroll under the row. */
export function tappable(onClick) {
if (!onClick) return {}
return {
role: 'button',
tabIndex: 0,
onClick,
onKeyDown: e => {
if (e.target !== e.currentTarget) return // a nested control handles its own keys
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault()
onClick(e)
}
}
}
}
@@ -0,0 +1,40 @@
import { describe, expect, it, vi } from 'vitest'
import { tappable } from './use-sheet-keyboard.js'
const keyEvent = (key, target) => {
const ev = { key, target, currentTarget: target, preventDefault: vi.fn() }
return ev
}
describe('tappable', () => {
it('turns a plain onClick into a keyboard-reachable button', () => {
const onClick = vi.fn()
const p = tappable(onClick)
expect(p.role).toBe('button')
expect(p.tabIndex).toBe(0)
expect(p.onClick).toBe(onClick)
const el = {}
p.onKeyDown(keyEvent('Enter', el))
expect(onClick).toHaveBeenCalledTimes(1)
const space = keyEvent(' ', el)
p.onKeyDown(space)
expect(onClick).toHaveBeenCalledTimes(2)
expect(space.preventDefault).toHaveBeenCalled() // Space must not scroll the page
})
it('ignores other keys and keys from nested controls', () => {
const onClick = vi.fn()
const p = tappable(onClick)
const el = {}
p.onKeyDown(keyEvent('a', el))
p.onKeyDown(keyEvent('Escape', el))
expect(onClick).not.toHaveBeenCalled()
const nested = { key: 'Enter', target: {}, currentTarget: el, preventDefault: vi.fn() }
p.onKeyDown(nested)
expect(onClick).not.toHaveBeenCalled()
})
it('gives an inert row nothing to react to', () => {
expect(tappable(undefined)).toEqual({})
})
})
+56 -1
View File
@@ -36,6 +36,8 @@ export default {
'rescheduled': 'verschoben',
'Prev': 'Zurück',
'Next': 'Weiter',
'Move up': 'Nach oben',
'Move down': 'Nach unten',
// --- days & months ---
'Sunday': 'Sonntag', 'Monday': 'Montag', 'Tuesday': 'Dienstag', 'Wednesday': 'Mittwoch',
'Thursday': 'Donnerstag', 'Friday': 'Freitag', 'Saturday': 'Samstag',
@@ -95,6 +97,12 @@ export default {
'Weight ({0})': 'Gewicht ({0})',
'Add to routine': 'Zur Routine hinzufügen',
'Remove exercise': 'Übung entfernen',
'Swap exercise': 'Übung wechseln',
'Swap exercise?': 'Übung tauschen?',
'Logged sets stay with the original exercise. Choose where the replacement belongs.': 'Aufgezeichnete Sätze bleiben bei der ursprünglichen Übung. Wähle, wo die Ersatzübung hingehört.',
'Keep replacement in this group': 'Ersatzübung in dieser Gruppe behalten',
'Insert after this group': 'Nach dieser Gruppe einfügen',
'Logged sets stay with the original exercise. The replacement will be inserted afterward.': 'Aufgezeichnete Sätze bleiben bei der ursprünglichen Übung. Die Ersatzübung wird danach eingefügt.',
'Remove {0}?': '{0} entfernen?',
'The sets you logged for this exercise in this session will be lost.': 'Die in dieser Einheit für diese Übung protokollierten Sätze gehen verloren.',
'This removes the exercise from your current session.': 'Dadurch wird die Übung aus deiner aktuellen Einheit entfernt.',
@@ -177,6 +185,7 @@ export default {
'Remove drop': 'Dropsatz entfernen',
'Remove burst': 'Burst entfernen',
'Rest (s)': 'Pause (s)',
'Rest after each set of this exercise. Leave at 0 to use your default rest timer.': 'Pause nach jedem Satz dieser Übung. Auf 0 lassen, um den Standard-Pausen-Timer zu nutzen.',
'Drop-set / rest-pause': 'Dropsatz / Rest-Pause',
'Intensifier': 'Intensivierungstechnik',
'None': 'Keine',
@@ -298,6 +307,7 @@ export default {
'Weight unit': 'Gewichtseinheit',
'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)',
@@ -469,6 +479,33 @@ export default {
'That file is empty': 'Diese Datei ist leer',
'That file\'s columns aren\'t recognised — see the docs for supported apps.': 'Die Spalten dieser Datei sind unbekannt — unterstützte Apps stehen in der Doku.',
'Nothing to import from that file': 'Aus dieser Datei gibt es nichts zu importieren',
// --- import from Hevy API ---
'Import from Hevy': 'Aus Hevy importieren',
'Pull your history with a Hevy Pro API key': 'Verlauf mit einem Hevy-Pro-API-Schlüssel holen',
'Pull your history with a Hevy Pro API key. The key is only used for this import and is not saved.': 'Verlauf mit einem Hevy-Pro-API-Schlüssel holen. Der Schlüssel gilt nur für diesen Import und wird nicht gespeichert.',
'Hevy API key': 'Hevy-API-Schlüssel',
'Get your API key': 'API-Schlüssel holen',
'Hevy → Settings → Developer': 'Hevy → Einstellungen → Developer',
'Paste your Hevy API key first': 'Zuerst den Hevy-API-Schlüssel einfügen',
'Fetch from Hevy': 'Von Hevy laden',
'Fetching from Hevy…': 'Wird von Hevy geladen…',
'Fetching exercises… ({0}/{1})': 'Übungen werden geladen… ({0}/{1})',
'Fetching workouts… ({0}/{1})': 'Trainings werden geladen… ({0}/{1})',
'Fetching weigh-ins… ({0}/{1})': 'Wiegungen werden geladen… ({0}/{1})',
'Matching exercises…': 'Übungen werden zugeordnet…',
'Could not reach Hevy — check the key and try again': 'Hevy nicht erreichbar — Schlüssel prüfen und erneut versuchen',
'That Hevy API key was refused': 'Dieser Hevy-API-Schlüssel wurde abgelehnt',
'Nothing to import from Hevy': 'Von Hevy gibt es nichts zu importieren',
'Import workouts': 'Trainings importieren',
'Import routines': 'Routinen importieren',
'Import weigh-ins': 'Wiegungen importieren',
'{0} new · {1} days already here': '{0} neu · {1} Tage schon vorhanden',
'{0} routines · {1} exercises — added as new plans': '{0} Routinen · {1} Übungen — als neue Pläne hinzugefügt',
'{0} routines imported': '{0} Routinen importiert',
'Fetching routines… ({0}/{1})': 'Routinen werden geladen… ({0}/{1})',
'Routines': 'Routinen',
'Hevy stores weights in kg — they will be converted to {0}.': 'Hevy speichert Gewichte in kg — sie werden nach {0} umgerechnet.',
'Back': 'Zurück',
// --- mobile build ---
'Your data': 'Deine Daten',
'All data stays on this phone': 'Alle Daten bleiben auf diesem Handy',
@@ -536,7 +573,11 @@ export default {
'Step ({0})': 'Schritt ({0})',
'Step (seconds)': 'Schritt (Sekunden)',
'Reps from': 'Wdh. ab',
'Reps up to': 'Wdh. bis',
'No automatic progression': 'Keine automatische Progression',
'Exclude from automatic progression': 'Von der automatischen Progression ausschließen',
'Use for planned deloads. Workouts stay in history and statistics.': 'Für geplante Deloads. Workouts bleiben im Verlauf und in den Statistiken.',
'The next regular target continues from the last included workout.': 'Das nächste reguläre Ziel setzt beim letzten einbezogenen Workout fort.',
'Linear progression': 'Lineare Progression',
'Greyskull LP': 'Greyskull LP',
'Double progression': 'Doppelte Progression',
@@ -690,5 +731,19 @@ export default {
'Add session note': 'Notiz zum Training',
'Edit session note': 'Notiz bearbeiten',
'How the session went as a whole.': 'Wie das Training insgesamt lief.',
'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': 'Rest-Pause trainiert immer als ein Aufwärmsatz mit dieser Wiederholungszahl und ein Rest-Pause-Arbeitssatz — „Sätze“ wird nicht verwendet.'
'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': 'Rest-Pause trainiert immer als ein Aufwärmsatz mit dieser Wiederholungszahl und ein Rest-Pause-Arbeitssatz — „Sätze“ wird nicht verwendet.',
'Open progression settings': 'Progressions-Einstellungen öffnen',
'Hevy is rate-limiting requests — wait a minute and try again': 'Hevy drosselt die Anfragen — eine Minute warten und erneut versuchen',
// --- log a past workout ---
'Log a past workout': 'Vergangenes Training eintragen',
'Logged on the usual workout screen, without timers.': 'Wird auf dem normalen Trainingsbildschirm erfasst, nur ohne Timer.',
'Date': 'Datum',
'Start time': 'Startzeit',
'Continue': 'Weiter',
'Pick a day up to today': 'Wähle einen Tag bis heute',
'There is already a workout on that day.': 'An diesem Tag gibt es bereits ein Training.',
'Replace': 'Ersetzen',
'Add as second workout': 'Als zweites Training hinzufügen',
'Finish the current workout first.': 'Beende zuerst das laufende Training.',
'Logging a past workout — no rest timers.': 'Vergangenes Training — keine Pausen-Timer.',
}
+56 -1
View File
@@ -35,6 +35,8 @@ export default {
'rescheduled': 'reprogramado',
'Prev': 'Anterior',
'Next': 'Siguiente',
'Move up': 'Subir',
'Move down': 'Bajar',
'Sunday': 'Domingo', 'Monday': 'Lunes', 'Tuesday': 'Martes', 'Wednesday': 'Miércoles',
'Thursday': 'Jueves', 'Friday': 'Viernes', 'Saturday': 'Sábado',
'Su': 'Do', 'Mo': 'Lu', 'Tu': 'Ma', 'We': 'Mi', 'Th': 'Ju', 'Fr': 'Vi', 'Sa': 'Sá',
@@ -91,6 +93,12 @@ export default {
'Weight ({0})': 'Peso ({0})',
'Add to routine': 'Añadir a la rutina',
'Remove exercise': 'Quitar ejercicio',
'Swap exercise': 'Cambiar ejercicio',
'Swap exercise?': '¿Cambiar ejercicio?',
'Logged sets stay with the original exercise. Choose where the replacement belongs.': 'Las series registradas permanecen con el ejercicio original. Elige dónde colocar el reemplazo.',
'Keep replacement in this group': 'Mantener el reemplazo en este grupo',
'Insert after this group': 'Insertar después de este grupo',
'Logged sets stay with the original exercise. The replacement will be inserted afterward.': 'Las series registradas permanecen con el ejercicio original. El reemplazo se insertará después.',
'Remove {0}?': '¿Quitar {0}?',
'The sets you logged for this exercise in this session will be lost.': 'Se perderán las series que registraste para este ejercicio en esta sesión.',
'This removes the exercise from your current session.': 'Esto quita el ejercicio de tu sesión actual.',
@@ -170,6 +178,7 @@ export default {
'Remove drop': 'Quitar bajada',
'Remove burst': 'Quitar ráfaga',
'Rest (s)': 'Descanso (s)',
'Rest after each set of this exercise. Leave at 0 to use your default rest timer.': 'Descanso tras cada serie de este ejercicio. Déjalo en 0 para usar tu temporizador de descanso por defecto.',
'Drop-set / rest-pause': 'Series descendentes / rest-pause',
'Intensifier': 'Intensificador',
'None': 'Ninguno',
@@ -284,6 +293,7 @@ export default {
'Weight unit': 'Unidad de peso',
'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)',
@@ -451,6 +461,33 @@ export default {
'That file is empty': 'Ese archivo está vacío',
'That file\'s columns aren\'t recognised — see the docs for supported apps.': 'No se reconocen las columnas del archivo — consulta la documentación.',
'Nothing to import from that file': 'No hay nada que importar de ese archivo',
// --- import from Hevy API ---
'Import from Hevy': 'Importar desde Hevy',
'Pull your history with a Hevy Pro API key': 'Trae tu historial con una clave API de Hevy Pro',
'Pull your history with a Hevy Pro API key. The key is only used for this import and is not saved.': 'Trae tu historial con una clave API de Hevy Pro. La clave solo se usa en esta importación y no se guarda.',
'Hevy API key': 'Clave API de Hevy',
'Get your API key': 'Obtener tu clave API',
'Hevy → Settings → Developer': 'Hevy → Ajustes → Developer',
'Paste your Hevy API key first': 'Pega primero tu clave API de Hevy',
'Fetch from Hevy': 'Cargar desde Hevy',
'Fetching from Hevy…': 'Cargando desde Hevy…',
'Fetching exercises… ({0}/{1})': 'Cargando ejercicios… ({0}/{1})',
'Fetching workouts… ({0}/{1})': 'Cargando entrenamientos… ({0}/{1})',
'Fetching weigh-ins… ({0}/{1})': 'Cargando pesajes… ({0}/{1})',
'Matching exercises…': 'Emparejando ejercicios…',
'Could not reach Hevy — check the key and try again': 'No se pudo contactar con Hevy — revisa la clave e inténtalo de nuevo',
'That Hevy API key was refused': 'Esa clave API de Hevy fue rechazada',
'Nothing to import from Hevy': 'No hay nada que importar desde Hevy',
'Import workouts': 'Importar entrenamientos',
'Import routines': 'Importar rutinas',
'{0} routines · {1} exercises — added as new plans': '{0} rutinas · {1} ejercicios — se añaden como planes nuevos',
'{0} routines imported': '{0} rutinas importadas',
'Fetching routines… ({0}/{1})': 'Cargando rutinas… ({0}/{1})',
'Routines': 'Rutinas',
'Import weigh-ins': 'Importar pesajes',
'{0} new · {1} days already here': '{0} nuevos · {1} días ya están',
'Hevy stores weights in kg — they will be converted to {0}.': 'Hevy guarda los pesos en kg — se convertirán a {0}.',
'Back': 'Atrás',
// --- mobile build ---
'Your data': 'Tus datos',
'All data stays on this phone': 'Todos los datos se quedan en este teléfono',
@@ -518,7 +555,11 @@ export default {
'Step ({0})': 'Incremento ({0})',
'Step (seconds)': 'Incremento (segundos)',
'Reps from': 'Reps desde',
'Reps up to': 'Reps hasta',
'No automatic progression': 'Sin progresión automática',
'Exclude from automatic progression': 'Excluir de la progresión automática',
'Use for planned deloads. Workouts stay in history and statistics.': 'Úsalo para descargas planificadas. Los entrenamientos permanecen en el historial y las estadísticas.',
'The next regular target continues from the last included workout.': 'El siguiente objetivo normal continúa desde el último entrenamiento incluido.',
'Linear progression': 'Progresión lineal',
'Greyskull LP': 'Greyskull LP',
'Double progression': 'Progresión doble',
@@ -673,5 +714,19 @@ export default {
'Add session note': 'Añadir nota de la sesión',
'Edit session note': 'Editar nota de la sesión',
'How the session went as a whole.': 'Cómo fue la sesión en conjunto.',
'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': 'Rest-pause siempre entrena como una serie de calentamiento con estas reps y una serie de trabajo rest-pause — «Series» no se usa.'
'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': 'Rest-pause siempre entrena como una serie de calentamiento con estas reps y una serie de trabajo rest-pause — «Series» no se usa.',
'Open progression settings': 'Abrir ajustes de progresión',
'Hevy is rate-limiting requests — wait a minute and try again': 'Hevy está limitando las solicitudes: espera un minuto y vuelve a intentarlo',
// --- log a past workout ---
'Log a past workout': 'Registrar un entrenamiento pasado',
'Logged on the usual workout screen, without timers.': 'Se registra en la pantalla de entrenamiento habitual, sin temporizadores.',
'Date': 'Fecha',
'Start time': 'Hora de inicio',
'Continue': 'Continuar',
'Pick a day up to today': 'Elige un día hasta hoy',
'There is already a workout on that day.': 'Ya hay un entrenamiento ese día.',
'Replace': 'Reemplazar',
'Add as second workout': 'Añadir como segundo entrenamiento',
'Finish the current workout first.': 'Termina primero el entrenamiento actual.',
'Logging a past workout — no rest timers.': 'Registrando un entrenamiento pasado — sin temporizadores de descanso.',
}
+56 -1
View File
@@ -35,6 +35,8 @@ export default {
'rescheduled': 'reprogrammé',
'Prev': 'Préc.',
'Next': 'Suiv.',
'Move up': 'Monter',
'Move down': 'Descendre',
'Sunday': 'Dimanche', 'Monday': 'Lundi', 'Tuesday': 'Mardi', 'Wednesday': 'Mercredi',
'Thursday': 'Jeudi', 'Friday': 'Vendredi', 'Saturday': 'Samedi',
'Su': 'Di', 'Mo': 'Lu', 'Tu': 'Ma', 'We': 'Me', 'Th': 'Je', 'Fr': 'Ve', 'Sa': 'Sa',
@@ -91,6 +93,12 @@ export default {
'Weight ({0})': 'Poids ({0})',
'Add to routine': 'Ajouter à la routine',
'Remove exercise': "Retirer l'exercice",
'Swap exercise': 'Remplacer l’exercice',
'Swap exercise?': 'Remplacer l’exercice ?',
'Logged sets stay with the original exercise. Choose where the replacement belongs.': 'Les séries enregistrées restent avec l’exercice d’origine. Choisis où placer le remplacement.',
'Keep replacement in this group': 'Garder le remplacement dans ce groupe',
'Insert after this group': 'Insérer après ce groupe',
'Logged sets stay with the original exercise. The replacement will be inserted afterward.': 'Les séries enregistrées restent avec l’exercice d’origine. Le remplacement sera inséré après.',
'Remove {0}?': 'Retirer {0} ?',
'The sets you logged for this exercise in this session will be lost.': 'Les séries enregistrées pour cet exercice pendant cette séance seront perdues.',
'This removes the exercise from your current session.': 'Cela retire l’exercice de ta séance actuelle.',
@@ -170,6 +178,7 @@ export default {
'Remove drop': 'Retirer le drop set',
'Remove burst': 'Retirer la rafale',
'Rest (s)': 'Repos (s)',
'Rest after each set of this exercise. Leave at 0 to use your default rest timer.': 'Repos après chaque série de cet exercice. Laisse à 0 pour utiliser ton minuteur de repos par défaut.',
'Drop-set / rest-pause': 'Drop-set / rest-pause',
'Intensifier': 'Intensificateur',
'None': 'Aucun',
@@ -284,6 +293,7 @@ export default {
'Weight unit': 'Unité de poids',
'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)',
@@ -451,6 +461,33 @@ export default {
'That file is empty': 'Ce fichier est vide',
'That file\'s columns aren\'t recognised — see the docs for supported apps.': 'Colonnes non reconnues — voir la documentation pour les apps prises en charge.',
'Nothing to import from that file': 'Rien à importer depuis ce fichier',
// --- import from Hevy API ---
'Import from Hevy': 'Importer depuis Hevy',
'Pull your history with a Hevy Pro API key': 'Récupérer l’historique avec une clé API Hevy Pro',
'Pull your history with a Hevy Pro API key. The key is only used for this import and is not saved.': 'Récupérer l’historique avec une clé API Hevy Pro. La clé ne sert qu’à cet import et n’est pas enregistrée.',
'Hevy API key': 'Clé API Hevy',
'Get your API key': 'Obtenir votre clé API',
'Hevy → Settings → Developer': 'Hevy → Réglages → Developer',
'Paste your Hevy API key first': 'Collez d’abord votre clé API Hevy',
'Fetch from Hevy': 'Charger depuis Hevy',
'Fetching from Hevy…': 'Chargement depuis Hevy…',
'Fetching exercises… ({0}/{1})': 'Chargement des exercices… ({0}/{1})',
'Fetching workouts… ({0}/{1})': 'Chargement des séances… ({0}/{1})',
'Fetching weigh-ins… ({0}/{1})': 'Chargement des pesées… ({0}/{1})',
'Matching exercises…': 'Association des exercices…',
'Could not reach Hevy — check the key and try again': 'Impossible de joindre Hevy — vérifiez la clé et réessayez',
'That Hevy API key was refused': 'Cette clé API Hevy a été refusée',
'Nothing to import from Hevy': 'Rien à importer depuis Hevy',
'Import workouts': 'Importer les séances',
'Import routines': 'Importer les routines',
'{0} routines · {1} exercises — added as new plans': '{0} routines · {1} exercices — ajoutées comme nouveaux plans',
'{0} routines imported': '{0} routines importées',
'Fetching routines… ({0}/{1})': 'Chargement des routines… ({0}/{1})',
'Routines': 'Routines',
'Import weigh-ins': 'Importer les pesées',
'{0} new · {1} days already here': '{0} nouveaux · {1} jours déjà présents',
'Hevy stores weights in kg — they will be converted to {0}.': 'Hevy enregistre les poids en kg — ils seront convertis en {0}.',
'Back': 'Retour',
// --- mobile build ---
'Your data': 'Vos données',
'All data stays on this phone': 'Toutes les données restent sur ce téléphone',
@@ -518,7 +555,11 @@ export default {
'Step ({0})': 'Palier ({0})',
'Step (seconds)': 'Palier (secondes)',
'Reps from': 'Reps à partir de',
'Reps up to': 'Reps jusqu’à',
'No automatic progression': 'Pas de progression automatique',
'Exclude from automatic progression': 'Exclure de la progression automatique',
'Use for planned deloads. Workouts stay in history and statistics.': 'À utiliser pour les semaines de décharge planifiées. Les séances restent dans l’historique et les statistiques.',
'The next regular target continues from the last included workout.': 'Le prochain objectif normal continue à partir de la dernière séance incluse.',
'Linear progression': 'Progression linéaire',
'Greyskull LP': 'Greyskull LP',
'Double progression': 'Double progression',
@@ -673,5 +714,19 @@ export default {
'Add session note': 'Ajouter une note de séance',
'Edit session note': 'Modifier la note de séance',
'How the session went as a whole.': 'Comment la séance s’est passée dans l’ensemble.',
'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': 'Le rest-pause s’entraîne toujours comme une série d’échauffement à ce nombre de reps, puis une série de travail rest-pause — « Séries » n’est pas utilisé.'
'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': 'Le rest-pause s’entraîne toujours comme une série d’échauffement à ce nombre de reps, puis une série de travail rest-pause — « Séries » n’est pas utilisé.',
'Open progression settings': 'Ouvrir les réglages de progression',
'Hevy is rate-limiting requests — wait a minute and try again': 'Hevy limite les requêtes — attendez une minute puis réessayez',
// --- log a past workout ---
'Log a past workout': 'Enregistrer une séance passée',
'Logged on the usual workout screen, without timers.': 'Saisie sur l’écran d’entraînement habituel, sans minuteurs.',
'Date': 'Date',
'Start time': 'Heure de début',
'Continue': 'Continuer',
'Pick a day up to today': 'Choisis un jour jusqu’à aujourd’hui',
'There is already a workout on that day.': 'Il y a déjà une séance ce jour-là.',
'Replace': 'Remplacer',
'Add as second workout': 'Ajouter comme deuxième séance',
'Finish the current workout first.': 'Termine d’abord la séance en cours.',
'Logging a past workout — no rest timers.': 'Séance passée — pas de minuteurs de repos.',
}
+56 -1
View File
@@ -35,6 +35,8 @@ export default {
'rescheduled': 'बदला गया',
'Prev': 'पिछला',
'Next': 'अगला',
'Move up': 'ऊपर ले जाएँ',
'Move down': 'नीचे ले जाएँ',
'Sunday': 'रविवार', 'Monday': 'सोमवार', 'Tuesday': 'मंगलवार', 'Wednesday': 'बुधवार',
'Thursday': 'गुरुवार', 'Friday': 'शुक्रवार', 'Saturday': 'शनिवार',
'Su': 'र', 'Mo': 'सो', 'Tu': 'मं', 'We': 'बु', 'Th': 'गु', 'Fr': 'शु', 'Sa': 'श',
@@ -91,6 +93,12 @@ export default {
'Weight ({0})': 'वज़न ({0})',
'Add to routine': 'रूटीन में जोड़ें',
'Remove exercise': 'व्यायाम हटाएँ',
'Swap exercise': 'व्यायाम बदलें',
'Swap exercise?': 'एक्सरसाइज़ बदलें?',
'Logged sets stay with the original exercise. Choose where the replacement belongs.': 'रिकॉर्ड किए गए सेट मूल एक्सरसाइज़ के साथ रहेंगे। बदलने वाली एक्सरसाइज़ की जगह चुनें।',
'Keep replacement in this group': 'बदलने वाली एक्सरसाइज़ इसी समूह में रखें',
'Insert after this group': 'इस समूह के बाद जोड़ें',
'Logged sets stay with the original exercise. The replacement will be inserted afterward.': 'रिकॉर्ड किए गए सेट मूल एक्सरसाइज़ के साथ रहेंगे। बदलने वाली एक्सरसाइज़ बाद में जोड़ी जाएगी।',
'Remove {0}?': '{0} हटाएँ?',
'The sets you logged for this exercise in this session will be lost.': 'इस सत्र में इस व्यायाम के लिए लॉग किए गए सेट मिट जाएँगे।',
'This removes the exercise from your current session.': 'यह व्यायाम आपके मौजूदा सत्र से हट जाएगा।',
@@ -170,6 +178,7 @@ export default {
'Remove drop': 'ड्रॉप सेट हटाएं',
'Remove burst': 'बर्स्ट हटाएं',
'Rest (s)': 'आराम (सेकंड)',
'Rest after each set of this exercise. Leave at 0 to use your default rest timer.': 'इस एक्सरसाइज़ के हर सेट के बाद आराम। अपना डिफ़ॉल्ट आराम टाइमर इस्तेमाल करने के लिए इसे 0 रहने दें।',
'Drop-set / rest-pause': 'ड्रॉप सेट / रेस्ट-पॉज़',
'Intensifier': 'इंटेंसिफायर',
'None': 'कोई नहीं',
@@ -284,6 +293,7 @@ export default {
'Weight unit': 'वज़न की इकाई',
'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)',
@@ -451,6 +461,33 @@ export default {
'That file is empty': 'वह फ़ाइल खाली है',
'That file\'s columns aren\'t recognised — see the docs for supported apps.': 'फ़ाइल के कॉलम पहचाने नहीं गए — समर्थित ऐप्स के लिए दस्तावेज़ देखें।',
'Nothing to import from that file': 'उस फ़ाइल से आयात करने को कुछ नहीं',
// --- import from Hevy API ---
'Import from Hevy': 'Hevy से आयात करें',
'Pull your history with a Hevy Pro API key': 'Hevy Pro API कुंजी से अपना इतिहास लाएँ',
'Pull your history with a Hevy Pro API key. The key is only used for this import and is not saved.': 'Hevy Pro API कुंजी से अपना इतिहास लाएँ। कुंजी केवल इस आयात के लिए उपयोग होती है और सहेजी नहीं जाती।',
'Hevy API key': 'Hevy API कुंजी',
'Get your API key': 'अपनी API कुंजी लें',
'Hevy → Settings → Developer': 'Hevy → सेटिंग्स → Developer',
'Paste your Hevy API key first': 'पहले अपनी Hevy API कुंजी चिपकाएँ',
'Fetch from Hevy': 'Hevy से लाएँ',
'Fetching from Hevy…': 'Hevy से लाया जा रहा है…',
'Fetching exercises… ({0}/{1})': 'व्यायाम लाए जा रहे हैं… ({0}/{1})',
'Fetching workouts… ({0}/{1})': 'वर्कआउट लाए जा रहे हैं… ({0}/{1})',
'Fetching weigh-ins… ({0}/{1})': 'वज़न लाए जा रहे हैं… ({0}/{1})',
'Matching exercises…': 'व्यायाम मिलाए जा रहे हैं…',
'Could not reach Hevy — check the key and try again': 'Hevy से संपर्क नहीं हो सका — कुंजी जाँचकर फिर कोशिश करें',
'That Hevy API key was refused': 'वह Hevy API कुंजी अस्वीकार कर दी गई',
'Nothing to import from Hevy': 'Hevy से आयात करने के लिए कुछ नहीं',
'Import workouts': 'वर्कआउट आयात करें',
'Import routines': 'रूटीन आयात करें',
'{0} routines · {1} exercises — added as new plans': '{0} रूटीन · {1} व्यायाम — नए प्लान के रूप में जोड़े जाते हैं',
'{0} routines imported': '{0} रूटीन आयात किए गए',
'Fetching routines… ({0}/{1})': 'रूटीन लाए जा रहे हैं… ({0}/{1})',
'Routines': 'रूटीन',
'Import weigh-ins': 'वज़न आयात करें',
'{0} new · {1} days already here': '{0} नए · {1} दिन पहले से मौजूद',
'Hevy stores weights in kg — they will be converted to {0}.': 'Hevy वज़न kg में रखता है — उन्हें {0} में बदला जाएगा।',
'Back': 'वापस',
// --- mobile build ---
'Your data': 'आपका डेटा',
'All data stays on this phone': 'सारा डेटा इसी फ़ोन पर रहता है',
@@ -518,7 +555,11 @@ export default {
'Step ({0})': 'स्टेप ({0})',
'Step (seconds)': 'स्टेप (सेकंड)',
'Reps from': 'रेप्स से',
'Reps up to': 'रेप्स तक',
'No automatic progression': 'कोई स्वचालित प्रोग्रेशन नहीं',
'Exclude from automatic progression': 'स्वचालित प्रोग्रेशन से बाहर रखें',
'Use for planned deloads. Workouts stay in history and statistics.': 'योजनाबद्ध डीलोड के लिए उपयोग करें। वर्कआउट इतिहास और आँकड़ों में रहते हैं।',
'The next regular target continues from the last included workout.': 'अगला सामान्य लक्ष्य अंतिम शामिल वर्कआउट से जारी रहता है।',
'Linear progression': 'रैखिक प्रोग्रेशन',
'Greyskull LP': 'Greyskull LP',
'Double progression': 'डबल प्रोग्रेशन',
@@ -673,5 +714,19 @@ export default {
'Add session note': 'सत्र का नोट जोड़ें',
'Edit session note': 'सत्र का नोट बदलें',
'How the session went as a whole.': 'पूरा सत्र कैसा रहा।',
'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': 'रेस्ट-पॉज़ हमेशा इसी रेप्स संख्या के एक वार्म-अप सेट और एक रेस्ट-पॉज़ वर्क सेट के रूप में किया जाता है — “सेट” का उपयोग नहीं होता।'
'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': 'रेस्ट-पॉज़ हमेशा इसी रेप्स संख्या के एक वार्म-अप सेट और एक रेस्ट-पॉज़ वर्क सेट के रूप में किया जाता है — “सेट” का उपयोग नहीं होता।',
'Open progression settings': 'प्रगति सेटिंग्स खोलें',
'Hevy is rate-limiting requests — wait a minute and try again': 'Hevy अनुरोधों को सीमित कर रहा है — एक मिनट रुकें और फिर से कोशिश करें',
// --- log a past workout ---
'Log a past workout': 'पिछला वर्कआउट दर्ज करें',
'Logged on the usual workout screen, without timers.': 'सामान्य वर्कआउट स्क्रीन पर दर्ज होता है, बस टाइमर के बिना।',
'Date': 'तारीख',
'Start time': 'शुरू होने का समय',
'Continue': 'जारी रखें',
'Pick a day up to today': 'आज तक का कोई दिन चुनें',
'There is already a workout on that day.': 'उस दिन पहले से एक वर्कआउट है।',
'Replace': 'बदलें',
'Add as second workout': 'दूसरे वर्कआउट के रूप में जोड़ें',
'Finish the current workout first.': 'पहले मौजूदा वर्कआउट पूरा करें।',
'Logging a past workout — no rest timers.': 'पिछला वर्कआउट दर्ज हो रहा है — कोई रेस्ट टाइमर नहीं।',
}
+737
View File
@@ -0,0 +1,737 @@
// Hungarian UI strings. Keys are the English source strings (see lib/i18n.js).
export default {
// --- generic ---
'Confirm': 'Megerősítés',
'Cancel': 'Mégse',
'Press back again to exit': 'Nyomd meg újra a vissza gombot a kilépéshez',
'Delete': 'Törlés',
'Save': 'Mentés',
'Import': 'Importálás',
'Discard': 'Elvetés',
'All': 'Összes',
'Rest': 'Pihenő',
'On': 'Be',
'Off': 'Ki',
'On 🔔': 'Be 🔔',
'Off 🔕': 'Ki 🔕',
'Skip': 'Kihagyás',
'New': 'Új',
'Log': 'Naplózás',
'Goal': 'Cél',
'Plan': 'Terv',
'Today': 'Ma',
'Home': 'Kezdőlap',
'Start': 'Indítás',
'Resume': 'Folytatás',
'Stats': 'Statisztika',
'Exercises': 'Gyakorlatok',
'History': 'Előzmények',
'Settings': 'Beállítások',
'Freestyle': 'Szabad edzés',
'Routine': 'Rutin',
'routine': 'rutin',
'Cardio': 'Kardió',
'Superset': 'Szuperszett',
'last': 'utoljára',
'rescheduled': 'áthelyezve',
'Prev': 'Előző',
'Next': 'Következő',
// --- days & months ---
'Sunday': 'Vasárnap', 'Monday': 'Hétfő', 'Tuesday': 'Kedd', 'Wednesday': 'Szerda',
'Thursday': 'Csütörtök', 'Friday': 'Péntek', 'Saturday': 'Szombat',
'Su': 'V', 'Mo': 'H', 'Tu': 'K', 'We': 'Sze', 'Th': 'Cs', 'Fr': 'P', 'Sa': 'Szo',
'Mon': 'Hét', 'Wed': 'Sze', 'Fri': 'Pén',
'Jan': 'Jan', 'Feb': 'Feb', 'Mar': 'Már', 'Apr': 'Ápr', 'May': 'Máj', 'Jun': 'Jún',
'Jul': 'Júl', 'Aug': 'Aug', 'Sep': 'Szept', 'Oct': 'Okt', 'Nov': 'Nov', 'Dec': 'Dec',
'January': 'Január', 'February': 'Február', 'March': 'Március', 'April': 'Április',
'June': 'Június', 'July': 'Július', 'August': 'Augusztus', 'September': 'Szeptember',
'October': 'Október', 'November': 'November', 'December': 'December',
// --- body weight & goal ---
'Quick check-in': 'Gyors bejelentkezés',
'Log body weight': 'Testsúly rögzítése',
'Slide or tap to set your weight — tracked before every workout so your curve stays honest.': 'Csúsztasd vagy koppints a súlyod beállításához — minden edzés előtt rögzítjük, hogy a görbéd valós maradjon.',
'Save & start workout': 'Mentés és edzés indítása',
'Start without weighing in': 'Indítás mérés nélkül',
'Choose a different workout': 'Másik edzés választása',
'Recent weigh-ins': 'Legutóbbi mérések',
'Enter a valid weight': 'Adj meg érvényes súlyt',
'Weight saved': 'Súly elmentve',
'Target weight': 'Célsúly',
'Your goal is drawn as a line through the weight charts, and gains/losses are colored by whether they move toward it.': 'A célod egy vonalként jelenik meg a súlygrafikonokon, a gyarapodás/fogyás pedig aszerint van színezve, hogy afelé mozog-e.',
'Save goal': 'Cél mentése',
'Goal set: {0}': 'Cél beállítva: {0}',
'{0} to go': 'még {0} van hátra',
'Goal removed': 'Cél eltávolítva',
'Remove goal': 'Cél eltávolítása',
'Body weight': 'Testsúly',
'reached!': 'elérve!',
'{0} to gain': 'még {0} felszedendő',
'{0} to lose': 'még {0} leadandó',
'No entries yet — log your weight to start the curve. It\'s also asked before every workout.': 'Még nincs bejegyzés — rögzítsd a súlyodat a görbe elindításához. Ezt minden edzés előtt is megkérdezzük.',
// --- exercise detail / picker / config ---
'Best:': 'Legjobb:',
'Add to my plan': 'Hozzáadás a tervemhez',
'How to': 'Végrehajtás',
'instructions in English': 'az utasítások angolul',
'New routine': 'Új rutin',
'Add “{0}”': '„{0}” hozzáadása',
'“{0}” added to {1}': '„{0}” hozzáadva ehhez: {1}',
'Pick a routine — sets, reps & weight come next.': 'Válassz egy rutint — a sorozatok, ismétlések és súly következnek.',
'{0} exercises': '{0} gyakorlat',
'{0} exercise': '{0} gyakorlat',
'already in': 'már benne van',
'Create one and start with this exercise': 'Hozz létre egyet, és kezdd ezzel a gyakorlattal',
'Add exercise': 'Gyakorlat hozzáadása',
'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.',
'No match': 'Nincs találat',
'Show more': 'Több megjelenítése',
'Intervals': 'Intervallumok',
'Minutes': 'Perc',
'Speed (km/h)': 'Sebesség (km/h)',
'Sets': 'Sorozatok',
'Reps': 'Ism.',
'Weight ({0})': 'Súly ({0})',
'Add to routine': 'Hozzáadás a rutinhoz',
'Remove exercise': 'Gyakorlat eltávolítása',
'Remove {0}?': '{0} eltávolítása?',
'The sets you logged for this exercise in this session will be lost.': 'Az ebben az edzésben ehhez a gyakorlathoz rögzített sorozatok elvesznek.',
'This removes the exercise from your current session.': 'Ez eltávolítja a gyakorlatot a jelenlegi edzésedből.',
'Remove': 'Eltávolítás',
'Which exercise in this superset do you want to remove?': 'Melyik gyakorlatot szeretnéd eltávolítani ebből a szuperszettből?',
'Pick an icon': 'Válassz ikont',
// --- day planning / calendar ---
'Back to weekly plan': 'Vissza a heti tervhez',
'{0} set to rest': '{0} pihenőnapra állítva',
'{0} planned for {1}': '{0} tervezve erre: {1}',
'Weekly plan:': 'Heti terv:',
'changed for this day': 'módosítva erre a napra',
'Sick, missed a day or want a different session? Pick what to train instead.': 'Beteg vagy, kihagytál egy napot, vagy másra van kedved? Válaszd ki, mit edzel helyette.',
'Rest / skip this day': 'Pihenő / nap kihagyása',
'Rest day': 'Pihenőnap',
'{0} workout': '{0} edzés',
'{0} workouts': '{0} edzés',
'No workouts this month': 'Nincs edzés ebben a hónapban',
'Trained': 'Edzett',
'Planned': 'Tervezett',
'Rescheduled': 'Áthelyezve',
'Tap a trained day for details · tap any other day to plan a session': 'Koppints egy edzett napra a részletekért · koppints bármely másik napra egy edzés tervezéséhez',
// --- workout lifecycle ---
'{0} sets': '{0} sorozat',
'no sets': 'nincs sorozat',
'Delete workout?': 'Törlöd az edzést?',
'This removes it from your history for good.': 'Ez véglegesen eltávolítja az előzményeidből.',
'Workout deleted': 'Edzés törölve',
'Delete workout': 'Edzés törlése',
'{0} done': '{0} kész',
'Confirm the weight you worked with — your highest becomes the default next time.': 'Erősítsd meg a súlyt, amivel dolgoztál — a legmagasabb lesz az alapértelmezett legközelebb.',
'Then finish the superset partner.': 'Aztán fejezd be a szuperszett párját.',
'Previous best:': 'Korábbi legjobb:',
'new record!': 'új rekord!',
'Save & next exercise': 'Mentés és következő gyakorlat',
'Just close': 'Csak bezárás',
'Save weight': 'Súly mentése',
'Tracked — next time starts at {0}': 'Rögzítve — legközelebb {0}-ról indul',
'That\'s the whole workout!': 'Ez volt az egész edzés!',
'Every exercise done — great work. Finish up, or keep going and add another exercise.': 'Minden gyakorlat kész — remek munka! Fejezd be, vagy folytasd, és adj hozzá egy újabb gyakorlatot.',
'Finish workout': 'Edzés befejezése',
'Continue workout': 'Edzés folytatása',
'Keep going — tap “+ Add exercise” below': 'Folytasd — koppints lent a „+ Gyakorlat hozzáadása” gombra',
'Workout complete!': 'Edzés kész!',
'Duration': 'Időtartam',
'Volume': 'Volumen',
'PRs': 'Rekordok',
'New PR:': 'Új rekord:',
'Nice!': 'Szuper!',
'Nothing logged yet': 'Még nincs rögzítve semmi',
'You haven’t checked off any sets. Finish the workout anyway?': 'Még egyetlen sorozatot sem pipáltál ki. Mindenképp befejezed az edzést?',
'Finish anyway': 'Befejezés mindenképp',
'Finish early?': 'Korábban befejezed?',
'{0} set still unchecked. Finish the workout now?': '{0} sorozat még nincs kipipálva. Befejezed most az edzést?',
'{0} sets still unchecked. Finish the workout now?': '{0} sorozat még nincs kipipálva. Befejezed most az edzést?',
// --- workout view ---
'Start workout': 'Edzés indítása',
'today is {0}': 'ma {0} van',
'rest day, but no one’s stopping you': 'pihenőnap — de senki sem állít meg',
'Today\'s plan': 'Mai terv',
'Start {0} ▶': '{0} indítása ▶',
'Other routines': 'Más rutinok',
'Start ▶': 'Indítás ▶',
'Freestyle workout (pick as you go)': 'Szabad edzés (útközben válassz)',
'Build a plan first': 'Előbb hozz létre egy tervet',
'Duration (min)': 'Időtartam (perc)',
'Last time': 'Legutóbb',
'Last time you hit all reps — try {0}': 'Legutóbb minden ismétlést teljesítettél — próbáld ki: {0}',
'Weights bumped to {0}': 'Súly megemelve erre: {0}',
'Remove set': 'Sorozat eltávolítása',
'Warm-up': 'Bemelegítés',
'Add warm-up set': 'Bemelegítő sorozat hozzáadása',
'Add set': 'Sorozat hozzáadása',
'Every set becomes rest-pause: {0} reps to start, then {1} more split into short bursts, {2}s rest before each, roughly halving each time.': 'Minden sorozat rest-pause-zá válik: kezdésként {0} ismétlés, majd további {1} rövid burstökre bontva, mindegyik előtt {2} mp pihenővel, nagyjából minden alkalommal megfeleződve.',
'Every set becomes a drop-set: after the main set, {0} drop(s) with no rest, each about {1}% lighter.': 'Minden sorozat dropszetté válik: a fő sorozat után {0} további lépés pihenő nélkül, mindegyik kb. {1}%-kal könnyebb.',
'Rest-pause rest': 'Rest-pause pihenő',
'Rest-pause reps': 'Rest-pause ismétlés',
'Weight drop (%)': 'Súlycsökkentés (%)',
'Drops': 'Dropszettek',
'Rest-pause': 'Rest-pause',
'Drop-set': 'Dropszett',
'None': 'Nincs',
'Intensifier': 'Intenzitásnövelő',
'Drop-set / rest-pause': 'Dropszett / rest-pause',
'Rest (s)': 'Pihenő (másodperc)',
'Remove burst': 'Burst eltávolítása',
'Remove drop': 'Dropszett eltávolítása',
'Burst {0}': 'Burst {0}',
'Drop {0}': 'Dropszett {0}',
'+ Burst': '+ Burst',
'+ Drop': '+ Dropszett',
'Cardio logged': 'Kardió rögzítve',
'Discard workout?': 'Elveted az edzést?',
'The sets you logged in this session will be lost.': 'Az ebben az edzésben rögzített sorozatok elvesznek.',
'Superset {0} / {1}': 'Szuperszett {0} / {1}',
'Exercise {0} / {1}': 'Gyakorlat {0} / {1}',
'Superset · do these back-to-back, rest when done': 'Szuperszett · végezd egymás után, pihenj csak utána',
'Freestyle workout — add your first exercise.': 'Szabad edzés — add hozzá az első gyakorlatot.',
'Finish workout early · {0} exercises': 'Edzés korai befejezése · {0} gyakorlat',
'Rest over — next set!': 'Pihenő vége — jöhet a következő sorozat!',
// --- home ---
'Hi {0}': 'Szia {0}',
'This week': 'Ezen a héten',
'{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)',
'Build my own plan': 'Saját terv készítése',
'{0} week streak': '{0} hetes sorozat',
'this week': 'ezen a héten',
'{0} workout total': 'összesen {0} edzés',
'{0} workouts total': 'összesen {0} edzés',
// --- stats ---
'Progress & history': 'Fejlődés & előzmények',
'Workouts': 'Edzések',
'This month': 'Ez a hónap',
'Week streak': 'Heti sorozat',
'Weight 30d': 'Súly 30 nap',
'Activity — last 12 months': 'Aktivitás — elmúlt 12 hónap',
'by time trained': 'edzésidő szerint',
'Exercise progress': 'Gyakorlat fejlődése',
'Top speed per workout': 'Csúcssebesség edzésenként',
'Best set weight per workout': 'Legjobb sorozatsúly edzésenként',
'Finish your first workout to see progress curves here.': 'Fejezd be az első edzésed, hogy itt lásd a fejlődési görbéket.',
'Recent workouts': 'Legutóbbi edzések',
'Less time': 'Kevesebb',
'More time': 'Több',
'No data yet': 'Még nincs adat',
// --- plan view ---
'Your weekly routine': 'A heti rutinod',
'Week schedule': 'Heti beosztás',
'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',
'No exercises yet — add your first one.': 'Még nincs gyakorlat — add hozzá az elsőt.',
'Tap the link button on an exercise to superset it with the one above — you’ll do them back-to-back.': 'Koppints egy gyakorlatnál az összekapcsolás gombra, hogy szuperszettbe kösd a fölötte lévővel — így egymás után csinálod majd őket.',
'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',
// --- 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',
'Profile created — data moved into it': 'Profil létrehozva — az adatok átkerültek bele',
'Welcome, {0}': 'Üdvözlünk, {0}',
'Welcome back, {0}': 'Üdvözlünk újra, {0}',
'Registration failed': 'A regisztráció sikertelen',
'Sign-in failed': 'A bejelentkezés sikertelen',
'Create your profile': 'Hozd létre a profilod',
'Pick a name, then confirm with {0}. The passkey is saved in your device — no password needed.': 'Válassz egy nevet, majd erősítsd meg ezzel: {0}. A jelszókulcs az eszközödön tárolódik — jelszóra nincs szükség.',
'Pick a name, then confirm with your device.': 'Válassz egy nevet, majd erősítsd meg az eszközöddel.',
'Your name': 'A neved',
'Create passkey': 'Jelszókulcs létrehozása',
'Your workouts. Your weights. Your profile.': 'A te edzéseid. A te súlyaid. A te profilod.',
'Sign in with passkey': 'Bejelentkezés jelszókulccsal',
'Create new profile': 'Új profil létrehozása',
'This browser doesn\'t support passkeys — you can still use openGym locally on this device.': 'Ez a böngésző nem támogatja a jelszókulcsokat — az openGym-et így is használhatod helyben, ezen az eszközön.',
'This browser doesn\'t support passkeys, and this instance requires an account. Try a browser or device with passkey support.': 'Ez a böngésző nem támogatja a jelszókulcsokat, ez a szerver pedig fiókot igényel. Próbálj egy jelszókulcsot támogató böngészőt vagy eszközt.',
'Continue without account': 'Folytatás fiók nélkül',
'Passkeys use {0} — no passwords.': 'A jelszókulcs ezt használja: {0} — jelszó nélkül.',
'Each profile keeps its own plan, workouts & body weight.': 'Minden profil megőrzi a saját tervét, edzéseit és testsúlyát.',
// --- settings ---
'Account': 'Fiók',
'Signed in with passkey — data syncs to this profile.': 'Bejelentkezve jelszókulccsal — az adatok szinkronizálódnak ezzel a profillal.',
'Sign out?': 'Kijelentkezel?',
'Your data is synced to your profile first, then cleared from this device.': 'Az adataid előbb szinkronizálódnak a profiloddal, majd törlődnek erről az eszközről.',
'Sign out': 'Kijelentkezés',
'Sign out everywhere?': 'Kijelentkezel mindenhonnan?',
'Signs this profile out on every device, including this one. Your passkeys keep working — sign in with them again anytime.': 'Kijelentkezteti ezt a profilt minden eszközön, ezen az eszközön is. A jelszókulcsaid továbbra is működnek — bármikor újra bejelentkezhetsz velük.',
'Sign out everywhere': 'Kijelentkezés mindenhonnan',
'Ends this profile’s sessions on all your devices.': 'Lezárja ennek a profilnak a munkameneteit minden eszközödön.',
'Signed out on all devices': 'Kijelentkezve minden eszközön',
'Could not sign out everywhere — you are still signed in.': 'Nem sikerült mindenhonnan kijelentkezni — továbbra is be vagy jelentkezve.',
'Guest mode — data lives only in this browser. Create a passkey profile to keep it safe and separate per person.': 'Vendég mód — az adatok csak ebben a böngészőben léteznek. Hozz létre egy jelszókulcs-profilt, hogy biztonságban és személyenként elkülönítve legyenek.',
'Create passkey profile': 'Jelszókulcs-profil létrehozása',
'Passkeys not supported in this browser.': 'A jelszókulcsok nem támogatottak ebben a böngészőben.',
'Appearance': 'Megjelenés',
'synced with your profile': 'szinkronizálva a profiloddal',
'Language': 'Nyelv',
'Exercise instructions aren\'t available in this language yet — they stay in English.': 'A gyakorlatleírások ezen a nyelven még nem érhetők el — angolul maradnak.',
'Theme': 'Téma',
'Dark': 'Sötét',
'Light': 'Világos',
'System': 'Rendszer',
'Accent color': 'Kiemelő szín',
'General': 'Általános',
'During a workout': 'Edzés közben',
'Keep screen awake': 'Képernyő ébren tartása',
'The screen stays on while a workout is running, so you don’t have to unlock your phone between sets.': 'A képernyő edzés közben bekapcsolva marad, így sorozatok között nem kell feloldanod a telefonod.',
'Weight unit': 'Súlymértékegység',
'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',
'Saves a dated copy to the Documents folder after finishing a workout or editing a routine — point a sync app at it, or copy it out by hand.': 'Dátumozott másolatot ment a Dokumentumok mappába egy edzés befejezése vagy egy rutin szerkesztése után — irányíts rá egy szinkronizáló appot, vagy másold ki kézzel.',
'Auto-backup on changes': 'Automatikus mentés módosításkor',
'Reset everything?': 'Mindent visszaállítasz?',
'Reset everything': 'Minden visszaállítása',
'Deletes your plan, workouts and body weight on this device. This cannot be undone.': 'Törli a terved, edzéseid és testsúlyod ezen az eszközön. Ez nem vonható vissza.',
'Delete everything': 'Minden törlése',
'All data reset': 'Minden adat visszaállítva',
'Backup exported': 'Biztonsági mentés exportálva',
'Import backup?': 'Importálod a biztonsági mentést?',
'This replaces all current data with the backup file.': 'Ez lecseréli az összes jelenlegi adatot a mentésfájlra.',
'Backup imported': 'Biztonsági mentés importálva',
'Import failed: {0}': 'Az importálás sikertelen: {0}',
'Tip': 'Tipp',
'In Chrome: ⋮ menu → Add to Home screen': 'Chrome-ban: ⋮ menü → Hozzáadás a kezdőképernyőhöz',
'In Safari: Share → Add to Home Screen': 'Safariban: Megosztás → Hozzáadás a kezdőképernyőhöz',
'to install openGym as a full-screen app.': 'hogy az openGym-et teljes képernyős appként telepítsd.',
'Your data syncs with your profile — sign in anywhere to see it.': 'Az adataid szinkronizálódnak a profiloddal — jelentkezz be bárhol, hogy lásd őket.',
'Guest data stays on this device — export a backup now and then!': 'A vendégadatok ezen az eszközön maradnak — időnként exportálj egy biztonsági mentést!',
'free & open source (AGPL v3)': 'ingyenes & nyílt forráskódú (AGPL v3)',
'Notifications': 'Értesítések',
'Not supported in this browser.': 'Nem támogatott ebben a böngészőben.',
'Push notifications': 'Push-értesítések',
'Rest-timer alerts, even if openGym is closed.': 'Pihenő időzítő riasztások, még ha az openGym be is van zárva.',
'Workout day reminder': 'Edzésnap-emlékeztető',
'Reminder time': 'Emlékeztető ideje',
'Only sent on days you have a routine planned and haven\'t logged a workout yet.': 'Csak azokon a napokon küldjük, amikor van tervezett rutinod, és még nem rögzítettél edzést.',
'Timezone: {0} (auto-detected, updates if you travel).': 'Időzóna: {0} (automatikusan felismerve, utazáskor frissül).',
'Send test notification': 'Teszt értesítés küldése',
'Test sent — should arrive any second': 'Teszt elküldve — bármelyik pillanatban megérkezhet',
'Test failed': 'A teszt sikertelen',
'Notifications off': 'Értesítések kikapcsolva',
'Notifications on': 'Értesítések bekapcsolva',
'Could not change notification settings': 'Az értesítési beállítások módosítása sikertelen',
// --- media ---
'tap to pause': 'koppints a szüneteltetéshez',
'tap to play': 'koppints a lejátszáshoz',
// --- data terms: body parts ---
'back': 'hát', 'cardio': 'kardió', 'chest': 'mell', 'lower arms': 'alkar',
'lower legs': 'lábszár', 'neck': 'nyak', 'shoulders': 'váll',
'upper arms': 'felkar', 'upper legs': 'comb', 'waist': 'derék',
// --- data terms: equipment ---
'Details': 'Részletek',
'Finish': 'Befejezés',
'Start {0}': '{0} indítása',
'Guest mode — data lives only in this browser.': 'Vendég mód — az adatok csak ebben a böngészőben léteznek.',
'Keeps your data safe and separate per person.': 'Biztonságban és személyenként elkülönítve tartja az adataidat.',
'Strength': 'Erő',
'Equipment': 'Eszköz',
'Recovery': 'Regeneráció',
'Any equipment': 'Bármilyen eszköz',
'assisted': 'segített', 'band': 'gumiszalag', 'barbell': 'rúd', 'body weight': 'testsúly',
'bosu ball': 'bosu labda', 'cable': 'kábel', 'dumbbell': 'súlyzó',
'elliptical machine': 'elliptikus tréner', 'ez barbell': 'EZ-rúd', 'hammer': 'kalapácsfogás',
'kettlebell': 'kettlebell', 'leverage machine': 'emelőkaros gép', 'medicine ball': 'medicinlabda',
'olympic barbell': 'olimpiai rúd', 'resistance band': 'ellenállószalag', 'roller': 'henger',
'rope': 'kötél', 'skierg machine': 'SkiErg', 'sled machine': 'szán',
'smith machine': 'Smith-gép', 'stability ball': 'fitneszlabda', 'stationary bike': 'szobabicikli',
'stepmill machine': 'lépcsőzőgép', 'tire': 'gumiabroncs', 'trap bar': 'trap rúd',
'upper body ergometer': 'felsőtest ergométer', 'weighted': 'súlyozott', 'wheel roller': 'hasgörgő',
// --- data terms: targets & muscles ---
'abductors': 'abduktorok', 'abs': 'has', 'adductors': 'adduktorok', 'biceps': 'bicepsz',
'calves': 'vádli', 'cardiovascular system': 'szív-érrendszer', 'delts': 'váll',
'forearms': 'alkar', 'glutes': 'farizom', 'hamstrings': 'combhajlító', 'lats': 'széles hátizom',
'levator scapulae': 'lapockaemelő', 'pectorals': 'mellizom', 'quads': 'combfeszítő',
'serratus anterior': 'fűrészizom', 'spine': 'gerinc', 'traps': 'csuklyás izom',
'triceps': 'tricepsz', 'upper back': 'felső hát',
'abdominals': 'hasizom', 'ankle stabilizers': 'bokastabilizátorok', 'ankles': 'boka',
'brachialis': 'karizom', 'core': 'törzs', 'deltoids': 'deltaizom', 'feet': 'láb',
'grip muscles': 'markolóerő', 'groin': 'lágyék', 'hands': 'kéz', 'hip flexors': 'csípőhajlító',
'inner thighs': 'combközelítő', 'latissimus dorsi': 'széles hátizom', 'lower abs': 'alsó has',
'lower back': 'deréktáj', 'obliques': 'ferde hasizom', 'quadriceps': 'combfeszítő',
'rear deltoids': 'hátsó váll', 'rhomboids': 'rombuszizom', 'rotator cuff': 'forgatómandzsetta',
'shins': 'sípcsont', 'soleus': 'lábikraizom', 'sternocleidomastoid': 'fejbiccentő izom',
'trapezius': 'csuklyás izom', 'upper chest': 'felső mell', 'wrist extensors': 'csuklófeszítő',
'wrist flexors': 'csuklóhajlító', 'wrists': 'csukló',
// --- custom exercises (#11) ---
'Create your own exercise': 'Saját gyakorlat létrehozása',
'Edit custom exercise': 'Egyéni gyakorlat szerkesztése',
'Name it and pick a body part — it behaves like any other exercise, just without an animation.': 'Nevezd el és válassz testrészt — úgy viselkedik, mint bármelyik más gyakorlat, csak animáció nélkül.',
'Exercise name': 'Gyakorlat neve',
'name + body part, no animation': 'név + testrész, animáció nélkül',
'Create exercise': 'Gyakorlat létrehozása',
'Give it a name': 'Adj neki egy nevet',
'Pick a body part': 'Válassz testrészt',
'“{0}” already exists': '„{0}” már létezik',
'“{0}” created': '„{0}” létrehozva',
'Cardio exercises log time + speed instead of weight × reps.': 'A kardió gyakorlatok időt + sebességet rögzítenek súly × ismétlés helyett.',
'custom': 'egyéni',
'Edit': 'Szerkesztés',
'Saved': 'Elmentve',
'Delete “{0}”?': '„{0}” törlése?',
'It will be removed from your routines. Already-logged workouts keep their sets.': 'El lesz távolítva a rutinjaidból. A már rögzített edzések megtartják a sorozataikat.',
'Exercise deleted': 'Gyakorlat törölve',
'Finish your current workout first': 'Fejezd be előbb a futó edzésed',
'Description (optional) — setup, cues, anything you want to remember': 'Leírás (opcionális) — beállítás, fogások, bármi, amit meg akarsz jegyezni',
'Delete exercise': 'Gyakorlat törlése',
'Edit or delete this exercise': 'Gyakorlat szerkesztése vagy törlése',
'Remove from routine': 'Eltávolítás a rutinból',
'Minimize': 'Kicsinyítés',
'Expand': 'Kibontás',
'Invite code': 'Meghívókód',
'This app is invite-only — enter the code you were given.': 'Ez az app csak meghívóval elérhető — add meg a kapott kódot.',
'An invite code is required': 'Meghívókód szükséges',
'Admin dashboard': 'Admin irányítópult',
// --- muscle map ---
'Muscle balance': 'Izomegyensúly',
'Fatigue': 'Fáradtság',
'Ready': 'Kész',
'Recovering': 'Regenerálódik',
'Fatigued': 'Fáradt',
'Fatigue shows how recently each muscle was trained. High means rest.': 'A fáradtság azt mutatja, mennyire nemrég edzetted az adott izmot. Magas érték: pihenj.',
'Strength shows retained muscle strength. Train again to reset it.': 'Az erő azt mutatja, mennyi izomerő maradt meg. Edz újra, hogy visszaálljon.',
'full': 'teljes',
'floor': 'minimum',
'Weeks since training: {0}': 'Utoljára {0} hete edzve',
'by sets worked': 'végzett sorozatok szerint',
'Week': 'Hét',
'not trained': 'nincs edzve',
'Not trained in this period': 'Ebben az időszakban nincs edzve',
'Every muscle group got some work in this period.': 'Minden izomcsoport kapott valamennyi munkát ebben az időszakban.',
'No workouts in this period yet.': 'Ebben az időszakban még nincs edzés.',
'What this session hits': 'Mit érint ez az edzés',
'What you just trained': 'Mit edzettél az imént',
'Body diagram': 'Testábra',
'Male': 'Férfi',
'Female': 'Nő',
'Less': 'Kevesebb',
'More': 'Több',
'Traps': 'Csuklyás izom',
'Shoulders': 'Váll',
'Chest': 'Mell',
'Upper back': 'Felső hát',
'Serratus': 'Fűrészizom',
'Biceps': 'Bicepsz',
'Triceps': 'Tricepsz',
'Forearms': 'Alkar',
'Abs': 'Has',
'Obliques': 'Ferde hasizom',
'Lower back': 'Deréktáj',
'Glutes': 'Farizom',
'Quads': 'Combfeszítő',
'Hamstrings': 'Combhajlító',
'Adductors': 'Adduktorok',
'Hip flexors': 'Csípőhajlító',
'Calves': 'Vádli',
'Shins': 'Sípcsont',
// --- import from another app ---
'Import from another app': 'Importálás másik appból',
'FitNotes, Strong, Hevy — or body weight from Apple Health': 'FitNotes, Strong, Hevy — vagy testsúly az Apple Healthből',
'Import from {0}': 'Importálás innen: {0}',
'Import history': 'Előzmények importálása',
'Weigh-ins': 'Mérések',
'Exercises matched': 'Egyeztetett gyakorlatok',
'Added as your own': 'Sajátként hozzáadva',
'The file is in {0} and your profile is in {1} — weights will be converted.': 'A fájl {0}-ban van, a profilod pedig {1}-ban — a súlyok át lesznek váltva.',
'The file does not say which unit it uses — numbers are imported as they are.': 'A fájl nem mondja meg, milyen mértékegységet használ — a számok változatlanul kerülnek importálásra.',
'The file mixes kg and lb — each set is converted to {0}.': 'A fájl kg-t és lb-t is tartalmaz — minden sorozat át lesz váltva erre: {0}.',
'{0} days already have data here and will be left alone.': '{0} napnak már van itt adata, ezek érintetlenek maradnak.',
'Not in the library — added as your own exercises': 'Nincs a könyvtárban — saját gyakorlatként hozzáadva',
'Nothing new to import': 'Nincs új importálnivaló',
'{0} workouts imported': '{0} edzés importálva',
'{0} weigh-ins imported': '{0} mérés importálva',
'Could not read that file': 'A fájlt nem sikerült beolvasni',
'That file is empty': 'Ez a fájl üres',
'That file\'s columns aren\'t recognised — see the docs for supported apps.': 'Ennek a fájlnak az oszlopai nem ismerhetők fel — a támogatott appok listáját lásd a dokumentációban.',
'Nothing to import from that file': 'Ebből a fájlból nincs mit importálni',
// --- mobile build ---
'Your data': 'A te adataid',
'All data stays on this phone': 'Minden adat ezen a telefonon marad',
'No account, no cloud — back it up anytime with Export below.': 'Nincs fiók, nincs felhő — bármikor menthetsz biztonsági másolatot lent az Exporttal.',
'Reminds you at this time on days that have a routine planned.': 'Ekkor emlékeztet azokon a napokon, amikor rutin van tervezve.',
'Workout day': 'Edzésnap',
'{0} is on the plan today — let’s go!': 'Ma {0} van a terven — gyerünk!',
// --- plan sharing ---
'Share your plan': 'Terv megosztása',
'Send your routines to a friend, or put your week on paper.': 'Küldd el a rutinjaidat egy barátnak, vagy vesd papírra a heted.',
'Export plan file': 'Tervfájl exportálása',
'A small file a friend imports into their own openGym — routines only, none of your workouts or weigh-ins.': 'Egy kis fájl, amit egy barát a saját openGym-jébe importál — csak rutinok, edzések és mérések nélkül.',
'Print / Save as PDF': 'Nyomtatás / Mentés PDF-ként',
'A clean one-page-per-plan printout — no exercise ever splits across a page.': 'Egy tiszta nyomtatvány, egy oldal tervenként — egyetlen gyakorlat sem törik meg oldalhatáron.',
'Add an exercise to a routine first — an empty plan has nothing to share.': 'Adj hozzá előbb egy gyakorlatot egy rutinhoz — egy üres tervnek nincs mit megosztania.',
'Got a plan from a friend?': 'Kaptál tervet egy baráttól?',
'Import a plan file': 'Tervfájl importálása',
'Plan file saved — send it to a friend': 'Tervfájl elmentve — küldd el egy barátnak',
'{0}’s plan': '{0} terve',
'Import “{0}”': '„{0}” importálása',
'Import this plan': 'Terv importálása',
'{0} routine': '{0} rutin',
'{0} routines': '{0} rutin',
'scheduled on {0} days': '{0} napra betervezve',
'scheduled on {0} day': '{0} napra betervezve',
'These are added as new routines — nothing you already have is changed.': 'Ezek új rutinként kerülnek hozzáadásra — semmi, ami már megvan, nem változik.',
'{0} exercise in the file isn’t in your library and was left out.': '{0} gyakorlat a fájlban nincs a könyvtáradban, ezért kimaradt.',
'{0} exercises in the file aren’t in your library and were left out.': '{0} gyakorlat a fájlban nincs a könyvtáradban, ezért kimaradt.',
'Use this weekly schedule': 'Heti beosztás alkalmazása',
'Replaces your current Mon–Sun assignments.': 'Lecseréli a jelenlegi H–V beosztásod.',
'Added {0} routines to your plan': '{0} rutin hozzáadva a tervedhez',
'this isn’t an openGym plan file': 'ez nem egy openGym tervfájl',
'Shared routine': 'Megosztott rutin',
'Unknown exercise': 'Ismeretlen gyakorlat',
'Weekly Training Plan': 'Heti edzésterv',
'Made with openGym': 'Az openGym-mel készült',
'Something went wrong': 'Hiba történt',
'This screen could not be drawn. Your data is safe on this device.': 'Ezt a képernyőt nem sikerült megjeleníteni. Az adataid biztonságban vannak ezen az eszközön.',
'Reload openGym': 'openGym újratöltése',
'Discard the running workout': 'A futó edzés elvetése',
// --- v1.2.2: timed sets, progression, estimated 1RM (#16 #17 #18) ---
'Top set': 'Legjobb sorozat',
'Est. 1RM': 'becs. 1RM',
'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.',
'From your log:': 'A naplódból:',
'{0} × {1} on {2}': '{0} × {1} – {2}',
'Estimate': 'Becslés',
'Enter a weight and 1–{0} reps — beyond that an estimate is guesswork.': 'Adj meg egy súlyt és 1–{0} ismétlést — afölött a becslés már csak találgatás.',
'Epley formula — a calculation from one set, not a tested max.': 'Epley-képlet — egyetlen sorozatból számolva, nem tesztelt maximum.',
'Best estimated 1RM:': 'Legjobb becsült 1RM:',
'Time': 'Idő',
'Seconds': 'Másodperc',
'A timer runs while you hold the set. Leave the weight at 0 for bodyweight holds.': 'Egy időzítő fut, amíg tartod a sorozatot. Testsúlyos tartásnál hagyd 0-n a súlyt.',
'Done': 'Kész',
'Start set': 'Sorozat indítása',
'Hold logged': 'Tartás rögzítve',
'Longest hold per workout': 'Leghosszabb tartás edzésenként',
'Progression': 'Progresszió',
'Rule': 'Szabály',
'Follow the routine ({0})': 'A rutin szabálya ({0})',
'Applies to every exercise in this routine that does not set its own rule.': 'Minden gyakorlatra vonatkozik ebben a rutinban, amelynek nincs saját szabálya.',
'Step ({0})': 'Lépésköz ({0})',
'Step (seconds)': 'Lépésköz (másodperc)',
'Reps from': 'Ismétlés ettől',
'No automatic progression': 'Nincs automatikus progresszió',
'Linear progression': 'Lineáris progresszió',
'Greyskull LP': 'Greyskull LP',
'Double progression': 'Dupla progresszió',
'Add time': 'Idő növelése',
'Targets stay where you set them.': 'A célértékek ott maradnak, ahova beállítottad őket.',
'Hit every rep in every set and the weight goes up. Repeated misses trigger a deload.': 'Ha minden sorozatban minden ismétlést teljesítesz, a súly emelkedik. Ismételt kihagyás deloadot indít.',
'Two straight sets plus a final set taken to failure. Beat the target on that set and the weight goes up — double if you double the reps. One failure resets 10 %.': 'Két rendes sorozat plusz egy utolsó, kimerülésig végzett sorozat. Ha az utolsó sorozatban túlteljesíted a célt, a súly emelkedik — duplán, ha az ismétlésszámot is duplázod. Egy sikertelen kísérlet 10%-kal visszaállítja.',
'Work up through a rep range at the same weight. Reach the top of the range in every set and the weight goes up, reps back to the bottom.': 'Ugyanazon a súlyon dolgozz végig egy ismétléstartományon. Ha minden sorozatban eléred a tartomány tetejét, a súly emelkedik, az ismétlésszám pedig visszaáll az aljára.',
'Hold every set for the full duration and the target goes up.': 'Ha minden sorozatot a teljes időn át tartasz, a célérték emelkedik.',
'Nothing logged yet — this session sets the baseline.': 'Még nincs rögzítve semmi — ez az edzés adja a kiindulópontot.',
'Held every set for the full time — target up by {0}s.': 'Minden sorozatot a teljes ideig tartottad — a cél {0} mp-cel emelkedik.',
'Short {0} sessions in a row — back off to {1}s and build up again.': '{0} egymást követő edzés volt rövid — vissza {1} mp-re, és építsd fel újra.',
'Last time came up short — same target again.': 'Legutóbb nem sikerült — ugyanaz a cél megint.',
'Top of the rep range in every set — {0} {1} more, back to {2} reps.': 'Az ismétléstartomány teteje minden sorozatban — {0} {1} plusz, vissza {2} ismétlésre.',
'Stalled {0} sessions — deload to {1} {2}.': '{0} edzés óta megrekedt — deload erre: {1} {2}.',
'Same weight — aim for {0} reps this time.': 'Ugyanaz a súly — most {0} ismétlést célozz meg.',
'Last set hit {0} reps — twice the target, so take a double jump of {1} {2}.': 'Az utolsó sorozat {0} ismétlést ért el — kétszerese a célnak, ezért dupla ugrás: {1} {2}.',
'Every rep last time — {0} {1} more.': 'Legutóbb minden ismétlés meglett — {0} {1} plusz.',
'Missed reps {0} sessions running — reset to {1} {2} and work back up.': '{0} edzés óta hiányoznak ismétlések — vissza {1} {2}, és építsd fel újra.',
'Missed reps — reset to {0} {1} and work back up.': 'Hiányoztak ismétlések — vissza {0} {1}, és építsd fel újra.',
'Missed reps last time — same weight again ({0} of {1} to go).': 'Legutóbb hiányoztak ismétlések — ugyanaz a súly megint (még {0} van hátra {1}-ból).',
'Bodyweight — every rep last time, so go for {0} this time.': 'Testsúly — legutóbb minden ismétlés meglett, most célozd meg ezt: {0}.',
'Bodyweight — same target again until every set is clean.': 'Testsúly — ugyanaz a cél megint, amíg minden sorozat tiszta nem lesz.',
// --- effort per set (RIR / RPE) ---
'{0} sets bring an {1} with them — switch on Effort per set in Settings to see it.': '{0} sorozat {1} hoz magával — kapcsold be a Megerőltetés sorozatonként opciót a Beállításokban, hogy lásd.',
'{0} sets bring an {1} with them.': '{0} sorozat {1} hoz magával.',
'RIR': 'RIR',
'RPE': 'RPE',
'Effort per set': 'Megerőltetés sorozatonként',
'What are RIR and RPE?': 'Mi az a RIR és RPE?',
'How hard a set was, logged next to weight and reps. Two scales for the same judgement, counted from opposite ends.': 'Mennyire volt nehéz egy sorozat, súly és ismétlésszám mellett rögzítve. Két skála ugyanarra a megítélésre, ellentétes végekről számolva.',
'How it felt': 'Milyen érzés volt',
'Nothing left — went to failure': 'Nem maradt semmi — kimerülésig ment',
'One more rep in the tank': 'Egy ismétlés még belefért volna',
'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',
'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 ---
'Effort': 'Megerőltetés',
'how close to failure': 'milyen közel a kimerüléshez',
'by hard sets': 'nehéz sorozatok szerint',
'Hard': 'Nehéz',
'no hard sets': 'nincs nehéz sorozat',
'No hard sets in this period': 'Ebben az időszakban nincs nehéz sorozat',
'Every muscle group got at least one hard set in this period.': 'Minden izomcsoport kapott legalább egy nehéz sorozatot ebben az időszakban.',
'No rated sets in this period.': 'Ebben az időszakban nincs értékelt sorozat.',
'average effort': 'átlagos megerőltetés',
'at {0} {1} or harder': '{0} {1} vagy nehezebb szinten',
'{0} of {1} finished sets rated': '{1}-ből {0} befejezett sorozat értékelve',
'Effort per set is switched off — turn it on in Settings to keep rating.': 'A Megerőltetés sorozatonként ki van kapcsolva — kapcsold be a Beállításokban a további értékeléshez.',
'Week by week': 'Hétről hétre',
'Where the sets land': 'Hova esnek a sorozatok',
'Most working sets belong close to failure without living there — half at the floor and half at the top average out to a healthy-looking middle.': 'A legtöbb munkasorozat közel van a kimerüléshez anélkül, hogy ott élne — fele lent, fele fent, ez egészségesnek tűnő átlagot ad.',
'Average effort per workout': 'Átlagos megerőltetés edzésenként',
'A fuller dot means less left in the tank — the same weight at a lower {0} is progress the line alone does not show.': 'Egy teltebb pont kevesebb tartalékot jelent — ugyanaz a súly alacsonyabb {0} mellett olyan fejlődés, amit a vonal önmagában nem mutat.',
// --- bodyweight & per side ---
'Bodyweight': 'Testsúly',
'No weight to enter — just log the reps.': 'Nincs beírandó súly — csak az ismétléseket rögzítsd.',
'Ask for a weight on every set.': 'Kérjen súlyt minden sorozatnál.',
'For dips or pull-ups with a belt. Progression then follows the weight.': 'Övvel végzett tolódzkodáshoz vagy húzódzkodáshoz. A progresszió ekkor a súlyt követi.',
'Reps per side': 'Ismétlés oldalanként',
'For lunges, single-arm rows and the like.': 'Kitörésekhez, egykezes evezéshez és hasonlókhoz.',
'Top of the range': 'A tartomány teteje',
'Reps climb by one whenever every set was clean. Set a ceiling to add sets instead of reps forever.': 'Az ismétlésszám eggyel nő, ha minden sorozat tiszta volt. Állíts be egy felső határt, hogy ne az ismétlések nőjenek a végtelenségig, hanem sorozat kerüljön hozzá.',
'Reps climb to {0}, then a set is added and the reps start over. At {1} sets it asks you to add weight instead.': 'Az ismétlésszám {0}-ig nő, utána egy sorozat kerül hozzá, és az ismétlés újraindul. {1} sorozatnál inkább súlynövelést javasol.',
'Added ({0})': 'Hozzáadva ({0})',
'{0}/side': '{0}/oldal',
'{0} reps in every set — add a set and go back to {1}.': '{0} ismétlés minden sorozatban — egy sorozat hozzáadva, vissza {1}-re.',
'{0} sets of {1} — time to add weight or move to a harder variation.': '{0} sorozat {1} ismétléssel — ideje súlyt hozzáadni vagy nehezebb variációra váltani.',
'{0} per side': '{0} oldalanként',
'You still log the total: {0} is {1} per side.': 'Továbbra is az összeset rögzíted: {0} az {1} oldalanként.',
'{0} sets · {1} work': '{0} sorozat · {1} munka',
'Make superset with previous': 'Szuperszett az előzővel',
'Make superset with next': 'Szuperszett a következővel',
'primary': 'elsődleges',
'secondary': 'másodlagos',
'No exercises with an estimated 1RM yet.': 'Még nincs gyakorlat becsült 1RM-mel.',
'Tap a muscle to see its exercises.': 'Koppints egy izomra, hogy lásd a hozzá tartozó gyakorlatokat.',
'Unpair': 'Szétkapcsolás',
'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': 'A rest-pause mindig egy bemelegítő sorozatként indul ennyi ismétléssel, majd egy rest-pause munkasorozatként folytatódik — a „Sorozatok” mező nem használt.',
'How the session went as a whole.': 'Hogyan ment az edzés egészében.',
'Edit session note': 'Edzésjegyzet szerkesztése',
'Add session note': 'Edzésjegyzet hozzáadása',
'Session note': 'Edzésjegyzet',
'From {0}:': 'Dátum: {0}',
'Seat height, pin position, a form cue — shown every session.': 'Ülésmagasság, pin pozíció, egy kivitelezési tipp — minden edzésen megjelenik.',
'Always for this exercise': 'Mindig ennél a gyakorlatnál',
'Brings it up again the next time you train this exercise.': 'Legközelebb, amikor ezt a gyakorlatot végzed, újra megjelenik.',
'Show this next time': 'Mutasd legközelebb is',
'How it went, what to change — kept with today’s workout.': 'Hogyan ment, mit változtass — a mai edzéssel együtt marad meg.',
'This session': 'Ez az edzés',
'Note': 'Megjegyzés',
'Ramp-up sets added before the work sets, so you do not have to add them by hand each session.': 'Fokozatosan növekvő sorozatok a munkasorozatok elé, hogy ne kelljen minden edzésen kézzel hozzáadnod őket.',
'Added before your work sets and left out of volume, records and progression. Each one closes half the gap to the work weight — you can still change any of them mid-session.': 'A munkasorozatok elé kerülnek, és nem számítanak bele a volumenbe, a rekordokba és a progresszióba. Mindegyik a felénél zárja a különbséget a munkasúlyhoz — edzés közben bármelyiket módosíthatod.',
'Warm-up sets': 'Bemelegítő sorozatok',
'Most reps in a set per workout': 'Legtöbb ismétlés egy sorozatban edzésenként',
'reps': 'ism.',
'Workout done': 'Edzés kész',
'{0} — done': '{0} — kész',
'Local keeps everything on this phone. Connecting syncs to your own openGym server instead — you can switch later in Settings.': 'A helyi mód mindent ezen a telefonon tart. A csatlakozás helyette a saját openGym szervereddel szinkronizál — ezt később a Beállításokban módosíthatod.',
'Use on this device': 'Használat ezen az eszközön',
'How do you want to use openGym?': 'Hogyan szeretnéd használni az openGym-et?',
'Connect': 'Csatlakozás',
'Connecting…': 'Csatlakozás…',
'Pairing code': 'Párosítási kód',
'Server address (e.g. gym.example.com)': 'Szerver címe (pl. gym.example.com)',
'Open Settings → “Pair the mobile app” on the openGym site you’re already signed into, then enter its address and the code shown there.': 'Nyisd meg a Beállítások → „Mobilalkalmazás párosítása” menüpontot azon az openGym oldalon, ahová már be vagy jelentkezve, majd add meg az ott látható címet és kódot.',
'Could not connect': 'Nem sikerült csatlakozni',
'Connected': 'Csatlakozva',
'Enter your server address and the code': 'Add meg a szervered címét és a kódot',
'On the openGym app, choose “Connect to my server”, then enter this address and the code below. It expires in 5 minutes.': 'Az openGym appban válaszd a „Csatlakozás a szerveremhez” lehetőséget, majd add meg ezt a címet és az alábbi kódot. 5 perc alatt jár le.',
'Could not generate a code': 'Nem sikerült kódot generálni',
'Connect the openGym app on your phone to this account.': 'Kösd össze a telefonodon lévő openGym appot ezzel a fiókkal.',
'Pair the mobile app': 'Mobilalkalmazás párosítása',
'Sync this device to your own self-hosted openGym instead.': 'Szinkronizáld inkább ezt az eszközt a saját self-hosted openGym-eddel.',
'Connect to my server': 'Csatlakozás a szerveremhez',
'Disconnected — back to local-only': 'Leválasztva — vissza csak-helyi módba',
'Your data is synced to your server first, then this device switches back to local-only.': 'Az adataid előbb szinkronizálódnak a szerverrel, majd ez az eszköz visszavált csak-helyi módba.',
'Disconnect from your server?': 'Leválasztás a szerverről?',
'Disconnect': 'Leválasztás',
'Synced with your openGym server.': 'Szinkronizálva az openGym szervereddel.',
'Your server': 'A szervered',
'No explicit muscle group': 'Nincs megadott izomcsoport',
'Additional muscle groups': 'További izomcsoportok',
'Primary muscle groups': 'Elsődleges izomcsoportok',
'Filters the exercise library and picker, and flags routine exercises that need something you don’t have in the active profile.': 'Szűri a gyakorlattárat és a választót, és megjelöli a rutinok azon gyakorlatait, amelyekhez olyasmi kell, ami nincs az aktív profilodban.',
'"{0}" and its equipment list will be removed.': '„{0}” és az eszközlistája el lesz távolítva.',
'Delete profile?': 'Profil törlése?',
'Add equipment profile': 'Eszközprofil hozzáadása',
'{0} equipment types': '{0} eszköztípus',
'Active profile': 'Aktív profil',
'Filter by equipment': 'Szűrés eszköz szerint',
'Needs {0} — not in your active profile': '{0} szükséges — nincs az aktív profilodban',
'{0} of {1} exercises need equipment outside "{2}"': '{0}/{1} gyakorlathoz kell eszköz a(z) „{2}” profilon kívülről',
'Body-weight exercises are always available, in every profile.': 'A testsúlyos gyakorlatok minden profilban mindig elérhetők.',
'Profile name': 'Profil neve',
'Name it after where you train — e.g. "Home" or "Gym" — then check what you have there.': 'Nevezd el arról a helyről, ahol edzel — pl. „Otthon” vagy „Terem” —, majd pipáld ki, ami ott megvan.',
'New equipment profile': 'Új eszközprofil',
'Edit profile': 'Profil szerkesztése',
'Filter by "{0}"': 'Szűrés erre: „{0}”',
'Show all equipment': 'Minden eszköz megjelenítése',
'Showing what you have in "{0}"': 'Az jelenik meg, ami megvan a(z) „{0}” profilban',
'Showing all equipment': 'Minden eszköz megjelenítve',
'Move up': 'Feljebb',
'Move down': 'Lejjebb',
'Swap exercise': 'Gyakorlat cseréje',
'Swap exercise?': 'Cseréled a gyakorlatot?',
'Logged sets stay with the original exercise. Choose where the replacement belongs.': 'A naplózott sorozatok az eredeti gyakorlatnál maradnak. Válaszd ki, hová kerüljön a csere.',
'Keep replacement in this group': 'A csere maradjon ebben a csoportban',
'Insert after this group': 'Beszúrás a csoport után',
'Logged sets stay with the original exercise. The replacement will be inserted afterward.': 'A naplózott sorozatok az eredeti gyakorlatnál maradnak. A csere utána kerül beszúrásra.',
'Rest after each set of this exercise. Leave at 0 to use your default rest timer.': 'Pihenő a gyakorlat minden sorozata után. Hagyd 0-n az alapértelmezett pihenőidőzítőhöz.',
'Flash screen when timer ends': 'Képernyő villogása, ha lejár az időzítő',
'Import from Hevy': 'Importálás a Hevyből',
'Pull your history with a Hevy Pro API key': 'Előzmények letöltése Hevy Pro API-kulccsal',
'Pull your history with a Hevy Pro API key. The key is only used for this import and is not saved.': 'Előzmények letöltése Hevy Pro API-kulccsal. A kulcs csak ehhez az importhoz kell, nem mentjük el.',
'Hevy API key': 'Hevy API-kulcs',
'Get your API key': 'API-kulcs beszerzése',
'Hevy → Settings → Developer': 'Hevy → Beállítások → Fejlesztő',
'Paste your Hevy API key first': 'Előbb illeszd be a Hevy API-kulcsot',
'Fetch from Hevy': 'Letöltés a Hevyből',
'Fetching from Hevy…': 'Letöltés a Hevyből…',
'Fetching exercises… ({0}/{1})': 'Gyakorlatok letöltése… ({0}/{1})',
'Fetching workouts… ({0}/{1})': 'Edzések letöltése… ({0}/{1})',
'Fetching weigh-ins… ({0}/{1})': 'Mérések letöltése… ({0}/{1})',
'Matching exercises…': 'Gyakorlatok párosítása…',
'Could not reach Hevy — check the key and try again': 'A Hevy nem érhető el — ellenőrizd a kulcsot, és próbáld újra',
'That Hevy API key was refused': 'A Hevy elutasította ezt az API-kulcsot',
'Nothing to import from Hevy': 'Nincs mit importálni a Hevyből',
'Import workouts': 'Edzések importálása',
'Import routines': 'Edzéstervek importálása',
'Import weigh-ins': 'Mérések importálása',
'{0} new · {1} days already here': '{0} új · {1} nap már megvan',
'{0} routines · {1} exercises — added as new plans': '{0} edzésterv · {1} gyakorlat — új tervekként hozzáadva',
'{0} routines imported': '{0} edzésterv importálva',
'Fetching routines… ({0}/{1})': 'Edzéstervek letöltése… ({0}/{1})',
'Hevy stores weights in kg — they will be converted to {0}.': 'A Hevy kg-ban tárolja a súlyokat — átváltjuk erre: {0}.',
'Back': 'Vissza',
'Reps up to': 'Ism. legfeljebb',
'Exclude from automatic progression': 'Kihagyás az automatikus progresszióból',
'Use for planned deloads. Workouts stay in history and statistics.': 'Tervezett deloadhoz. Az edzések megmaradnak az előzményekben és a statisztikában.',
'The next regular target continues from the last included workout.': 'A következő normál cél az utolsó beszámított edzéstől folytatódik.',
'Open progression settings': 'Progresszió beállításainak megnyitása',
'Hevy is rate-limiting requests — wait a minute and try again': 'A Hevy korlátozza a kéréseket — várj egy percet, és próbáld újra',
// --- log a past workout ---
'Log a past workout': 'Korábbi edzés rögzítése',
'Logged on the usual workout screen, without timers.': 'A szokásos edzésképernyőn rögzíted, csak időzítők nélkül.',
'Date': 'Dátum',
'Start time': 'Kezdés ideje',
'Continue': 'Tovább',
'Pick a day up to today': 'Válassz egy napot a mai napig',
'There is already a workout on that day.': 'Azon a napon már van egy edzés.',
'Replace': 'Csere',
'Add as second workout': 'Hozzáadás második edzésként',
'Finish the current workout first.': 'Előbb fejezd be a folyó edzést.',
'Logging a past workout — no rest timers.': 'Korábbi edzés rögzítése — nincs pihenőidőzítő.',
}
+56 -1
View File
@@ -35,6 +35,8 @@ export default {
'rescheduled': 'riprogrammato',
'Prev': 'Prec.',
'Next': 'Succ.',
'Move up': 'Sposta su',
'Move down': 'Sposta giù',
'Sunday': 'Domenica', 'Monday': 'Lunedì', 'Tuesday': 'Martedì', 'Wednesday': 'Mercoledì',
'Thursday': 'Giovedì', 'Friday': 'Venerdì', 'Saturday': 'Sabato',
'Su': 'Do', 'Mo': 'Lu', 'Tu': 'Ma', 'We': 'Me', 'Th': 'Gi', 'Fr': 'Ve', 'Sa': 'Sa',
@@ -91,6 +93,12 @@ export default {
'Weight ({0})': 'Peso ({0})',
'Add to routine': 'Aggiungi alla routine',
'Remove exercise': 'Rimuovi esercizio',
'Swap exercise': 'Sostituisci esercizio',
'Swap exercise?': 'Sostituire l’esercizio?',
'Logged sets stay with the original exercise. Choose where the replacement belongs.': 'Le serie registrate restano con l’esercizio originale. Scegli dove inserire il sostituto.',
'Keep replacement in this group': 'Mantieni il sostituto in questo gruppo',
'Insert after this group': 'Inserisci dopo questo gruppo',
'Logged sets stay with the original exercise. The replacement will be inserted afterward.': 'Le serie registrate restano con l’esercizio originale. Il sostituto verrà inserito dopo.',
'Remove {0}?': 'Rimuovere {0}?',
'The sets you logged for this exercise in this session will be lost.': 'Le serie registrate per questo esercizio in questa sessione andranno perse.',
'This removes the exercise from your current session.': 'Questo rimuove l’esercizio dalla sessione corrente.',
@@ -170,6 +178,7 @@ export default {
'Remove drop': 'Rimuovi drop set',
'Remove burst': 'Rimuovi burst',
'Rest (s)': 'Recupero (s)',
'Rest after each set of this exercise. Leave at 0 to use your default rest timer.': 'Recupero dopo ogni serie di questo esercizio. Lascialo a 0 per usare il timer di riposo predefinito.',
'Drop-set / rest-pause': 'Drop-set / rest-pause',
'Intensifier': 'Intensificatore',
'None': 'Nessuno',
@@ -284,6 +293,7 @@ export default {
'Weight unit': 'Unità di peso',
'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)',
@@ -451,6 +461,33 @@ export default {
'That file is empty': 'Il file è vuoto',
'That file\'s columns aren\'t recognised — see the docs for supported apps.': 'Colonne non riconosciute — vedi la documentazione per le app supportate.',
'Nothing to import from that file': 'Niente da importare da questo file',
// --- import from Hevy API ---
'Import from Hevy': 'Importa da Hevy',
'Pull your history with a Hevy Pro API key': 'Importa lo storico con una chiave API Hevy Pro',
'Pull your history with a Hevy Pro API key. The key is only used for this import and is not saved.': 'Importa lo storico con una chiave API Hevy Pro. La chiave serve solo a questo import e non viene salvata.',
'Hevy API key': 'Chiave API Hevy',
'Get your API key': 'Ottieni la chiave API',
'Hevy → Settings → Developer': 'Hevy → Impostazioni → Developer',
'Paste your Hevy API key first': 'Incolla prima la chiave API Hevy',
'Fetch from Hevy': 'Scarica da Hevy',
'Fetching from Hevy…': 'Download da Hevy…',
'Fetching exercises… ({0}/{1})': 'Download esercizi… ({0}/{1})',
'Fetching workouts… ({0}/{1})': 'Download allenamenti… ({0}/{1})',
'Fetching weigh-ins… ({0}/{1})': 'Download pesate… ({0}/{1})',
'Matching exercises…': 'Abbinamento esercizi…',
'Could not reach Hevy — check the key and try again': 'Impossibile contattare Hevy — controlla la chiave e riprova',
'That Hevy API key was refused': 'Questa chiave API Hevy è stata rifiutata',
'Nothing to import from Hevy': 'Niente da importare da Hevy',
'Import workouts': 'Importa allenamenti',
'Import routines': 'Importa routine',
'{0} routines · {1} exercises — added as new plans': '{0} routine · {1} esercizi — aggiunte come nuovi piani',
'{0} routines imported': '{0} routine importate',
'Fetching routines… ({0}/{1})': 'Download routine… ({0}/{1})',
'Routines': 'Routine',
'Import weigh-ins': 'Importa pesate',
'{0} new · {1} days already here': '{0} nuovi · {1} giorni già presenti',
'Hevy stores weights in kg — they will be converted to {0}.': 'Hevy memorizza i pesi in kg — verranno convertiti in {0}.',
'Back': 'Indietro',
// --- mobile build ---
'Your data': 'I tuoi dati',
'All data stays on this phone': 'Tutti i dati restano su questo telefono',
@@ -518,7 +555,11 @@ export default {
'Step ({0})': 'Incremento ({0})',
'Step (seconds)': 'Incremento (secondi)',
'Reps from': 'Rip. da',
'Reps up to': 'Rip. fino a',
'No automatic progression': 'Nessuna progressione automatica',
'Exclude from automatic progression': 'Escludi dalla progressione automatica',
'Use for planned deloads. Workouts stay in history and statistics.': 'Usa per gli scarichi programmati. Gli allenamenti restano nella cronologia e nelle statistiche.',
'The next regular target continues from the last included workout.': 'Il prossimo obiettivo normale continua dall’ultimo allenamento incluso.',
'Linear progression': 'Progressione lineare',
'Greyskull LP': 'Greyskull LP',
'Double progression': 'Doppia progressione',
@@ -673,5 +714,19 @@ export default {
'Add session note': 'Aggiungi nota della sessione',
'Edit session note': 'Modifica nota della sessione',
'How the session went as a whole.': 'Com’è andata la sessione nel complesso.',
'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': 'Il rest-pause si allena sempre come una serie di riscaldamento a queste ripetizioni e una serie di lavoro rest-pause — “Serie” non viene usato.'
'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': 'Il rest-pause si allena sempre come una serie di riscaldamento a queste ripetizioni e una serie di lavoro rest-pause — “Serie” non viene usato.',
'Open progression settings': 'Apri le impostazioni di progressione',
'Hevy is rate-limiting requests — wait a minute and try again': 'Hevy sta limitando le richieste: attendi un minuto e riprova',
// --- log a past workout ---
'Log a past workout': 'Registra un allenamento passato',
'Logged on the usual workout screen, without timers.': 'Si registra nella solita schermata di allenamento, solo senza timer.',
'Date': 'Data',
'Start time': 'Ora di inizio',
'Continue': 'Continua',
'Pick a day up to today': 'Scegli un giorno fino a oggi',
'There is already a workout on that day.': 'C’è già un allenamento quel giorno.',
'Replace': 'Sostituisci',
'Add as second workout': 'Aggiungi come secondo allenamento',
'Finish the current workout first.': 'Termina prima l’allenamento in corso.',
'Logging a past workout — no rest timers.': 'Allenamento passato — nessun timer di recupero.',
}
+56 -1
View File
@@ -35,6 +35,8 @@ export default {
'rescheduled': '변경됨',
'Prev': '이전',
'Next': '다음',
'Move up': '위로 이동',
'Move down': '아래로 이동',
'Sunday': '일요일', 'Monday': '월요일', 'Tuesday': '화요일', 'Wednesday': '수요일',
'Thursday': '목요일', 'Friday': '금요일', 'Saturday': '토요일',
'Su': '일', 'Mo': '월', 'Tu': '화', 'We': '수', 'Th': '목', 'Fr': '금', 'Sa': '토',
@@ -91,6 +93,12 @@ export default {
'Weight ({0})': '무게 ({0})',
'Add to routine': '루틴에 추가',
'Remove exercise': '운동 제거',
'Swap exercise': '운동 바꾸기',
'Swap exercise?': '운동을 바꿀까요?',
'Logged sets stay with the original exercise. Choose where the replacement belongs.': '기록한 세트는 원래 운동에 남습니다. 대체 운동을 넣을 위치를 선택하세요.',
'Keep replacement in this group': '대체 운동을 이 그룹에 유지',
'Insert after this group': '이 그룹 뒤에 삽입',
'Logged sets stay with the original exercise. The replacement will be inserted afterward.': '기록한 세트는 원래 운동에 남습니다. 대체 운동은 뒤에 삽입됩니다.',
'Remove {0}?': '{0}을(를) 제거할까요?',
'The sets you logged for this exercise in this session will be lost.': '이 세션에서 이 운동에 기록한 세트가 사라집니다.',
'This removes the exercise from your current session.': '현재 세션에서 이 운동을 제거합니다.',
@@ -170,6 +178,7 @@ export default {
'Remove drop': '드롭세트 제거',
'Remove burst': '버스트 제거',
'Rest (s)': '휴식(초)',
'Rest after each set of this exercise. Leave at 0 to use your default rest timer.': '이 운동의 세트마다 갖는 휴식이에요. 기본 휴식 타이머를 쓰려면 0으로 두세요.',
'Drop-set / rest-pause': '드롭세트 / 레스트포즈',
'Intensifier': '강도 기법',
'None': '없음',
@@ -284,6 +293,7 @@ export default {
'Weight unit': '무게 단위',
'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)',
@@ -451,6 +461,33 @@ export default {
'That file is empty': '파일이 비어 있습니다',
'That file\'s columns aren\'t recognised — see the docs for supported apps.': '열을 인식할 수 없습니다 — 지원 앱은 문서를 참고하세요.',
'Nothing to import from that file': '이 파일에서 가져올 내용이 없습니다',
// --- import from Hevy API ---
'Import from Hevy': 'Hevy에서 가져오기',
'Pull your history with a Hevy Pro API key': 'Hevy Pro API 키로 기록을 가져옵니다',
'Pull your history with a Hevy Pro API key. The key is only used for this import and is not saved.': 'Hevy Pro API 키로 기록을 가져옵니다. 키는 이번 가져오기에만 사용되며 저장되지 않습니다.',
'Hevy API key': 'Hevy API 키',
'Get your API key': 'API 키 받기',
'Hevy → Settings → Developer': 'Hevy → 설정 → Developer',
'Paste your Hevy API key first': '먼저 Hevy API 키를 붙여넣으세요',
'Fetch from Hevy': 'Hevy에서 가져오기',
'Fetching from Hevy…': 'Hevy에서 가져오는 중…',
'Fetching exercises… ({0}/{1})': '운동 가져오는 중… ({0}/{1})',
'Fetching workouts… ({0}/{1})': '운동 기록 가져오는 중… ({0}/{1})',
'Fetching weigh-ins… ({0}/{1})': '체중 가져오는 중… ({0}/{1})',
'Matching exercises…': '운동 매칭 중…',
'Could not reach Hevy — check the key and try again': 'Hevy에 연결할 수 없습니다 — 키를 확인하고 다시 시도하세요',
'That Hevy API key was refused': 'Hevy API 키가 거부되었습니다',
'Nothing to import from Hevy': 'Hevy에서 가져올 항목이 없습니다',
'Import workouts': '운동 기록 가져오기',
'Import routines': '루틴 가져오기',
'{0} routines · {1} exercises — added as new plans': '루틴 {0}개 · 운동 {1}개 — 새 계획으로 추가',
'{0} routines imported': '루틴 {0}개 가져옴',
'Fetching routines… ({0}/{1})': '루틴 가져오는 중… ({0}/{1})',
'Routines': '루틴',
'Import weigh-ins': '체중 가져오기',
'{0} new · {1} days already here': '새 {0}개 · 이미 있는 날 {1}개',
'Hevy stores weights in kg — they will be converted to {0}.': 'Hevy는 무게를 kg로 저장합니다 — {0}(으)로 변환됩니다.',
'Back': '뒤로',
// --- mobile build ---
'Your data': '내 데이터',
'All data stays on this phone': '모든 데이터는 이 휴대폰에만 저장됩니다',
@@ -518,7 +555,11 @@ export default {
'Step ({0})': '증가폭 ({0})',
'Step (seconds)': '증가폭 (초)',
'Reps from': '최소 횟수',
'Reps up to': '최대 횟수',
'No automatic progression': '자동 증가 없음',
'Exclude from automatic progression': '자동 증가에서 제외',
'Use for planned deloads. Workouts stay in history and statistics.': '계획된 디로딩에 사용합니다. 운동은 기록과 통계에 남습니다.',
'The next regular target continues from the last included workout.': '다음 일반 목표는 마지막으로 포함된 운동에서 이어집니다.',
'Linear progression': '선형 증가',
'Greyskull LP': 'Greyskull LP',
'Double progression': '이중 점증',
@@ -673,5 +714,19 @@ export default {
'Add session note': '운동 메모 추가',
'Edit session note': '운동 메모 편집',
'How the session went as a whole.': '이번 운동이 전체적으로 어땠는지.',
'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': '레스트포즈는 항상 이 횟수의 워밍업 세트 하나와 레스트포즈 작업 세트 하나로 진행됩니다 — ‘세트’는 사용하지 않습니다.'
'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': '레스트포즈는 항상 이 횟수의 워밍업 세트 하나와 레스트포즈 작업 세트 하나로 진행됩니다 — ‘세트’는 사용하지 않습니다.',
'Open progression settings': '진행 설정 열기',
'Hevy is rate-limiting requests — wait a minute and try again': 'Hevy가 요청을 제한하고 있습니다 — 잠시 기다렸다가 다시 시도하세요',
// --- log a past workout ---
'Log a past workout': '지난 운동 기록',
'Logged on the usual workout screen, without timers.': '평소 운동 화면에서 기록하며 타이머만 없습니다.',
'Date': '날짜',
'Start time': '시작 시간',
'Continue': '계속',
'Pick a day up to today': '오늘까지의 날짜를 선택하세요',
'There is already a workout on that day.': '그날에 이미 운동이 있습니다.',
'Replace': '바꾸기',
'Add as second workout': '두 번째 운동으로 추가',
'Finish the current workout first.': '먼저 진행 중인 운동을 마치세요.',
'Logging a past workout — no rest timers.': '지난 운동 기록 중 — 휴식 타이머 없음.',
}
+56 -1
View File
@@ -35,6 +35,8 @@ export default {
'rescheduled': 'przełożono',
'Prev': 'Wstecz',
'Next': 'Dalej',
'Move up': 'Przenieś w górę',
'Move down': 'Przenieś w dół',
'Sunday': 'Niedziela', 'Monday': 'Poniedziałek', 'Tuesday': 'Wtorek', 'Wednesday': 'Środa',
'Thursday': 'Czwartek', 'Friday': 'Piątek', 'Saturday': 'Sobota',
'Su': 'Nd', 'Mo': 'Pn', 'Tu': 'Wt', 'We': 'Śr', 'Th': 'Cz', 'Fr': 'Pt', 'Sa': 'So',
@@ -91,6 +93,12 @@ export default {
'Weight ({0})': 'Ciężar ({0})',
'Add to routine': 'Dodaj do planu',
'Remove exercise': 'Usuń ćwiczenie',
'Swap exercise': 'Zamień ćwiczenie',
'Swap exercise?': 'Zamienić ćwiczenie?',
'Logged sets stay with the original exercise. Choose where the replacement belongs.': 'Zapisane serie pozostają przy oryginalnym ćwiczeniu. Wybierz miejsce dla zamiennika.',
'Keep replacement in this group': 'Zachowaj zamiennik w tej grupie',
'Insert after this group': 'Wstaw za tą grupą',
'Logged sets stay with the original exercise. The replacement will be inserted afterward.': 'Zapisane serie pozostają przy oryginalnym ćwiczeniu. Zamiennik zostanie wstawiony za nim.',
'Remove {0}?': 'Usunąć {0}?',
'The sets you logged for this exercise in this session will be lost.': 'Serie zapisane dla tego ćwiczenia w tej sesji zostaną utracone.',
'This removes the exercise from your current session.': 'Spowoduje to usunięcie ćwiczenia z bieżącej sesji.',
@@ -170,6 +178,7 @@ export default {
'Remove drop': 'Usuń serię zniżkującą',
'Remove burst': 'Usuń serię rest-pause',
'Rest (s)': 'Odpoczynek (s)',
'Rest after each set of this exercise. Leave at 0 to use your default rest timer.': 'Odpoczynek po każdej serii tego ćwiczenia. Zostaw 0, żeby użyć domyślnego minutnika przerwy.',
'Drop-set / rest-pause': 'Seria zniżkująca / rest-pause',
'Intensifier': 'Technika intensyfikująca',
'None': 'Brak',
@@ -284,6 +293,7 @@ export default {
'Weight unit': 'Jednostka wagi',
'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)',
@@ -451,6 +461,33 @@ export default {
'That file is empty': 'Ten plik jest pusty',
'That file\'s columns aren\'t recognised — see the docs for supported apps.': 'Nie rozpoznano kolumn — obsługiwane aplikacje znajdziesz w dokumentacji.',
'Nothing to import from that file': 'Brak danych do importu z tego pliku',
// --- import from Hevy API ---
'Import from Hevy': 'Importuj z Hevy',
'Pull your history with a Hevy Pro API key': 'Pobierz historię kluczem API Hevy Pro',
'Pull your history with a Hevy Pro API key. The key is only used for this import and is not saved.': 'Pobierz historię kluczem API Hevy Pro. Klucz służy tylko do tego importu i nie jest zapisywany.',
'Hevy API key': 'Klucz API Hevy',
'Get your API key': 'Pobierz klucz API',
'Hevy → Settings → Developer': 'Hevy → Ustawienia → Developer',
'Paste your Hevy API key first': 'Najpierw wklej klucz API Hevy',
'Fetch from Hevy': 'Pobierz z Hevy',
'Fetching from Hevy…': 'Pobieranie z Hevy…',
'Fetching exercises… ({0}/{1})': 'Pobieranie ćwiczeń… ({0}/{1})',
'Fetching workouts… ({0}/{1})': 'Pobieranie treningów… ({0}/{1})',
'Fetching weigh-ins… ({0}/{1})': 'Pobieranie ważenia… ({0}/{1})',
'Matching exercises…': 'Dopasowywanie ćwiczeń…',
'Could not reach Hevy — check the key and try again': 'Nie udało się połączyć z Hevy — sprawdź klucz i spróbuj ponownie',
'That Hevy API key was refused': 'Ten klucz API Hevy został odrzucony',
'Nothing to import from Hevy': 'Nie ma nic do zaimportowania z Hevy',
'Import workouts': 'Importuj treningi',
'Import routines': 'Importuj rutyny',
'{0} routines · {1} exercises — added as new plans': '{0} rutyn · {1} ćwiczeń — dodane jako nowe plany',
'{0} routines imported': 'Zaimportowano {0} rutyn',
'Fetching routines… ({0}/{1})': 'Pobieranie rutyn… ({0}/{1})',
'Routines': 'Rutyny',
'Import weigh-ins': 'Importuj ważenia',
'{0} new · {1} days already here': '{0} nowych · {1} dni już jest',
'Hevy stores weights in kg — they will be converted to {0}.': 'Hevy zapisuje ciężary w kg — zostaną przeliczone na {0}.',
'Back': 'Wstecz',
// --- mobile build ---
'Your data': 'Twoje dane',
'All data stays on this phone': 'Wszystkie dane zostają na tym telefonie',
@@ -518,7 +555,11 @@ export default {
'Step ({0})': 'Skok ({0})',
'Step (seconds)': 'Skok (sekundy)',
'Reps from': 'Powt. od',
'Reps up to': 'Powt. do',
'No automatic progression': 'Bez automatycznej progresji',
'Exclude from automatic progression': 'Wyklucz z automatycznej progresji',
'Use for planned deloads. Workouts stay in history and statistics.': 'Użyj dla planowanych deloadów. Treningi pozostają w historii i statystykach.',
'The next regular target continues from the last included workout.': 'Następny zwykły cel bazuje na ostatnim uwzględnionym treningu.',
'Linear progression': 'Progresja liniowa',
'Greyskull LP': 'Greyskull LP',
'Double progression': 'Podwójna progresja',
@@ -673,5 +714,19 @@ export default {
'Add session note': 'Dodaj notatkę do sesji',
'Edit session note': 'Edytuj notatkę do sesji',
'How the session went as a whole.': 'Jak przebiegła cała sesja.',
'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': 'Rest-pause zawsze trenuje się jako jedna seria rozgrzewkowa o tej liczbie powtórzeń i jedna seria robocza rest-pause — „Serie” nie są używane.'
'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': 'Rest-pause zawsze trenuje się jako jedna seria rozgrzewkowa o tej liczbie powtórzeń i jedna seria robocza rest-pause — „Serie” nie są używane.',
'Open progression settings': 'Otwórz ustawienia progresji',
'Hevy is rate-limiting requests — wait a minute and try again': 'Hevy ogranicza liczbę zapytań — odczekaj minutę i spróbuj ponownie',
// --- log a past workout ---
'Log a past workout': 'Zapisz miniony trening',
'Logged on the usual workout screen, without timers.': 'Zapisujesz na zwykłym ekranie treningu, tylko bez minutników.',
'Date': 'Data',
'Start time': 'Godzina rozpoczęcia',
'Continue': 'Dalej',
'Pick a day up to today': 'Wybierz dzień do dzisiaj',
'There is already a workout on that day.': 'Tego dnia jest już trening.',
'Replace': 'Zastąp',
'Add as second workout': 'Dodaj jako drugi trening',
'Finish the current workout first.': 'Najpierw zakończ bieżący trening.',
'Logging a past workout — no rest timers.': 'Zapisywanie minionego treningu — bez minutników przerw.',
}
+51 -1
View File
@@ -5,6 +5,7 @@ import pt from './pt.js'
export const PT_BR_OVERRIDES = {
'Press back again to exit': 'Pressione voltar novamente para sair',
'Reps up to': 'Reps até',
'Delete': 'Excluir',
'Save': 'Salvar',
'Log': 'Registrar',
@@ -28,6 +29,12 @@ export const PT_BR_OVERRIDES = {
'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.',
'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?',
'Logged sets stay with the original exercise. Choose where the replacement belongs.': 'As séries registradas ficam com o exercício original. Escolha onde colocar o substituto.',
'Keep replacement in this group': 'Manter o substituto neste grupo',
'Insert after this group': 'Inserir depois deste grupo',
'Logged sets stay with the original exercise. The replacement will be inserted afterward.': 'As séries registradas ficam com o exercício original. O substituto será inserido depois.',
'This removes the exercise from your current session.': 'Isso remove o exercício da sua sessão atual.',
'Which exercise in this superset do you want to remove?': 'Qual exercício deste superset você quer remover?',
'Pick an icon': 'Escolha um ícone',
@@ -59,6 +66,9 @@ export const PT_BR_OVERRIDES = {
'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.',
'The next regular target continues from the last included workout.': 'A próxima meta normal continua a partir do último treino incluído.',
'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',
@@ -90,6 +100,7 @@ export const PT_BR_OVERRIDES = {
'Create passkey profile': 'Criar perfil com chave de acesso',
'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',
@@ -134,6 +145,33 @@ export const PT_BR_OVERRIDES = {
'That file\'s columns aren\'t recognised — see the docs for supported apps.': 'Colunas não reconhecidas — consulte a documentação dos aplicativos compatíveis.',
'That file is empty': 'Esse arquivo está vazio',
'Nothing to import from that file': 'Não há nada para importar desse arquivo',
// --- import from Hevy API ---
'Import from Hevy': 'Importar do Hevy',
'Pull your history with a Hevy Pro API key': 'Traga seu histórico com uma chave de API do Hevy Pro',
'Pull your history with a Hevy Pro API key. The key is only used for this import and is not saved.': 'Traga seu histórico com uma chave de API do Hevy Pro. A chave só é usada nesta importação e não é salva.',
'Hevy API key': 'Chave de API do Hevy',
'Get your API key': 'Obter sua chave de API',
'Hevy → Settings → Developer': 'Hevy → Configurações → Developer',
'Paste your Hevy API key first': 'Cole primeiro sua chave de API do Hevy',
'Fetch from Hevy': 'Buscar no Hevy',
'Fetching from Hevy…': 'Buscando no Hevy…',
'Fetching exercises… ({0}/{1})': 'Buscando exercícios… ({0}/{1})',
'Fetching workouts… ({0}/{1})': 'Buscando treinos… ({0}/{1})',
'Fetching weigh-ins… ({0}/{1})': 'Buscando pesagens… ({0}/{1})',
'Matching exercises…': 'Associando exercícios…',
'Could not reach Hevy — check the key and try again': 'Não foi possível contatar o Hevy — confira a chave e tente de novo',
'That Hevy API key was refused': 'Essa chave de API do Hevy foi recusada',
'Nothing to import from Hevy': 'Nada para importar do Hevy',
'Import workouts': 'Importar treinos',
'Import routines': 'Importar rotinas',
'{0} routines · {1} exercises — added as new plans': '{0} rotinas · {1} exercícios — adicionadas como planos novos',
'{0} routines imported': '{0} rotinas importadas',
'Fetching routines… ({0}/{1})': 'Buscando rotinas… ({0}/{1})',
'Routines': 'Rotinas',
'Import weigh-ins': 'Importar pesagens',
'{0} new · {1} days already here': '{0} novos · {1} dias já existentes',
'Hevy stores weights in kg — they will be converted to {0}.': 'O Hevy guarda os pesos em kg — eles serão convertidos para {0}.',
'Back': 'Voltar',
'Your data': 'Seus dados',
'All data stays on this phone': 'Todos os dados ficam neste celular',
'No account, no cloud — back it up anytime with Export below.': 'Sem conta e sem nuvem — faça um backup quando quiser usando a opção Exportar abaixo.',
@@ -180,6 +218,8 @@ export const PT_BR_OVERRIDES = {
// Regional wording inherited from pt-PT would otherwise leak into pt-BR.
'Next': 'Próximo',
'Move up': 'Mover para cima',
'Move down': 'Mover para baixo',
'{0} to gain': '{0} para ganhar',
'{0} to lose': '{0} para perder',
'{0} set still unchecked. Finish the workout now?': 'Falta {0} série sem marcar. Finalizar o treino agora?',
@@ -302,7 +342,17 @@ export const PT_BR_OVERRIDES = {
'Brings it up again the next time you train this exercise.': 'Aparece de novo na próxima vez que você treinar este exercício.',
'Seat height, pin position, a form cue — shown every session.': 'Altura do banco, posição do pino, uma dica de execução — aparece em todos os treinos.',
'How the session went as a whole.': 'Como foi o treino como um todo.',
'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': 'O rest-pause sempre treina como uma série de aquecimento com essas repetições e uma série de trabalho rest-pause — “Séries” não é usado.'
'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': 'O rest-pause sempre treina como uma série de aquecimento com essas repetições e uma série de trabalho rest-pause — “Séries” não é usado.',
// --- per-exercise rest ---
'Rest after each set of this exercise. Leave at 0 to use your default rest timer.': 'Descanso depois de cada série deste exercício. Deixe em 0 para usar o temporizador de descanso padrão.',
'Open progression settings': 'Abrir configurações de progressão',
'Hevy is rate-limiting requests — wait a minute and try again': 'O Hevy está limitando as solicitações — espere um minuto e tente novamente',
'Log a past workout': 'Registrar um treino passado',
'Logged on the usual workout screen, without timers.': 'Registrado na tela de treino habitual, só sem temporizadores.',
'Pick a day up to today': 'Escolha um dia até hoje',
'Finish the current workout first.': 'Termine primeiro o treino atual.',
'Logging a past workout — no rest timers.': 'Registrando um treino passado — sem temporizadores de descanso.',
}
export default { ...pt, ...PT_BR_OVERRIDES }
+56 -1
View File
@@ -35,6 +35,8 @@ export default {
'rescheduled': 'reagendado',
'Prev': 'Anterior',
'Next': 'Seguinte',
'Move up': 'Mover para cima',
'Move down': 'Mover para baixo',
'Sunday': 'Domingo', 'Monday': 'Segunda-feira', 'Tuesday': 'Terça-feira', 'Wednesday': 'Quarta-feira',
'Thursday': 'Quinta-feira', 'Friday': 'Sexta-feira', 'Saturday': 'Sábado',
'Su': 'Do', 'Mo': 'Se', 'Tu': 'Te', 'We': 'Qa', 'Th': 'Qi', 'Fr': 'Sx', 'Sa': 'Sá',
@@ -91,6 +93,12 @@ export default {
'Weight ({0})': 'Peso ({0})',
'Add to routine': 'Adicionar à rotina',
'Remove exercise': 'Remover exercício',
'Swap exercise': 'Trocar exercício',
'Swap exercise?': 'Trocar exercício?',
'Logged sets stay with the original exercise. Choose where the replacement belongs.': 'As séries registadas ficam com o exercício original. Escolhe onde colocar o substituto.',
'Keep replacement in this group': 'Manter o substituto neste grupo',
'Insert after this group': 'Inserir depois deste grupo',
'Logged sets stay with the original exercise. The replacement will be inserted afterward.': 'As séries registadas ficam com o exercício original. O substituto será inserido depois.',
'Remove {0}?': 'Remover {0}?',
'The sets you logged for this exercise in this session will be lost.': 'As séries registadas para este exercício nesta sessão serão perdidas.',
'This removes the exercise from your current session.': 'Isto remove o exercício da tua sessão atual.',
@@ -170,6 +178,7 @@ export default {
'Remove drop': 'Remover queda',
'Remove burst': 'Remover rajada',
'Rest (s)': 'Descanso (s)',
'Rest after each set of this exercise. Leave at 0 to use your default rest timer.': 'Descanso depois de cada série deste exercício. Deixa a 0 para usares o temporizador de descanso predefinido.',
'Drop-set / rest-pause': 'Séries decrescentes / rest-pause',
'Intensifier': 'Intensificador',
'None': 'Nenhum',
@@ -284,6 +293,7 @@ export default {
'Weight unit': 'Unidade de peso',
'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)',
@@ -451,6 +461,33 @@ export default {
'That file is empty': 'Esse ficheiro está vazio',
'That file\'s columns aren\'t recognised — see the docs for supported apps.': 'Colunas não reconhecidas — vê a documentação para apps suportadas.',
'Nothing to import from that file': 'Nada para importar desse ficheiro',
// --- import from Hevy API ---
'Import from Hevy': 'Importar do Hevy',
'Pull your history with a Hevy Pro API key': 'Traz o historial com uma chave API Hevy Pro',
'Pull your history with a Hevy Pro API key. The key is only used for this import and is not saved.': 'Traz o historial com uma chave API Hevy Pro. A chave só é usada neste import e não é guardada.',
'Hevy API key': 'Chave API Hevy',
'Get your API key': 'Obter a chave API',
'Hevy → Settings → Developer': 'Hevy → Definições → Developer',
'Paste your Hevy API key first': 'Cola primeiro a chave API Hevy',
'Fetch from Hevy': 'Carregar do Hevy',
'Fetching from Hevy…': 'A carregar do Hevy…',
'Fetching exercises… ({0}/{1})': 'A carregar exercícios… ({0}/{1})',
'Fetching workouts… ({0}/{1})': 'A carregar treinos… ({0}/{1})',
'Fetching weigh-ins… ({0}/{1})': 'A carregar pesagens… ({0}/{1})',
'Matching exercises…': 'A associar exercícios…',
'Could not reach Hevy — check the key and try again': 'Não foi possível contactar o Hevy — verifica a chave e tenta de novo',
'That Hevy API key was refused': 'Essa chave API Hevy foi recusada',
'Nothing to import from Hevy': 'Nada para importar do Hevy',
'Import workouts': 'Importar treinos',
'Import routines': 'Importar rotinas',
'{0} routines · {1} exercises — added as new plans': '{0} rotinas · {1} exercícios — adicionadas como planos novos',
'{0} routines imported': '{0} rotinas importadas',
'Fetching routines… ({0}/{1})': 'A carregar rotinas… ({0}/{1})',
'Routines': 'Rotinas',
'Import weigh-ins': 'Importar pesagens',
'{0} new · {1} days already here': '{0} novos · {1} dias já existentes',
'Hevy stores weights in kg — they will be converted to {0}.': 'O Hevy guarda os pesos em kg — serão convertidos para {0}.',
'Back': 'Voltar',
// --- mobile build ---
'Your data': 'Os teus dados',
'All data stays on this phone': 'Todos os dados ficam neste telemóvel',
@@ -518,7 +555,11 @@ export default {
'Step ({0})': 'Incremento ({0})',
'Step (seconds)': 'Incremento (segundos)',
'Reps from': 'Reps a partir de',
'Reps up to': 'Reps até',
'No automatic progression': 'Sem progressão automática',
'Exclude from automatic progression': 'Excluir da progressão automática',
'Use for planned deloads. Workouts stay in history and statistics.': 'Use para deloads planeados. Os treinos permanecem no histórico e nas estatísticas.',
'The next regular target continues from the last included workout.': 'O próximo objetivo normal continua a partir do último treino incluído.',
'Linear progression': 'Progressão linear',
'Greyskull LP': 'Greyskull LP',
'Double progression': 'Progressão dupla',
@@ -673,5 +714,19 @@ export default {
'Add session note': 'Adicionar nota da sessão',
'Edit session note': 'Editar nota da sessão',
'How the session went as a whole.': 'Como correu a sessão no seu todo.',
'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': 'O rest-pause treina sempre como uma série de aquecimento com estas repetições e uma série de trabalho rest-pause — «Séries» não é usado.'
'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': 'O rest-pause treina sempre como uma série de aquecimento com estas repetições e uma série de trabalho rest-pause — «Séries» não é usado.',
'Open progression settings': 'Abrir definições de progressão',
'Hevy is rate-limiting requests — wait a minute and try again': 'O Hevy está a limitar os pedidos — espere um minuto e tente novamente',
// --- log a past workout ---
'Log a past workout': 'Registar um treino passado',
'Logged on the usual workout screen, without timers.': 'Registado no ecrã de treino habitual, só sem temporizadores.',
'Date': 'Data',
'Start time': 'Hora de início',
'Continue': 'Continuar',
'Pick a day up to today': 'Escolhe um dia até hoje',
'There is already a workout on that day.': 'Já existe um treino nesse dia.',
'Replace': 'Substituir',
'Add as second workout': 'Adicionar como segundo treino',
'Finish the current workout first.': 'Termina primeiro o treino em curso.',
'Logging a past workout — no rest timers.': 'A registar um treino passado — sem temporizadores de descanso.',
}
+56 -1
View File
@@ -35,6 +35,8 @@ export default {
'rescheduled': 'перенесено',
'Prev': 'Назад',
'Next': 'Далее',
'Move up': 'Переместить вверх',
'Move down': 'Переместить вниз',
'Sunday': 'Воскресенье', 'Monday': 'Понедельник', 'Tuesday': 'Вторник', 'Wednesday': 'Среда',
'Thursday': 'Четверг', 'Friday': 'Пятница', 'Saturday': 'Суббота',
'Su': 'Вс', 'Mo': 'Пн', 'Tu': 'Вт', 'We': 'Ср', 'Th': 'Чт', 'Fr': 'Пт', 'Sa': 'Сб',
@@ -91,6 +93,12 @@ export default {
'Weight ({0})': 'Вес ({0})',
'Add to routine': 'Добавить в программу',
'Remove exercise': 'Убрать упражнение',
'Swap exercise': 'Заменить упражнение',
'Swap exercise?': 'Заменить упражнение?',
'Logged sets stay with the original exercise. Choose where the replacement belongs.': 'Записанные подходы останутся у исходного упражнения. Выберите место для замены.',
'Keep replacement in this group': 'Оставить замену в этой группе',
'Insert after this group': 'Вставить после этой группы',
'Logged sets stay with the original exercise. The replacement will be inserted afterward.': 'Записанные подходы останутся у исходного упражнения. Замена будет вставлена после него.',
'Remove {0}?': 'Удалить {0}?',
'The sets you logged for this exercise in this session will be lost.': 'Подходы, записанные для этого упражнения в этой сессии, будут потеряны.',
'This removes the exercise from your current session.': 'Упражнение будет удалено из текущей сессии.',
@@ -170,6 +178,7 @@ export default {
'Remove drop': 'Убрать дроп-сет',
'Remove burst': 'Убрать серию',
'Rest (s)': 'Отдых (с)',
'Rest after each set of this exercise. Leave at 0 to use your default rest timer.': 'Отдых после каждого подхода этого упражнения. Оставь 0, чтобы работал таймер отдыха по умолчанию.',
'Drop-set / rest-pause': 'Дроп-сет / рест-пауза',
'Intensifier': 'Интенсификатор',
'None': 'Нет',
@@ -284,6 +293,7 @@ export default {
'Weight unit': 'Единица веса',
'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)',
@@ -451,6 +461,33 @@ export default {
'That file is empty': 'Файл пуст',
'That file\'s columns aren\'t recognised — see the docs for supported apps.': 'Колонки не распознаны — список поддерживаемых приложений в документации.',
'Nothing to import from that file': 'В этом файле нечего импортировать',
// --- import from Hevy API ---
'Import from Hevy': 'Импорт из Hevy',
'Pull your history with a Hevy Pro API key': 'Загрузить историю с API-ключом Hevy Pro',
'Pull your history with a Hevy Pro API key. The key is only used for this import and is not saved.': 'Загрузить историю с API-ключом Hevy Pro. Ключ используется только для этого импорта и не сохраняется.',
'Hevy API key': 'API-ключ Hevy',
'Get your API key': 'Получить API-ключ',
'Hevy → Settings → Developer': 'Hevy → Настройки → Developer',
'Paste your Hevy API key first': 'Сначала вставьте API-ключ Hevy',
'Fetch from Hevy': 'Загрузить из Hevy',
'Fetching from Hevy…': 'Загрузка из Hevy…',
'Fetching exercises… ({0}/{1})': 'Загрузка упражнений… ({0}/{1})',
'Fetching workouts… ({0}/{1})': 'Загрузка тренировок… ({0}/{1})',
'Fetching weigh-ins… ({0}/{1})': 'Загрузка взвешиваний… ({0}/{1})',
'Matching exercises…': 'Сопоставление упражнений…',
'Could not reach Hevy — check the key and try again': 'Не удалось связаться с Hevy — проверьте ключ и попробуйте снова',
'That Hevy API key was refused': 'Этот API-ключ Hevy отклонён',
'Nothing to import from Hevy': 'Из Hevy нечего импортировать',
'Import workouts': 'Импортировать тренировки',
'Import routines': 'Импортировать программы',
'{0} routines · {1} exercises — added as new plans': '{0} программ · {1} упражнений — добавляются как новые планы',
'{0} routines imported': 'Импортировано программ: {0}',
'Fetching routines… ({0}/{1})': 'Загрузка программ… ({0}/{1})',
'Routines': 'Программы',
'Import weigh-ins': 'Импортировать взвешивания',
'{0} new · {1} days already here': '{0} новых · {1} дней уже есть',
'Hevy stores weights in kg — they will be converted to {0}.': 'Hevy хранит веса в кг — они будут переведены в {0}.',
'Back': 'Назад',
// --- mobile build ---
'Your data': 'Ваши данные',
'All data stays on this phone': 'Все данные остаются на этом телефоне',
@@ -518,7 +555,11 @@ export default {
'Step ({0})': 'Шаг ({0})',
'Step (seconds)': 'Шаг (секунды)',
'Reps from': 'Повт. от',
'Reps up to': 'Повт. до',
'No automatic progression': 'Без автопрогрессии',
'Exclude from automatic progression': 'Исключить из автоматической прогрессии',
'Use for planned deloads. Workouts stay in history and statistics.': 'Используйте для плановых разгрузок. Тренировки остаются в истории и статистике.',
'The next regular target continues from the last included workout.': 'Следующая обычная цель продолжает прогрессию от последней учтённой тренировки.',
'Linear progression': 'Линейная прогрессия',
'Greyskull LP': 'Greyskull LP',
'Double progression': 'Двойная прогрессия',
@@ -673,5 +714,19 @@ export default {
'Add session note': 'Добавить заметку',
'Edit session note': 'Изменить заметку',
'How the session went as a whole.': 'Как прошла тренировка в целом.',
'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': 'Rest-pause всегда выполняется как один разминочный подход с этим числом повторений и один рабочий подход rest-pause — «Подходы» не используются.'
'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': 'Rest-pause всегда выполняется как один разминочный подход с этим числом повторений и один рабочий подход rest-pause — «Подходы» не используются.',
'Open progression settings': 'Открыть настройки прогрессии',
'Hevy is rate-limiting requests — wait a minute and try again': 'Hevy ограничивает запросы — подождите минуту и попробуйте снова',
// --- log a past workout ---
'Log a past workout': 'Записать прошлую тренировку',
'Logged on the usual workout screen, without timers.': 'Записывается на обычном экране тренировки, только без таймеров.',
'Date': 'Дата',
'Start time': 'Время начала',
'Continue': 'Продолжить',
'Pick a day up to today': 'Выбери день не позже сегодняшнего',
'There is already a workout on that day.': 'В этот день уже есть тренировка.',
'Replace': 'Заменить',
'Add as second workout': 'Добавить как вторую тренировку',
'Finish the current workout first.': 'Сначала заверши текущую тренировку.',
'Logging a past workout — no rest timers.': 'Запись прошлой тренировки — без таймеров отдыха.',
}
+745
View File
@@ -0,0 +1,745 @@
// Thai UI strings. Keys are the English source strings (see lib/i18n.js).
export default {
// --- generic ---
'Confirm': 'ยืนยัน',
'Cancel': 'ยกเลิก',
'Press back again to exit': 'กดย้อนกลับอีกครั้งเพื่อออก',
'Delete': 'ลบ',
'Save': 'บันทึก',
'Import': 'นำเข้า',
'Discard': 'ทิ้ง',
'All': 'ทั้งหมด',
'Rest': 'พัก',
'On': 'เปิด',
'Off': 'ปิด',
'On 🔔': 'เปิด 🔔',
'Off 🔕': 'ปิด 🔕',
'Skip': 'ข้าม',
'New': 'ใหม่',
'Log': 'บันทึก',
'Goal': 'เป้าหมาย',
'Plan': 'แผน',
'Today': 'วันนี้',
'Home': 'หน้าหลัก',
'Start': 'เริ่ม',
'Resume': 'เล่นต่อ',
'Stats': 'สถิติ',
'Exercises': 'ท่าออกกำลังกาย',
'History': 'ประวัติ',
'Settings': 'ตั้งค่า',
'Freestyle': 'ฟรีสไตล์',
'Routine': 'รูทีน',
'routine': 'รูทีน',
'Cardio': 'คาร์ดิโอ',
'Superset': 'ซูเปอร์เซ็ต',
'last': 'ครั้งล่าสุด',
'rescheduled': 'เลื่อนแล้ว',
'Prev': 'ก่อนหน้า',
'Next': 'ถัดไป',
// --- days & months ---
'Sunday': 'วันอาทิตย์', 'Monday': 'วันจันทร์', 'Tuesday': 'วันอังคาร', 'Wednesday': 'วันพุธ',
'Thursday': 'วันพฤหัสบดี', 'Friday': 'วันศุกร์', 'Saturday': 'วันเสาร์',
'Su': 'อา', 'Mo': 'จ', 'Tu': 'อ', 'We': 'พ', 'Th': 'พฤ', 'Fr': 'ศ', 'Sa': 'ส',
'Mon': 'จ', 'Wed': 'พ', 'Fri': 'ศ',
'Jan': 'ม.ค.', 'Feb': 'ก.พ.', 'Mar': 'มี.ค.', 'Apr': 'เม.ย.', 'May': 'พ.ค.', 'Jun': 'มิ.ย.',
'Jul': 'ก.ค.', 'Aug': 'ส.ค.', 'Sep': 'ก.ย.', 'Oct': 'ต.ค.', 'Nov': 'พ.ย.', 'Dec': 'ธ.ค.',
'January': 'มกราคม', 'February': 'กุมภาพันธ์', 'March': 'มีนาคม', 'April': 'เมษายน',
'June': 'มิถุนายน', 'July': 'กรกฎาคม', 'August': 'สิงหาคม', 'September': 'กันยายน',
'October': 'ตุลาคม', 'November': 'พฤศจิกายน', 'December': 'ธันวาคม',
// --- body weight & goal ---
'Quick check-in': 'เช็คอินด่วน',
'Log body weight': 'บันทึกน้ำหนักตัว',
'Slide or tap to set your weight — tracked before every workout so your curve stays honest.': 'เลื่อนหรือแตะเพื่อตั้งน้ำหนัก — บันทึกก่อนออกกำลังกายทุกครั้งเพื่อให้กราฟตรงตามจริง',
'Save & start workout': 'บันทึกแล้วเริ่มออกกำลังกาย',
'Start without weighing in': 'เริ่มโดยไม่ชั่งน้ำหนัก',
'Choose a different workout': 'เลือกโปรแกรมอื่น',
'Recent weigh-ins': 'น้ำหนักล่าสุด',
'Enter a valid weight': 'กรอกน้ำหนักที่ถูกต้อง',
'Weight saved': 'บันทึกน้ำหนักแล้ว',
'Target weight': 'น้ำหนักเป้าหมาย',
'Your goal is drawn as a line through the weight charts, and gains/losses are colored by whether they move toward it.': 'เป้าหมายจะแสดงเป็นเส้นในกราฟน้ำหนัก และการเพิ่ม/ลดจะใช้สีบอกว่ากำลังเข้าใกล้เป้าหมายหรือไม่',
'Save goal': 'บันทึกเป้าหมาย',
'Goal set: {0}': 'ตั้งเป้าหมาย: {0}',
'{0} to go': 'เหลืออีก {0}',
'Goal removed': 'ลบเป้าหมายแล้ว',
'Remove goal': 'ลบเป้าหมาย',
'Body weight': 'น้ำหนักตัว',
'reached!': 'ถึงเป้าแล้ว!',
'{0} to gain': 'ต้องเพิ่มอีก {0}',
'{0} to lose': 'ต้องลดอีก {0}',
"No entries yet — log your weight to start the curve. It's also asked before every workout.": 'ยังไม่มีข้อมูล — บันทึกน้ำหนักเพื่อเริ่มกราฟ ระบบจะถามทุกครั้งก่อนออกกำลังกายด้วย',
// --- exercise detail / picker / config ---
'Best:': 'ดีที่สุด:',
'Add to my plan': 'เพิ่มเข้าแผนของฉัน',
'How to': 'วิธีทำ',
'instructions in English': 'คำแนะนำเป็นภาษาอังกฤษ',
'New routine': 'รูทีนใหม่',
'Add “{0}”': 'เพิ่ม “{0}”',
'“{0}” added to {1}': 'เพิ่ม “{0}” เข้า {1} แล้ว',
'Pick a routine — sets, reps & weight come next.': 'เลือกรูทีน — เซ็ต, ครั้ง และน้ำหนักตามมาทีหลัง',
'{0} exercises': '{0} ท่า',
'{0} exercise': '{0} ท่า',
'already in': 'มีอยู่แล้วใน',
'Create one and start with this exercise': 'สร้างใหม่และเริ่มด้วยท่านี้',
'Add exercise': 'เพิ่มท่าออกกำลังกาย',
'Search {0} exercises…': 'ค้นหาใน {0} ท่า…',
'Chosen': 'ที่เลือกไว้',
'Nothing chosen yet — add exercises and they’ll show up here.': 'ยังไม่ได้เลือกอะไรเลย — เพิ่มท่าออกกำลังกายแล้วจะโผล่มาที่นี่',
'No match': 'ไม่พบผลลัพธ์',
'Show more': 'แสดงเพิ่ม',
'Intervals': 'อินเทอร์วัล',
'Minutes': 'นาที',
'Speed (km/h)': 'ความเร็ว (กม./ชม.)',
'Sets': 'เซ็ต',
'Reps': 'ครั้ง',
'Weight ({0})': 'น้ำหนัก ({0})',
'Add to routine': 'เพิ่มเข้ารูทีน',
'Remove exercise': 'ลบท่าออกกำลังกาย',
'Remove {0}?': 'ลบ {0}?',
'The sets you logged for this exercise in this session will be lost.': 'เซ็ตที่บันทึกไว้สำหรับท่านี้ในรอบนี้จะหายไป',
'This removes the exercise from your current session.': 'จะลบท่านี้ออกจากรอบออกกำลังกายปัจจุบันของคุณ',
'Remove': 'ลบ',
'Which exercise in this superset do you want to remove?': 'ต้องการลบท่าไหนในซูเปอร์เซ็ตนี้?',
'Pick an icon': 'เลือกไอคอน',
// --- day planning / calendar ---
'Back to weekly plan': 'กลับไปแผนรายสัปดาห์',
'{0} set to rest': 'ตั้ง {0} เป็นวันพักแล้ว',
'{0} planned for {1}': 'วางแผน {0} ไว้สำหรับ {1}',
'Weekly plan:': 'แผนรายสัปดาห์:',
'changed for this day': 'เปลี่ยนสำหรับวันนี้',
'Sick, missed a day or want a different session? Pick what to train instead.': 'ป่วย, ขาดวัน หรืออยากเปลี่ยนโปรแกรม? เลือกสิ่งที่จะฝึกแทนได้เลย',
'Rest / skip this day': 'พัก / ข้ามวันนี้',
'Rest day': 'วันพัก',
'{0} workout': '{0} ครั้ง',
'{0} workouts': '{0} ครั้ง',
'No workouts this month': 'ไม่มีการออกกำลังกายในเดือนนี้',
'Trained': 'ออกกำลังกายแล้ว',
'Planned': 'วางแผนไว้',
'Rescheduled': 'เลื่อนแล้ว',
'Tap a trained day for details · tap any other day to plan a session': 'แตะวันที่ออกกำลังกายแล้วเพื่อดูรายละเอียด · แตะวันอื่นเพื่อวางแผน',
// --- workout lifecycle ---
'{0} sets': '{0} เซ็ต',
'no sets': 'ไม่มีเซ็ต',
'Delete workout?': 'ลบการออกกำลังกายนี้?',
'This removes it from your history for good.': 'จะลบออกจากประวัติอย่างถาวร',
'Workout deleted': 'ลบการออกกำลังกายแล้ว',
'Delete workout': 'ลบการออกกำลังกาย',
'{0} done': 'เสร็จแล้ว {0}',
'Confirm the weight you worked with — your highest becomes the default next time.': 'ยืนยันน้ำหนักที่ใช้ — น้ำหนักสูงสุดจะถูกตั้งเป็นค่าเริ่มต้นในครั้งถัดไป',
'Then finish the superset partner.': 'จากนั้นทำท่าคู่ซูเปอร์เซ็ตให้เสร็จ',
'Previous best:': 'สถิติก่อนหน้า:',
'new record!': 'สถิติใหม่!',
'Save & next exercise': 'บันทึกแล้วไปท่าถัดไป',
'Just close': 'ปิดเฉยๆ',
'Save weight': 'บันทึกน้ำหนัก',
'Tracked — next time starts at {0}': 'บันทึกแล้ว — ครั้งถัดไปเริ่มที่ {0}',
"That's the whole workout!": 'ครบทุกท่าแล้ว!',
'Every exercise done — great work. Finish up, or keep going and add another exercise.': 'ทำครบทุกท่าแล้ว เยี่ยมมาก จะจบเลยหรือเพิ่มท่าต่อก็ได้',
'Finish workout': 'จบการออกกำลังกาย',
'Continue workout': 'ออกกำลังกายต่อ',
'Keep going — tap “+ Add exercise” below': 'ทำต่อได้เลย — แตะ “+ เพิ่มท่าออกกำลังกาย” ด้านล่าง',
'Workout complete!': 'ออกกำลังกายเสร็จสิ้น!',
'Duration': 'ระยะเวลา',
'Volume': 'ปริมาณงาน',
'PRs': 'สถิติใหม่',
'New PR:': 'สถิติใหม่:',
'Nice!': 'เยี่ยม!',
'Nothing logged yet': 'ยังไม่มีการบันทึก',
'You haven’t checked off any sets. Finish the workout anyway?': 'คุณยังไม่ได้ติ๊กเซ็ตไหนเลย จะจบการออกกำลังกายเลยไหม?',
'Finish anyway': 'จบเลย',
'Finish early?': 'จบก่อนกำหนด?',
'{0} set still unchecked. Finish the workout now?': 'ยังมี {0} เซ็ตที่ยังไม่ติ๊ก จะจบตอนนี้เลยไหม?',
'{0} sets still unchecked. Finish the workout now?': 'ยังมี {0} เซ็ตที่ยังไม่ติ๊ก จะจบตอนนี้เลยไหม?',
// --- workout view ---
'Start workout': 'เริ่มออกกำลังกาย',
'today is {0}': 'วันนี้คือ {0}',
'rest day, but no one’s stopping you': 'วันพัก แต่ไม่มีใครห้ามคุณได้หรอก',
"Today's plan": 'แผนวันนี้',
'Start {0} ▶': 'เริ่ม {0} ▶',
'Other routines': 'รูทีนอื่น',
'Start ▶': 'เริ่ม ▶',
'Freestyle workout (pick as you go)': 'ออกกำลังกายแบบฟรีสไตล์ (เลือกท่าไปเรื่อยๆ)',
'Build a plan first': 'สร้างแผนก่อน',
'Duration (min)': 'ระยะเวลา (นาที)',
'Last time': 'ครั้งก่อน',
'Last time you hit all reps — try {0}': 'ครั้งก่อนทำครบทุกครั้งแล้ว — ลอง {0}',
'Weights bumped to {0}': 'เพิ่มน้ำหนักเป็น {0}',
'Remove set': 'ลบเซ็ต',
'Warm-up': 'วอร์มอัพ',
'Add warm-up set': 'เพิ่มเซ็ตวอร์มอัพ',
'Add set': 'เพิ่มเซ็ต',
'+ Drop': '+ ดรอป',
'+ Burst': '+ เบิร์สต์',
'Drop {0}': 'ดรอป {0}',
'Burst {0}': 'เบิร์สต์ {0}',
'Remove drop': 'ลบดรอป',
'Remove burst': 'ลบเบิร์สต์',
'Rest (s)': 'พัก (วินาที)',
'Drop-set / rest-pause': 'ดรอปเซ็ต / เรสต์-พอส',
'Intensifier': 'เทคนิคเพิ่มความหนัก',
'None': 'ไม่มี',
'Drop-set': 'ดรอปเซ็ต',
'Rest-pause': 'เรสต์-พอส',
'Drops': 'จำนวนดรอป',
'Weight drop (%)': 'ลดน้ำหนัก (%)',
'Rest-pause reps': 'จำนวนครั้งเรสต์-พอส',
'Rest-pause rest': 'พักเรสต์-พอส',
'Every set becomes a drop-set: after the main set, {0} drop(s) with no rest, each about {1}% lighter.': 'ทุกเซ็ตจะกลายเป็นดรอปเซ็ต: หลังเซ็ตหลักจะมี {0} ดรอปโดยไม่พัก แต่ละดรอปเบาลงประมาณ {1}%',
'Every set becomes rest-pause: {0} reps to start, then {1} more split into short bursts, {2}s rest before each, roughly halving each time.': 'ทุกเซ็ตจะกลายเป็นเรสต์-พอส: เริ่มด้วย {0} ครั้ง จากนั้นอีก {1} ครั้งแบ่งเป็นชุดสั้น ๆ พัก {2} วินาทีก่อนแต่ละชุด โดยลดลงเกือบครึ่งทุกครั้ง',
'Cardio logged': 'บันทึกคาร์ดิโอแล้ว',
'Discard workout?': 'ทิ้งการออกกำลังกายนี้?',
'The sets you logged in this session will be lost.': 'เซ็ตที่บันทึกไว้ในรอบนี้จะหายไป',
'Superset {0} / {1}': 'ซูเปอร์เซ็ต {0} / {1}',
'Exercise {0} / {1}': 'ท่า {0} / {1}',
'Superset · do these back-to-back, rest when done': 'ซูเปอร์เซ็ต · ทำต่อเนื่องกัน แล้วค่อยพักหลังทำครบทั้งคู่',
'Freestyle workout — add your first exercise.': 'ออกกำลังกายแบบฟรีสไตล์ — เพิ่มท่าแรกของคุณ',
'Finish workout early · {0} exercises': 'จบก่อนกำหนด · {0} ท่า',
'Rest over — next set!': 'หมดเวลาพัก — เซ็ตถัดไป!',
// --- home ---
'Hi {0}': 'สวัสดี {0}',
'This week': 'สัปดาห์นี้',
'{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)',
'Build my own plan': 'สร้างแผนของตัวเอง',
'{0} week streak': 'ต่อเนื่อง {0} สัปดาห์',
'this week': 'สัปดาห์นี้',
'{0} workout total': 'รวมทั้งหมด {0} ครั้ง',
'{0} workouts total': 'รวมทั้งหมด {0} ครั้ง',
// --- stats ---
'Progress & history': 'ความคืบหน้าและประวัติ',
'Workouts': 'การออกกำลังกาย',
'This month': 'เดือนนี้',
'Week streak': 'ต่อเนื่องรายสัปดาห์',
'Weight 30d': 'น้ำหนัก 30 วัน',
'Activity — last 12 months': 'กิจกรรม — 12 เดือนล่าสุด',
'by time trained': 'ตามเวลาที่ฝึก',
'Exercise progress': 'ความคืบหน้าของท่า',
'Top speed per workout': 'ความเร็วสูงสุดต่อครั้ง',
'Best set weight per workout': 'น้ำหนักเซ็ตดีที่สุดต่อครั้ง',
'Finish your first workout to see progress curves here.': 'จบการออกกำลังกายครั้งแรกเพื่อดูกราฟความคืบหน้าที่นี่',
'Recent workouts': 'การออกกำลังกายล่าสุด',
'Less time': 'เวลาน้อย',
'More time': 'เวลามาก',
'No data yet': 'ยังไม่มีข้อมูล',
// --- plan view ---
'Your weekly routine': 'รูทีนรายสัปดาห์ของคุณ',
'Week schedule': 'ตารางรายสัปดาห์',
'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 แผ่นต่อข้างทุกเซ็ต" หรืออะไรก็ตามที่อยากจดจำไว้',
'No exercises yet — add your first one.': 'ยังไม่มีท่า — เพิ่มท่าแรกของคุณ',
'Tap the link button on an exercise to superset it with the one above — you’ll do them back-to-back.': 'แตะปุ่มเชื่อมที่ท่าออกกำลังกายเพื่อทำเป็นซูเปอร์เซ็ตกับท่าด้านบน — จะทำต่อเนื่องกัน',
'Delete routine?': 'ลบรูทีนนี้?',
'“{0}” and its exercises will be removed.': '“{0}” และท่าทั้งหมดในนั้นจะถูกลบ',
'Delete routine': 'ลบรูทีน',
// --- 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': 'สร้างโปรไฟล์แล้ว — ย้ายข้อมูลจากเครื่องนี้เข้าไปแล้ว',
'Profile created — data moved into it': 'สร้างโปรไฟล์แล้ว — ย้ายข้อมูลเข้าไปแล้ว',
'Welcome, {0}': 'ยินดีต้อนรับ {0}',
'Welcome back, {0}': 'ยินดีต้อนรับกลับมา {0}',
'Registration failed': 'สมัครไม่สำเร็จ',
'Sign-in failed': 'เข้าสู่ระบบไม่สำเร็จ',
'Create your profile': 'สร้างโปรไฟล์ของคุณ',
'Pick a name, then confirm with {0}. The passkey is saved in your device — no password needed.': 'ตั้งชื่อแล้วยืนยันด้วย {0} พาสคีย์จะถูกเก็บไว้ในเครื่องคุณ — ไม่ต้องใช้รหัสผ่าน',
'Pick a name, then confirm with your device.': 'ตั้งชื่อแล้วยืนยันด้วยเครื่องของคุณ',
'Your name': 'ชื่อของคุณ',
'Create passkey': 'สร้างพาสคีย์',
'Your workouts. Your weights. Your profile.': 'การออกกำลังกายของคุณ น้ำหนักของคุณ โปรไฟล์ของคุณ',
'Sign in with passkey': 'เข้าสู่ระบบด้วยพาสคีย์',
'Create new profile': 'สร้างโปรไฟล์ใหม่',
"This browser doesn't support passkeys — you can still use openGym locally on this device.": 'เบราว์เซอร์นี้ไม่รองรับพาสคีย์ — แต่ยังใช้ openGym บนเครื่องนี้ได้ตามปกติ',
"This browser doesn't support passkeys, and this instance requires an account. Try a browser or device with passkey support.": 'เบราว์เซอร์นี้ไม่รองรับพาสคีย์ และเซิร์ฟเวอร์นี้ต้องมีบัญชีผู้ใช้ ลองใช้เบราว์เซอร์หรืออุปกรณ์ที่รองรับพาสคีย์',
'Continue without account': 'ใช้งานต่อโดยไม่มีบัญชี',
'Passkeys use {0} — no passwords.': 'พาสคีย์ใช้ {0} — ไม่ต้องใช้รหัสผ่าน',
'Each profile keeps its own plan, workouts & body weight.': 'แต่ละโปรไฟล์เก็บแผน, การออกกำลังกาย และน้ำหนักตัวของตัวเองแยกกัน',
// --- settings ---
'Account': 'บัญชี',
'Signed in with passkey — data syncs to this profile.': 'เข้าสู่ระบบด้วยพาสคีย์แล้ว — ข้อมูลจะซิงค์กับโปรไฟล์นี้',
'Sign out?': 'ออกจากระบบ?',
'Your data is synced to your profile first, then cleared from this device.': 'ข้อมูลจะถูกซิงค์กับโปรไฟล์ก่อน แล้วค่อยล้างออกจากเครื่องนี้',
'Sign out': 'ออกจากระบบ',
'Sign out everywhere?': 'ออกจากระบบทุกอุปกรณ์?',
'Signs this profile out on every device, including this one. Your passkeys keep working — sign in with them again anytime.': 'จะออกจากระบบโปรไฟล์นี้ในทุกอุปกรณ์ รวมถึงเครื่องนี้ด้วย พาสคีย์ของคุณยังใช้ได้ปกติ — เข้าสู่ระบบใหม่ได้ทุกเมื่อ',
'Sign out everywhere': 'ออกจากระบบทุกอุปกรณ์',
'Ends this profile’s sessions on all your devices.': 'จะยุติเซสชันของโปรไฟล์นี้ในทุกอุปกรณ์ของคุณ',
'Signed out on all devices': 'ออกจากระบบทุกอุปกรณ์แล้ว',
'Could not sign out everywhere — you are still signed in.': 'ออกจากระบบทุกอุปกรณ์ไม่สำเร็จ — คุณยังคงเข้าสู่ระบบอยู่',
'Guest mode — data lives only in this browser. Create a passkey profile to keep it safe and separate per person.': 'โหมดผู้เยี่ยมชม — ข้อมูลอยู่ในเบราว์เซอร์นี้เท่านั้น สร้างโปรไฟล์พาสคีย์เพื่อความปลอดภัยและแยกข้อมูลแต่ละคน',
'Create passkey profile': 'สร้างโปรไฟล์พาสคีย์',
'Passkeys not supported in this browser.': 'เบราว์เซอร์นี้ไม่รองรับพาสคีย์',
'Appearance': 'ลักษณะที่ปรากฏ',
'synced with your profile': 'ซิงค์กับโปรไฟล์ของคุณ',
'Language': 'ภาษา',
"Exercise instructions aren't available in this language yet — they stay in English.": 'คำแนะนำท่าออกกำลังกายยังไม่มีในภาษานี้ — จะแสดงเป็นภาษาอังกฤษ',
'Theme': 'ธีม',
'Dark': 'มืด',
'Light': 'สว่าง',
'System': 'ระบบ',
'Accent color': 'สีเน้น',
'General': 'ทั่วไป',
'During a workout': 'ระหว่างออกกำลังกาย',
'Keep screen awake': 'ไม่ให้จอปิด',
'The screen stays on while a workout is running, so you don’t have to unlock your phone between sets.': 'จอจะไม่ปิดขณะออกกำลังกาย จะได้ไม่ต้องปลดล็อกโทรศัพท์ระหว่างเซ็ต',
'Weight unit': 'หน่วยน้ำหนัก',
'Rest timer': 'ตัวจับเวลาพัก',
'Sounds': 'เสียง',
'Note: switching units only changes the label — logged numbers are not converted.': 'หมายเหตุ: การเปลี่ยนหน่วยจะเปลี่ยนแค่ป้ายกำกับ — ตัวเลขที่บันทึกไว้จะไม่ถูกแปลง',
'Data': 'ข้อมูล',
'Export backup (JSON)': 'ส่งออกข้อมูลสำรอง (JSON)',
'Import backup': 'นำเข้าข้อมูลสำรอง',
'Auto-backup on changes': 'สำรองข้อมูลอัตโนมัติเมื่อมีการเปลี่ยนแปลง',
'Saves a dated copy to the Documents folder after finishing a workout or editing a routine — point a sync app at it, or copy it out by hand.': 'บันทึกสำเนาที่มีวันที่กำกับไว้ในโฟลเดอร์ Documents หลังจบการออกกำลังกายหรือแก้ไขรูทีน — ตั้งแอปซิงก์ให้ชี้มาที่นี่ หรือคัดลอกออกไปเองก็ได้',
'Reset everything?': 'รีเซ็ตทุกอย่าง?',
'Reset everything': 'รีเซ็ตทุกอย่าง',
'Deletes your plan, workouts and body weight on this device. This cannot be undone.': 'จะลบแผน, การออกกำลังกาย และน้ำหนักตัวบนเครื่องนี้ ไม่สามารถย้อนกลับได้',
'Delete everything': 'ลบทุกอย่าง',
'All data reset': 'รีเซ็ตข้อมูลทั้งหมดแล้ว',
'Backup exported': 'ส่งออกข้อมูลสำรองแล้ว',
'Import backup?': 'นำเข้าข้อมูลสำรอง?',
'This replaces all current data with the backup file.': 'จะแทนที่ข้อมูลปัจจุบันทั้งหมดด้วยไฟล์สำรอง',
'Backup imported': 'นำเข้าข้อมูลสำรองแล้ว',
'Import failed: {0}': 'นำเข้าไม่สำเร็จ: {0}',
'Tip': 'เคล็ดลับ',
'In Chrome: ⋮ menu → Add to Home screen': 'ใน Chrome: เมนู ⋮ → เพิ่มไปยังหน้าจอหลัก',
'In Safari: Share → Add to Home Screen': 'ใน Safari: แชร์ → เพิ่มไปยังหน้าจอโฮม',
'to install openGym as a full-screen app.': 'เพื่อติดตั้ง openGym เป็นแอปเต็มหน้าจอ',
'Your data syncs with your profile — sign in anywhere to see it.': 'ข้อมูลของคุณซิงค์กับโปรไฟล์ — เข้าสู่ระบบที่ไหนก็เห็นข้อมูล',
'Guest data stays on this device — export a backup now and then!': 'ข้อมูลผู้เยี่ยมชมอยู่บนเครื่องนี้เท่านั้น — อย่าลืมส่งออกข้อมูลสำรองเป็นระยะ!',
'free & open source (AGPL v3)': 'ฟรีและโอเพนซอร์ส (AGPL v3)',
'Notifications': 'การแจ้งเตือน',
'Not supported in this browser.': 'เบราว์เซอร์นี้ไม่รองรับ',
'Push notifications': 'การแจ้งเตือนแบบพุช',
'Rest-timer alerts, even if openGym is closed.': 'แจ้งเตือนหมดเวลาพัก แม้ปิดแอป openGym อยู่',
'Workout day reminder': 'เตือนวันออกกำลังกาย',
'Reminder time': 'เวลาแจ้งเตือน',
"Only sent on days you have a routine planned and haven't logged a workout yet.": 'จะแจ้งเตือนเฉพาะวันที่มีแผนไว้และยังไม่ได้บันทึกการออกกำลังกาย',
'Timezone: {0} (auto-detected, updates if you travel).': 'เขตเวลา: {0} (ตรวจจับอัตโนมัติ อัปเดตเมื่อคุณเดินทาง)',
'Send test notification': 'ส่งการแจ้งเตือนทดสอบ',
'Test sent — should arrive any second': 'ส่งทดสอบแล้ว — น่าจะมาถึงในไม่กี่วินาที',
'Test failed': 'ทดสอบไม่สำเร็จ',
'Notifications off': 'ปิดการแจ้งเตือน',
'Notifications on': 'เปิดการแจ้งเตือน',
'Could not change notification settings': 'เปลี่ยนการตั้งค่าการแจ้งเตือนไม่สำเร็จ',
// --- media ---
'tap to pause': 'แตะเพื่อหยุดชั่วคราว',
'tap to play': 'แตะเพื่อเล่น',
// --- data terms: body parts ---
'back': 'หลัง', 'cardio': 'คาร์ดิโอ', 'chest': 'อก', 'lower arms': 'แขนท่อนล่าง',
'lower legs': 'ขาท่อนล่าง', 'neck': 'คอ', 'shoulders': 'ไหล่',
'upper arms': 'แขนท่อนบน', 'upper legs': 'ขาท่อนบน', 'waist': 'เอว',
// --- data terms: equipment ---
'Details': 'รายละเอียด',
'Finish': 'เสร็จสิ้น',
'Start {0}': 'เริ่ม {0}',
'Guest mode — data lives only in this browser.': 'โหมดผู้เยี่ยมชม — ข้อมูลอยู่ในเบราว์เซอร์นี้เท่านั้น',
'Keeps your data safe and separate per person.': 'เก็บข้อมูลของคุณให้ปลอดภัยและแยกตามแต่ละคน',
'Strength': 'ความแข็งแรง',
'Equipment': 'อุปกรณ์',
'Recovery': 'การฟื้นตัว',
'Any equipment': 'อุปกรณ์ใดก็ได้',
'assisted': 'มีตัวช่วย', 'band': 'ยางยืด', 'barbell': 'บาร์เบล', 'body weight': 'น้ำหนักตัว',
'bosu ball': 'บอลโบซู', 'cable': 'สายเคเบิล', 'dumbbell': 'ดัมเบล',
'elliptical machine': 'เครื่องเอลลิปติคัล', 'ez barbell': 'อีซีบาร์', 'hammer': 'แฮมเมอร์',
'kettlebell': 'เคทเทิลเบล', 'leverage machine': 'เครื่องคานงัด', 'medicine ball': 'เมดิซินบอล',
'olympic barbell': 'บาร์เบลโอลิมปิก', 'resistance band': 'ยางยืดออกกำลังกาย', 'roller': 'ลูกกลิ้ง',
'rope': 'เชือก', 'skierg machine': 'เครื่องสกีเอิร์ก', 'sled machine': 'สเลด',
'smith machine': 'สมิธแมชชีน', 'stability ball': 'บอลออกกำลังกาย', 'stationary bike': 'จักรยานปั่นอยู่กับที่',
'stepmill machine': 'เครื่องเดินขึ้นบันได', 'tire': 'ยางรถ', 'trap bar': 'แทร็ปบาร์',
'upper body ergometer': 'เครื่องปั่นแขน', 'weighted': 'มีน้ำหนักถ่วง', 'wheel roller': 'ล้อกลิ้งหน้าท้อง',
// --- data terms: targets & muscles ---
'abductors': 'กล้ามเนื้อกางขา', 'abs': 'หน้าท้อง', 'adductors': 'กล้ามเนื้อหุบขา', 'biceps': 'ไบเซ็ป',
'calves': 'น่อง', 'cardiovascular system': 'ระบบหัวใจและหลอดเลือด', 'delts': 'ไหล่',
'forearms': 'แขนท่อนล่าง', 'glutes': 'สะโพก', 'hamstrings': 'ต้นขาด้านหลัง', 'lats': 'ปีกหลัง',
'levator scapulae': 'กล้ามเนื้อยกสะบัก', 'pectorals': 'กล้ามเนื้ออก', 'quads': 'ต้นขาด้านหน้า',
'serratus anterior': 'กล้ามเนื้อซี่โครงด้านข้าง', 'spine': 'กระดูกสันหลัง', 'traps': 'กล้ามเนื้อบ่า',
'triceps': 'ไทรเซ็ป', 'upper back': 'หลังส่วนบน',
'abdominals': 'หน้าท้อง', 'ankle stabilizers': 'กล้ามเนื้อพยุงข้อเท้า', 'ankles': 'ข้อเท้า',
'brachialis': 'กล้ามเนื้อแขนงอ', 'core': 'แกนกลางลำตัว', 'deltoids': 'กล้ามเนื้อไหล่', 'feet': 'เท้า',
'grip muscles': 'กล้ามเนื้อการจับ', 'groin': 'ขาหนีบ', 'hands': 'มือ', 'hip flexors': 'กล้ามเนื้องอสะโพก',
'inner thighs': 'ต้นขาด้านใน', 'latissimus dorsi': 'ปีกหลัง', 'lower abs': 'หน้าท้องส่วนล่าง',
'lower back': 'หลังส่วนล่าง', 'obliques': 'กล้ามเนื้อข้างลำตัว', 'quadriceps': 'ต้นขาด้านหน้า',
'rear deltoids': 'ไหล่ด้านหลัง', 'rhomboids': 'กล้ามเนื้อสะบักคู่', 'rotator cuff': 'เอ็นหมุนไหล่',
'shins': 'หน้าแข้ง', 'soleus': 'กล้ามเนื้อน่องด้านใน', 'sternocleidomastoid': 'กล้ามเนื้อคอ',
'trapezius': 'กล้ามเนื้อบ่า', 'upper chest': 'อกส่วนบน', 'wrist extensors': 'กล้ามเนื้อเหยียดข้อมือ',
'wrist flexors': 'กล้ามเนื้องอข้อมือ', 'wrists': 'ข้อมือ',
// --- custom exercises (#11) ---
'Create your own exercise': 'สร้างท่าออกกำลังกายของตัวเอง',
'Edit custom exercise': 'แก้ไขท่าที่สร้างเอง',
'Name it and pick a body part — it behaves like any other exercise, just without an animation.': 'ตั้งชื่อและเลือกส่วนร่างกาย — ใช้งานเหมือนท่าปกติ แค่ไม่มีภาพเคลื่อนไหว',
'Exercise name': 'ชื่อท่าออกกำลังกาย',
'name + body part, no animation': 'ชื่อ + ส่วนร่างกาย ไม่มีภาพเคลื่อนไหว',
'Create exercise': 'สร้างท่าออกกำลังกาย',
'Give it a name': 'ตั้งชื่อให้',
'Pick a body part': 'เลือกส่วนร่างกาย',
'“{0}” already exists': '“{0}” มีอยู่แล้ว',
'“{0}” created': 'สร้าง “{0}” แล้ว',
'Cardio exercises log time + speed instead of weight × reps.': 'ท่าคาร์ดิโอจะบันทึกเวลา + ความเร็ว แทนน้ำหนัก × จำนวนครั้ง',
'custom': 'สร้างเอง',
'Edit': 'แก้ไข',
'Saved': 'บันทึกแล้ว',
'Delete “{0}”?': 'ลบ “{0}”?',
'It will be removed from your routines. Already-logged workouts keep their sets.': 'จะถูกลบออกจากรูทีนของคุณ ส่วนการออกกำลังกายที่บันทึกไว้แล้วจะยังคงเซ็ตเดิมไว้',
'Exercise deleted': 'ลบท่าออกกำลังกายแล้ว',
'Finish your current workout first': 'จบการออกกำลังกายปัจจุบันก่อน',
'Description (optional) — setup, cues, anything you want to remember': 'คำอธิบาย (ไม่บังคับ) — วิธีตั้งท่า, จุดสังเกต หรืออะไรก็ตามที่อยากจำ',
'Delete exercise': 'ลบท่าออกกำลังกาย',
'Edit or delete this exercise': 'แก้ไขหรือลบท่านี้',
'Remove from routine': 'ลบออกจากรูทีน',
'Minimize': 'ย่อ',
'Expand': 'ขยาย',
'Invite code': 'รหัสเชิญ',
'This app is invite-only — enter the code you were given.': 'แอปนี้ต้องมีรหัสเชิญ — กรอกรหัสที่ได้รับมา',
'An invite code is required': 'ต้องมีรหัสเชิญ',
'Admin dashboard': 'แดชบอร์ดผู้ดูแลระบบ',
// --- muscle map ---
'Muscle balance': 'ความสมดุลของกล้ามเนื้อ',
'Fatigue': 'ความล้า',
'Ready': 'พร้อม',
'Recovering': 'กำลังฟื้นตัว',
'Fatigued': 'ล้า',
'Fatigue shows how recently each muscle was trained. High means rest.': 'ความล้าแสดงว่าแต่ละกล้ามเนื้อถูกฝึกเมื่อไหร่ ค่าสูงหมายถึงควรพัก',
'Strength shows retained muscle strength. Train again to reset it.': 'ความแข็งแรงแสดงกำลังกล้ามเนื้อที่ยังคงเหลืออยู่ ฝึกอีกครั้งเพื่อรีเซ็ตค่านี้',
'full': 'เต็ม',
'floor': 'ต่ำสุด',
'Weeks since training: {0}': 'ไม่ได้ฝึกมา {0} สัปดาห์',
'by sets worked': 'ตามจำนวนเซ็ตที่ฝึก',
'Week': 'สัปดาห์',
'not trained': 'ยังไม่ได้ฝึก',
'Not trained in this period': 'ยังไม่ได้ฝึกในช่วงนี้',
'Every muscle group got some work in this period.': 'ทุกกลุ่มกล้ามเนื้อได้รับการฝึกในช่วงนี้แล้ว',
'No workouts in this period yet.': 'ยังไม่มีการออกกำลังกายในช่วงนี้',
'What this session hits': 'ท่านี้ฝึกกล้ามเนื้อส่วนไหนบ้าง',
'What you just trained': 'สิ่งที่เพิ่งฝึกไป',
'Body diagram': 'แผนภาพร่างกาย',
'Male': 'ชาย',
'Female': 'หญิง',
'Less': 'น้อย',
'More': 'มาก',
'Traps': 'กล้ามเนื้อบ่า',
'Shoulders': 'ไหล่',
'Chest': 'อก',
'Upper back': 'หลังส่วนบน',
'Serratus': 'กล้ามเนื้อซี่โครงด้านข้าง',
'Biceps': 'ไบเซ็ป',
'Triceps': 'ไทรเซ็ป',
'Forearms': 'แขนท่อนล่าง',
'Abs': 'หน้าท้อง',
'Obliques': 'กล้ามเนื้อข้างลำตัว',
'Lower back': 'หลังส่วนล่าง',
'Glutes': 'สะโพก',
'Quads': 'ต้นขาด้านหน้า',
'Hamstrings': 'ต้นขาด้านหลัง',
'Adductors': 'กล้ามเนื้อหุบขา',
'Hip flexors': 'กล้ามเนื้องอสะโพก',
'Calves': 'น่อง',
'Shins': 'หน้าแข้ง',
// --- import from another app ---
'Import from another app': 'นำเข้าจากแอปอื่น',
'FitNotes, Strong, Hevy — or body weight from Apple Health': 'FitNotes, Strong, Hevy — หรือน้ำหนักตัวจาก Apple Health',
'Import from {0}': 'นำเข้าจาก {0}',
'Import history': 'นำเข้าประวัติ',
'Weigh-ins': 'บันทึกน้ำหนัก',
'Exercises matched': 'ท่าที่จับคู่ได้',
'Added as your own': 'เพิ่มเป็นท่าของตัวเอง',
'The file is in {0} and your profile is in {1} — weights will be converted.': 'ไฟล์เป็นหน่วย {0} ส่วนโปรไฟล์คุณเป็น {1} — น้ำหนักจะถูกแปลงหน่วยให้',
'The file does not say which unit it uses — numbers are imported as they are.': 'ไฟล์ไม่ได้ระบุหน่วยที่ใช้ — จะนำเข้าตัวเลขตามที่เป็นอยู่',
'The file mixes kg and lb — each set is converted to {0}.': 'ไฟล์มีทั้ง kg และ lb ปนกัน — แต่ละเซ็ตจะถูกแปลงเป็น {0}',
'{0} days already have data here and will be left alone.': '{0} วันมีข้อมูลอยู่แล้ว จะไม่ถูกเปลี่ยนแปลง',
'Not in the library — added as your own exercises': 'ไม่มีในคลังท่า — เพิ่มเป็นท่าของตัวเองแล้ว',
'Nothing new to import': 'ไม่มีอะไรใหม่ให้นำเข้า',
'{0} workouts imported': 'นำเข้าการออกกำลังกาย {0} ครั้งแล้ว',
'{0} weigh-ins imported': 'นำเข้าบันทึกน้ำหนัก {0} รายการแล้ว',
'Could not read that file': 'อ่านไฟล์นั้นไม่ได้',
'That file is empty': 'ไฟล์นั้นว่างเปล่า',
"That file's columns aren't recognised — see the docs for supported apps.": 'ไม่รู้จักคอลัมน์ในไฟล์นั้น — ดูรายชื่อแอปที่รองรับได้ในเอกสาร',
'Nothing to import from that file': 'ไม่มีอะไรให้นำเข้าจากไฟล์นั้น',
// --- mobile build ---
'Your data': 'ข้อมูลของคุณ',
'All data stays on this phone': 'ข้อมูลทั้งหมดอยู่บนโทรศัพท์เครื่องนี้',
'No account, no cloud — back it up anytime with Export below.': 'ไม่ต้องมีบัญชี ไม่ต้องใช้คลาวด์ — สำรองข้อมูลได้ทุกเมื่อผ่านปุ่มส่งออกด้านล่าง',
'Reminds you at this time on days that have a routine planned.': 'จะเตือนคุณตามเวลานี้ในวันที่มีรูทีนวางแผนไว้',
'Workout day': 'วันออกกำลังกาย',
'{0} is on the plan today — let’s go!': 'วันนี้มี {0} ในแผน — ลุยเลย!',
// --- plan sharing ---
'Share your plan': 'แชร์แผนของคุณ',
'Send your routines to a friend, or put your week on paper.': 'ส่งรูทีนให้เพื่อน หรือพิมพ์แผนรายสัปดาห์ออกมาเป็นกระดาษ',
'Export plan file': 'ส่งออกไฟล์แผน',
'A small file a friend imports into their own openGym — routines only, none of your workouts or weigh-ins.': 'ไฟล์เล็กๆ ให้เพื่อนนำเข้า openGym ของตัวเอง — มีแค่รูทีนเท่านั้น ไม่มีการออกกำลังกายหรือน้ำหนักของคุณ',
'Print / Save as PDF': 'พิมพ์ / บันทึกเป็น PDF',
'A clean one-page-per-plan printout — no exercise ever splits across a page.': 'พิมพ์ออกมาสวยงาม 1 หน้าต่อ 1 แผน — ไม่มีท่าไหนถูกตัดข้ามหน้า',
'Add an exercise to a routine first — an empty plan has nothing to share.': 'เพิ่มท่าเข้ารูทีนก่อน — แผนว่างเปล่าไม่มีอะไรให้แชร์',
'Got a plan from a friend?': 'ได้รับแผนจากเพื่อนหรือเปล่า?',
'Import a plan file': 'นำเข้าไฟล์แผน',
'Plan file saved — send it to a friend': 'บันทึกไฟล์แผนแล้ว — ส่งให้เพื่อนได้เลย',
'{0}’s plan': 'แผนของ {0}',
'Import “{0}”': 'นำเข้า “{0}”',
'Import this plan': 'นำเข้าแผนนี้',
'{0} routine': '{0} รูทีน',
'{0} routines': '{0} รูทีน',
'scheduled on {0} days': 'วางแผนไว้ {0} วัน',
'scheduled on {0} day': 'วางแผนไว้ {0} วัน',
'These are added as new routines — nothing you already have is changed.': 'จะถูกเพิ่มเป็นรูทีนใหม่ — ของเดิมที่มีอยู่จะไม่ถูกเปลี่ยนแปลง',
'{0} exercise in the file isn’t in your library and was left out.': 'มี {0} ท่าในไฟล์ที่ไม่มีในคลังของคุณ จึงถูกข้ามไป',
'{0} exercises in the file aren’t in your library and were left out.': 'มี {0} ท่าในไฟล์ที่ไม่มีในคลังของคุณ จึงถูกข้ามไป',
'Use this weekly schedule': 'ใช้ตารางรายสัปดาห์นี้',
'Replaces your current Mon–Sun assignments.': 'จะแทนที่ตารางจันทร์–อาทิตย์ปัจจุบันของคุณ',
'Added {0} routines to your plan': 'เพิ่ม {0} รูทีนเข้าแผนของคุณแล้ว',
'this isn’t an openGym plan file': 'นี่ไม่ใช่ไฟล์แผนของ openGym',
'Shared routine': 'รูทีนที่แชร์มา',
'Unknown exercise': 'ท่าที่ไม่รู้จัก',
'Weekly Training Plan': 'แผนการฝึกรายสัปดาห์',
'Made with openGym': 'สร้างด้วย openGym',
'Something went wrong': 'มีบางอย่างผิดพลาด',
'This screen could not be drawn. Your data is safe on this device.': 'แสดงหน้าจอนี้ไม่ได้ ข้อมูลของคุณยังปลอดภัยอยู่บนเครื่องนี้',
'Reload openGym': 'โหลด openGym ใหม่',
'Discard the running workout': 'ทิ้งการออกกำลังกายที่กำลังทำอยู่',
// --- v1.2.2: timed sets, progression, estimated 1RM (#16 #17 #18) ---
'Top set': 'เซ็ตที่หนักที่สุด',
'Est. 1RM': '1RM โดยประมาณ',
'Estimated 1RM': '1RM โดยประมาณ',
'Estimated 1RM per workout': '1RM โดยประมาณต่อครั้ง',
'Best estimate from {0} on {1} — an estimate, not a tested max.': 'ประมาณการดีที่สุดจาก {0} เมื่อ {1} — เป็นค่าประมาณ ไม่ใช่ค่าที่ทดสอบจริง',
'From your log:': 'จากบันทึกของคุณ:',
'{0} × {1} on {2}': '{0} × {1} เมื่อ {2}',
'Estimate': 'ประมาณการ',
'Enter a weight and 1–{0} reps — beyond that an estimate is guesswork.': 'กรอกน้ำหนักและ 1–{0} ครั้ง — เกินจากนี้การประมาณจะไม่แม่นยำ',
'Epley formula — a calculation from one set, not a tested max.': 'สูตร Epley — คำนวณจากหนึ่งเซ็ต ไม่ใช่ค่าที่ทดสอบจริง',
'Best estimated 1RM:': '1RM โดยประมาณดีที่สุด:',
'Time': 'เวลา',
'Seconds': 'วินาที',
'A timer runs while you hold the set. Leave the weight at 0 for bodyweight holds.': 'ตัวจับเวลาจะทำงานขณะทำเซ็ตค้าง ปล่อยน้ำหนักไว้ที่ 0 สำหรับท่าค้างด้วยน้ำหนักตัว',
'Done': 'เสร็จแล้ว',
'Start set': 'เริ่มเซ็ต',
'Hold logged': 'บันทึกเวลาค้างแล้ว',
'Longest hold per workout': 'เวลาค้างนานที่สุดต่อครั้ง',
'Progression': 'การเพิ่มระดับ',
'Rule': 'กฎ',
'Follow the routine ({0})': 'ตามกฎของรูทีน ({0})',
'Applies to every exercise in this routine that does not set its own rule.': 'ใช้กับทุกท่าในรูทีนนี้ที่ไม่ได้ตั้งกฎเฉพาะของตัวเอง',
'Step ({0})': 'ขั้นละ ({0})',
'Step (seconds)': 'ขั้นละ (วินาที)',
'Reps from': 'จำนวนครั้งเริ่มจาก',
'No automatic progression': 'ไม่มีการเพิ่มระดับอัตโนมัติ',
'Linear progression': 'เพิ่มแบบเส้นตรง',
'Greyskull LP': 'Greyskull LP',
'Double progression': 'เพิ่มระดับคู่',
'Add time': 'เพิ่มเวลา',
'Targets stay where you set them.': 'เป้าหมายจะคงที่ตามที่คุณตั้งไว้',
'Hit every rep in every set and the weight goes up. Repeated misses trigger a deload.': 'ทำครบทุกครั้งในทุกเซ็ตแล้วน้ำหนักจะเพิ่มขึ้น ถ้าพลาดซ้ำๆ จะลดน้ำหนักลง',
'Two straight sets plus a final set taken to failure. Beat the target on that set and the weight goes up — double if you double the reps. One failure resets 10 %.': 'สองเซ็ตแรกตามปกติ บวกเซ็ตสุดท้ายที่ทำจนหมดแรง ถ้าทำได้เกินเป้าในเซ็ตนั้น น้ำหนักจะเพิ่มขึ้น — เพิ่มเป็นสองเท่าถ้าทำจำนวนครั้งได้สองเท่า พลาดหนึ่งครั้งจะลดลง 10%',
'Work up through a rep range at the same weight. Reach the top of the range in every set and the weight goes up, reps back to the bottom.': 'ไต่ระดับจำนวนครั้งด้วยน้ำหนักเดิม ถ้าถึงจำนวนครั้งสูงสุดในทุกเซ็ต น้ำหนักจะเพิ่มขึ้นและจำนวนครั้งกลับไปเริ่มที่ต่ำสุด',
'Hold every set for the full duration and the target goes up.': 'ค้างทุกเซ็ตให้ครบเวลา แล้วเป้าหมายจะเพิ่มขึ้น',
'Nothing logged yet — this session sets the baseline.': 'ยังไม่มีการบันทึก — ครั้งนี้จะเป็นค่าเริ่มต้น',
'Held every set for the full time — target up by {0}s.': 'ค้างครบเวลาทุกเซ็ต — เพิ่มเป้าหมายอีก {0} วินาที',
'Short {0} sessions in a row — back off to {1}s and build up again.': 'ทำได้ไม่ครบเวลาติดต่อกัน {0} ครั้ง — ลดกลับไปที่ {1} วินาที แล้วค่อยไต่ขึ้นใหม่',
'Last time came up short — same target again.': 'ครั้งก่อนทำไม่ครบ — ใช้เป้าหมายเดิมอีกครั้ง',
'Top of the rep range in every set — {0} {1} more, back to {2} reps.': 'ถึงจำนวนครั้งสูงสุดในทุกเซ็ต — เพิ่มอีก {0} {1} กลับไปที่ {2} ครั้ง',
'Stalled {0} sessions — deload to {1} {2}.': 'ไม่คืบหน้า {0} ครั้ง — ลดน้ำหนักลงเหลือ {1} {2}',
'Same weight — aim for {0} reps this time.': 'น้ำหนักเดิม — ตั้งเป้าที่ {0} ครั้งในรอบนี้',
'Last set hit {0} reps — twice the target, so take a double jump of {1} {2}.': 'เซ็ตสุดท้ายทำได้ {0} ครั้ง — เกินเป้าสองเท่า จึงเพิ่มน้ำหนักแบบก้าวกระโดด {1} {2}',
'Every rep last time — {0} {1} more.': 'ครั้งก่อนทำครบทุกครั้ง — เพิ่มอีก {0} {1}',
'Missed reps {0} sessions running — reset to {1} {2} and work back up.': 'พลาดจำนวนครั้งติดต่อกัน {0} ครั้ง — รีเซ็ตกลับไปที่ {1} {2} แล้วค่อยไต่ขึ้นใหม่',
'Missed reps — reset to {0} {1} and work back up.': 'พลาดจำนวนครั้ง — รีเซ็ตกลับไปที่ {0} {1} แล้วค่อยไต่ขึ้นใหม่',
'Missed reps last time — same weight again ({0} of {1} to go).': 'ครั้งก่อนพลาดจำนวนครั้ง — น้ำหนักเดิมอีกครั้ง (เหลืออีก {0} จาก {1})',
'Bodyweight — every rep last time, so go for {0} this time.': 'น้ำหนักตัว — ครั้งก่อนทำครบทุกครั้ง รอบนี้ลองตั้งเป้าที่ {0}',
'Bodyweight — same target again until every set is clean.': 'น้ำหนักตัว — ใช้เป้าหมายเดิมจนกว่าจะทำครบทุกเซ็ต',
// --- effort per set (RIR / RPE) ---
'{0} sets bring an {1} with them — switch on Effort per set in Settings to see it.': '{0} เซ็ตมาพร้อม {1} — เปิด “ความหนักต่อเซ็ต” ในตั้งค่าเพื่อดู',
'{0} sets bring an {1} with them.': '{0} เซ็ตมาพร้อม {1}',
'RIR': 'RIR',
'RPE': 'RPE',
'Effort per set': 'ความหนักต่อเซ็ต',
'What are RIR and RPE?': 'RIR และ RPE คืออะไร?',
'How hard a set was, logged next to weight and reps. Two scales for the same judgement, counted from opposite ends.': 'ความหนักของแต่ละเซ็ต บันทึกคู่กับน้ำหนักและจำนวนครั้ง เป็นสองมาตรวัดของสิ่งเดียวกัน นับจากคนละด้าน',
'How it felt': 'รู้สึกยังไง',
'Nothing left — went to failure': 'ไม่เหลือแรงแล้ว — ทำจนหมดแรง',
'One more rep in the tank': 'ยังเหลืออีกหนึ่งครั้งถ้าจะฝืน',
'Two more reps': 'ยังเหลืออีกสองครั้ง',
'Three more reps': 'ยังเหลืออีกสามครั้ง',
'Easy — warm-up territory': 'ง่าย — ระดับวอร์มอัป',
'RIR counts the reps you left; RPE reads the same effort off a 10-point scale — so RPE ≈ 10 − RIR. Pick the one you already think in.': 'RIR นับจำนวนครั้งที่เหลือ ส่วน RPE วัดความหนักเดียวกันบนสเกล 10 ระดับ — ดังนั้น RPE ≈ 10 − RIR เลือกแบบที่คุณคุ้นเคยได้เลย',
'The highlighted row is where most working sets land. Sets you have already logged keep their own scale, and nothing else reads the value — progression and estimated 1RM are unaffected.': 'แถวที่ไฮไลต์คือช่วงที่เซ็ตส่วนใหญ่มักอยู่ เซ็ตที่บันทึกไปแล้วจะคงมาตรวัดเดิมไว้ และไม่มีส่วนอื่นนำค่านี้ไปใช้ — การเพิ่มระดับและ 1RM โดยประมาณจะไม่ได้รับผลกระทบ',
// --- effort in the stats ---
'Effort': 'ความหนัก',
'how close to failure': 'ใกล้หมดแรงแค่ไหน',
'by hard sets': 'ตามจำนวนเซ็ตที่หนัก',
'Hard': 'หนัก',
'no hard sets': 'ไม่มีเซ็ตที่หนัก',
'No hard sets in this period': 'ไม่มีเซ็ตที่หนักในช่วงนี้',
'Every muscle group got at least one hard set in this period.': 'ทุกกลุ่มกล้ามเนื้อได้เซ็ตหนักอย่างน้อยหนึ่งเซ็ตในช่วงนี้',
'No rated sets in this period.': 'ไม่มีเซ็ตที่ให้คะแนนในช่วงนี้',
'average effort': 'ความหนักเฉลี่ย',
'at {0} {1} or harder': 'ที่ {0} {1} ขึ้นไป',
'{0} of {1} finished sets rated': 'ให้คะแนนแล้ว {0} จาก {1} เซ็ตที่ทำเสร็จ',
'Effort per set is switched off — turn it on in Settings to keep rating.': 'ปิด “ความหนักต่อเซ็ต” อยู่ — เปิดในตั้งค่าเพื่อให้คะแนนต่อ',
'Week by week': 'รายสัปดาห์',
'Where the sets land': 'เซ็ตส่วนใหญ่อยู่ระดับไหน',
'Most working sets belong close to failure without living there — half at the floor and half at the top average out to a healthy-looking middle.': 'เซ็ตส่วนใหญ่ควรอยู่ใกล้จุดหมดแรงโดยไม่ถึงจุดนั้น — ครึ่งหนึ่งอยู่ต่ำสุดและครึ่งหนึ่งอยู่สูงสุด เฉลี่ยแล้วจะออกมาสมดุลดี',
'Average effort per workout': 'ความหนักเฉลี่ยต่อครั้ง',
'A fuller dot means less left in the tank — the same weight at a lower {0} is progress the line alone does not show.': 'จุดที่เต็มกว่าหมายถึงเหลือแรงน้อยกว่า — น้ำหนักเท่าเดิมที่ {0} ต่ำกว่าคือความคืบหน้าที่กราฟเส้นเพียงอย่างเดียวไม่แสดงให้เห็น',
// --- bodyweight & per side ---
'Bodyweight': 'น้ำหนักตัว',
'No weight to enter — just log the reps.': 'ไม่ต้องกรอกน้ำหนัก — บันทึกแค่จำนวนครั้ง',
'Ask for a weight on every set.': 'ถามน้ำหนักทุกเซ็ต',
'For dips or pull-ups with a belt. Progression then follows the weight.': 'สำหรับท่าดิปหรือพูลอัพที่ใช้เข็มขัดถ่วงน้ำหนัก การเพิ่มระดับจะอิงตามน้ำหนักแทน',
'Reps per side': 'จำนวนครั้งต่อข้าง',
'For lunges, single-arm rows and the like.': 'สำหรับท่าลันจ์, โรว์แขนเดียว และท่าคล้ายกัน',
'Top of the range': 'จำนวนครั้งสูงสุด',
'Reps climb by one whenever every set was clean. Set a ceiling to add sets instead of reps forever.': 'จำนวนครั้งจะเพิ่มทีละหนึ่งเมื่อทำครบทุกเซ็ต ตั้งเพดานไว้เพื่อเปลี่ยนไปเพิ่มเซ็ตแทนการเพิ่มจำนวนครั้งไปเรื่อยๆ',
'Reps climb to {0}, then a set is added and the reps start over. At {1} sets it asks you to add weight instead.': 'จำนวนครั้งจะเพิ่มถึง {0} จากนั้นจะเพิ่มเซ็ตและเริ่มนับจำนวนครั้งใหม่ พอถึง {1} เซ็ตจะแนะนำให้เพิ่มน้ำหนักแทน',
'Added ({0})': 'น้ำหนักเพิ่ม ({0})',
'{0}/side': '{0}/ข้าง',
'{0} reps in every set — add a set and go back to {1}.': 'ทำได้ {0} ครั้งในทุกเซ็ต — เพิ่มเซ็ตและกลับไปที่ {1}',
'{0} sets of {1} — time to add weight or move to a harder variation.': '{0} เซ็ตของ {1} — ถึงเวลาเพิ่มน้ำหนักหรือเปลี่ยนไปท่าที่ยากขึ้น',
'{0} per side': '{0} ต่อข้าง',
'You still log the total: {0} is {1} per side.': 'บันทึกจำนวนรวมตามปกติ: {0} คือ {1} ต่อข้าง',
'{0} sets · {1} work': '{0} เซ็ต · เซ็ตหลัก {1}',
'Make superset with previous': 'รวมเป็นซูเปอร์เซ็ตกับท่าก่อนหน้า',
'Make superset with next': 'รวมเป็นซูเปอร์เซ็ตกับท่าถัดไป',
'primary': 'หลัก',
'secondary': 'รอง',
'No exercises with an estimated 1RM yet.': 'ยังไม่มีท่าที่มีการประเมิน 1RM',
'Tap a muscle to see its exercises.': 'แตะกล้ามเนื้อเพื่อดูท่าที่เกี่ยวข้อง',
'Unpair': 'ยกเลิกการจับคู่',
// --- equipment profiles ---
'Showing all equipment': 'กำลังแสดงอุปกรณ์ทั้งหมด',
'Showing what you have in "{0}"': 'แสดงเฉพาะที่คุณมีใน "{0}"',
'Show all equipment': 'แสดงอุปกรณ์ทั้งหมด',
'Filter by "{0}"': 'กรองตาม "{0}"',
'Edit profile': 'แก้ไขโปรไฟล์',
'New equipment profile': 'โปรไฟล์อุปกรณ์ใหม่',
'Name it after where you train — e.g. "Home" or "Gym" — then check what you have there.': 'ตั้งชื่อตามสถานที่ที่คุณฝึก เช่น "บ้าน" หรือ "ยิม" แล้วเลือกอุปกรณ์ที่มีอยู่ที่นั่น',
'Profile name': 'ชื่อโปรไฟล์',
'Body-weight exercises are always available, in every profile.': 'ท่าที่ใช้น้ำหนักตัวจะพร้อมใช้งานเสมอในทุกโปรไฟล์',
'{0} of {1} exercises need equipment outside "{2}"': '{0} จาก {1} ท่าต้องใช้อุปกรณ์นอกเหนือจาก "{2}"',
'Needs {0} — not in your active profile': 'ต้องใช้ {0} — ไม่มีในโปรไฟล์ที่ใช้งานอยู่',
'Filter by equipment': 'กรองตามอุปกรณ์',
'Active profile': 'โปรไฟล์ที่ใช้งานอยู่',
'{0} equipment types': 'อุปกรณ์ {0} ประเภท',
'Add equipment profile': 'เพิ่มโปรไฟล์อุปกรณ์',
'Delete profile?': 'ลบโปรไฟล์นี้?',
'"{0}" and its equipment list will be removed.': '"{0}" และรายการอุปกรณ์จะถูกลบ',
'Filters the exercise library and picker, and flags routine exercises that need something you don’t have in the active profile.': 'กรองคลังท่าออกกำลังกายและตัวเลือกท่า พร้อมทั้งทำเครื่องหมายท่าในรูทีนที่ต้องใช้อุปกรณ์ที่ไม่มีในโปรไฟล์ที่ใช้งานอยู่',
// --- muscle groups ---
'Primary muscle groups': 'กลุ่มกล้ามเนื้อหลัก',
'Additional muscle groups': 'กลุ่มกล้ามเนื้อเสริม',
'No explicit muscle group': 'ไม่มีกลุ่มกล้ามเนื้อที่ระบุ',
// "Connect to my server" (mobile app pairing)
'Your server': 'เซิร์ฟเวอร์ของคุณ',
'Synced with your openGym server.': 'ซิงก์กับเซิร์ฟเวอร์ openGym ของคุณแล้ว',
'Disconnect': 'ยกเลิกการเชื่อมต่อ',
'Disconnect from your server?': 'ยกเลิกการเชื่อมต่อกับเซิร์ฟเวอร์?',
'Your data is synced to your server first, then this device switches back to local-only.': 'ข้อมูลของคุณจะถูกซิงก์กับเซิร์ฟเวอร์ก่อน จากนั้นอุปกรณ์นี้จะกลับไปใช้งานแบบเก็บข้อมูลในเครื่องเท่านั้น',
'Disconnected — back to local-only': 'ยกเลิกการเชื่อมต่อแล้ว — กลับไปใช้งานแบบเก็บข้อมูลในเครื่อง',
'Connect to my server': 'เชื่อมต่อกับเซิร์ฟเวอร์ของฉัน',
'Sync this device to your own self-hosted openGym instead.': 'ซิงก์อุปกรณ์นี้กับ openGym ที่คุณโฮสต์เองแทน',
'Pair the mobile app': 'จับคู่แอปมือถือ',
'Connect the openGym app on your phone to this account.': 'เชื่อมต่อแอป openGym บนโทรศัพท์ของคุณกับบัญชีนี้',
'Could not generate a code': 'สร้างรหัสไม่สำเร็จ',
'On the openGym app, choose “Connect to my server”, then enter this address and the code below. It expires in 5 minutes.': 'ในแอป openGym เลือก “เชื่อมต่อกับเซิร์ฟเวอร์ของฉัน” แล้วป้อนที่อยู่นี้พร้อมรหัสด้านล่าง รหัสจะหมดอายุใน 5 นาที',
'Enter your server address and the code': 'ป้อนที่อยู่เซิร์ฟเวอร์และรหัส',
'Connected': 'เชื่อมต่อแล้ว',
'Could not connect': 'เชื่อมต่อไม่สำเร็จ',
'Open Settings → “Pair the mobile app” on the openGym site you’re already signed into, then enter its address and the code shown there.': 'เปิดการตั้งค่า → “จับคู่แอปมือถือ” บนเว็บไซต์ openGym ที่คุณเข้าสู่ระบบอยู่แล้ว จากนั้นป้อนที่อยู่และรหัสที่แสดงไว้ที่นั่น',
'Server address (e.g. gym.example.com)': 'ที่อยู่เซิร์ฟเวอร์ (เช่น gym.example.com)',
'Pairing code': 'รหัสจับคู่',
'Connecting…': 'กำลังเชื่อมต่อ…',
'Connect': 'เชื่อมต่อ',
'How do you want to use openGym?': 'คุณต้องการใช้งาน openGym แบบไหน?',
'Use on this device': 'ใช้งานบนอุปกรณ์นี้',
'Local keeps everything on this phone. Connecting syncs to your own openGym server instead — you can switch later in Settings.': 'แบบเก็บในเครื่องจะเก็บทุกอย่างไว้ในโทรศัพท์นี้ ส่วนการเชื่อมต่อจะซิงก์กับเซิร์ฟเวอร์ openGym ของคุณแทน — เปลี่ยนภายหลังได้ในการตั้งค่า',
// --- workout notes and planned warm-ups ---
'{0} — done': '{0} — เสร็จแล้ว',
'Workout done': 'ออกกำลังกายเสร็จแล้ว',
'reps': 'ครั้ง',
'Most reps in a set per workout': 'จำนวนครั้งมากที่สุดในหนึ่งเซ็ตต่อการออกกำลังกาย',
'Warm-up sets': 'เซ็ตวอร์มอัพ',
'Added before your work sets and left out of volume, records and progression. Each one closes half the gap to the work weight — you can still change any of them mid-session.': 'เพิ่มไว้ก่อนเซ็ตหลัก และไม่นับรวมในปริมาณงาน สถิติ หรือการปรับน้ำหนัก แต่ละเซ็ตจะลดช่องว่างไปครึ่งหนึ่งของน้ำหนักเซ็ตหลัก — ยังปรับเปลี่ยนได้ระหว่างออกกำลังกาย',
'Ramp-up sets added before the work sets, so you do not have to add them by hand each session.': 'เพิ่มเซ็ตไต่ระดับไว้ก่อนเซ็ตหลัก จะได้ไม่ต้องเพิ่มเองทุกครั้ง',
'Note': 'บันทึก',
'This session': 'รอบนี้',
'How it went, what to change — kept with today’s workout.': 'เป็นอย่างไรบ้าง อยากเปลี่ยนอะไร — จะถูกเก็บไว้กับการออกกำลังกายวันนี้',
'Show this next time': 'แสดงอีกครั้งครั้งถัดไป',
'Brings it up again the next time you train this exercise.': 'จะแสดงขึ้นอีกครั้งเมื่อคุณฝึกท่านี้ครั้งถัดไป',
'Always for this exercise': 'ใช้ตลอดสำหรับท่านี้',
'Seat height, pin position, a form cue — shown every session.': 'ความสูงเบาะ ตำแหน่งพิน หรือเคล็ดลับท่าทาง — แสดงทุกครั้งที่ฝึก',
'From {0}:': 'จาก {0}:',
'Session note': 'บันทึกประจำรอบ',
'Add session note': 'เพิ่มบันทึกประจำรอบ',
'Edit session note': 'แก้ไขบันทึกประจำรอบ',
'How the session went as a whole.': 'ภาพรวมของการออกกำลังกายรอบนี้เป็นอย่างไร',
'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': 'เรสต์-พอสจะฝึกเป็นเซ็ตวอร์มอัพหนึ่งเซ็ตที่จำนวนครั้งนี้ ตามด้วยเซ็ตหลักแบบเรสต์-พอสหนึ่งเซ็ตเสมอ — ไม่ใช้ค่า "เซ็ต"',
'Move up': 'เลื่อนขึ้น',
'Move down': 'เลื่อนลง',
'Swap exercise': 'สลับท่าออกกำลังกาย',
'Swap exercise?': 'สลับท่าออกกำลังกาย?',
'Logged sets stay with the original exercise. Choose where the replacement belongs.': 'เซ็ตที่บันทึกแล้วจะอยู่กับท่าเดิม เลือกว่าจะวางท่าใหม่ไว้ตรงไหน',
'Keep replacement in this group': 'เก็บท่าใหม่ไว้ในกลุ่มนี้',
'Insert after this group': 'แทรกหลังกลุ่มนี้',
'Logged sets stay with the original exercise. The replacement will be inserted afterward.': 'เซ็ตที่บันทึกแล้วจะอยู่กับท่าเดิม ท่าใหม่จะถูกแทรกไว้ถัดไป',
'Rest after each set of this exercise. Leave at 0 to use your default rest timer.': 'พักหลังแต่ละเซ็ตของท่านี้ ปล่อยไว้ที่ 0 เพื่อใช้ตัวจับเวลาพักค่าเริ่มต้น',
'Flash screen when timer ends': 'กะพริบหน้าจอเมื่อหมดเวลา',
'Import from Hevy': 'นำเข้าจาก Hevy',
'Pull your history with a Hevy Pro API key': 'ดึงประวัติด้วยคีย์ API ของ Hevy Pro',
'Pull your history with a Hevy Pro API key. The key is only used for this import and is not saved.': 'ดึงประวัติด้วยคีย์ API ของ Hevy Pro คีย์ใช้สำหรับการนำเข้าครั้งนี้เท่านั้นและจะไม่ถูกบันทึก',
'Hevy API key': 'คีย์ API ของ Hevy',
'Get your API key': 'รับคีย์ API ของคุณ',
'Hevy → Settings → Developer': 'Hevy → การตั้งค่า → นักพัฒนา',
'Paste your Hevy API key first': 'วางคีย์ API ของ Hevy ก่อน',
'Fetch from Hevy': 'ดึงจาก Hevy',
'Fetching from Hevy…': 'กำลังดึงจาก Hevy…',
'Fetching exercises… ({0}/{1})': 'กำลังดึงท่าออกกำลังกาย… ({0}/{1})',
'Fetching workouts… ({0}/{1})': 'กำลังดึงการฝึก… ({0}/{1})',
'Fetching weigh-ins… ({0}/{1})': 'กำลังดึงน้ำหนักตัว… ({0}/{1})',
'Matching exercises…': 'กำลังจับคู่ท่าออกกำลังกาย…',
'Could not reach Hevy — check the key and try again': 'ติดต่อ Hevy ไม่ได้ — ตรวจสอบคีย์แล้วลองอีกครั้ง',
'That Hevy API key was refused': 'คีย์ API ของ Hevy ถูกปฏิเสธ',
'Nothing to import from Hevy': 'ไม่มีอะไรให้นำเข้าจาก Hevy',
'Import workouts': 'นำเข้าการฝึก',
'Import routines': 'นำเข้าโปรแกรม',
'Import weigh-ins': 'นำเข้าน้ำหนักตัว',
'{0} new · {1} days already here': 'ใหม่ {0} · มีอยู่แล้ว {1} วัน',
'{0} routines · {1} exercises — added as new plans': '{0} โปรแกรม · {1} ท่า — เพิ่มเป็นแผนใหม่',
'{0} routines imported': 'นำเข้า {0} โปรแกรมแล้ว',
'Fetching routines… ({0}/{1})': 'กำลังดึงโปรแกรม… ({0}/{1})',
'Hevy stores weights in kg — they will be converted to {0}.': 'Hevy เก็บน้ำหนักเป็นกก. — จะถูกแปลงเป็น {0}',
'Back': 'กลับ',
'Reps up to': 'ครั้งสูงสุด',
'Exclude from automatic progression': 'ไม่รวมในการเพิ่มน้ำหนักอัตโนมัติ',
'Use for planned deloads. Workouts stay in history and statistics.': 'ใช้สำหรับดีโหลดที่วางแผนไว้ การฝึกยังอยู่ในประวัติและสถิติ',
'The next regular target continues from the last included workout.': 'เป้าหมายปกติครั้งถัดไปจะต่อจากการฝึกล่าสุดที่นับรวม',
'Open progression settings': 'เปิดการตั้งค่าการเพิ่มน้ำหนัก',
'Hevy is rate-limiting requests — wait a minute and try again': 'Hevy จำกัดจำนวนคำขอ — รอสักครู่แล้วลองอีกครั้ง',
// --- log a past workout ---
'Log a past workout': 'บันทึกการฝึกย้อนหลัง',
'Logged on the usual workout screen, without timers.': 'บันทึกบนหน้าจอฝึกตามปกติ เพียงแต่ไม่มีตัวจับเวลา',
'Date': 'วันที่',
'Start time': 'เวลาเริ่ม',
'Continue': 'ดำเนินการต่อ',
'Pick a day up to today': 'เลือกวันได้ไม่เกินวันนี้',
'There is already a workout on that day.': 'วันนั้นมีการฝึกอยู่แล้ว',
'Replace': 'แทนที่',
'Add as second workout': 'เพิ่มเป็นการฝึกครั้งที่สอง',
'Finish the current workout first.': 'จบการฝึกปัจจุบันก่อน',
'Logging a past workout — no rest timers.': 'กำลังบันทึกการฝึกย้อนหลัง — ไม่มีตัวจับเวลาพัก',
}
+56 -1
View File
@@ -35,6 +35,8 @@ export default {
'rescheduled': 'ertelendi',
'Prev': 'Önceki',
'Next': 'Sonraki',
'Move up': 'Yukarı taşı',
'Move down': 'Aşağı taşı',
'Sunday': 'Pazar', 'Monday': 'Pazartesi', 'Tuesday': 'Salı', 'Wednesday': 'Çarşamba',
'Thursday': 'Perşembe', 'Friday': 'Cuma', 'Saturday': 'Cumartesi',
'Su': 'Pz', 'Mo': 'Pt', 'Tu': 'Sa', 'We': 'Ça', 'Th': 'Pe', 'Fr': 'Cu', 'Sa': 'Ct',
@@ -91,6 +93,12 @@ export default {
'Weight ({0})': 'Ağırlık ({0})',
'Add to routine': 'Rutine ekle',
'Remove exercise': 'Egzersizi kaldır',
'Swap exercise': 'Egzersizi değiştir',
'Swap exercise?': 'Egzersiz değiştirilsin mi?',
'Logged sets stay with the original exercise. Choose where the replacement belongs.': 'Kaydedilen setler özgün egzersizde kalır. Yeni egzersizin nereye geleceğini seç.',
'Keep replacement in this group': 'Yeni egzersizi bu grupta tut',
'Insert after this group': 'Bu gruptan sonra ekle',
'Logged sets stay with the original exercise. The replacement will be inserted afterward.': 'Kaydedilen setler özgün egzersizde kalır. Yeni egzersiz sonrasına eklenir.',
'Remove {0}?': '{0} kaldırılsın mı?',
'The sets you logged for this exercise in this session will be lost.': 'Bu seansta bu egzersiz için kaydettiğin setler kaybolacak.',
'This removes the exercise from your current session.': 'Bu işlem egzersizi mevcut seansından kaldırır.',
@@ -170,6 +178,7 @@ export default {
'Remove drop': 'Düşüş setini kaldır',
'Remove burst': 'Patlamayı kaldır',
'Rest (s)': 'Dinlenme (sn)',
'Rest after each set of this exercise. Leave at 0 to use your default rest timer.': 'Bu egzersizin her setinden sonraki dinlenme. Varsayılan dinlenme sayacını kullanmak için 0 bırak.',
'Drop-set / rest-pause': 'Düşüş seti / rest-pause',
'Intensifier': 'Yoğunlaştırıcı',
'None': 'Yok',
@@ -284,6 +293,7 @@ export default {
'Weight unit': 'Ağırlık birimi',
'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)',
@@ -451,6 +461,33 @@ export default {
'That file is empty': 'Bu dosya boş',
'That file\'s columns aren\'t recognised — see the docs for supported apps.': 'Sütunlar tanınmadı — desteklenen uygulamalar için belgelere bak.',
'Nothing to import from that file': 'Bu dosyada içe aktarılacak bir şey yok',
// --- import from Hevy API ---
'Import from Hevy': 'Hevy’den içe aktar',
'Pull your history with a Hevy Pro API key': 'Hevy Pro API anahtarıyla geçmişini çek',
'Pull your history with a Hevy Pro API key. The key is only used for this import and is not saved.': 'Hevy Pro API anahtarıyla geçmişini çek. Anahtar yalnızca bu içe aktarım için kullanılır ve kaydedilmez.',
'Hevy API key': 'Hevy API anahtarı',
'Get your API key': 'API anahtarını al',
'Hevy → Settings → Developer': 'Hevy → Ayarlar → Developer',
'Paste your Hevy API key first': 'Önce Hevy API anahtarını yapıştır',
'Fetch from Hevy': 'Hevy’den getir',
'Fetching from Hevy…': 'Hevy’den getiriliyor…',
'Fetching exercises… ({0}/{1})': 'Egzersizler getiriliyor… ({0}/{1})',
'Fetching workouts… ({0}/{1})': 'Antrenmanlar getiriliyor… ({0}/{1})',
'Fetching weigh-ins… ({0}/{1})': 'Tartımlar getiriliyor… ({0}/{1})',
'Matching exercises…': 'Egzersizler eşleştiriliyor…',
'Could not reach Hevy — check the key and try again': 'Hevy’ye ulaşılamadı — anahtarı kontrol edip tekrar dene',
'That Hevy API key was refused': 'Bu Hevy API anahtarı reddedildi',
'Nothing to import from Hevy': 'Hevy’den içe aktarılacak bir şey yok',
'Import workouts': 'Antrenmanları içe aktar',
'Import routines': 'Rutinleri içe aktar',
'{0} routines · {1} exercises — added as new plans': '{0} rutin · {1} egzersiz — yeni plan olarak eklenir',
'{0} routines imported': '{0} rutin içe aktarıldı',
'Fetching routines… ({0}/{1})': 'Rutinler getiriliyor… ({0}/{1})',
'Routines': 'Rutinler',
'Import weigh-ins': 'Tartımları içe aktar',
'{0} new · {1} days already here': '{0} yeni · {1} gün zaten var',
'Hevy stores weights in kg — they will be converted to {0}.': 'Hevy ağırlıkları kg olarak saklar — {0} birimine çevrilecek.',
'Back': 'Geri',
// --- mobile build ---
'Your data': 'Verileriniz',
'All data stays on this phone': 'Tüm veriler bu telefonda kalır',
@@ -518,7 +555,11 @@ export default {
'Step ({0})': 'Artış ({0})',
'Step (seconds)': 'Artış (saniye)',
'Reps from': 'Tekrar en az',
'Reps up to': 'Tekrar en çok',
'No automatic progression': 'Otomatik ilerleme yok',
'Exclude from automatic progression': 'Otomatik ilerlemeden hariç tut',
'Use for planned deloads. Workouts stay in history and statistics.': 'Planlı deloadlar için kullanın. Antrenmanlar geçmişte ve istatistiklerde kalır.',
'The next regular target continues from the last included workout.': 'Sonraki normal hedef, dahil edilen son antrenmandan devam eder.',
'Linear progression': 'Doğrusal ilerleme',
'Greyskull LP': 'Greyskull LP',
'Double progression': 'Çift ilerleme',
@@ -673,5 +714,19 @@ export default {
'Add session note': 'Antrenman notu ekle',
'Edit session note': 'Antrenman notunu düzenle',
'How the session went as a whole.': 'Antrenmanın genel olarak nasıl geçtiği.',
'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': 'Rest-pause her zaman bu tekrar sayısında bir ısınma seti ve bir rest-pause çalışma seti olarak çalışılır — “Setler” kullanılmaz.'
'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': 'Rest-pause her zaman bu tekrar sayısında bir ısınma seti ve bir rest-pause çalışma seti olarak çalışılır — “Setler” kullanılmaz.',
'Open progression settings': 'İlerleme ayarlarını aç',
'Hevy is rate-limiting requests — wait a minute and try again': 'Hevy istekleri sınırlıyor — bir dakika bekleyip tekrar deneyin',
// --- log a past workout ---
'Log a past workout': 'Geçmiş bir antrenman kaydet',
'Logged on the usual workout screen, without timers.': 'Her zamanki antrenman ekranında kaydedilir, sadece zamanlayıcı olmadan.',
'Date': 'Tarih',
'Start time': 'Başlangıç saati',
'Continue': 'Devam',
'Pick a day up to today': 'Bugüne kadar bir gün seç',
'There is already a workout on that day.': 'O gün zaten bir antrenman var.',
'Replace': 'Değiştir',
'Add as second workout': 'İkinci antrenman olarak ekle',
'Finish the current workout first.': 'Önce mevcut antrenmanı bitir.',
'Logging a past workout — no rest timers.': 'Geçmiş antrenman kaydediliyor — dinlenme zamanlayıcısı yok.',
}
+56 -1
View File
@@ -35,6 +35,8 @@ export default {
'rescheduled': '已改期',
'Prev': '上一个',
'Next': '下一个',
'Move up': '上移',
'Move down': '下移',
'Sunday': '星期日', 'Monday': '星期一', 'Tuesday': '星期二', 'Wednesday': '星期三',
'Thursday': '星期四', 'Friday': '星期五', 'Saturday': '星期六',
'Su': '日', 'Mo': '一', 'Tu': '二', 'We': '三', 'Th': '四', 'Fr': '五', 'Sa': '六',
@@ -91,6 +93,12 @@ export default {
'Weight ({0})': '重量({0})',
'Add to routine': '加入训练日',
'Remove exercise': '移除动作',
'Swap exercise': '更换动作',
'Swap exercise?': '要更换动作吗?',
'Logged sets stay with the original exercise. Choose where the replacement belongs.': '已记录的组数会保留在原动作上。请选择替换动作的位置。',
'Keep replacement in this group': '将替换动作保留在此组',
'Insert after this group': '插入到此组之后',
'Logged sets stay with the original exercise. The replacement will be inserted afterward.': '已记录的组数会保留在原动作上。替换动作将插入其后。',
'Remove {0}?': '移除 {0}?',
'The sets you logged for this exercise in this session will be lost.': '本次训练中为该动作记录的组数将丢失。',
'This removes the exercise from your current session.': '这会从当前训练中移除该动作。',
@@ -170,6 +178,7 @@ export default {
'Remove drop': '移除递减组',
'Remove burst': '移除爆发组',
'Rest (s)': '休息(秒)',
'Rest after each set of this exercise. Leave at 0 to use your default rest timer.': '这个动作每组之后的休息时间。留在 0 就使用默认的休息计时。',
'Drop-set / rest-pause': '递减组 / 歇息暂停组',
'Intensifier': '强化技巧',
'None': '无',
@@ -284,6 +293,7 @@ export default {
'Weight unit': '重量单位',
'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)',
@@ -451,6 +461,33 @@ export default {
'That file is empty': '该文件是空的',
'That file\'s columns aren\'t recognised — see the docs for supported apps.': '无法识别该文件的列 — 支持的应用请见文档。',
'Nothing to import from that file': '该文件中没有可导入的内容',
// --- import from Hevy API ---
'Import from Hevy': '从 Hevy 导入',
'Pull your history with a Hevy Pro API key': '使用 Hevy Pro API 密钥拉取训练记录',
'Pull your history with a Hevy Pro API key. The key is only used for this import and is not saved.': '使用 Hevy Pro API 密钥拉取训练记录。密钥仅用于本次导入,不会保存。',
'Hevy API key': 'Hevy API 密钥',
'Get your API key': '获取 API 密钥',
'Hevy → Settings → Developer': 'Hevy → 设置 → Developer',
'Paste your Hevy API key first': '请先粘贴 Hevy API 密钥',
'Fetch from Hevy': '从 Hevy 获取',
'Fetching from Hevy…': '正在从 Hevy 获取…',
'Fetching exercises… ({0}/{1})': '正在获取动作… ({0}/{1})',
'Fetching workouts… ({0}/{1})': '正在获取训练… ({0}/{1})',
'Fetching weigh-ins… ({0}/{1})': '正在获取体重… ({0}/{1})',
'Matching exercises…': '正在匹配动作…',
'Could not reach Hevy — check the key and try again': '无法连接 Hevy — 请检查密钥后重试',
'That Hevy API key was refused': '该 Hevy API 密钥被拒绝',
'Nothing to import from Hevy': 'Hevy 没有可导入的内容',
'Import workouts': '导入训练',
'Import routines': '导入训练计划',
'{0} routines · {1} exercises — added as new plans': '{0} 个计划 · {1} 个动作 — 作为新计划添加',
'{0} routines imported': '已导入 {0} 个训练计划',
'Fetching routines… ({0}/{1})': '正在获取计划… ({0}/{1})',
'Routines': '训练计划',
'Import weigh-ins': '导入体重',
'{0} new · {1} days already here': '{0} 条新记录 · {1} 天已有数据',
'Hevy stores weights in kg — they will be converted to {0}.': 'Hevy 以公斤存储重量 — 将换算为 {0}。',
'Back': '返回',
// --- mobile build ---
'Your data': '你的数据',
'All data stays on this phone': '所有数据都保存在这部手机上',
@@ -518,7 +555,11 @@ export default {
'Step ({0})': '加量({0})',
'Step (seconds)': '加量(秒)',
'Reps from': '次数下限',
'Reps up to': '次数上限',
'No automatic progression': '不自动进阶',
'Exclude from automatic progression': '不计入自动进阶',
'Use for planned deloads. Workouts stay in history and statistics.': '用于计划性减载。训练仍保留在历史记录和统计中。',
'The next regular target continues from the last included workout.': '下一个常规目标从上一次计入的训练继续。',
'Linear progression': '线性进阶',
'Greyskull LP': 'Greyskull LP',
'Double progression': '双重进阶',
@@ -673,5 +714,19 @@ export default {
'Add session note': '添加训练备注',
'Edit session note': '编辑训练备注',
'How the session went as a whole.': '这次训练整体感觉如何。',
'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': 'Rest-pause 始终按这个次数练一个热身组,再加一个 rest-pause 正式组 —— 不使用“组数”。'
'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': 'Rest-pause 始终按这个次数练一个热身组,再加一个 rest-pause 正式组 —— 不使用“组数”。',
'Open progression settings': '打开进阶设置',
'Hevy is rate-limiting requests — wait a minute and try again': 'Hevy 正在限制请求——请稍等一分钟后重试',
// --- log a past workout ---
'Log a past workout': '补记过去的训练',
'Logged on the usual workout screen, without timers.': '在平时的训练界面记录,只是没有计时器。',
'Date': '日期',
'Start time': '开始时间',
'Continue': '继续',
'Pick a day up to today': '请选择今天或之前的日期',
'There is already a workout on that day.': '那天已经有一次训练了。',
'Replace': '替换',
'Add as second workout': '添加为第二次训练',
'Finish the current workout first.': '请先完成当前训练。',
'Logging a past workout — no rest timers.': '正在补记过去的训练 — 没有休息计时器。',
}
+3
View File
@@ -4,6 +4,9 @@ import App from './App.jsx'
import { MOBILE } from './lib/mobile.js'
import './index.css'
// App.jsx restores per-route scroll itself; the browser's own attempt races it.
if ('scrollRestoration' in history) history.scrollRestoration = 'manual'
createRoot(document.getElementById('root')).render(
<StrictMode><App /></StrictMode>
)
+66
View File
@@ -0,0 +1,66 @@
// @vitest-environment happy-dom
import React, { act } from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { createRoot } from 'react-dom/client'
import { useStore } from './store/useStore.js'
import { useUI } from './store/useUI.js'
import { logPastWorkoutSheet } from './sheets.jsx'
import { todayISO } from './lib/format.js'
const mounted = []
function type(el, value) {
Object.getOwnPropertyDescriptor(el.constructor.prototype, 'value').set.call(el, value)
el.dispatchEvent(new Event('input', { bubbles: true }))
}
function mountTopSheet() {
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 button = (host, text) => [...host.querySelectorAll('button')].find(b => b.textContent.trim() === text)
describe('log a past workout', () => {
beforeEach(() => {
globalThis.IS_REACT_ACT_ENVIRONMENT = true
useUI.setState({ sheets: [], toasts: [] })
useStore.setState(s => ({ S: { ...s.S, active: null, routines: [], workouts: [{ id: 'old', d: todayISO(), start: 1, end: 2, name: 'Old', entries: [], prs: [] }] } }))
document.body.innerHTML = ''
})
afterEach(() => { act(() => { mounted.splice(0).forEach(root => root.unmount()) }) })
it('refuses while a workout is running', () => {
const toast = vi.fn()
useUI.setState({ toast })
useStore.setState(s => ({ S: { ...s.S, active: { id: 'a', entries: [] } } }))
logPastWorkoutSheet()
expect(useUI.getState().sheets).toHaveLength(0)
expect(toast).toHaveBeenCalledWith('Finish the current workout first.')
})
it('asks what to do when the day already has a workout', () => {
logPastWorkoutSheet()
const host = mountTopSheet()
expect(host.querySelector('h3').textContent).toBe('Log a past workout')
act(() => { type(host.querySelector('input[type=date]'), todayISO()) })
act(() => { button(host, 'Continue').click() })
const prompt = mountTopSheet()
expect(prompt.textContent).toContain('There is already a workout on that day.')
expect(['Replace', 'Add as second workout', 'Cancel'].map(t => !!button(prompt, t))).toEqual([true, true, true])
expect(useStore.getState().S.active).toBeNull()
})
it('starts a backfilled session straight away on a free day', () => {
logPastWorkoutSheet()
const host = mountTopSheet()
act(() => { type(host.querySelector('input[type=date]'), '2020-01-02') })
act(() => { button(host, 'Continue').click() })
const A = useStore.getState().S.active
expect(A.d).toBe('2020-01-02')
expect(new Date(A.start).getHours()).toBe(18)
expect(A.backfill).toEqual({ durationMin: 60, replaceId: null })
})
})
+464 -53
View File
@@ -3,7 +3,7 @@ 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, uid, exCount, DAYN, MONTHS_LONG, ACCENTS } from './lib/format.js'
import { fmtDate, fmtNum, fmtVol, fmtDur, durPart, todayISO, isoOf, uid, exCount, DAYN, MONTHS_LONG, ACCENTS } from './lib/format.js'
import { lastEntryFor, bestWeightFor, buildSets, effectiveRoutineId, workoutVolume, setsDone, setsDoneActive, lastBW, supersetUnits, unitOf, setLabel, defaultConfig, cleanupSg, modeOf, effortOf, isBw, isPerSide, sideReps, workSetsDone, applyIntensifierPlan, MAX_PLANNED_WARMUPS, NOTE_MAX } from './lib/history.js'
import { beep, vibrate } from './lib/sound.js'
import { t, instrFor, exerciseNameFor, getLang, INSTR_LANGS } from './lib/i18n.js'
@@ -17,13 +17,19 @@ import { glyphOf, GLYPH_GROUPS, DEFAULT_GLYPH } from './lib/glyphs.js'
import BodyMap from './components/BodyMap.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 { normalizeRepRange } from './lib/rep-range.js'
import { MOBILE, shareExport } from './lib/mobile.js'
import { buildCompletedWorkout } from './lib/finish-workout.js'
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 { buildSessionEntries } from './lib/session-start.js'
import { workoutsOn, backfillStart, backfillEnd, completeBackfill } from './lib/backfill.js'
const S = () => useStore.getState().S
const update = (...a) => useStore.getState().update(...a)
@@ -239,6 +245,204 @@ export function importFromApp(file, onDone) {
rd.readAsText(file)
}
/* ============================ import from Hevy API ============================ */
// The key lives in React state for this sheet only — dismissed with the sheet, never
// written to the store / localStorage / the server. After a successful fetch the user
// picks workouts and/or weigh-ins before anything is merged.
export function importFromHevy() {
ui().openSheet(close => <HevyImportSheet close={close} />)
}
function hevyProgressLabel(p) {
if (!p) return t('Fetching from Hevy…')
if (p.stage === 'templates') return t('Fetching exercises… ({0}/{1})', p.page, p.pageCount)
if (p.stage === 'workouts') return t('Fetching workouts… ({0}/{1})', p.page, p.pageCount)
if (p.stage === 'routines') return t('Fetching routines… ({0}/{1})', p.page, p.pageCount)
if (p.stage === 'body') return t('Fetching weigh-ins… ({0}/{1})', p.page, p.pageCount)
if (p.stage === 'parse') return t('Matching exercises…')
return t('Fetching from Hevy…')
}
function HevyImportSheet({ close }) {
const st = useStore(s => s.S)
const [apiKey, setApiKey] = useState('')
const [busy, setBusy] = useState(false)
const [progress, setProgress] = useState(null)
const [payload, setPayload] = useState(null) // { workouts, routines, bodyweight }
const [wantWorkouts, setWantWorkouts] = useState(true)
const [wantRoutines, setWantRoutines] = useState(true)
const [wantBody, setWantBody] = useState(true)
const keyRef = useRef(null)
// Drop the key from memory when the sheet goes away (unmount or successful import).
useEffect(() => () => { setApiKey('') }, [])
const wipeKey = () => { setApiKey(''); if (keyRef.current) keyRef.current.value = '' }
const fetchAccount = async () => {
const key = apiKey.trim()
if (!key) { toast(t('Paste your Hevy API key first')); return }
setBusy(true)
setProgress({ stage: 'templates', page: 1, pageCount: 1 })
setPayload(null)
try {
const data = await importHevyData(key, { unit: st.unit, onProgress: setProgress })
wipeKey()
const empty = !data.workouts.workouts.length && !data.routines.routines.length && !data.bodyweight.bodyweight.length
if (empty) {
toast(t('Nothing to import from Hevy'))
return
}
setWantWorkouts(!!data.workouts.workouts.length)
setWantRoutines(!!data.routines.routines.length)
setWantBody(!!data.bodyweight.bodyweight.length)
setPayload(data)
} catch (e) {
if (e instanceof HevyApiError && e.message === 'auth') toast(t('That Hevy API key was refused'))
else if (e instanceof HevyApiError && e.message === 'rate-limit') toast(t('Hevy is rate-limiting requests — wait a minute and try again'))
else if (e instanceof HevyApiError && e.message === 'empty') toast(t('Paste your Hevy API key first'))
else toast(t('Could not reach Hevy — check the key and try again'))
} finally {
setBusy(false)
setProgress(null)
}
}
const doImport = () => {
if (!payload) return
const parts = []
let addedW = 0, addedR = 0, addedB = 0
update(s => {
if (wantWorkouts && payload.workouts.workouts.length) {
const res = mergeImport(s, payload.workouts)
addedW = res.added
parts.push(t('{0} workouts imported', res.added))
}
if (wantRoutines && payload.routines.routines.length) {
const res = mergeHevyRoutines(s, payload.routines)
addedR = res.added
parts.push(t('{0} routines imported', res.added))
}
if (wantBody && payload.bodyweight.bodyweight.length) {
const res = mergeImport(s, payload.bodyweight)
addedB = res.added
parts.push(t('{0} weigh-ins imported', res.added))
}
})
close()
if (!addedW && !addedR && !addedB) toast(t('Nothing new to import'))
else toast(parts.join(' · '))
}
if (!payload) {
return <>
<h3>{t('Import from Hevy')}</h3>
<div className="muted small" style={{ marginBottom: 14, lineHeight: 1.5 }}>
{t('Pull your history with a Hevy Pro API key. The key is only used for this import and is not saved.')}
</div>
<label className="small dim" style={{ display: 'block', marginBottom: 6 }}>{t('Hevy API key')}</label>
<TextField
ref={keyRef}
type="password"
autoComplete="off"
spellCheck={false}
placeholder="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
value={apiKey}
disabled={busy}
onChange={e => setApiKey(e.target.value)}
onKeyDown={e => { if (e.key === 'Enter' && !busy) fetchAccount() }}
/>
<div className="small" style={{ margin: '10px 0 16px', lineHeight: 1.45 }}>
<a href={HEVY_DEV_SETTINGS} target="_blank" rel="noopener noreferrer">{t('Get your API key')}</a>
<span className="dim"> — {t('Hevy → Settings → Developer')}</span>
</div>
{busy && <div className="small dim" style={{ marginBottom: 12 }}>{hevyProgressLabel(progress)}</div>}
<Button variant="primary" onClick={fetchAccount} disabled={busy || !apiKey.trim()}>
{busy ? t('Fetching from Hevy…') : t('Fetch from Hevy')}
</Button>
<div style={{ height: 8 }} />
<Button variant="ghost" className="dim" onClick={close} disabled={busy}>{t('Cancel')}</Button>
</>
}
const w = payload.workouts
const r = payload.routines
const b = payload.bodyweight
const haveW = w.workouts.filter(x => st.workouts.some(y => y.d === x.d)).length
const freshW = w.workouts.length - haveW
const haveB = b.bodyweight.filter(x => st.bodyweight.some(y => y.d === x.d)).length
const freshB = b.bodyweight.length - haveB
// Routines are always added as new copies (same as plan import).
const freshR = r.routines.length
const canImport = (wantWorkouts && freshW > 0) || (wantRoutines && freshR > 0) || (wantBody && freshB > 0)
const unmatched = [...new Set([
...(wantWorkouts ? w.unmatchedNames : []),
...(wantRoutines ? r.unmatchedNames : []),
])].sort()
return <>
<h3>{t('Import from Hevy')}</h3>
<div className="muted small" style={{ marginBottom: 12 }}>
{w.from && (w.from === w.to ? fmtDate(w.from, true) : fmtDate(w.from, true) + ' – ' + fmtDate(w.to, true))}
{!w.from && b.from && (b.from === b.to ? fmtDate(b.from, true) : fmtDate(b.from, true) + ' – ' + fmtDate(b.to, true))}
</div>
<div className="tiles" style={{ textAlign: 'left' }}>
<div className="tile"><div className="l">{t('Workouts')}</div><div className="v" style={{ fontSize: '1.1rem' }}>{w.workouts.length}</div></div>
<div className="tile"><div className="l">{t('Routines')}</div><div className="v" style={{ fontSize: '1.1rem' }}>{r.routines.length}</div></div>
<div className="tile"><div className="l">{t('Exercises matched')}</div><div className="v" style={{ fontSize: '1.1rem' }}>{w.matched + r.matched}</div></div>
<div className="tile"><div className="l">{t('Added as your own')}</div><div className="v" style={{ fontSize: '1.1rem' }}>{w.created + r.created}</div></div>
</div>
{w.workouts.length > 0 && <div className="row between" style={{ padding: '10px 2px', borderTop: '1px solid var(--sep)', gap: 12 }}>
<div>
<div className="tt" style={{ fontSize: 15 }}>{t('Import workouts')}</div>
<div className="small dim">{t('{0} new · {1} days already here', freshW, haveW)}</div>
</div>
<Switch checked={wantWorkouts} onChange={setWantWorkouts} />
</div>}
{r.routines.length > 0 && <div className="row between" style={{ padding: '10px 2px', borderTop: '1px solid var(--sep)', gap: 12 }}>
<div>
<div className="tt" style={{ fontSize: 15 }}>{t('Import routines')}</div>
<div className="small dim">{t('{0} routines · {1} exercises — added as new plans', freshR, r.exerciseCount)}</div>
</div>
<Switch checked={wantRoutines} onChange={setWantRoutines} />
</div>}
{b.bodyweight.length > 0 && <div className="row between" style={{ padding: '10px 2px', borderTop: '1px solid var(--sep)', borderBottom: '1px solid var(--sep)', gap: 12, marginBottom: 8 }}>
<div>
<div className="tt" style={{ fontSize: 15 }}>{t('Import weigh-ins')}</div>
<div className="small dim">{t('{0} new · {1} days already here', freshB, haveB)}</div>
</div>
<Switch checked={wantBody} onChange={setWantBody} />
</div>}
{!b.bodyweight.length && <div style={{ borderBottom: '1px solid var(--sep)', marginBottom: 8 }} />}
{(w.converted || r.converted) && <div className="small" style={{ color: 'var(--yellow)', marginBottom: 10 }}>
{t('Hevy stores weights in kg — they will be converted to {0}.', st.unit)}
</div>}
{wantWorkouts && (w.rirSets + w.rpeSets) > 0 && <div className="small dim" style={{ marginBottom: 10 }}>
{t(effortOf(st) === 'none'
? '{0} sets bring an {1} with them — switch on Effort per set in Settings to see it.'
: '{0} sets bring an {1} with them.',
w.rirSets || w.rpeSets, w.rirSets ? 'RIR' : 'RPE')}
</div>}
{unmatched.length > 0 && <>
<h4 className="sec">{t('Not in the library — added as your own exercises')}</h4>
<div className="mchips" style={{ marginBottom: 12 }}>
{unmatched.slice(0, 12).map(n => <span key={n} className="mchip capitalize">{n}</span>)}
{unmatched.length > 12 && <span className="mchip">+{unmatched.length - 12}</span>}
</div>
</>}
<Button variant="primary" onClick={doImport} disabled={!canImport}>
{canImport ? t('Import') : t('Nothing new to import')}
</Button>
<div style={{ height: 8 }} />
<Button variant="ghost" className="dim" onClick={() => { setPayload(null); wipeKey() }}>{t('Back')}</Button>
</>
}
/* ============================ target weight ============================ */
export function bwDeltaColor(delta, currentW) {
if (!delta) return 'var(--label-2)'
@@ -342,12 +546,12 @@ function AddToRoutine({ ex, close }) {
<h3 className="capitalize">{t('Add “{0}”', exerciseNameFor(ex))}</h3>
<div className="muted small" style={{ marginBottom: 12 }}>{t('Pick a routine — sets, reps & weight come next.')}</div>
<div className="list">
{st.routines.map(r => <div key={r.id} className="item" onClick={() => pick(r.id)}>
{st.routines.map(r => <div key={r.id} className="item" {...tappable(() => pick(r.id))}>
<span className="lrow-i"><Icon name={glyphOf(r.emoji)} /></span>
<div className="grow"><div className="tt">{r.name}</div><div className="ss">{exCount(r.ex.length)}</div></div>
{r.ex.some(e => e.id === ex.id) && <span className="tag">{t('already in')}</span>}<Icon name="plus" className="chev" />
</div>)}
<div className="item" onClick={() => pick('_new')}><span className="lrow-i" style={{ background: 'var(--surface-3)' }}><Icon name="sparkles" /></span>
<div className="item" {...tappable(() => pick('_new'))}><span className="lrow-i" style={{ background: 'var(--surface-3)' }}><Icon name="sparkles" /></span>
<div className="grow"><div className="tt">{t('New routine')}</div><div className="ss">{t('Create one and start with this exercise')}</div></div><Icon name="plus" className="chev" /></div>
</div>
</>
@@ -358,6 +562,8 @@ export const addToRoutineSheet = ex => ui().openSheet(close => <AddToRoutine ex=
// Name + body part is all it takes — the exercise then behaves like any built-in one
// (planning, logging, PRs, stats), just without an animation.
function CustomExForm({ existing, prefill, onDone, close }) {
const nameRef = useRef(null)
const onNameFocus = useSheetKeyboard(nameRef)
const [n, setN] = useState(existing ? existing.n : (prefill || ''))
const [bp, setBp] = useState(existing ? existing.bp : '')
const [desc, setDesc] = useState(existing ? (existing.desc || '') : '')
@@ -398,7 +604,7 @@ function CustomExForm({ existing, prefill, onDone, close }) {
return <>
<h3>{existing ? t('Edit custom exercise') : t('Create your own exercise')}</h3>
<div className="muted small" style={{ marginBottom: 12 }}>{t('Name it and pick a body part — it behaves like any other exercise, just without an animation.')}</div>
<input className="input" placeholder={t('Exercise name')} value={n} onChange={e => setN(e.target.value)} />
<input ref={nameRef} className="input" placeholder={t('Exercise name')} value={n} onFocus={onNameFocus} onChange={e => setN(e.target.value)} />
<div className="chips" style={{ margin: '12px 0' }}>
{BODYPARTS.map(b => <button key={b} className={'chip' + (bp === b ? ' on' : '')} onClick={() => setBp(b)}>{t(b)}</button>)}
</div>
@@ -463,6 +669,9 @@ function ExercisePicker({ onPick, close }) {
const [eq, setEq] = useState('') // '' = any equipment
const [showAll, setShowAll] = useState(false)
const [shown, setShown] = useState(50)
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 =>
@@ -475,10 +684,14 @@ function ExercisePicker({ onPick, close }) {
const eqOn = eqOpts.includes(eq) ? eq : ''
const f = eqOn ? eqFiltered.filter(e => e.eq === eqOn) : eqFiltered
const chosenCount = Object.keys(usage).length
useRevealActiveChip(bpStrip, bp)
useRevealActiveChip(eqStrip, eqOn)
return <>
<h3>{t('Add exercise')}</h3>
<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>
<input className="input" placeholder={t('Search {0} exercises…', all.length)} value={q} onChange={e => { setQ(e.target.value); setShown(50) }} /></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>
<input ref={searchRef} className="input" placeholder={t('Search {0} exercises…', all.length)} value={q} onFocus={onSearchFocus} onChange={e => { setQ(e.target.value); setShown(50) }} /></div></div>
{profile && <div className="small dim row" style={{ margin: '8px 0 2px', gap: 6, alignItems: 'center' }}>
<Icon name="dumbbell" style={{ fontSize: 13 }} />
{showAll ? t('Showing all equipment') : t('Showing what you have in "{0}"', profile.name)}
@@ -486,21 +699,21 @@ function ExercisePicker({ onPick, close }) {
{showAll ? t('Filter by "{0}"', profile.name) : t('Show all equipment')}
</button>
</div>}
<div className="chips" style={{ margin: eqOpts.length > 1 ? '10px 0 6px' : '10px 0' }}>
<div className="chips" ref={bpStrip} style={{ margin: eqOpts.length > 1 ? '10px 0 6px' : '10px 0' }}>
{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>)}
</div>
{eqOpts.length > 1 && <div className="chips" style={{ marginBottom: 10 }}>
{eqOpts.length > 1 && <div className="chips" ref={eqStrip} style={{ marginBottom: 10 }}>
<button className={'chip nocap' + (!eqOn ? ' on' : '')} onClick={() => { setEq(''); setShown(50) }}>{t('Any equipment')}</button>
{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" onClick={() => customExSheet(null, ex => onPick(ex), q.trim())}>
{bp !== '★' && <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" onClick={() => onPick(e)}>
{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" />
</div>)}
@@ -511,6 +724,68 @@ function ExercisePicker({ onPick, close }) {
}
export const exercisePicker = onPick => ui().openSheet(close => <ExercisePicker onPick={onPick} close={close} />)
/** Start a safe swap for one exact active-workout occurrence. */
export function swapActiveWorkoutExercise(index) {
const active = S().active
if (!active?.entries?.[index]) return
const picker = exercisePicker(ex => exConfigSheet(ex, null, 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()
const full = { ...cfg, id: ex.id }
const st = S()
// 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 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 replacement = {
id: ex.id,
target: { ...cfg },
plan,
sets: applyIntensifierPlan(freestyle ? built : applyPrescription(built, plan, step), full)
}
const current = S().active?.entries?.[index]
if (!current) return
const apply = options => {
// A timed callback closes over entry/set indexes. Invalidate it, and the current rest,
// before the selected occurrence can be replaced or a new entry shifts those indexes.
ui().stopWork()
ui().stopRest()
update(state => { swapActiveExercise(state.active, index, replacement, options) }, true)
}
const logged = (current.sets || []).some(set => set.done === true)
if (!logged) { apply(); return }
if (current.sg) {
ui().openSheet(close => <>
<h3>{t('Swap exercise?')}</h3>
<div className="muted small" style={{ marginBottom: 12 }}>
{t('Logged sets stay with the original exercise. Choose where the replacement belongs.')}
</div>
<Button variant="primary" onClick={() => { close(); apply({ loggedConfirmed: true, groupDisposition: 'keep' }) }}>
{t('Keep replacement in this group')}
</Button>
<div style={{ height: 8 }} />
<Button variant="ghost" onClick={() => { close(); apply({ loggedConfirmed: true, groupDisposition: 'detach' }) }}>
{t('Insert after this group')}
</Button>
</>)
return
}
confirmSheet({
title: t('Swap exercise?'),
message: t('Logged sets stay with the original exercise. The replacement will be inserted afterward.'),
confirmText: t('Continue'),
onConfirm: () => apply({ loggedConfirmed: true })
})
}))
}
/* ============================ equipment profiles ============================ */
// Create or edit one profile ("Home", "Gym", ...): a name plus a checklist of what you have.
function EquipmentProfileSheet({ profile, close }) {
@@ -564,17 +839,25 @@ const progressionStepOf = (c, mode, ex, unit) =>
const progressionStepIsValid = (step, policy) =>
policy === 'off' || (Number.isFinite(step) && step > 0)
function ProgressionFields({ ex, mode, c, setC, routine, unit }) {
function ProgressionFields({ ex, mode, c, setC, routine, unit, perSide }) {
const options = POLICIES_FOR[mode] || ['off']
if (options.length < 2) return null
const inherited = policyFor({ id: ex.id }, routine, mode)
const active = policyFor({ ...c, id: ex.id }, routine, mode)
const inc = progressionStepOf(c, mode, ex, unit)
const invalid = !progressionStepIsValid(inc, active)
const stride = mode === 'reps' && perSide ? 2 : 1
const range = active === 'double' ? normalizeRepRange(c.reps, c.repsMin, stride) : null
const setRule = v => setC(x => {
const next = { ...x, prog: v || undefined }
return policyFor({ ...next, id: ex.id }, routine, mode) === 'double'
? { ...next, ...normalizeRepRange(next.reps, next.repsMin, stride) }
: next
})
return <>
<h4 className="sec">{t('Progression')}</h4>
<div className="sect-b" style={{ marginBottom: 8 }}>
<SelectRow title={t('Rule')} sheetTitle={t('Progression')} value={c.prog || ''} onChange={v => setC(x => ({ ...x, prog: v || undefined }))}
<SelectRow title={t('Rule')} sheetTitle={t('Progression')} value={c.prog || ''} onChange={setRule}
options={[{ value: '', label: t('Follow the routine ({0})', t(POLICY_NAME[inherited])) },
...options.map(p => ({ value: p, label: t(POLICY_NAME[p]) }))]} />
</div>
@@ -583,8 +866,14 @@ function ProgressionFields({ ex, mode, c, setC, routine, unit }) {
<Stepper label={mode === 'time' ? t('Step (seconds)') : t('Step ({0})', unit)} value={inc}
step={mode === 'time' ? 5 : 1.25} decimal={mode !== 'time'} invalid={invalid} className={invalid ? 'invalid' : ''}
onChange={v => setC(x => ({ ...x, inc: v }))} />
{active === 'double' && <Stepper label={t('Reps from')} value={c.repsMin || Math.max(1, (c.reps || 10) - 2)}
step={1} decimal={false} onChange={v => setC(x => ({ ...x, repsMin: v }))} />}
{active === 'double' && <>
{/* The draft stays as typed: normalising on every keystroke turned "12" into 92 (the
"1" was pulled above the lower bound first). Save and the engine normalise anyway. */}
<Stepper label={t('Reps from')} value={c.repsMin ?? range.repsMin} step={stride} decimal={false}
onChange={v => setC(x => ({ ...x, repsMin: v }))} />
<Stepper label={t('Reps up to')} value={c.reps ?? range.reps} step={stride} decimal={false}
onChange={v => setC(x => ({ ...x, reps: v }))} />
</>}
</div>}
{invalid && <div className="small" role="alert" style={{ color: 'var(--red)', marginTop: -10, marginBottom: 18 }}>
{t('Enter a positive step to use this progression rule.')}
@@ -595,7 +884,13 @@ function ProgressionFields({ ex, mode, c, setC, routine, unit }) {
function ExConfig({ ex, existing, onSave, onDelete, close, routine, initial }) {
const st = useStore(s => s.S)
const cardio = isCardio(ex.id)
const [c, setC] = useState(existing || initial || defaultConfig(ex.id))
const seed = existing || initial || defaultConfig(ex.id)
const [c, setC] = useState(() => {
const cfg = { ...seed }
return policyFor({ ...cfg, id: ex.id }, routine, modeOf({ ...cfg, id: ex.id })) === 'double'
? { ...cfg, ...normalizeRepRange(cfg.reps, cfg.repsMin, isPerSide(cfg) ? 2 : 1) }
: cfg
})
// Cardio keeps its own duration+speed form; the reps/time choice (issue #16) is offered for
// everything else, which is where the gap was — planks, hangs, wall sits, loaded carries.
const mode = cardio ? 'cardio' : modeOf({ ...c, id: ex.id })
@@ -604,8 +899,15 @@ function ExConfig({ ex, existing, onSave, onDelete, close, routine, initial }) {
const perSide = isPerSide(c)
const progressionPolicy = policyFor({ ...c, id: ex.id }, routine, mode)
const progressionStepInvalid = !progressionStepIsValid(progressionStepOf(c, mode, ex, st.unit), progressionPolicy)
const activePolicy = policyFor({ ...c, id: ex.id }, routine, mode)
const double = mode === 'reps' && activePolicy === 'double'
// Keep whatever the other mode already had (sets, weight) and fill only what is missing.
const setMode = m => setC(x => ({ ...defaultConfig(ex.id, m), ...x, mode: m }))
const setMode = m => setC(x => {
const next = { ...defaultConfig(ex.id, m), ...x, mode: m }
return m === 'reps' && policyFor({ ...next, id: ex.id }, routine, 'reps') === 'double'
? { ...next, ...normalizeRepRange(next.reps, next.repsMin, isPerSide(next) ? 2 : 1) }
: next
})
const save = () => {
if (progressionStepInvalid) return
close()
@@ -631,15 +933,26 @@ function ExConfig({ ex, existing, onSave, onDelete, close, routine, initial }) {
// shape it had — and reads back as 0 either way (buildSets).
const warmupSets = Math.max(0, Math.min(MAX_PLANNED_WARMUPS, Math.round(c.warmupSets) || 0))
const withWarmups = warmupSets ? { warmupSets } : {}
if (cardio) onSave({ sets, min: Math.max(1, Math.round(c.min) || 20), speed: Math.max(0, c.speed || 8), ...withNote })
else if (mode === 'time') onSave({ sets, mode: 'time', sec: Math.max(1, Math.round(c.sec) || 45), weight: Math.max(0, c.weight || 0), ...flags, ...prog, ...withNote, ...withWarmups })
// Per-exercise rest (issue #10): written only when a positive value was set, so 0 keeps
// inheriting the global rest timer and a config that never touched it stays the shape it
// was. Mode-independent — a heavy triple, a plank and a cardio interval all rest.
const restSec = Math.max(0, Math.round(c.restSec) || 0)
const withRest = restSec ? { restSec } : {}
if (cardio) onSave({ sets, min: Math.max(1, Math.round(c.min) || 20), speed: Math.max(0, c.speed || 8), ...withNote, ...withRest })
else if (mode === 'time') onSave({ sets, mode: 'time', sec: Math.max(1, Math.round(c.sec) || 45), weight: Math.max(0, c.weight || 0), ...flags, ...prog, ...withNote, ...withWarmups, ...withRest })
else {
// A unilateral target is stored even: the split has to divide, and a typed 15 would
// otherwise plan seven reps on one side and eight on the other, every session.
const typed = Math.max(1, Math.round(c.reps) || 10)
const reps = perSide ? Math.ceil(typed / 2) * 2 : typed
const out = { sets, mode: 'reps', reps, weight: Math.max(0, c.weight || 0), ...flags, ...(perSide ? { side: true } : {}), ...prog, ...withNote, ...withWarmups }
if (policyFor({ ...c, id: ex.id }, routine, 'reps') === 'double') out.repsMin = Math.min(reps, Math.max(1, Math.round(c.repsMin) || Math.max(1, reps - 2)))
const stride = perSide ? 2 : 1
let reps = perSide ? Math.ceil(typed / stride) * stride : typed
let range = null
if (double) {
range = normalizeRepRange(reps, c.repsMin, stride)
reps = range.reps
}
const out = { sets, mode: 'reps', reps, weight: Math.max(0, c.weight || 0), ...flags, ...(perSide ? { side: true } : {}), ...prog, ...withNote, ...withWarmups, ...withRest }
if (double) out.repsMin = range.repsMin
// A ceiling below the working reps would tell you to add a set on day one.
if (bw && !(out.weight > 0) && c.repsMax > 0) out.repsMax = Math.max(reps, Math.round(c.repsMax))
// Every set in this exercise becomes a drop-set/rest-pause (buildSets stamps the rows) —
@@ -679,7 +992,7 @@ function ExConfig({ ex, existing, onSave, onDelete, close, routine, initial }) {
rest-pause work set — so "Sets" has nothing left to mean and only invites a mismatch. */}
{c.intensifier?.type !== 'restpause' &&
<Stepper label={t('Sets')} value={c.sets} step={1} decimal={false} onChange={v => setC(x => ({ ...x, sets: v }))} />}
<Stepper label={t('Reps')} value={c.reps} step={perSide ? 2 : 1} decimal={false} onChange={v => setC(x => ({ ...x, reps: v }))} />
{!double && <Stepper label={t('Reps')} value={c.reps} step={perSide ? 2 : 1} decimal={false} onChange={v => setC(x => ({ ...x, reps: v }))} />}
{/* On bodyweight work the weight stepper is the click #32 is about, so it is not here
until there is a belt to describe — see the added-weight row below. */}
{!bw && <Stepper label={t('Weight ({0})', st.unit)} value={c.weight} step={2.5} onChange={v => setC(x => ({ ...x, weight: v }))} />}
@@ -705,6 +1018,16 @@ function ExConfig({ ex, existing, onSave, onDelete, close, routine, initial }) {
{mode === 'time' && !bw && <div className="small dim" style={{ marginBottom: 18 }}>
{t('A timer runs while you hold the set. Leave the weight at 0 for bodyweight holds.')}
</div>}
{/* Per-exercise rest (issue #10). Its own full-width row, like the other steppers with an
explanation under them, and outside every mode branch because a heavy triple, a plank
and a cardio interval all rest — they just do not all want the same break. */}
<div className="row cfgrow" style={{ marginBottom: 6 }}>
<Stepper label={t('Rest (s)')} value={c.restSec || 0} step={15} decimal={false}
onChange={v => setC(x => ({ ...x, restSec: v }))} />
</div>
<div className="small dim" style={{ marginBottom: 18 }}>
{t('Rest after each set of this exercise. Leave at 0 to use your default rest timer.')}
</div>
{/* ---------- bodyweight + per side (issues #31/#32/#33) ---------- */}
{!cardio && <div className="sect-b" style={{ marginBottom: 8 }}>
<Row icon="figureStrength" iconTint="var(--acc)" title={t('Bodyweight')}
@@ -715,7 +1038,12 @@ function ExConfig({ ex, existing, onSave, onDelete, close, routine, initial }) {
subtitle={perSide ? t('You still log the total: {0} is {1} per side.', c.reps || 0, fmtNum(sideReps(c.reps))) : t('For lunges, single-arm rows and the like.')}>
{/* Turning it on rounds the target up to an even number, since half of an odd
total is a rep one side does not get. */}
<Switch checked={perSide} onChange={v => setC(x => ({ ...x, side: v || undefined, reps: v ? Math.ceil((x.reps || 0) / 2) * 2 : x.reps }))} />
<Switch checked={perSide} onChange={v => setC(x => {
const next = { ...x, side: v || undefined, reps: v ? Math.ceil((x.reps || 0) / 2) * 2 : x.reps }
return policyFor({ ...next, id: ex.id }, routine, 'reps') === 'double'
? { ...next, ...normalizeRepRange(next.reps, next.repsMin, v ? 2 : 1) }
: next
})} />
</Row>}
</div>}
{/* A stepper is too wide to sit in a list row next to a label — it squeezes the text to
@@ -777,7 +1105,7 @@ function ExConfig({ ex, existing, onSave, onDelete, close, routine, initial }) {
: t('Every set becomes rest-pause: {0} reps to start, then {1} more split into short bursts, {2}s rest before each, roughly halving each time.', c.reps || 0, c.intensifier.totalReps, c.intensifier.restSec)}
</div>}
</>}
<ProgressionFields ex={ex} mode={mode} c={c} setC={setC} routine={routine} unit={st.unit} />
<ProgressionFields ex={ex} mode={mode} c={c} setC={setC} routine={routine} unit={st.unit} perSide={perSide} />
<textarea className="input" rows={3} maxLength={500} style={{ marginBottom: 18 }}
placeholder={t('Note (optional) — loading cues, "bar only then +1 plate/side each set", anything worth remembering here')}
value={c.note || ''} onChange={e => setC(x => ({ ...x, note: e.target.value }))} />
@@ -908,12 +1236,12 @@ function DayOverride({ iso, close }) {
<h3>{fmtDate(iso, true)}</h3>
<div className="muted small" style={{ marginBottom: 12 }}>{t('Weekly plan:')} {weeklyR ? weeklyR.name : t('Rest')}{hasOvr && <span style={{ color: 'var(--orange)' }}> · {t('changed for this day')}</span>}<br />{t('Sick, missed a day or want a different session? Pick what to train instead.')}</div>
<div className="list">
{st.routines.map(r => <div key={r.id} className="item" onClick={() => set(r.id)}>
{st.routines.map(r => <div key={r.id} className="item" {...tappable(() => set(r.id))}>
<span className="lrow-i"><Icon name={glyphOf(r.emoji)} /></span>
<div className="grow"><div className="tt">{r.name}</div><div className="ss">{exCount(r.ex.length)}</div></div>
{effId === r.id && <Icon name="check" className="accent" />}</div>)}
<div className="item" onClick={() => set('rest')}><span className="lrow-i" style={{ background: 'var(--surface-3)' }}><Icon name="moon" /></span><div className="grow"><div className="tt">{t('Rest / skip this day')}</div></div>{effId === null && <Icon name="check" className="accent" />}</div>
{hasOvr && <div className="item" onClick={() => set('')}><span className="lrow-i" style={{ background: 'var(--surface-3)' }}><Icon name="reset" /></span><div className="grow"><div className="tt">{t('Back to weekly plan')}</div></div></div>}
<div className="item" {...tappable(() => set('rest'))}><span className="lrow-i" style={{ background: 'var(--surface-3)' }}><Icon name="moon" /></span><div className="grow"><div className="tt">{t('Rest / skip this day')}</div></div>{effId === null && <Icon name="check" className="accent" />}</div>
{hasOvr && <div className="item" {...tappable(() => set(''))}><span className="lrow-i" style={{ background: 'var(--surface-3)' }}><Icon name="reset" /></span><div className="grow"><div className="tt">{t('Back to weekly plan')}</div></div></div>}
</div>
</>
}
@@ -925,8 +1253,8 @@ function DayAssign({ day, close }) {
return <>
<h3>{t(DAYN[day])}</h3>
<div className="list">
<div className="item" onClick={() => set('')}><span className="lrow-i" style={{ background: 'var(--surface-3)' }}><Icon name="moon" /></span><div className="grow"><div className="tt">{t('Rest day')}</div></div>{!st.week[day] && <Icon name="check" className="accent" />}</div>
{st.routines.map(r => <div key={r.id} className="item" onClick={() => set(r.id)}>
<div className="item" {...tappable(() => set(''))}><span className="lrow-i" style={{ background: 'var(--surface-3)' }}><Icon name="moon" /></span><div className="grow"><div className="tt">{t('Rest day')}</div></div>{!st.week[day] && <Icon name="check" className="accent" />}</div>
{st.routines.map(r => <div key={r.id} className="item" {...tappable(() => set(r.id))}>
<span className="lrow-i"><Icon name={glyphOf(r.emoji)} /></span>
<div className="grow"><div className="tt">{r.name}</div><div className="ss">{exCount(r.ex.length)}</div></div>
{st.week[day] === r.id && <Icon name="check" className="accent" />}</div>)}
@@ -937,6 +1265,8 @@ export const dayAssignSheet = day => ui().openSheet(close => <DayAssign day={day
/* ============================ workout detail ============================ */
function WorkoutDetail({ w, close }) {
const noteRef = useRef(null)
const onNoteFocus = useSheetKeyboard(noteRef)
const st = useStore(s => s.S)
const update = useStore(s => s.update)
// The session note is editable here rather than only at the finish sheet: what you want to
@@ -979,9 +1309,9 @@ function WorkoutDetail({ w, close }) {
</div>
})}
<div className="small muted" style={{ margin: '4px 0 6px' }}>{t('Session note')}</div>
<textarea className="input" rows={2} maxLength={NOTE_MAX} value={note}
<textarea ref={noteRef} className="input" rows={2} maxLength={NOTE_MAX} value={note}
placeholder={t('How the session went as a whole.')}
onChange={e => setNote(e.target.value)} onBlur={saveNote} />
onFocus={onNoteFocus} onChange={e => setNote(e.target.value)} onBlur={saveNote} />
<div style={{ height: 14 }} />
<Button variant="danger" onClick={() => confirmSheet({ title: t('Delete workout?'), message: t('This removes it from your history for good.'), confirmText: t('Delete'), danger: true, onConfirm: () => { update(s => { s.workouts = s.workouts.filter(x => x.id !== w.id) }); close(); toast(t('Workout deleted')) } })}>{t('Delete workout')}</Button>
</>
@@ -1034,7 +1364,7 @@ export const calendarSheet = start => ui().openSheet(close => <Calendar start={s
export function WorkoutRow({ w, onClick }) {
const st = useStore(s => s.S)
const glyph = glyphOf((st.routines.find(r => r.id === w.routineId) || {}).emoji)
return <div className="item" onClick={onClick}>
return <div className="item" {...tappable(onClick)}>
<span className="lrow-i" style={{ width: 34, height: 34, borderRadius: 8, fontSize: 19 }}><Icon name={glyph} /></span>
<div className="grow"><div className="tt">{w.name}</div>
<div className="ss">{[fmtDate(w.d, true), ...durPart(w.end - w.start), t('{0} sets', setsDone(w)), fmtVol(w.vol, st.unit)].join(' · ')}</div></div>
@@ -1050,17 +1380,87 @@ export function startFlow(routineId) {
export function beginWorkout(routineId, bw) {
const st = S()
const r = routineId ? st.routines.find(x => x.id === routineId) : null
// The prescription is applied as the session is built, so you walk up to the bar with the
// right weight already on the screen instead of being told about it afterwards. `plan` is
// kept on the entry purely so the workout can explain the number it chose.
const entries = (r ? r.ex : []).map(cfg => {
const plan = nextPrescription(st, cfg, r)
const step = defaultIncrement(cfg.id, st.unit)
const sets = applyIntensifierPlan(applyPrescription(buildSets(st, cfg, { step }), plan, step), cfg)
return { id: cfg.id, sg: cfg.sg, target: { ...cfg }, plan, sets }
})
const { entries, excluded } = buildSessionEntries(st, r)
update(s => {
s.active = { id: uid(), d: todayISO(), start: Date.now(), routineId, name: r ? r.name : t('Freestyle'), bw: bw || null, cur: 0, entries }
s.active = {
id: uid(), d: todayISO(), start: Date.now(), routineId,
name: r ? r.name : t('Freestyle'), bw: bw || null, cur: 0, entries,
...(excluded ? { excludeFromProgression: true } : {})
}
})
useUI.getState().stopRest()
nav('/workout')
}
/* ============================ log a past workout ============================ */
// The same screen as a live session, pointed at another day. `backfill` on the active
// session is what tells the workout screen to drop the clock and the rest timers, and tells
// the finish path to file the workout where its date belongs instead of at the end.
function LogPastWorkout({ close }) {
const st = useStore(s => s.S)
const yesterday = new Date(); yesterday.setDate(yesterday.getDate() - 1)
const [date, setDate] = useState(isoOf(yesterday))
const [time, setTime] = useState('18:00')
const [dur, setDur] = useState(60)
const [routineId, setRoutineId] = useState('')
const today = todayISO()
const options = [{ value: '', label: t('Freestyle') }, ...st.routines.map(r => ({ value: r.id, label: r.name }))]
const go = replaceId => {
close()
beginBackfill({ iso: date, time, durationMin: dur, routineId: routineId || null, replaceId })
}
const submit = () => {
if (!date || date > today) { toast(t('Pick a day up to today')); return }
const existing = workoutsOn(st, date)
if (!existing.length) { go(null); return }
ui().openSheet(c => <SameDayChoice iso={date} existing={existing} close={c}
onReplace={id => { c(); go(id) }} onAdd={() => { c(); go(null) }} />, { kind: 'center' })
}
return <>
<h3>{t('Log a past workout')}</h3>
<div className="muted small" style={{ marginBottom: 12 }}>{t('Logged on the usual workout screen, without timers.')}</div>
<Row icon="calendar" title={t('Date')}>
<input type="date" className="timef" value={date} max={today} onChange={e => setDate(e.target.value)} /></Row>
<Row icon="clock" title={t('Start time')}>
<input type="time" className="timef" value={time} onChange={e => setTime(e.target.value)} /></Row>
<Stepper label={t('Duration')} unit="min" value={dur} step={5} decimal={false} onChange={v => setDur(Math.max(1, Math.round(v)))} />
<div style={{ height: 8 }} />
<SelectRow icon="dumbbell" title={t('Routine')} value={routineId} options={options} onChange={setRoutineId} />
<div style={{ height: 18 }} />
<Button variant="primary" onClick={submit}>{t('Continue')}</Button>
</>
}
// Three ways out when the day already has a workout. Replacing with several on that day means
// picking which one; the rest of the day is left alone.
function SameDayChoice({ iso, existing, onReplace, onAdd, close }) {
return <div style={{ textAlign: 'center', padding: '4px 0' }}>
<h3 style={{ marginBottom: 8 }}>{fmtDate(iso, true)}</h3>
<div className="muted" style={{ marginBottom: 18, lineHeight: 1.5 }}>{t('There is already a workout on that day.')}</div>
{existing.map(w => <div key={w.id} style={{ marginBottom: 8 }}>
<button className="btn danger" onClick={() => onReplace(w.id)}>{existing.length > 1 ? t('Replace') + ' · ' + w.name : t('Replace')}</button>
</div>)}
<button className="btn primary" onClick={onAdd}>{t('Add as second workout')}</button>
<div style={{ height: 8 }} />
<Button variant="ghost" className="dim" onClick={close}>{t('Cancel')}</Button>
</div>
}
export function logPastWorkoutSheet() {
if (S().active) { toast(t('Finish the current workout first.')); return }
ui().openSheet(close => <LogPastWorkout close={close} />)
}
function beginBackfill({ iso, time, durationMin, routineId, replaceId }) {
const st = S()
const r = routineId ? st.routines.find(x => x.id === routineId) : null
const { entries, excluded } = buildSessionEntries(st, r)
update(s => {
s.active = {
id: uid(), d: iso, start: backfillStart(iso, time), routineId,
name: r ? r.name : t('Freestyle'), bw: null, cur: 0, entries,
backfill: { durationMin, replaceId: replaceId || null },
...(excluded ? { excludeFromProgression: true } : {})
}
})
useUI.getState().stopRest()
nav('/workout')
@@ -1128,6 +1528,8 @@ export const topWeightSheet = entryIdx => ui().openSheet(close => <TopWeight ent
A routine's own `note` (a plan's instruction for this exercise) is edited in the config sheet
and is deliberately not here: it belongs to the plan, not to the day or to the movement. */
function ExerciseNote({ entryIdx, close }) {
const noteRef = useRef(null)
const onNoteFocus = useSheetKeyboard(noteRef)
const st = useStore(s => s.S)
const update = useStore(s => s.update)
const A = st.active
@@ -1158,9 +1560,9 @@ function ExerciseNote({ entryIdx, close }) {
return <>
<h3 className="capitalize">{exerciseNameFor(ex)}</h3>
<div className="small muted" style={{ marginBottom: 6 }}>{t('This session')}</div>
<textarea className="input" rows={3} maxLength={NOTE_MAX} value={note}
<textarea ref={noteRef} className="input" rows={3} maxLength={NOTE_MAX} value={note}
placeholder={t('How it went, what to change — kept with today’s workout.')}
onChange={e => setNote(e.target.value)} />
onFocus={onNoteFocus} onChange={e => setNote(e.target.value)} />
<div style={{ height: 10 }} />
<div className="sect-b">
<Row icon="flag" iconTint="var(--yellow)" title={t('Show this next time')}
@@ -1185,6 +1587,8 @@ export const exerciseNoteSheet = entryIdx => ui().openSheet(close => <ExerciseNo
fact because "notes you can write during a workout" is the point; a note you can only add
once the session is filed is a different, smaller feature. */
function SessionNote({ close }) {
const noteRef = useRef(null)
const onNoteFocus = useSheetKeyboard(noteRef)
const st = useStore(s => s.S)
const update = useStore(s => s.update)
const A = st.active
@@ -1200,9 +1604,9 @@ function SessionNote({ close }) {
return <>
<h3>{t('Session note')}</h3>
<textarea className="input" rows={4} maxLength={NOTE_MAX} value={note}
<textarea ref={noteRef} className="input" rows={4} maxLength={NOTE_MAX} value={note}
placeholder={t('How the session went as a whole.')}
onChange={e => setNote(e.target.value)} />
onFocus={onNoteFocus} onChange={e => setNote(e.target.value)} />
<div style={{ height: 18 }} />
<Button variant="primary" onClick={save}>{t('Save')}</Button>
</>
@@ -1261,9 +1665,12 @@ function doFinishWorkout() {
const st = S()
const A = st.active
if (!A) return
const past = !!A.backfill
const prs = []
const e1prs = []
A.entries.forEach(e => {
// A workout logged into the past cannot claim records against the history that came after
// it, so a backfilled session reports none and leaves the confirmed weights alone.
if (!past) A.entries.forEach(e => {
const mx = Math.max(0, ...e.sets.filter(s => s.done && !isWarmupRow(s)).map(s => s.w))
if (mx > 0 && mx > bestWeightFor(st, e.id)) prs.push(e.id)
// A heavier estimate without a heavier top set is its own kind of progress —
@@ -1272,17 +1679,21 @@ function doFinishWorkout() {
if (rec && !prs.includes(e.id)) e1prs.push({ id: e.id, ...rec })
})
const w = buildCompletedWorkout(A, {
end: Date.now(),
end: past ? backfillEnd(A) : Date.now(),
prs,
snapshotFor: e => EXIDX[e.id]?.custom ? exerciseMuscleSnapshot(EXIDX[e.id]) : null,
})
w.vol = workoutVolume(w)
update(s => {
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)
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)
if (past) {
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)
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)
}
s.active = null
})
useStore.getState().autoBackupNow()
+86
View File
@@ -0,0 +1,86 @@
// @vitest-environment happy-dom
import { LANGS } from './lib/i18n-core.js'
import { act } from 'react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { swapActiveWorkoutExercise } from './sheets.jsx'
import { EXDB } from './lib/exercises.js'
import { DEF, useStore } from './store/useStore.js'
import { useUI } from './store/useUI.js'
const clone = value => JSON.parse(JSON.stringify(value))
const ids = EXDB.slice(0, 3).map(exercise => exercise.id)
function entry(id, done = false) {
return {
id,
target: { mode: 'reps', sets: 1, reps: 5, weight: 40 },
sets: [{ w: 40, r: 5, done }]
}
}
function installActive() {
const S = clone(DEF)
S.active = {
id: 'swap-test', d: '2026-08-27', start: Date.now(), routineId: null,
name: 'Swap test', bw: null, cur: 1,
entries: [entry(ids[0]), entry(ids[0]), entry(ids[1])]
}
useStore.setState({ S, user: null })
}
function submitSwap(index, exercise, config) {
swapActiveWorkoutExercise(index)
const picker = useUI.getState().sheets.at(-1)
const pickerView = picker.render(picker.close)
act(() => pickerView.props.onPick(exercise))
const configSheet = useUI.getState().sheets.at(-1)
const configView = configSheet.render(configSheet.close)
act(() => configView.props.onSave(config))
}
beforeEach(() => {
vi.useFakeTimers()
localStorage.clear()
useUI.getState().stopRest()
useUI.getState().stopWork()
useUI.setState({ sheets: [], timer: null, work: null })
installActive()
})
describe('active exercise swap sheet flow', () => {
it('invalidates a timed callback and replaces only the selected duplicate', () => {
const callback = vi.fn()
useUI.getState().startWork(5, 'Hold', callback)
submitSwap(1, EXDB[2], { mode: 'reps', sets: 2, reps: 8, weight: 30, note: 'New target' })
vi.advanceTimersByTime(10_000)
const active = useStore.getState().S.active
expect(useUI.getState().work).toBeNull()
expect(callback).not.toHaveBeenCalled()
expect(active.entries.map(value => value.id)).toEqual([ids[0], ids[2], ids[1]])
expect(active.entries[1].target).toMatchObject({ mode: 'reps', sets: 2, reps: 8, weight: 30, note: 'New target' })
expect(active.entries[0].sets).toEqual([{ w: 40, r: 5, done: false }])
expect(active.entries[2].sets).toEqual([{ w: 40, r: 5, done: false }])
expect(active.cur).toBe(1)
})
})
describe('active exercise swap locale coverage', () => {
const required = [
'Swap exercise',
'Swap exercise?',
'Logged sets stay with the original exercise. Choose where the replacement belongs.',
'Keep replacement in this group',
'Insert after this group',
'Logged sets stay with the original exercise. The replacement will be inserted afterward.'
]
const packs = import.meta.glob('./locales/*.js', { eager: true, import: 'default' })
it('defines every new prompt in all twelve locale packs', () => {
expect(Object.keys(packs)).toHaveLength(Object.keys(LANGS).length - 1)
Object.entries(packs).forEach(([path, pack]) => {
required.forEach(key => expect(pack, `${path} is missing ${key}`).toHaveProperty(key))
})
})
})
+19 -12
View File
@@ -4,12 +4,12 @@ import { localTZ } from '../lib/format.js'
import { registerCustom } from '../lib/exercises.js'
import { DEMO, DEMO_SEEDED } from '../lib/demo.js'
import { guestAllowed } from '../lib/guest.js'
import { MOBILE, nativeLoad, nativeSave, syncReminder, writeAutoBackup } from '../lib/mobile.js'
import { MOBILE, initReminderSync, nativeLoad, nativeSave, syncReminder, writeAutoBackup } from '../lib/mobile.js'
import { loadRemote, chooseLocal, forgetRemote, connect } from '../lib/remote.js'
const KEY = 'gym_state_v1'
export const DEF = {
unit: 'kg', restSec: 90, restPauseSec: 15, sound: true, keepAwake: true, lang: 'en',
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',
@@ -21,10 +21,6 @@ export const DEF = {
// Equipment profiles (issue: filter Library/picker/routines by what you actually own —
// e.g. "Home" vs "Gym" — building on the session-only equipment filter from issue #6).
equipProfiles: [], activeEquipId: null, equipFilterOn: false,
// Standing per-exercise notes, keyed by exercise id: the gym-specific facts that are true
// 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: {},
}
const clone = o => JSON.parse(JSON.stringify(o))
@@ -38,10 +34,22 @@ function loadState() {
const hasData = st => !!((st.workouts || []).length || (st.routines || []).length || (st.bodyweight || []).length)
// Decide whether a pulled account state may replace the local saved state. A local active workout
// is deliberately carried forward: the server stores completed/saved state, while the in-progress
// session belongs to the device that is currently running it.
export function restoredStateFor(local, remote, dirty = false) {
if (!remote || (hasData(local) && (dirty || (remote._ts || 0) < (local._ts || 0)))) return null
const next = Object.assign(clone(DEF), remote)
if (local.active) next.active = local.active
return next
}
export const useStore = create((set, get) => {
let pushTm = null
let saveTm = null
initReminderSync(() => get().S)
// Mobile build: mirror the state into a file in the app's data directory (survives WebView
// storage eviction) and keep the native reminder schedule in step with the weekly plan.
const nativePersist = () => {
@@ -71,6 +79,7 @@ export const useStore = create((set, get) => {
clearTimeout(saveTm)
saveTm = null
nativeSave(get().S)
syncReminder(get().S)
}
if (pushTm) {
clearTimeout(pushTm)
@@ -140,11 +149,9 @@ export const useStore = create((set, get) => {
const { state } = await api('/api/data')
const S = get().S
const dirty = localStorage.getItem('gym_dirty') === '1'
if (state && (!hasData(S) || ((state._ts || 0) >= (S._ts || 0) && !dirty))) {
const active = S.active
const next = Object.assign(clone(DEF), state)
if (active) next.active = active
persist(next, false)
const restored = restoredStateFor(S, state, dirty)
if (restored) {
persist(restored, false)
} else if (hasData(S)) { await get().pushState() }
} catch (e) { /* offline — keep local */ }
},
@@ -269,4 +276,4 @@ export const useStore = create((set, get) => {
}
})
export { hasData }
export { hasData }
@@ -0,0 +1,107 @@
// @vitest-environment happy-dom
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
vi.mock('../lib/api.js', () => ({ api: vi.fn() }))
import { api } from '../lib/api.js'
import { DEF, restoredStateFor, useStore } from './useStore.js'
const clone = value => JSON.parse(JSON.stringify(value))
const routine = id => ({ id, name: id, ex: [] })
beforeEach(() => {
localStorage.clear()
api.mockReset()
useStore.setState({ S: clone(DEF), user: null, ready: false })
})
afterEach(() => {
localStorage.clear()
useStore.setState({ S: clone(DEF), user: null, ready: false })
})
describe('saved workout state sync and restore', () => {
it('returns null for an older or dirty local state', () => {
const local = { ...clone(DEF), _ts: 20, routines: [routine('local')] }
const remote = { ...clone(DEF), _ts: 10, routines: [routine('remote')] }
expect(restoredStateFor(local, remote)).toBeNull()
expect(restoredStateFor(local, { ...remote, _ts: 30 }, true)).toBeNull()
})
it('overlays defaults and carries the device-local active workout', () => {
const active = { id: 'active-1', routineId: 'local', entries: [] }
const local = { ...clone(DEF), active }
const restored = restoredStateFor(local, { _ts: 20, routines: [routine('remote')] })
expect(restored.routines.map(r => r.id)).toEqual(['remote'])
expect(restored.active).toEqual(active)
expect(restored.restSec).toBe(90)
})
it('adopts a newer clean remote state while preserving a local active workout', async () => {
const active = { id: 'active-1', d: '2026-08-29', routineId: 'local', name: 'Local', entries: [] }
const local = { ...clone(DEF), _ts: 10, routines: [routine('local')], active }
const remote = { ...clone(DEF), _ts: 20, routines: [routine('remote')], active: null }
useStore.setState({ S: local, user: { id: 'user-1' }, ready: true })
api.mockResolvedValue({ state: remote })
await useStore.getState().pullState()
expect(useStore.getState().S.routines.map(r => r.id)).toEqual(['remote'])
expect(useStore.getState().S.active).toEqual(active)
expect(JSON.parse(localStorage.getItem('gym_state_v1')).active).toEqual(active)
expect(api).toHaveBeenCalledTimes(1)
})
it('pushes local data instead of replacing it when the local state is newer', async () => {
const local = { ...clone(DEF), _ts: 20, routines: [routine('local')] }
const remote = { ...clone(DEF), _ts: 10, routines: [routine('remote')] }
useStore.setState({ S: local, user: { id: 'user-1' }, ready: true })
api.mockResolvedValueOnce({ state: remote }).mockResolvedValueOnce({})
await useStore.getState().pullState()
expect(api).toHaveBeenCalledTimes(2)
expect(api.mock.calls[1][0]).toBe('/api/data')
expect(JSON.parse(api.mock.calls[1][1].body).state.routines.map(r => r.id)).toEqual(['local'])
expect(useStore.getState().S.routines.map(r => r.id)).toEqual(['local'])
})
it('pushes local data instead of overwriting a dirty local state', async () => {
const local = { ...clone(DEF), _ts: 10, routines: [routine('local')] }
const remote = { ...clone(DEF), _ts: 20, routines: [routine('remote')] }
localStorage.setItem('gym_dirty', '1')
useStore.setState({ S: local, user: { id: 'user-1' }, ready: true })
api.mockResolvedValueOnce({ state: remote }).mockResolvedValueOnce({})
await useStore.getState().pullState()
expect(api).toHaveBeenCalledTimes(2)
expect(JSON.parse(api.mock.calls[1][1].body).state.routines.map(r => r.id)).toEqual(['local'])
expect(useStore.getState().S.routines.map(r => r.id)).toEqual(['local'])
})
it('restores a remote state over defaults when the local profile is empty', async () => {
const remote = { _ts: 30, routines: [routine('remote')], workouts: [] }
api.mockResolvedValue({ state: remote })
await useStore.getState().pullState()
expect(useStore.getState().S.routines.map(r => r.id)).toEqual(['remote'])
expect(useStore.getState().S.restSec).toBe(90)
expect(useStore.getState().S.lang).toBe('en')
})
it('keeps the local saved state when the restore request fails', async () => {
const local = { ...clone(DEF), _ts: 10, routines: [routine('local')] }
useStore.setState({ S: local, user: { id: 'user-1' }, ready: true })
api.mockRejectedValue(new Error('offline'))
await useStore.getState().pullState()
expect(useStore.getState().S.routines.map(r => r.id)).toEqual(['local'])
expect(api).toHaveBeenCalledTimes(1)
})
})
+8 -2
View File
@@ -59,6 +59,12 @@ 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
flashTimer() {
if (!useStore.getState().S.timerFlash) return
set(s => ({ timerFlashId: s.timerFlashId + 1 }))
},
openSheet(render, { kind = 'sheet', locked = false } = {}) {
const id = uid()
@@ -92,7 +98,7 @@ export const useUI = create((set, get) => ({
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]); maybeRestNotification(); get().toast(t('Rest over — next set!')); get().stopRest(); return
vibrate([200, 100, 200]); get().flashTimer(); maybeRestNotification(); get().toast(t('Rest over — next set!')); get().stopRest(); return
}
if (left <= 3) beep(snd, 660, 0.1)
set({ timer: { ...tm, left } })
@@ -147,7 +153,7 @@ export const useUI = create((set, get) => ({
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])
vibrate([200, 100, 200]); get().flashTimer()
const done = workDone
get().stopWork()
if (done) done(wk.total)
+39
View File
@@ -2,6 +2,7 @@
// useUI pulls in api.js, which reads navigator.userAgent at module scope.
import { describe, expect, it, beforeEach, afterEach, vi } from 'vitest'
import { useUI } from './useUI.js'
import { useStore } from './useStore.js'
// "Off" has to hold at the timer itself, not at the four places that start one — the same
// reason the rest-after-a-set rule is a shared condition rather than four copies.
@@ -26,3 +27,41 @@ describe('rest timer set to Off', () => {
expect(useUI.getState().timer.total).toBe(90)
})
})
describe('opt-in timer screen flash', () => {
let originalSettings
beforeEach(() => {
vi.useFakeTimers()
originalSettings = useStore.getState().S
useStore.setState({ S: { ...originalSettings, sound: false, timerFlash: false } })
useUI.setState({ timer: null, work: null, timerFlashId: 0 })
})
afterEach(() => {
useUI.getState().stopRest()
useUI.getState().stopWork()
useStore.setState({ S: originalSettings })
vi.useRealTimers()
})
it('stays off unless enabled in Settings', () => {
useUI.getState().startRest(1)
vi.advanceTimersByTime(1000)
expect(useUI.getState().timerFlashId).toBe(0)
})
it('flashes when the rest timer finishes', () => {
useStore.setState({ S: { ...useStore.getState().S, timerFlash: true } })
useUI.getState().startRest(1)
vi.advanceTimersByTime(1000)
expect(useUI.getState().timerFlashId).toBe(1)
})
it('flashes when a timed exercise finishes', () => {
useStore.setState({ S: { ...useStore.getState().S, timerFlash: true } })
useUI.getState().startWork(1, 'Plank', vi.fn())
vi.advanceTimersByTime(1000)
expect(useUI.getState().timerFlashId).toBe(1)
})
})
+3 -1
View File
@@ -1,7 +1,8 @@
import { useNavigate } from 'react-router-dom'
import { useStore } from '../store/useStore.js'
import { t } from '../lib/i18n.js'
import { WorkoutRow, workoutDetailSheet } from '../sheets.jsx'
import { WorkoutRow, workoutDetailSheet, logPastWorkoutSheet } from '../sheets.jsx'
import { Button } from '../components/ui.jsx'
import Icon from '../components/Icon.jsx'
export default function History() {
@@ -10,6 +11,7 @@ export default function History() {
return <>
<div className="hdr"><button className="iconbtn" onClick={() => nav('/stats')} aria-label={t('Stats')}><Icon name="chevronLeft" /></button>
<div style={{ flex: 1, marginLeft: 12 }}><h1>{t('History')}</h1><div className="sub">{t('{0} workouts', S.workouts.length)}</div></div></div>
<Button icon="plus" onClick={logPastWorkoutSheet} style={{ marginBottom: 12 }}>{t('Log a past workout')}</Button>
{S.workouts.length ? <div className="list">{[...S.workouts].reverse().map(w => <WorkoutRow key={w.id} w={w} onClick={() => workoutDetailSheet(w)} />)}</div>
: <div className="empty"><div className="ico"><Icon name="history" /></div>{t('No workouts yet.')}</div>}
</>
+4 -3
View File
@@ -8,6 +8,7 @@ import { bwSheet, goalSheet, dayOverrideSheet, calendarSheet, startFlow, loadSta
import LineChart from '../components/LineChart.jsx'
import Icon from '../components/Icon.jsx'
import { Button } from '../components/ui.jsx'
import { tappable } from '../lib/use-sheet-keyboard.js'
import { glyphOf } from '../lib/glyphs.js'
// Home = what to do now + a quick glance. Deep charts & history live in Stats.
@@ -35,7 +36,7 @@ export default function Home() {
const iso = isoOf(d)
const eff = effectiveRoutineId(S, iso), ovr = S.dayPlan[iso] !== undefined, done = doneDays.has(iso)
const dot = done ? ' done' : ovr && eff ? ' ovr' : eff ? ' plan' : ''
strip.push(<div key={i} className={'wday' + (iso === todayISO() ? ' today' : '')} onClick={() => dayOverrideSheet(iso)}>
strip.push(<div key={i} className={'wday' + (iso === todayISO() ? ' today' : '')} {...tappable(() => dayOverrideSheet(iso))}>
<div className="lbl">{t(DAYS[d.getDay()])}</div><div className="num">{d.getDate()}</div><div className={'dot' + dot} /></div>)
}
const sunday = new Date(monday); sunday.setDate(monday.getDate() + 6)
@@ -66,7 +67,7 @@ export default function Home() {
routine name behind a green Start tag and read as still outstanding (issue #4).
An in-progress session still wins — that one is happening right now. Tapping the
row keeps working, so a second session in one day is a tap away, just not urged. */}
<div className="today-row" onClick={onToday}>
<div className="today-row" {...tappable(onToday)}>
<div className="row" style={{ gap: 9, minWidth: 0 }}>
<span className="lrow-i" style={{ background: S.active ? 'var(--orange)' : doneToday ? 'var(--surface-3)' : routine ? 'var(--acc)' : 'var(--surface-3)' }}>
<Icon name={S.active ? 'timer' : doneToday ? 'checkCircle' : routine ? glyphOf(routine.emoji) : 'moon'}
@@ -128,7 +129,7 @@ export default function Home() {
</> : <div className="muted small">{t("No entries yet — log your weight to start the curve. It's also asked before every workout.")}</div>}
</div>
<div className="card tappable" style={{ cursor: 'pointer' }} onClick={() => calendarSheet()}>
<div className="card tappable" style={{ cursor: 'pointer' }} {...tappable(() => calendarSheet())}>
<div className="row between">
<div>
<div className="row" style={{ gap: 7, fontSize: 22, fontWeight: 600, letterSpacing: '-.021em' }}>
+9 -5
View File
@@ -1,4 +1,4 @@
import { useState } from 'react'
import { useRef, useState } from 'react'
import { useStore } from '../store/useStore.js'
import { EXDB, BODYPARTS, allExercises, equipmentOf, matchExercise } from '../lib/exercises.js'
import { activeProfile, exAvailable } from '../lib/equipment.js'
@@ -9,6 +9,7 @@ import { Thumb } from '../components/Media.jsx'
import { exerciseDetailSheet, addToRoutineSheet, customExSheet } from '../sheets.jsx'
import Icon from '../components/Icon.jsx'
import { Button } from '../components/ui.jsx'
import { tappable, useRevealActiveChip } from '../lib/use-sheet-keyboard.js'
export default function Library() {
const S = useStore(s => s.S)
@@ -17,6 +18,7 @@ export default function Library() {
const [eq, setEq] = useState('')
const [showAll, setShowAll] = useState(false) // ignore the active equipment profile for this session
const [shown, setShown] = useState(40)
const bpStrip = useRef(null), eqStrip = useRef(null)
const profile = activeProfile(S)
const base = allExercises(S).filter(e => (!bp || e.bp === bp) && matchExercise(e, q))
const eqFiltered = (profile && !showAll) ? base.filter(e => exAvailable(S, e)) : base
@@ -24,6 +26,8 @@ export default function Library() {
// 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
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>
@@ -36,22 +40,22 @@ export default function Library() {
{showAll ? t('Filter by "{0}"', profile.name) : t('Show all equipment')}
</button>
</div>}
<div className="chips" style={{ marginBottom: eqOpts.length > 1 ? 8 : 12 }}>
<div className="chips" ref={bpStrip} 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 }}>
{eqOpts.length > 1 && <div className="chips" ref={eqStrip} 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">
<div className="item" onClick={() => customExSheet(null, ex => exerciseDetailSheet(ex), q.trim())}>
<div className="item" {...tappable(() => customExSheet(null, ex => exerciseDetailSheet(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 => {
const best = bestWeightFor(S, e.id)
return <div key={e.id} className="item" onClick={() => exerciseDetailSheet(e)}>
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>
{best > 0 && <span className="tag acc">{fmtNum(best)}</span>}
+3 -2
View File
@@ -5,6 +5,7 @@ import { t } from '../lib/i18n.js'
import { dayAssignSheet, loadStarterPlan, planToolsSheet } from '../sheets.jsx'
import Icon from '../components/Icon.jsx'
import { Button } from '../components/ui.jsx'
import { tappable } from '../lib/use-sheet-keyboard.js'
import { glyphOf, DEFAULT_GLYPH } from '../lib/glyphs.js'
export default function Plan() {
@@ -28,7 +29,7 @@ export default function Plan() {
<div className="list" style={{ display: 'flex', flexDirection: 'column' }}>
{[1, 2, 3, 4, 5, 6, 0].map(d => {
const r = S.routines.find(x => x.id === S.week[d])
return <div key={d} className="item" onClick={() => dayAssignSheet(d)}>
return <div key={d} className="item" {...tappable(() => dayAssignSheet(d))}>
<div className="grow"><div className="tt">{t(DAYN[d])}</div></div>
{r ? <span className="tag acc"><Icon name={glyphOf(r.emoji)} />{r.name}</span> : <span className="tag">{t('Rest')}</span>}
<Icon name="chevronRight" className="chev" /></div>
@@ -39,7 +40,7 @@ export default function Plan() {
<h4 className="sec" style={{ margin: 0 }}>{t('Routines')}</h4>
<Button size="sm" variant="tinted" icon="plus" onClick={addRoutine}>{t('New')}</Button>
</div>
{S.routines.length ? <div className="list">{S.routines.map(r => <div key={r.id} className="item" onClick={() => nav('/plan/r/' + r.id)}>
{S.routines.length ? <div className="list">{S.routines.map(r => <div key={r.id} className="item" {...tappable(() => nav('/plan/r/' + r.id))}>
<span className="lrow-i"><Icon name={glyphOf(r.emoji)} /></span>
<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> : <>
@@ -0,0 +1,450 @@
// @vitest-environment happy-dom
import React, { act } from 'react'
import { createRoot } from 'react-dom/client'
import { MemoryRouter, Route, Routes } from 'react-router-dom'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
const sheets = vi.hoisted(() => ({
exConfigSheet: vi.fn(), exercisePicker: vi.fn(), glyphPicker: vi.fn(), confirmSheet: vi.fn(),
}))
vi.mock('../lib/api.js', () => ({ api: vi.fn(() => Promise.resolve({})) }))
vi.mock('../sheets.jsx', () => sheets)
vi.mock('../components/Media.jsx', () => ({ Thumb: ({ ex }) => <span data-thumb={ex.id} /> }))
vi.mock('../components/BodyMap.jsx', () => ({ default: () => null }))
import RoutineEdit, { ROUTINE_DRAG_SLOP, ROUTINE_LONG_PRESS_MS, reorderRoutineUnit } from './RoutineEdit.jsx'
import { DEF, useStore } from '../store/useStore.js'
globalThis.IS_REACT_ACT_ENVIRONMENT = true
const clone = value => JSON.parse(JSON.stringify(value))
const configured = (id, extra = {}) => ({ id, mode: 'reps', sets: 3, reps: 5, weight: 0, ...extra })
let root
let host
function stateFor(entries) {
const S = clone(DEF)
S.routines = [{ id: 'r1', name: 'Drag routine', emoji: 'dumbbell', prog: 'linear', ex: entries }]
return S
}
function rect(top, height, left = 20, width = 340) {
return { x: left, y: top, left, right: left + width, top, bottom: top + height, width, height }
}
const rows = () => [...host.querySelectorAll('[data-routine-row]')]
function geometry(heights = rows().map(() => 70)) {
const list = host.querySelector('.routine-list')
let top = 100
const tops = [], bottoms = [], centers = []
rows().forEach((row, i) => {
const height = heights[i] ?? 70
tops.push(top); bottoms.push(top + height); centers.push(top + height / 2)
vi.spyOn(row, 'getBoundingClientRect').mockImplementation(() => rect(tops[i], height))
top += height + 10
})
const listRect = rect(80, top - 80)
vi.spyOn(list, 'getBoundingClientRect').mockImplementation(() => listRect)
return { list, tops, bottoms, centers, listRect }
}
function mount(entries) {
useStore.setState({ S: stateFor(entries), user: null })
host = document.createElement('div')
document.body.appendChild(host)
root = createRoot(host)
act(() => root.render(<MemoryRouter initialEntries={['/plan/r/r1']}><Routes><Route path="/plan/r/:id" element={<RoutineEdit />} /></Routes></MemoryRouter>))
return geometry()
}
function remountCurrentState() {
host = document.createElement('div')
document.body.appendChild(host)
root = createRoot(host)
act(() => root.render(<MemoryRouter initialEntries={['/plan/r/r1']}><Routes><Route path="/plan/r/:id" element={<RoutineEdit />} /></Routes></MemoryRouter>))
return geometry()
}
function pointer(target, type, { id = 7, kind = 'touch', primary = true, button = 0, x = 120, y = 120 } = {}) {
const event = new Event(type, { bubbles: true, cancelable: true })
for (const [key, value] of Object.entries({ pointerId: id, pointerType: kind, isPrimary: primary, button, clientX: x, clientY: y })) {
Object.defineProperty(event, key, { configurable: true, value })
}
act(() => target.dispatchEvent(event))
return event
}
function lift(row, y, x = 120) {
pointer(row.querySelector('.item'), 'pointerdown', { x, y })
act(() => vi.advanceTimersByTime(ROUTINE_LONG_PRESS_MS))
}
const exercises = () => useStore.getState().S.routines[0].ex
beforeEach(() => {
vi.useFakeTimers()
vi.spyOn(window, 'requestAnimationFrame').mockImplementation(cb => window.setTimeout(() => cb(Date.now()), 16))
vi.spyOn(window, 'cancelAnimationFrame').mockImplementation(id => window.clearTimeout(id))
localStorage.clear()
Object.values(sheets).forEach(mock => mock.mockReset())
root = null; host = null
})
afterEach(() => {
if (root) act(() => root.unmount())
host?.remove()
vi.clearAllTimers(); vi.restoreAllMocks(); vi.useRealTimers()
})
describe('routine long-press reorder', () => {
it('exports the frozen threshold/slop and keeps a short press as a normal click', () => {
expect(ROUTINE_LONG_PRESS_MS).toBe(380)
expect(ROUTINE_DRAG_SLOP).toBe(8)
const layout = mount([configured('1001'), configured('1002')])
const item = rows()[0].querySelector('.item')
pointer(item, 'pointerdown', { y: layout.centers[0] })
act(() => vi.advanceTimersByTime(379))
expect(host.querySelector('.is-dragging')).toBeNull()
pointer(item, 'pointerup', { y: layout.centers[0] })
act(() => item.click())
expect(sheets.exConfigSheet).toHaveBeenCalledOnce()
expect(exercises().map(e => e.id)).toEqual(['1001', '1002'])
})
it('lifts at exactly 380 ms and yields pre-lift movement strictly over 8 px to scrolling', () => {
let layout = mount([configured('1001'), configured('1002')])
let item = rows()[0].querySelector('.item')
pointer(item, 'pointerdown', { x: 100, y: layout.centers[0] })
const atEight = pointer(item, 'pointermove', { x: 108, y: layout.centers[0] })
expect(atEight.defaultPrevented).toBe(false)
act(() => vi.advanceTimersByTime(380))
expect(rows()[0].classList.contains('is-dragging')).toBe(true)
pointer(item, 'pointercancel', { x: 108, y: layout.centers[0] })
act(() => root.unmount()); host.remove(); root = null; host = null
layout = mount([configured('1001'), configured('1002')])
item = rows()[0].querySelector('.item')
pointer(item, 'pointerdown', { x: 100, y: layout.centers[0] })
const atNine = pointer(item, 'pointermove', { x: 109, y: layout.centers[0] })
act(() => vi.advanceTimersByTime(380))
expect(atNine.defaultPrevented).toBe(false)
expect(host.querySelector('.is-dragging')).toBeNull()
})
it('owns active movement, renders an indicator, and suppresses the compatibility click after cancel', () => {
const layout = mount([configured('1001'), configured('1002'), configured('1003')])
const row = rows()[1], item = row.querySelector('.item')
const capture = vi.fn(), release = vi.fn()
item.setPointerCapture = capture; item.releasePointerCapture = release
lift(row, layout.centers[1])
expect(capture).toHaveBeenCalledWith(7)
expect(row.classList.contains('is-dragging')).toBe(true)
expect(host.querySelector('[data-testid="routine-drop-indicator"]')).toBeTruthy()
const move = pointer(item, 'pointermove', { y: layout.centers[2] })
expect(move.defaultPrevented).toBe(true)
pointer(item, 'pointercancel', { y: layout.centers[2] })
expect(release).toHaveBeenCalledWith(7)
act(() => item.click())
expect(sheets.exConfigSheet).not.toHaveBeenCalled()
expect(exercises().map(e => e.id)).toEqual(['1001', '1002', '1003'])
})
it('moves across measured slots and persists one complete changed order', () => {
const layout = mount([configured('a'), configured('b'), configured('c'), configured('d')])
const before = localStorage.getItem('gym_state_v1')
const writes = vi.spyOn(Storage.prototype, 'setItem')
const row = rows()[0], item = row.querySelector('.item')
lift(row, layout.centers[0])
pointer(item, 'pointermove', { y: layout.centers[2] + 1 })
pointer(item, 'pointerup', { y: layout.centers[2] + 1 })
expect(exercises().map(e => e.id)).toEqual(['b', 'c', 'a', 'd'])
expect(JSON.parse(localStorage.getItem('gym_state_v1')).routines[0].ex.map(e => e.id)).toEqual(['b', 'c', 'a', 'd'])
expect(localStorage.getItem('gym_state_v1')).not.toBe(before)
expect(writes).toHaveBeenCalledTimes(1)
})
it('suppresses the compatibility click after a successful changed drop', () => {
const layout = mount([configured('a'), configured('b'), configured('c')])
const item = rows()[0].querySelector('.item')
lift(rows()[0], layout.centers[0])
pointer(item, 'pointermove', { y: layout.centers[2] + 1 })
pointer(item, 'pointerup', { y: layout.centers[2] + 1 })
expect(exercises().map(e => e.id)).toEqual(['b', 'c', 'a'])
act(() => item.click())
expect(sheets.exConfigSheet).not.toHaveBeenCalled()
})
it('lets a real tap shortly after a drop open the row again', () => {
const layout = mount([configured('a'), configured('b'), configured('c')])
const item = rows()[0].querySelector('.item')
lift(rows()[0], layout.centers[0])
pointer(item, 'pointermove', { y: layout.centers[2] + 1 })
pointer(item, 'pointerup', { y: layout.centers[2] + 1 })
expect(exercises().map(e => e.id)).toEqual(['b', 'c', 'a'])
act(() => vi.advanceTimersByTime(200))
const target = rows()[1].querySelector('.item')
pointer(target, 'pointerdown', { y: layout.centers[1] })
pointer(target, 'pointerup', { y: layout.centers[1] })
act(() => target.click())
expect(sheets.exConfigSheet).toHaveBeenCalledTimes(1)
})
it('never eats a tap that starts with its own pointerdown, even right after a drop', () => {
const layout = mount([configured('a'), configured('b'), configured('c')])
const item = rows()[0].querySelector('.item')
lift(rows()[0], layout.centers[0])
pointer(item, 'pointermove', { y: layout.centers[2] + 1 })
pointer(item, 'pointerup', { y: layout.centers[2] + 1 })
const target = rows()[1].querySelector('.item')
pointer(target, 'pointerdown', { y: layout.centers[1] })
pointer(target, 'pointerup', { y: layout.centers[1] })
act(() => target.click())
expect(sheets.exConfigSheet).toHaveBeenCalledTimes(1)
})
it('moves a whole grouped unit, never splits another group, and preserves every occurrence payload', () => {
const pairA = configured('dup', { sg: 'pair', weight: 11, note: 'first', future: { a: 1 } })
const pairB = configured('dup', { sg: 'pair', weight: 22, note: 'second', future: { b: 2 } })
const layout = mount([pairA, pairB, configured('c'), configured('d')])
const row = rows()[1], item = row.querySelector('.item')
lift(row, layout.centers[1])
expect(rows().slice(0, 2).every(node => node.classList.contains('is-dragging'))).toBe(true)
pointer(item, 'pointermove', { y: layout.listRect.bottom - 1 })
pointer(item, 'pointerup', { y: layout.listRect.bottom - 1 })
expect(exercises()).toEqual([configured('c'), configured('d'), pairA, pairB])
act(() => root.unmount()); host.remove(); root = null; host = null
const splitLayout = mount([configured('a'), configured('b', { sg: 'g' }), configured('c', { sg: 'g' }), configured('tail')])
const tail = rows()[3], tailItem = tail.querySelector('.item')
lift(tail, splitLayout.centers[3])
const betweenMembers = (splitLayout.bottoms[1] + splitLayout.tops[2]) / 2
pointer(tailItem, 'pointermove', { y: betweenMembers })
pointer(tailItem, 'pointerup', { y: betweenMembers })
expect(exercises().map(e => e.id)).toEqual(['a', 'tail', 'b', 'c'])
})
it('moves the selected duplicate occurrence rather than finding by catalogue id', () => {
const first = configured('dup', { weight: 10, reps: 3, note: 'first' })
const second = configured('dup', { weight: 20, reps: 9, note: 'second' })
const layout = mount([first, configured('middle'), second, configured('tail')])
const row = rows()[2], item = row.querySelector('.item')
lift(row, layout.centers[2])
pointer(item, 'pointermove', { y: layout.tops[0] + 1 })
pointer(item, 'pointerup', { y: layout.tops[0] + 1 })
expect(exercises()).toEqual([second, first, configured('middle'), configured('tail')])
})
it('cancels without persistence on outside release, lost capture, Escape, blur, hidden document, or second pointer', () => {
const cancelCases = ['outside', 'lost', 'escape', 'blur', 'hidden', 'second']
for (const cancel of cancelCases) {
if (root) { act(() => root.unmount()); host.remove(); root = null; host = null }
const layout = mount([configured('a'), configured('b'), configured('c')])
const row = rows()[0], item = row.querySelector('.item')
const before = localStorage.getItem('gym_state_v1')
lift(row, layout.centers[0])
pointer(item, 'pointermove', { y: layout.centers[2] })
if (cancel === 'outside') pointer(item, 'pointerup', { x: layout.listRect.right + 20, y: layout.centers[2] })
if (cancel === 'lost') pointer(item, 'lostpointercapture', { y: layout.centers[2] })
if (cancel === 'escape') act(() => document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true })))
if (cancel === 'blur') act(() => window.dispatchEvent(new Event('blur')))
if (cancel === 'hidden') {
Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'hidden' })
act(() => document.dispatchEvent(new Event('visibilitychange')))
Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'visible' })
}
if (cancel === 'second') pointer(rows()[1].querySelector('.item'), 'pointerdown', { id: 8, y: layout.centers[1] })
expect(exercises().map(e => e.id), cancel).toEqual(['a', 'b', 'c'])
expect(localStorage.getItem('gym_state_v1'), cancel).toBe(before)
expect(host.querySelector('.is-dragging'), cancel).toBeNull()
}
})
it('ignores non-primary/control pointers and leaves accessible move buttons working', () => {
const layout = mount([configured('a'), configured('b')])
const down = host.querySelector('button[aria-label="Move down"]')
pointer(down, 'pointerdown', { y: layout.centers[0] })
act(() => vi.advanceTimersByTime(380))
expect(host.querySelector('.is-dragging')).toBeNull()
act(() => down.click())
expect(exercises().map(e => e.id)).toEqual(['b', 'a'])
const item = rows()[0].querySelector('.item')
pointer(item, 'pointerdown', { primary: false, y: layout.centers[0] })
act(() => vi.advanceTimersByTime(380))
expect(host.querySelector('.is-dragging')).toBeNull()
})
it('autoscrolls only after lift and stops frames on cancel', () => {
const layout = mount([configured('a'), configured('b'), configured('c'), configured('d')])
host.style.overflowY = 'auto'
Object.defineProperty(host, 'clientHeight', { configurable: true, value: 320 })
Object.defineProperty(host, 'scrollHeight', { configurable: true, value: 900 })
host.scrollTop = 100
vi.spyOn(host, 'getBoundingClientRect').mockImplementation(() => rect(0, 320))
const row = rows()[2], item = row.querySelector('.item')
pointer(item, 'pointerdown', { y: 310 })
act(() => vi.advanceTimersByTime(16))
expect(host.scrollTop).toBe(100)
act(() => vi.advanceTimersByTime(ROUTINE_LONG_PRESS_MS - 16 + 16))
expect(host.scrollTop).toBeGreaterThan(100)
pointer(item, 'pointercancel', { y: 310 })
const stopped = host.scrollTop
act(() => vi.advanceTimersByTime(64))
expect(host.scrollTop).toBe(stopped)
})
it('fails closed when row geometry disappears during an active drag', () => {
const layout = mount([configured('a'), configured('b'), configured('c')])
const row = rows()[0], item = row.querySelector('.item')
const before = localStorage.getItem('gym_state_v1')
lift(row, layout.centers[0])
rows()[1].getBoundingClientRect.mockReturnValue(undefined)
pointer(item, 'pointermove', { y: layout.centers[2] })
pointer(item, 'pointerup', { y: layout.centers[2] })
expect(exercises().map(e => e.id)).toEqual(['a', 'b', 'c'])
expect(localStorage.getItem('gym_state_v1')).toBe(before)
expect(host.querySelector('.is-dragging')).toBeNull()
})
it('cleans pending and active gestures on unmount without late writes', () => {
const layout = mount([configured('a'), configured('b')])
const item = rows()[0].querySelector('.item')
const before = localStorage.getItem('gym_state_v1')
pointer(item, 'pointerdown', { y: layout.centers[0] })
act(() => root.unmount()); root = null
act(() => vi.advanceTimersByTime(1000))
expect(localStorage.getItem('gym_state_v1')).toBe(before)
const activeLayout = mount([configured('a'), configured('b')])
const activeItem = rows()[0].querySelector('.item')
const release = vi.fn()
activeItem.releasePointerCapture = release
lift(rows()[0], activeLayout.centers[0])
act(() => root.unmount()); root = null
act(() => vi.advanceTimersByTime(1000))
expect(release).toHaveBeenCalledWith(7)
expect(localStorage.getItem('gym_state_v1')).toBe(before)
})
it('covers reverse measured slots and an unchanged original slot', () => {
let layout = mount([configured('a'), configured('b'), configured('c'), configured('d')])
let item = rows()[3].querySelector('.item')
lift(rows()[3], layout.centers[3])
pointer(item, 'pointermove', { y: layout.tops[1] + 1 })
pointer(item, 'pointerup', { y: layout.tops[1] + 1 })
expect(exercises().map(e => e.id)).toEqual(['a', 'd', 'b', 'c'])
act(() => root.unmount()); host.remove(); root = null; host = null
layout = mount([configured('a'), configured('b'), configured('c')])
const before = localStorage.getItem('gym_state_v1')
item = rows()[1].querySelector('.item')
lift(rows()[1], layout.centers[1])
pointer(item, 'pointermove', { y: layout.centers[1] + ROUTINE_DRAG_SLOP + 1 })
pointer(item, 'pointerup', { y: layout.centers[1] + ROUTINE_DRAG_SLOP + 1 })
expect(exercises().map(e => e.id)).toEqual(['a', 'b', 'c'])
expect(localStorage.getItem('gym_state_v1')).toBe(before)
})
it('reads the persisted changed order back after a fresh remount', () => {
const layout = mount([configured('a'), configured('b'), configured('c')])
const item = rows()[0].querySelector('.item')
lift(rows()[0], layout.centers[0])
pointer(item, 'pointermove', { y: layout.centers[2] + 1 })
pointer(item, 'pointerup', { y: layout.centers[2] + 1 })
const saved = JSON.parse(localStorage.getItem('gym_state_v1'))
act(() => root.unmount()); host.remove(); root = null; host = null
useStore.setState({ S: saved, user: null })
remountCurrentState()
expect(exercises().map(e => e.id)).toEqual(['b', 'c', 'a'])
})
it('cancels active ownership for a second pointer outside the list and pending lost capture', () => {
let layout = mount([configured('a'), configured('b'), configured('c')])
let item = rows()[0].querySelector('.item')
const before = localStorage.getItem('gym_state_v1')
lift(rows()[0], layout.centers[0])
pointer(item, 'pointermove', { y: layout.centers[2] })
pointer(document.body, 'pointerdown', { id: 8, y: 20 })
pointer(item, 'pointerup', { y: layout.centers[2] })
expect(exercises().map(e => e.id)).toEqual(['a', 'b', 'c'])
expect(localStorage.getItem('gym_state_v1')).toBe(before)
expect(host.querySelector('.is-dragging')).toBeNull()
act(() => root.unmount()); host.remove(); root = null; host = null
layout = mount([configured('a'), configured('b')])
item = rows()[0].querySelector('.item')
pointer(item, 'pointerdown', { y: layout.centers[0] })
pointer(item, 'lostpointercapture', { y: layout.centers[0] })
act(() => vi.advanceTimersByTime(ROUTINE_LONG_PRESS_MS))
expect(host.querySelector('.is-dragging')).toBeNull()
})
it('cancels when equal serialized exercises acquire a new current routine/list identity', () => {
let layout = mount([configured('a'), configured('b'), configured('c')])
let item = rows()[0].querySelector('.item')
lift(rows()[0], layout.centers[0])
pointer(item, 'pointermove', { y: layout.centers[2] })
act(() => useStore.getState().update(s => {
const current = s.routines[0]
s.routines[0] = { ...current, ex: clone(current.ex) }
}))
pointer(item, 'pointerup', { y: layout.centers[2] })
expect(exercises().map(e => e.id)).toEqual(['a', 'b', 'c'])
expect(host.querySelector('.is-dragging')).toBeNull()
act(() => root.unmount()); host.remove(); root = null; host = null
layout = mount([configured('a'), configured('b')])
item = rows()[0].querySelector('.item')
pointer(item, 'pointerdown', { y: layout.centers[0] })
act(() => useStore.getState().update(s => {
const current = s.routines[0]
s.routines[0] = { ...current, ex: clone(current.ex) }
}))
act(() => vi.advanceTimersByTime(ROUTINE_LONG_PRESS_MS))
expect(host.querySelector('.is-dragging')).toBeNull()
})
it('never owns nested link, Move up, or Move down controls', () => {
const layout = mount([configured('a'), configured('b')])
const controls = [
rows()[1].querySelector('button[title]'),
rows()[1].querySelector('button[aria-label="Move up"]'),
rows()[1].querySelector('button[aria-label="Move down"]'),
]
for (const control of controls) {
pointer(control, 'pointerdown', { y: layout.centers[1] })
act(() => vi.advanceTimersByTime(ROUTINE_LONG_PRESS_MS))
expect(host.querySelector('.is-dragging')).toBeNull()
pointer(control, 'pointerup', { y: layout.centers[1] })
}
})
it('falls back to page/window autoscroll without a nested scroll host', () => {
const layout = mount([configured('a'), configured('b'), configured('c')])
const rootElement = document.documentElement
Object.defineProperty(document, 'scrollingElement', { configurable: true, value: rootElement })
Object.defineProperty(rootElement, 'clientHeight', { configurable: true, value: 300 })
Object.defineProperty(rootElement, 'scrollHeight', { configurable: true, value: 900 })
Object.defineProperty(window, 'innerHeight', { configurable: true, value: 300 })
Object.defineProperty(window, 'scrollY', { configurable: true, writable: true, value: 100 })
const scrollBy = vi.spyOn(window, 'scrollBy').mockImplementation((_, delta) => { window.scrollY += delta })
const item = rows()[2].querySelector('.item')
lift(rows()[2], 295)
act(() => vi.advanceTimersByTime(16))
expect(scrollBy).toHaveBeenCalled()
expect(window.scrollY).toBeGreaterThan(100)
pointer(item, 'pointercancel', { y: 295 })
})
it('invalidates ownership before cleanup synchronously emits lost capture', () => {
const layout = mount([configured('a'), configured('b')])
const item = rows()[0].querySelector('.item')
const release = vi.fn(pointerId => pointer(document, 'lostpointercapture', { id: pointerId, y: layout.centers[0] }))
item.releasePointerCapture = release
lift(rows()[0], layout.centers[0])
act(() => root.unmount()); root = null
expect(release).toHaveBeenCalledTimes(1)
})
})
describe('reorderRoutineUnit', () => {
it('splices complete units at canonical slots and cleans true orphans', () => {
const items = [configured('a', { sg: 'pair' }), configured('b', { sg: 'pair' }), configured('c', { sg: 'orphan' }), configured('d')]
expect(reorderRoutineUnit(items, 3, 1)).toBe(true)
expect(items.map(e => e.id)).toEqual(['a', 'b', 'd', 'c'])
expect(items[0].sg).toBe('pair'); expect(items[1].sg).toBe('pair'); expect(items[3].sg).toBeUndefined()
})
})
+324 -12
View File
@@ -1,20 +1,305 @@
import { useNavigate, useParams } from 'react-router-dom'
import { useEffect } from 'react'
import { useEffect, useRef, useState } from 'react'
import { useStore } from '../store/useStore.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, cleanupSg, exLine } from '../lib/history.js'
import { supersetUnits, moveSupersetUnit, cleanupSg, exLine } 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, SelectRow } from '../components/ui.jsx'
import { Button, Row, SelectRow, Switch } from '../components/ui.jsx'
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'
export const ROUTINE_LONG_PRESS_MS = 380
export const ROUTINE_DRAG_SLOP = 8
const clamp = (value, low, high) => Math.max(low, Math.min(high, value))
// Slots are defined after removing the source unit, so a grouped run can never be split.
export function reorderRoutineUnit(exercises, sourceIndex, targetSlot) {
if (!Array.isArray(exercises) || !exercises.length) return false
const units = supersetUnits(exercises)
const sourcePosition = units.findIndex(unit => unit.includes(sourceIndex))
if (sourcePosition < 0) return false
const remaining = units.filter((_, position) => position !== sourcePosition)
const slot = clamp(Number.isFinite(targetSlot) ? Math.trunc(targetSlot) : sourcePosition, 0, remaining.length)
if (slot === sourcePosition) return false
const source = units[sourcePosition]
const moved = exercises.splice(source[0], source.length)
const insertAt = remaining.slice(0, slot).reduce((count, unit) => count + unit.length, 0)
exercises.splice(insertAt, 0, ...moved)
cleanupSg(exercises)
return true
}
function unitGeometry(list, exercises) {
const rows = new Map([...list.querySelectorAll('[data-routine-row]')]
.map(row => [Number(row.dataset.exIndex), row]))
const units = supersetUnits(exercises)
const geometry = units.map((unit, position) => {
const rects = unit.map(index => rows.get(index)?.getBoundingClientRect()).filter(Boolean)
if (rects.length !== unit.length) return null
const top = Math.min(...rects.map(rect => rect.top))
const bottom = Math.max(...rects.map(rect => rect.bottom))
return { unit, position, top, bottom, center: top + (bottom - top) / 2 }
})
return geometry.every(Boolean) ? geometry : null
}
function scrollHostFor(node) {
for (let parent = node.parentElement; parent && parent !== document.body; parent = parent.parentElement) {
const overflowY = window.getComputedStyle(parent).overflowY
if (/(auto|scroll)/.test(overflowY) && parent.scrollHeight > parent.clientHeight) return parent
}
return window
}
function autoScrollStep(host, clientY) {
const edge = 64
const maxStep = 14
let top, bottom, scrollTop, maxScroll
if (host === window) {
const root = document.scrollingElement || document.documentElement
top = window.visualViewport?.offsetTop || 0
bottom = top + (window.visualViewport?.height || window.innerHeight || root.clientHeight)
scrollTop = window.scrollY || root.scrollTop || 0
maxScroll = Math.max(root.scrollHeight, document.body?.scrollHeight || 0) - (bottom - top)
} else {
const rect = host.getBoundingClientRect()
top = rect.top; bottom = rect.bottom
scrollTop = host.scrollTop; maxScroll = host.scrollHeight - host.clientHeight
}
if (clientY < top + edge && scrollTop > 0) return -Math.ceil(maxStep * clamp((top + edge - clientY) / edge, 0, 1))
if (clientY > bottom - edge && scrollTop < maxScroll) return Math.ceil(maxStep * clamp((clientY - bottom + edge) / edge, 0, 1))
return 0
}
function useRoutineReorder(routineIdentity, exercises, onDrop) {
const listRef = useRef(null)
const gestureRef = useRef(null)
const exercisesRef = useRef(exercises)
const routineIdentityRef = useRef(routineIdentity)
const onDropRef = useRef(onDrop)
const suppressClickRef = useRef(false)
const suppressTimerRef = useRef(null)
const [drag, setDrag] = useState(null)
exercisesRef.current = exercises
routineIdentityRef.current = routineIdentity
onDropRef.current = onDrop
const hasRows = exercises.length > 0
useEffect(() => () => {
suppressClickRef.current = false
window.clearTimeout(suppressTimerRef.current)
}, [])
useEffect(() => {
const list = listRef.current
if (!list) return undefined
let frame = null
setDrag(current => current ? null : current)
const clearFrame = () => {
if (frame != null) window.cancelAnimationFrame(frame)
frame = null
}
const clearTimer = gesture => {
if (gesture?.timer != null) window.clearTimeout(gesture.timer)
if (gesture) gesture.timer = null
}
const matchesSnapshot = gesture => routineIdentityRef.current === gesture.routineIdentity
&& exercisesRef.current === gesture.listIdentity
&& JSON.stringify(exercisesRef.current) === gesture.snapshot
const releaseCapture = gesture => {
const target = gesture?.captureTarget
if (!target?.releasePointerCapture) return
try { target.releasePointerCapture(gesture.pointerId) } catch { /* already released */ }
}
const finish = (gesture, commit, x = gesture?.lastX, y = gesture?.lastY) => {
if (!gesture || gestureRef.current !== gesture) return
clearTimer(gesture)
clearFrame()
gestureRef.current = null
if (!gesture.active) return
releaseCapture(gesture)
suppressClickRef.current = true
window.clearTimeout(suppressTimerRef.current)
// The compatibility click lands synchronously after pointerup; anything
// later is a real tap, so the guard only needs to outlive that one event.
suppressTimerRef.current = window.setTimeout(() => { suppressClickRef.current = false }, 150)
setDrag(null)
const rect = list.getBoundingClientRect()
const inside = x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom
const geometry = unitGeometry(list, exercisesRef.current)
if (commit && inside && geometry && matchesSnapshot(gesture) && gesture.targetSlot !== gesture.sourcePosition) {
onDropRef.current(gesture.sourceIndex, gesture.targetSlot)
}
}
const indicatorTop = (geometry, gesture, slot, listRect) => {
if (slot === gesture.sourcePosition) return clamp(gesture.sourceTop - listRect.top, 0, listRect.height)
const remaining = geometry.filter(unit => unit.position !== gesture.sourcePosition)
let top
if (slot <= 0) top = remaining[0]?.top ?? gesture.sourceTop
else if (slot >= remaining.length) top = remaining.at(-1)?.bottom ?? gesture.sourceBottom
else top = (remaining[slot - 1].bottom + remaining[slot].top) / 2
return clamp(top - listRect.top, 0, listRect.height)
}
const updateDrag = (gesture, x, y, schedule = true) => {
if (gestureRef.current !== gesture || !gesture.active || !matchesSnapshot(gesture)) {
if (gestureRef.current === gesture) finish(gesture, false)
return
}
const geometry = unitGeometry(list, exercisesRef.current)
if (!geometry) { finish(gesture, false); return }
const listRect = list.getBoundingClientRect()
const remaining = geometry.filter(unit => unit.position !== gesture.sourcePosition)
const probeY = clamp(y, listRect.top, listRect.bottom)
const moved = Math.hypot(x - gesture.startX, y - gesture.startY) > ROUTINE_DRAG_SLOP
const slot = moved ? remaining.reduce((count, unit) => count + (probeY > unit.center ? 1 : 0), 0) : gesture.sourcePosition
const rawDelta = y - gesture.grabOffset - gesture.sourceTop
const deltaY = clamp(rawDelta, listRect.top - gesture.sourceTop, listRect.bottom - gesture.sourceBottom)
gesture.lastX = x; gesture.lastY = y; gesture.targetSlot = slot
setDrag({ first: gesture.sourceUnit[0], last: gesture.sourceUnit.at(-1), deltaY, indicatorTop: indicatorTop(geometry, gesture, slot, listRect) })
if (schedule && frame == null) frame = window.requestAnimationFrame(runAutoScroll)
}
function runAutoScroll() {
frame = null
const gesture = gestureRef.current
if (!gesture?.active) return
const step = autoScrollStep(gesture.scrollHost, gesture.lastY)
if (!step) return
if (gesture.scrollHost === window) window.scrollBy(0, step)
else gesture.scrollHost.scrollTop += step
updateDrag(gesture, gesture.lastX, gesture.lastY, false)
if (gestureRef.current === gesture) frame = window.requestAnimationFrame(runAutoScroll)
}
const lift = gesture => {
if (gestureRef.current !== gesture) return
if (!matchesSnapshot(gesture)) { finish(gesture, false); return }
const geometry = unitGeometry(list, exercisesRef.current)
const source = geometry?.find(unit => unit.unit.includes(gesture.sourceIndex))
if (!source) { finish(gesture, false); return }
gesture.active = true; gesture.timer = null
gesture.sourcePosition = source.position; gesture.sourceUnit = source.unit
gesture.sourceTop = source.top; gesture.sourceBottom = source.bottom
gesture.grabOffset = gesture.lastY - source.top; gesture.targetSlot = source.position
gesture.scrollHost = scrollHostFor(list)
gesture.captureTarget = gesture.downTarget
try { gesture.captureTarget.setPointerCapture?.(gesture.pointerId) } catch { /* unsupported */ }
suppressClickRef.current = true
window.clearTimeout(suppressTimerRef.current)
updateDrag(gesture, gesture.lastX, gesture.lastY)
}
const onPointerDown = event => {
// a new touch is intentional — never let the post-drop guard eat its click
suppressClickRef.current = false
window.clearTimeout(suppressTimerRef.current)
const current = gestureRef.current
if (current) {
if (event.pointerId !== current.pointerId) finish(current, false)
return
}
if (event.isPrimary === false || (event.pointerType === 'mouse' && event.button !== 0)) return
const target = event.target
if (!target?.closest || target.closest('button,a,input,textarea,select,[data-nodrag]')) return
const row = target.closest('[data-routine-row]')
if (!row || !list.contains(row)) return
const sourceIndex = Number(row.dataset.exIndex)
if (!Number.isInteger(sourceIndex)) return
const gesture = {
pointerId: event.pointerId, sourceIndex, downTarget: target,
startX: event.clientX, startY: event.clientY, lastX: event.clientX, lastY: event.clientY,
routineIdentity: routineIdentityRef.current,
listIdentity: exercisesRef.current,
snapshot: JSON.stringify(exercisesRef.current), active: false, timer: null,
}
gesture.timer = window.setTimeout(() => lift(gesture), ROUTINE_LONG_PRESS_MS)
gestureRef.current = gesture
}
const onPointerMove = event => {
const gesture = gestureRef.current
if (!gesture || event.pointerId !== gesture.pointerId) return
if (!gesture.active) {
if (Math.hypot(event.clientX - gesture.startX, event.clientY - gesture.startY) > ROUTINE_DRAG_SLOP) {
clearTimer(gesture); gestureRef.current = null
} else { gesture.lastX = event.clientX; gesture.lastY = event.clientY }
return
}
event.preventDefault()
updateDrag(gesture, event.clientX, event.clientY)
}
const onPointerUp = event => {
const gesture = gestureRef.current
if (!gesture || event.pointerId !== gesture.pointerId) return
if (gesture.active) event.preventDefault()
finish(gesture, gesture.active, event.clientX, event.clientY)
}
const onPointerCancel = event => {
const gesture = gestureRef.current
if (gesture && event.pointerId === gesture.pointerId) finish(gesture, false)
}
const onLostCapture = event => {
const gesture = gestureRef.current
if (gesture && event.pointerId === gesture.pointerId) finish(gesture, false)
}
const cancelActive = () => finish(gestureRef.current, false)
const onKeyDown = event => {
if (event.key !== 'Escape' || !gestureRef.current) return
event.preventDefault(); cancelActive()
}
const onVisibility = () => { if (document.visibilityState === 'hidden') cancelActive() }
const onContextMenu = event => { if (gestureRef.current?.active && event.target.closest?.('[data-routine-row]')) event.preventDefault() }
const onDragStart = event => { if (event.target.closest?.('[data-routine-row]')) event.preventDefault() }
// Touch: the rows keep `touch-action: pan-y` so the list still scrolls with a finger, but once
// a long-press has lifted a row the browser must not claim the vertical drag as a pan — it
// would fire pointercancel and scroll instead. preventDefault on a pointer event cannot stop
// that; only a non-passive touchmove listener can, and only while a drag is actually active.
const onTouchMove = event => { if (gestureRef.current?.active) event.preventDefault() }
document.addEventListener('pointerdown', onPointerDown)
document.addEventListener('touchmove', onTouchMove, { passive: false })
document.addEventListener('pointermove', onPointerMove, { passive: false })
document.addEventListener('pointerup', onPointerUp, { passive: false })
document.addEventListener('pointercancel', onPointerCancel)
document.addEventListener('lostpointercapture', onLostCapture)
document.addEventListener('keydown', onKeyDown)
document.addEventListener('visibilitychange', onVisibility)
list.addEventListener('contextmenu', onContextMenu)
list.addEventListener('dragstart', onDragStart)
window.addEventListener('blur', cancelActive)
return () => {
const gesture = gestureRef.current
clearTimer(gesture); clearFrame(); gestureRef.current = null
releaseCapture(gesture)
document.removeEventListener('pointerdown', onPointerDown)
document.removeEventListener('touchmove', onTouchMove)
document.removeEventListener('pointermove', onPointerMove)
document.removeEventListener('pointerup', onPointerUp)
document.removeEventListener('pointercancel', onPointerCancel)
document.removeEventListener('lostpointercapture', onLostCapture)
document.removeEventListener('keydown', onKeyDown)
document.removeEventListener('visibilitychange', onVisibility)
list.removeEventListener('contextmenu', onContextMenu)
list.removeEventListener('dragstart', onDragStart)
window.removeEventListener('blur', cancelActive)
}
}, [hasRows, routineIdentity, exercises])
const onClickCapture = event => {
if (!suppressClickRef.current) return
suppressClickRef.current = false
window.clearTimeout(suppressTimerRef.current)
event.preventDefault(); event.stopPropagation()
}
return { listRef, drag, onClickCapture }
}
export default function RoutineEdit() {
const nav = useNavigate()
const { id } = useParams()
@@ -26,10 +311,21 @@ export default function RoutineEdit() {
// auto-backup on the way out (not per keystroke) covers the whole editing session, deletion
// included: this still unmounts after the delete button navigates away.
useEffect(() => () => useStore.getState().autoBackupNow(), [])
if (!r) return null
const edit = fn => update(s => { fn(s.routines.find(x => x.id === id).ex) })
const move = (i, dir) => edit(ex => { const j = i + dir; if (j < 0 || j >= ex.length) return;[ex[i], ex[j]] = [ex[j], ex[i]]; cleanupSg(ex) })
const reorder = useRoutineReorder(r, r?.ex || [], (sourceIndex, targetSlot) => {
edit(exercises => { reorderRoutineUnit(exercises, sourceIndex, targetSlot) })
})
if (!r) return null
const move = (i, dir) => {
// Guard before update so a stale/boundary activation cannot trigger persistence or cleanup.
if (!moveSupersetUnit(r.ex, i, dir)) return
edit(ex => {
const reordered = moveSupersetUnit(ex, i, dir)
if (!reordered) return
ex.splice(0, ex.length, ...reordered)
cleanupSg(ex)
})
}
const toggleLink = i => edit(ex => {
if (i < 1) return
const cur = ex[i], prev = ex[i - 1]
@@ -39,6 +335,7 @@ export default function RoutineEdit() {
})
const units = supersetUnits(r.ex)
const unitIndex = new Map(units.flatMap((unit, index) => unit.map(i => [i, index])))
const unitFirst = new Set(units.filter(u => u.length > 1).map(u => u[0]))
const inSS = new Set(units.filter(u => u.length > 1).flat())
const profile = activeProfile(S)
@@ -58,9 +355,19 @@ export default function RoutineEdit() {
<SelectRow icon="chartLine" title={t('Progression')} sheetTitle={t('Progression')}
value={r.prog || 'linear'} onChange={v => update(s => { s.routines.find(x => x.id === id).prog = v })}
options={POLICIES_FOR.reps.map(p => ({ value: p, label: t(POLICY_NAME[p]), subtitle: t(POLICY_DESC[p]) }))} />
<Row icon="pause" iconTint="var(--orange)" title={t('Exclude from automatic progression')}
subtitle={t('Use for planned deloads. Workouts stay in history and statistics.')}>
<Switch checked={r.excludeFromProgression === true} onChange={v => update(s => {
const routine = s.routines.find(x => x.id === id)
if (v) routine.excludeFromProgression = true
else delete routine.excludeFromProgression
})} />
</Row>
</div>
<div className="small dim" style={{ margin: '-10px 2px 16px' }}>
{t('Applies to every exercise in this routine that does not set its own rule.')}
{r.excludeFromProgression
? t('The next regular target continues from the last included workout.')
: t('Applies to every exercise in this routine that does not set its own rule.')}
</div>
{missingCount > 0 && <div className="card" style={{ marginBottom: 16, borderColor: 'var(--orange)' }}>
@@ -70,13 +377,17 @@ export default function RoutineEdit() {
</div>
</div>}
{r.ex.length ? <div className="list">{r.ex.map((e, i) => {
{r.ex.length ? <div ref={reorder.listRef} onClickCapture={reorder.onClickCapture}
className={'list routine-list' + (reorder.drag ? ' is-reordering' : '')}>{r.ex.map((e, i) => {
// An unresolvable id is shown rather than skipped — hiding it left an entry you
// could neither see nor delete, but that still turned up in the workout.
const ex = exOr(e.id)
const noEquip = profile && !exAvailable(S, ex)
const linkedPrev = i > 0 && e.sg && r.ex[i - 1].sg === e.sg
return <div key={i}>
const isDragging = reorder.drag && i >= reorder.drag.first && i <= reorder.drag.last
return <div key={i} data-routine-row data-ex-index={i}
className={'routine-drag-row' + (isDragging ? ' is-dragging' : '')}
style={isDragging ? { transform: `translate3d(0, ${reorder.drag.deltaY}px, 0)` } : undefined}>
{unitFirst.has(i) && <div className="ss-label"><Icon name="link" />{t('Superset')}</div>}
<div className={'item' + (inSS.has(i) ? ' in-ss' : '')} onClick={() => {
exConfigSheet(ex, e, cfg => edit(x => { x[i] = { id: x[i].id, sg: x[i].sg, ...cfg } }), () => edit(x => { x.splice(i, 1); cleanupSg(x) }), r)
@@ -88,13 +399,14 @@ export default function RoutineEdit() {
<div style={{ display: 'flex', flexDirection: 'column', gap: 2, flex: 'none', alignItems: 'center' }}>
{i > 0 && <button className={'iconbtn' + (linkedPrev ? ' on-ss' : '')} title={t('Superset with exercise above')} style={{ width: 32, height: 28, borderRadius: 8, fontSize: 15 }} onClick={ev => { ev.stopPropagation(); toggleLink(i) }}><Icon name="link" /></button>}
<div style={{ display: 'flex', gap: 2 }}>
<button className="iconbtn" aria-label="Move up" style={{ width: 28, height: 24, borderRadius: 7, fontSize: 12 }} onClick={ev => { ev.stopPropagation(); move(i, -1) }}><Icon name="chevronUp" /></button>
<button className="iconbtn" aria-label="Move down" style={{ width: 28, height: 24, borderRadius: 7, fontSize: 12 }} onClick={ev => { ev.stopPropagation(); move(i, 1) }}><Icon name="chevronDown" /></button>
<button className="iconbtn" aria-label={t('Move up')} title={t('Move up')} disabled={unitIndex.get(i) === 0} style={{ width: 28, height: 24, borderRadius: 7, fontSize: 12 }} onClick={ev => { ev.stopPropagation(); move(i, -1) }}><Icon name="chevronUp" /></button>
<button className="iconbtn" aria-label={t('Move down')} title={t('Move down')} disabled={unitIndex.get(i) === units.length - 1} style={{ width: 28, height: 24, borderRadius: 7, fontSize: 12 }} onClick={ev => { ev.stopPropagation(); move(i, 1) }}><Icon name="chevronDown" /></button>
</div>
</div>
</div>
</div>
})}</div> : <div className="empty"><div className="ico"><Icon name="dumbbell" /></div>{t('No exercises yet — add your first one.')}</div>}
})}{reorder.drag && <div className="routine-drop-indicator" data-testid="routine-drop-indicator"
aria-hidden="true" style={{ top: `${reorder.drag.indicatorTop}px` }} />}</div> : <div className="empty"><div className="ico"><Icon name="dumbbell" /></div>{t('No exercises yet — add your first one.')}</div>}
{/* Coverage of the routine as planned, so a gap shows up while you're building it
rather than after a month of training around it. */}
@@ -0,0 +1,226 @@
// @vitest-environment happy-dom
import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
import React, { act } from 'react'
import { LANGS } from '../lib/i18n-core.js'
import { createRoot } from 'react-dom/client'
import { MemoryRouter, Route, Routes } from 'react-router-dom'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import RoutineEdit from './RoutineEdit.jsx'
import { DEF, useStore } from '../store/useStore.js'
import { _setLangState } from '../lib/i18n-core.js'
import de from '../locales/de.js'
import { buildPlanBundle, parsePlan } from '../lib/plan-share.js'
const cssSource = readFileSync(resolve(process.cwd(), 'src/index.css'), 'utf8')
const mocks = vi.hoisted(() => ({ exConfigSheet: vi.fn() }))
vi.mock('../lib/api.js', () => ({ api: vi.fn(() => Promise.resolve({})) }))
vi.mock('../sheets.jsx', () => ({
glyphPicker: vi.fn(), exercisePicker: vi.fn(), exConfigSheet: mocks.exConfigSheet, confirmSheet: vi.fn()
}))
vi.mock('../components/Media.jsx', () => ({ Thumb: () => null }))
vi.mock('../components/BodyMap.jsx', () => ({ default: () => null }))
globalThis.IS_REACT_ACT_ENVIRONMENT = true
const clone = value => JSON.parse(JSON.stringify(value))
const custom = id => ({ id, n: id, bp: 'chest', eq: 'body weight', tg: 'chest', custom: true })
const entry = (id, setup, sg) => ({
id, sets: 3, reps: 5, weight: setup, note: `setup-${setup}`,
...(sg ? { sg } : {})
})
let root
let container
function setRoutine(ex) {
const S = clone(DEF)
S.routines = [{ id: 'r1', name: 'Move test', emoji: 'dumbbell', ex }]
S.customEx = ['c1', 'c2', 'c3', 'c4'].map(custom)
useStore.setState({ S, user: null })
}
function renderRoutine() {
container = document.createElement('div')
document.body.appendChild(container)
root = createRoot(container)
act(() => root.render(
<MemoryRouter initialEntries={['/routine/r1']}>
<Routes><Route path="/routine/:id" element={<RoutineEdit />} /></Routes>
</MemoryRouter>
))
}
function itemFor(name) {
return [...container.querySelectorAll('.item')].find(item => item.textContent.includes(name))
}
function moveButton(name, direction) {
return itemFor(name).querySelector(`button[aria-label="${direction}"]`)
}
function pointerActivateArea(button) {
// Model browser hit-testing: pointer-events:none removes the disabled button
// from the target chain, exposing the clickable routine row underneath.
const disabledRule = cssSource.match(/\.iconbtn:disabled\s*\{[^}]*\}/)?.[0] || ''
const target = /pointer-events\s*:\s*none/.test(disabledRule)
? button.closest('.item')
: button
act(() => {
target.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true }))
target.dispatchEvent(new PointerEvent('pointerup', { bubbles: true }))
if (!(target instanceof HTMLButtonElement && target.disabled)) {
target.dispatchEvent(new MouseEvent('click', { bubbles: true }))
}
})
}
beforeEach(() => {
localStorage.clear()
mocks.exConfigSheet.mockClear()
_setLangState('en', null, null, null)
root = null
container = null
})
afterEach(() => {
if (root) act(() => root.unmount())
if (container) container.remove()
_setLangState('en', null, null, null)
})
describe('routine move controls', () => {
it('moves a selected superset member as one contiguous unit and persists complete occurrences', () => {
setRoutine([
entry('c1', 10, 'g'),
entry('c2', 20, 'g'),
entry('c3', 30)
])
renderRoutine()
act(() => moveButton('setup-20', 'Move down').click())
const moved = useStore.getState().S.routines[0].ex
expect(moved).toEqual([
entry('c3', 30),
entry('c1', 10, 'g'),
entry('c2', 20, 'g')
])
expect(JSON.parse(localStorage.getItem('gym_state_v1')).routines[0].ex).toEqual(moved)
})
it('moves the selected duplicate occurrence without aliasing its configuration', () => {
setRoutine([
entry('c1', 10),
entry('c2', 20),
entry('c1', 30)
])
renderRoutine()
act(() => moveButton('setup-30', 'Move up').click())
expect(useStore.getState().S.routines[0].ex).toEqual([
entry('c1', 10),
entry('c1', 30),
entry('c2', 20)
])
})
it('moves a standalone occurrence down with every configuration field intact', () => {
const selected = {
...entry('c1', 10),
mode: 'reps', prog: 'double', repsMin: 4, repsMax: 12,
side: true, warmupSets: 2,
intensifier: { type: 'restpause', pauseSec: 20 }
}
setRoutine([selected, entry('c2', 20), entry('c3', 30)])
renderRoutine()
act(() => moveButton('setup-10', 'Move down').click())
expect(useStore.getState().S.routines[0].ex).toEqual([
entry('c2', 20), selected, entry('c3', 30)
])
})
it('disables unit-boundary directions without cleaning or persisting state', () => {
setRoutine([
entry('c1', 10, 'orphan'),
entry('c2', 20)
])
renderRoutine()
const before = useStore.getState().S
expect(moveButton('c1', 'Move up').disabled).toBe(true)
expect(moveButton('c2', 'Move down').disabled).toBe(true)
act(() => moveButton('c1', 'Move up').click())
expect(useStore.getState().S).toBe(before)
expect(useStore.getState().S.routines[0].ex[0].sg).toBe('orphan')
expect(localStorage.getItem('gym_state_v1')).toBeNull()
})
it('keeps pointer activation in both disabled boundary areas isolated from the routine row', () => {
setRoutine([
entry('c1', 10, 'orphan'),
entry('c2', 20)
])
renderRoutine()
const before = useStore.getState().S
const firstUp = moveButton('c1', 'Move up')
const lastDown = moveButton('c2', 'Move down')
expect(firstUp.disabled).toBe(true)
expect(lastDown.disabled).toBe(true)
pointerActivateArea(firstUp)
pointerActivateArea(lastDown)
expect(mocks.exConfigSheet).not.toHaveBeenCalled()
expect(useStore.getState().S).toBe(before)
expect(useStore.getState().S.routines[0].ex[0].sg).toBe('orphan')
expect(localStorage.getItem('gym_state_v1')).toBeNull()
})
it('uses localized accessible names and titles, retains button focus, and does not open config', () => {
_setLangState('de', de, null, null)
setRoutine([entry('c1', 10), entry('c2', 20)])
renderRoutine()
const button = moveButton('c2', 'Nach oben')
expect(button.title).toBe('Nach oben')
button.focus()
act(() => button.click())
expect(document.activeElement?.tagName).toBe('BUTTON')
expect(mocks.exConfigSheet).not.toHaveBeenCalled()
})
it('retains reordered occurrence order and grouping through plan export and import', () => {
setRoutine([
entry('c1', 10, 'g'),
entry('c2', 20, 'g'),
entry('c3', 30)
])
renderRoutine()
act(() => moveButton('setup-10', 'Move down').click())
const parsed = parsePlan(JSON.stringify(buildPlanBundle(useStore.getState().S, 'Move test')))
expect(parsed.routines[0].ex).toEqual([
entry('c3', 30),
entry('c1', 10, 'g'),
entry('c2', 20, 'g')
])
})
})
describe('routine move-control locale coverage', () => {
const packs = import.meta.glob('../locales/*.js', { eager: true, import: 'default' })
it('defines both accessible names in every non-English locale pack', () => {
expect(Object.keys(packs)).toHaveLength(Object.keys(LANGS).length - 1)
Object.entries(packs).forEach(([path, pack]) => {
expect(pack, `${path} is missing Move up`).toHaveProperty('Move up')
expect(pack, `${path} is missing Move down`).toHaveProperty('Move down')
})
})
})
+7 -1
View File
@@ -11,7 +11,7 @@ import { t, LANGS, INSTR_LANGS } from '../lib/i18n.js'
import { DEMO, REPO } from '../lib/demo.js'
import { MOBILE, shareExport, syncReminder } from '../lib/mobile.js'
import { ConnectSheet } from './MobileOnboarding.jsx'
import { loadStarterPlan, confirmSheet, importFromApp, equipmentProfileSheet } from '../sheets.jsx'
import { loadStarterPlan, confirmSheet, importFromApp, importFromHevy, equipmentProfileSheet } from '../sheets.jsx'
import Icon from '../components/Icon.jsx'
import { Section, Row, SelectRow, Switch, Segmented, Button, TextField } from '../components/ui.jsx'
@@ -148,6 +148,9 @@ export default function Settings() {
<Row icon="bell" iconTint="var(--pink)" title={t('Sounds')}>
<Switch checked={!!S.sound} onChange={v => update(s => { s.sound = v })} />
</Row>
<Row icon="sun" iconTint="var(--yellow)" title={t('Flash screen when timer ends')}>
<Switch checked={!!S.timerFlash} onChange={v => update(s => { s.timerFlash = v })} />
</Row>
{/* Two names for the same judgement, so the column asks in the scale you already think in.
The (i) sits before the control — you read it on the way to the choice, not after it. */}
<Row icon="target" iconTint="var(--purple)" title={t('Effort per set')}>
@@ -203,6 +206,9 @@ export default function Settings() {
<Row icon="shuffle" iconTint="var(--teal)" title={t('Import from another app')}
subtitle={t('FitNotes, Strong, Hevy — or body weight from Apple Health')}
accessory="chevron" onClick={() => importRef.current.click()} />
<Row icon="key" iconTint="var(--teal)" title={t('Import from Hevy')}
subtitle={t('Pull your history with a Hevy Pro API key')}
accessory="chevron" onClick={importFromHevy} />
<Row icon="upload" iconTint="var(--blue)" title={t('Import backup')} accessory="chevron" onClick={() => fileRef.current.click()} />
<Row icon="download" iconTint="var(--blue)" title={t('Export backup (JSON)')} accessory="chevron" onClick={doExport} />
{MOBILE && <Row icon="history" iconTint="var(--blue)" title={t('Auto-backup on changes')}
+45 -10
View File
@@ -1,16 +1,16 @@
import { useEffect, useMemo, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useStore } from '../store/useStore.js'
import { EXIDX } from '../lib/exercises.js'
import { EXIDX, matchExercise } from '../lib/exercises.js'
import { lastBW, streakWeeks, setLabel, modeOf, effortOf, metricModeForEntry, metricRowsForEntry, bestWeightForEntry } from '../lib/history.js'
import { fmtNum, fmtDate, fmtVol, todayISO, weekKey } from '../lib/format.js'
import { fmtNum, fmtDate, fmtVol, todayISO } from '../lib/format.js'
import { t, exerciseNameFor, getLang } from '../lib/i18n.js'
import { bwSheet, goalSheet, calendarSheet, workoutDetailSheet, WorkoutRow, bwDeltaColor } from '../sheets.jsx'
import LineChart from '../components/LineChart.jsx'
import Heatmap from '../components/Heatmap.jsx'
import Icon from '../components/Icon.jsx'
import BodyMap, { BodyMapLegend } from '../components/BodyMap.jsx'
import { loadOfWorkouts, rankOf, MUSCLE_NAME, musclesOf } from '../lib/muscles.js'
import { loadOfWorkouts, muscleBalanceWindow, rankOf, MUSCLE_NAME, musclesOf } from '../lib/muscles.js'
import { fatigueOf, strengthOf, STRENGTH_FLOOR, LB_TO_KG } from '../lib/recovery.js'
import { strengthExerciseRowsForMuscle } from '../lib/strength-exercises.js'
import { fatigueStateOf } from '../lib/recovery-view.js'
@@ -20,6 +20,7 @@ import {
effortHistogram, isHardSet, HARD_RIR
} from '../lib/effort.js'
import { Button, Segmented, SelectRow } from '../components/ui.jsx'
import { tappable } from '../lib/use-sheet-keyboard.js'
import { isWarmupRow } from '../lib/workout-model.js'
// Which muscles the training in a window actually hit — and, the point of the card,
@@ -122,10 +123,7 @@ function MuscleBalance({ S }) {
return t('Weeks since training: {0}', weeks)
}
const toggleSel = m => setSel(s => (s === m ? null : m))
const inWin = S.workouts.filter(w =>
win === 0 ? true
: win === 7 ? weekKey(w.d) === weekKey(todayISO())
: (w.start || new Date(w.d).getTime()) > now - win * 86400000)
const inWin = muscleBalanceWindow(S.workouts, win, now)
// Counting only the sets taken near failure turns the map from "where did the volume go"
// into "where did the stimulus go" — a muscle can lead on sets and still never be trained
// hard. Offered only when the window holds ratings at all, since with none the hard map
@@ -192,7 +190,7 @@ function MuscleBalance({ S }) {
{sel && <>
<h4 className="sec" style={{ marginTop: 14 }}>{t('Exercises')} · {t(MUSCLE_NAME[sel])}</h4>
{muscleExercises.length ? muscleExercises.map(row => (
<div key={row.id} className="mrow" style={{ minHeight: 48, alignItems: 'stretch', cursor: 'pointer' }} onClick={() => onExercise && onExercise(row.id)}>
<div key={row.id} className="mrow" style={{ minHeight: 48, alignItems: 'stretch', cursor: 'pointer' }} {...tappable(() => onExercise && onExercise(row.id))}>
<span className="nm" style={{ whiteSpace: 'normal', lineHeight: 1.35, display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
<span style={{ display: 'block', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{row.name}
@@ -291,7 +289,38 @@ export default function Stats() {
const workouts = S.workouts
const monthW = workouts.filter(w => String(w.d || '').slice(0, 7) === todayISO().slice(0, 7)).length
const nameOf = id => EXIDX[id] ? exerciseNameFor(EXIDX[id]) : (workouts.flatMap(w => w.entries).find(e => e.id === id)?.n || id)
const entryOf = id => workouts.flatMap(w => w.entries).find(e => e.id === id)
const listOf = value => Array.isArray(value) ? value : value == null || value === '' ? [] : [value]
const firstAvailable = (...values) => {
for (const value of values) {
const list = listOf(value)
if (list.length) return list
}
return []
}
const nameOf = id => {
if (EXIDX[id]) return exerciseNameFor(EXIDX[id])
const entry = entryOf(id)
return entry?.muscleSnapshot?.n || entry?.n || id
}
const matcherOf = id => {
if (EXIDX[id]) return EXIDX[id]
const entry = entryOf(id)
const snapshot = entry?.muscleSnapshot || {}
const primaries = firstAvailable(snapshot.primaries, entry?.primaries)
const secondaries = firstAvailable(
snapshot.sm, snapshot.secondaries, snapshot.muscleGroups,
entry?.sm, entry?.secondaries, entry?.muscleGroups,
)
return {
n: snapshot.n || entry?.n || id,
bp: snapshot.bp || entry?.bp || '',
tg: primaries[0] || snapshot.tg || entry?.tg || '',
sm: secondaries,
eq: snapshot.eq || entry?.eq || '',
desc: snapshot.desc || entry?.desc || '',
}
}
const currentOf = id => {
for (let i = workouts.length - 1; i >= 0; i--) {
const en = workouts[i].entries.find(e => e.id === id)
@@ -428,7 +457,13 @@ export default function Stats() {
{exHist.length ? <>
<div className="sect-b" style={{ marginBottom: 10 }}>
<SelectRow title={t('Exercise')} sheetTitle={t('Exercise progress')} value={curEx} onChange={setExId} stackedValue
options={exHist.map(id => ({ value: id, label: nameOf(id) + (exCurrent[id].mx ? ' ' + '—' + ' ' + fmtNum(exCurrent[id].mx) + ' ' + exCurrent[id].unit : '') }))} />
options={exHist.map(id => ({ value: id, label: nameOf(id) + (exCurrent[id].mx ? ' ' + '—' + ' ' + fmtNum(exCurrent[id].mx) + ' ' + exCurrent[id].unit : '') }))}
search={{
placeholder: t('Search…'),
label: t('Search…'),
emptyLabel: t('No match'),
match: (option, query) => matchExercise(matcherOf(option.value), query),
}} />
</div>
{exOpts.length > 1 && <Segmented className="seg-range" value={onEff ? 'effort' : onE1 ? 'e1rm' : 'top'} onChange={setExMetric} options={exOpts} />}
<div className="chart">
+108 -1
View File
@@ -1,15 +1,21 @@
// @vitest-environment happy-dom
import React, { act } from 'react'
import { createRoot } from 'react-dom/client'
import { Window } from 'happy-dom'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { EXIDX } from '../lib/exercises.js'
import { MUSCLES, levelsOf } from '../lib/muscles.js'
import { FATIGUE_STATES, STRENGTH_FLOOR } from '../lib/recovery.js'
import { fatigueStateOf } from '../lib/recovery-view.js'
import Stats from './Stats.jsx'
import Modals from '../components/Modals.jsx'
import { bindUI } from '../components/ui.jsx'
import { useUI } from '../store/useUI.js'
const DAY = 86400000
const HOUR = 3600000
const BASE_NOW = Date.UTC(2026, 0, 22, 12)
const LEGACY_SNAPSHOT_ID = 'legacy-snapshot-only'
const mocks = vi.hoisted(() => ({
maps: [],
@@ -50,6 +56,8 @@ vi.mock('../components/BodyMap.jsx', () => ({
BodyMapLegend: () => React.createElement('div', { 'data-balance-legend': true }),
}))
bindUI(useUI)
let dom
let root
let container
@@ -105,19 +113,43 @@ function allSubfullWorkout(now = BASE_NOW) {
return workout('all-subfull', now - 15 * DAY, [entry('1254', [set(true)])])
}
function exercisePickerWorkouts(now = BASE_NOW) {
return [
workout('bench', now, [entry('0025', [set(true, { w: 80 })])]),
workout('squat', now - DAY, [entry('0043', [set(true, { w: 60 })])]),
workout('legacy', now - 2 * DAY, [
{
id: LEGACY_SNAPSHOT_ID,
muscleSnapshot: {
n: 'Legacy shoulder press',
bp: 'shoulders',
primaries: ['deltoids'],
secondaries: ['triceps'],
muscleGroups: ['deltoids', 'triceps'],
},
sets: [set(true, { w: 50 })],
},
]),
]
}
function resetFixture(workouts = lifecycleWorkouts()) {
mocks.S.unit = 'kg'
mocks.S.bodyweight = []
mocks.S.workouts = workouts
mocks.maps.length = 0
mocks.mapMounts = 0
useUI.setState({ sheets: [] })
}
function installDom() {
dom = new Window({ url: 'http://localhost/' })
dom.scrollTo = vi.fn()
globalThis.window = dom
globalThis.document = dom.document
Object.defineProperty(globalThis, 'navigator', { configurable: true, value: dom.navigator })
Object.defineProperty(globalThis, 'location', { configurable: true, value: dom.location })
Object.defineProperty(globalThis, 'history', { configurable: true, value: dom.history })
for (const key of ['HTMLElement', 'HTMLIFrameElement', 'Node', 'Element', 'Event', 'MouseEvent']) {
globalThis[key] = dom[key]
}
@@ -129,7 +161,7 @@ function installDom() {
async function mountStats() {
installDom()
await act(async () => { root.render(React.createElement(Stats)) })
await act(async () => { root.render(React.createElement(React.Fragment, null, React.createElement(Stats), React.createElement(Modals))) })
}
async function unmountStats() {
@@ -179,6 +211,7 @@ beforeEach(() => {
afterEach(async () => {
await unmountStats()
useUI.setState({ sheets: [] })
vi.useRealTimers()
vi.restoreAllMocks()
})
@@ -272,3 +305,77 @@ describe('Stats muscle recovery view runtime', () => {
expect(strengthMap.thresholds.at(-1)).toEqual({ at: 1, level: 4 })
})
})
describe('Stats exercise progress picker', () => {
it('filters with the shared exercise matcher and still selects from the mounted sheet', async () => {
resetFixture(exercisePickerWorkouts())
await mountStats()
expect(EXIDX[LEGACY_SNAPSHOT_ID]).toBeUndefined()
const card = [...container.querySelectorAll('.card')].find(el => el.querySelector('h2')?.textContent.trim() === 'Exercise progress')
const selector = [...card.querySelectorAll('button')].find(button => button.querySelector('.lrow-t')?.textContent.trim() === 'Exercise')
await click(selector)
const modal = document.querySelector('#modal-root')
const input = modal.querySelector('input')
expect(input).toBeTruthy()
expect(input.getAttribute('aria-label')).toBe('Search…')
expect(input.getAttribute('placeholder')).toBe('Search…')
expect(modal.querySelector('.picker-search')).toBeTruthy()
const optionButtons = () => [...modal.querySelectorAll('.sect-b button')]
const initialOptionCount = optionButtons().length
expect(initialOptionCount).toBe(3)
expect(modal.textContent).toContain('Legacy shoulder press')
expect(input.compareDocumentPosition(optionButtons()[0]) & globalThis.Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()
const setter = Object.getOwnPropertyDescriptor(input.constructor.prototype, 'value').set
const setSearch = async value => act(async () => {
setter.call(input, value)
input.dispatchEvent(new Event('input', { bubbles: true }))
input.dispatchEvent(new Event('change', { bubbles: true }))
})
// A focused search can leave a newly narrowed result below the visual viewport. The
// correction must advance the sheet's own scroll position, not the page behind it.
const sheet = modal.querySelector('.sheet')
const firstOption = optionButtons()[0]
Object.defineProperties(sheet, {
clientHeight: { configurable: true, value: 400 },
scrollHeight: { configurable: true, value: 1000 },
})
vi.spyOn(sheet, 'getBoundingClientRect').mockReturnValue({ bottom: 600 })
vi.spyOn(firstOption, 'getBoundingClientRect').mockReturnValue({ bottom: 500 })
Object.defineProperty(window, 'visualViewport', { configurable: true, value: { height: 300 } })
input.focus()
expect(sheet.style.getPropertyValue('--picker-visual-height')).toBe('300px')
expect(sheet.style.getPropertyValue('--picker-keyboard-bottom')).toBe(`${Math.max(0, window.innerHeight - 300)}px`)
await setSearch('bench')
await tick(100)
expect(sheet.scrollTop).toBeGreaterThan(0)
await setSearch('no such historical exercise')
expect(modal.textContent).toContain('No match')
expect(optionButtons()).toHaveLength(0)
await click(modal.querySelector('button[aria-label="Clear"]'))
expect(input.value).toBe('')
expect(optionButtons()).toHaveLength(initialOptionCount)
expect(modal.textContent).toContain('Legacy shoulder press')
await setSearch('legacy shoulder press shoulders deltoids triceps')
expect(optionButtons()).toHaveLength(1)
expect(optionButtons()[0].textContent).toContain('Legacy shoulder press')
await click(modal.querySelector('button[aria-label="Clear"]'))
await setSearch('squat full bárbell')
expect(modal.textContent).toContain('barbell full squat')
expect(modal.textContent).not.toContain('barbell bench press')
const matching = [...modal.querySelectorAll('button')].find(button => button.textContent.includes('barbell full squat'))
await click(matching)
expect(useUI.getState().sheets).toHaveLength(0)
expect(card.querySelector('.lrow-v').textContent).toContain('barbell full squat')
})
})
+1 -1
View File
@@ -19,7 +19,7 @@ describe('Stats mixed-entry metric contract', () => {
it('renders one clickable muscle exercise list rather than a duplicate non-clickable copy', () => {
expect((source.match(/muscleExercises\.length \? muscleExercises\.map\(row =>/g) || []).length).toBe(1)
expect(source).toContain('onClick={() => onExercise && onExercise(row.id)}')
expect(source).toContain('{...tappable(() => onExercise && onExercise(row.id))}')
})
it('uses the shared metric mode and row helpers rather than entryMode as a chart gate', () => {
+178 -27
View File
@@ -8,14 +8,20 @@ import { fmtNum, fmtDate, todayISO, exCount, DAYN } from '../lib/format.js'
import { beep, vibrate } from '../lib/sound.js'
import { t, exerciseNameFor } from '../lib/i18n.js'
import { api } from '../lib/api.js'
import { insertionIndexAfterCurrentUnit, nextUnfinishedUnit, setProgressHighWater, supersetFlowStep, restAfterSet, restOnRecheck } from '../lib/supersetFlow.js'
import { insertionIndexAfterCurrentUnit, nextUnfinishedUnit, setProgressHighWater, supersetFlowStep, restAfterSet, restOnRecheck, restSecFor } from '../lib/supersetFlow.js'
import Media from '../components/Media.jsx'
import { startFlow, exercisePicker, exConfigSheet, exerciseDetailSheet, topWeightSheet, finishWorkout, workoutCompleteSheet, confirmSheet, exerciseNoteSheet, sessionNoteSheet } from '../sheets.jsx'
import { startFlow, exercisePicker, exConfigSheet, exerciseDetailSheet, topWeightSheet, finishWorkout, workoutCompleteSheet, confirmSheet, exerciseNoteSheet, sessionNoteSheet, swapActiveWorkoutExercise } from '../sheets.jsx'
import Icon from '../components/Icon.jsx'
import { Button, Check, NumberField } from '../components/ui.jsx'
import { nextPrescription, applyPrescription, defaultIncrement } from '../lib/progression.js'
import { progressionGuidance } from '../lib/progression-copy.js'
import { glyphOf } from '../lib/glyphs.js'
import { isWarmupRow, isDropSet, isRestPauseSet, dropsOf, clustersOf, addDrop, addCluster, removeDropAt, removeClusterAt, setDropAt, setClusterAt, nextDropWeight, nextBurstReps } from '../lib/workout-model.js'
import { canMoveActiveWorkoutUnit, moveActiveWorkoutUnit } from '../lib/active-workout-order.js'
const SWIPE_MIN_DISTANCE = 48
const SWIPE_AXIS_RATIO = 1.25
const SWIPE_IGNORED_TARGETS = 'button,input,textarea,select,a,[role="button"],[role="checkbox"],[role="switch"],[role="slider"],[contenteditable="true"],.exmedia,[data-swipe-ignore]'
/* ---------- start chooser (no active workout) ---------- */
function StartChooser() {
@@ -56,7 +62,7 @@ function Elapsed({ start }) {
}
/* ---------- one exercise block (reps: weight×reps · time: a held duration · cardio: duration+speed) ---------- */
function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemoveSet, onAddWarmup, onRemoveSetAt, onStartTimed, onPairPrev, onPairNext }) {
function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemoveSet, onAddWarmup, onRemoveSetAt, onStartTimed, onPairPrev, onPairNext, onSetRowRef, onProgressionSettings }) {
const S = useStore(s => s.S)
const update = useStore(s => s.update)
const working = useUI(s => s.work)
@@ -106,6 +112,7 @@ function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemov
// What the progression policy decided for this session, and why (issue #17). Computed when
// the session was built so the reason matches the numbers already in the rows.
const plan = entry.plan
const guidance = progressionGuidance(plan)
// A bodyweight set has no weight to type, so the column is not there (issue #32) — one
// stepper instead of two, which is the whole point of the flag. Adding a belt weight in the
// config brings it back, now labelled as the addition it is.
@@ -190,10 +197,11 @@ function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemov
</div>}
{entry.note && <div className="exnote">{entry.note}</div>}
{last && <div className="small dim" style={{ marginBottom: 4 }}>{t('Last time')} ({fmtDate(last.d)}): {last.sets.map(s => setLabel(entry.id, s, last.target)).join(', ')}</div>}
{plan && plan.why && plan.kind !== 'off' && <div className={'progline' + (plan.kind === 'deload' ? ' warn' : '')}>
{guidance && <button type="button" className={'progline' + (plan.kind === 'deload' ? ' warn' : '')}
aria-label={t('Open progression settings')} onClick={onProgressionSettings}>
<Icon name={plan.kind === 'up' ? 'arrowUp' : plan.kind === 'deload' ? 'arrowDown' : 'lightbulb'} />
<span>{t(...plan.why)}</span>
</div>}
<span><strong>{t(guidance.policyLabel)}</strong> · {t(...guidance.why)}</span>
</button>}
<div className="card" style={{ marginTop: 10, marginBottom: 0 }}>
{/* the header carries the same eff3 sizing as the rows, or the labels drift off their columns */}
<div className={'sethead' + (col3 ? ' eff3' : '')}><span className="n-sp" /><span className="w-sp">{col1.hd}</span>{col2 && <span className="r-sp">{col2.hd}</span>}{col3 && <span className="eff-sp">{col3.hd}</span>}{timed && <span className="ck-sp" />}<span className="ck-sp" /></div>
@@ -206,7 +214,7 @@ function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemov
return <div key={i}>
{isFirstWarmup && <div className="setph">{t('Warm-up')}</div>}
{!warm && warmBefore && <div className="setsep" />}
<div className={'setrow' + (s.done ? ' done' : '') + (col3 ? ' eff3' : '')}>
<div ref={el => onSetRowRef?.(i, el)} className={'setrow' + (s.done ? ' done' : '') + (col3 ? ' eff3' : '')}>
<div className="n">{phaseNum}</div>
{cell(s, i, col1, 'w')}
{col2 && cell(s, i, col2, 'r')}
@@ -282,16 +290,41 @@ function ActiveWorkout() {
const nav = useNavigate()
const S = useStore(s => s.S)
const update = useStore(s => s.update)
const { startRest, stopRest, stopWork, work } = useUI()
const { startRest: liveRest, stopRest, stopWork, work } = useUI()
const A = S.active
// A past workout has no rest to time — the sets were done days ago. The work timer for
// timed sets stays, since counting a hold is how its duration gets entered.
const startRest = A.backfill ? () => {} : liveRest
const units = supersetUnits(A.entries)
const cur = Math.min(A.cur, Math.max(0, A.entries.length - 1))
const cur = Number.isInteger(A.cur)
? Math.min(Math.max(A.cur, 0), Math.max(0, A.entries.length - 1))
: 0
const unit = A.entries.length ? unitOf(units, cur) : []
const unitIdx = units.findIndex(u => u === unit)
const isSuperset = unit.length > 1
// Superset flow: keep the active exercise in view - completing a set scrolls to the
// next exercise in the group, then back up to the first exercise of the next round.
const exRefs = useRef({})
// Superset flow: center the actionable row when completing a set moves to the partner or
// back to the first exercise of the next round. Entry-bound maps keep repeated exercise IDs
// distinct, while each rendered set index identifies the existing row within that entry.
const exRefs = useRef(new Map())
const setRefs = useRef(new Map())
const bindExRef = (entry, el) => {
if (el) exRefs.current.set(entry, el)
else {
exRefs.current.delete(entry)
setRefs.current.delete(entry)
}
}
const bindSetRef = (entry, setIdx, el) => {
let refs = setRefs.current.get(entry)
if (el) {
if (!refs) { refs = new Map(); setRefs.current.set(entry, refs) }
refs.set(setIdx, el)
} else if (refs) {
refs.delete(setIdx)
if (!refs.size) setRefs.current.delete(entry)
}
}
const swipe = useRef(null)
const progressHighWater = useRef(A.entries.map(e => e.sets.filter(s => s.done).length))
// The marks are index-keyed, and removing an exercise shifts every index above it down
// (removeActiveExercise splices). Re-baseline whenever the list length changes, otherwise a
@@ -299,10 +332,22 @@ function ActiveWorkout() {
useEffect(() => {
progressHighWater.current = A.entries.map(e => e.sets.filter(s => s.done).length)
}, [A.entries.length])
useEffect(() => {
const liveEntries = new Set(A.entries)
for (const entry of exRefs.current.keys()) {
if (!liveEntries.has(entry)) exRefs.current.delete(entry)
}
for (const entry of setRefs.current.keys()) {
if (!liveEntries.has(entry)) setRefs.current.delete(entry)
}
})
useEffect(() => {
if (!isSuperset) return
const el = exRefs.current[cur]
if (el && typeof el.scrollIntoView === 'function') el.scrollIntoView({ behavior: 'smooth', block: 'nearest' })
const entry = A.entries[cur]
const firstIncomplete = entry?.sets.findIndex(s => !s.done) ?? -1
const setIdx = firstIncomplete >= 0 ? firstIncomplete : (entry?.sets.length ?? 0) - 1
const el = (setIdx >= 0 && setRefs.current.get(entry)?.get(setIdx)) || exRefs.current.get(entry)
if (el && typeof el.scrollIntoView === 'function') el.scrollIntoView({ behavior: 'smooth', block: 'center' })
}, [cur, isSuperset, A.entries.length])
const total = A.entries.reduce((n, e) => n + e.sets.length, 0)
@@ -341,6 +386,84 @@ function ActiveWorkout() {
})
const onPairPrev = !isSuperset && cur > 0 ? () => pairAt(cur - 1, cur) : null
const onPairNext = !isSuperset && cur < A.entries.length - 1 ? () => pairAt(cur, cur + 1) : null
const moveCurrentUnit = direction => {
const ui = useUI.getState()
const active = useStore.getState().S.active
if (ui.work || !canMoveActiveWorkoutUnit(active, active?.cur, direction)) return
// Invalidate an old timed callback before indexes shift. A running rest is not cancelled:
// it belongs to an exercise (timer.forIdx), and that exercise only changes position.
ui.stopWork()
update(s => {
const moved = moveActiveWorkoutUnit(s.active, s.active?.cur, direction)
if (!moved) return
progressHighWater.current = moved.indices.map(index => progressHighWater.current[index])
const rest = useUI.getState().timer
if (rest && rest.forIdx != null) {
const forIdx = moved.indices.indexOf(rest.forIdx)
if (forIdx >= 0) useUI.setState({ timer: { ...rest, forIdx } })
}
}, true)
}
const navigateUnit = direction => {
const targetFor = active => {
if (!active || !Array.isArray(active.entries) || !Number.isInteger(active.cur)) return null
if (active.cur < 0 || active.cur >= active.entries.length) return null
const freshUnits = supersetUnits(active.entries)
const freshUnitIdx = freshUnits.findIndex(candidate => candidate.includes(active.cur))
return freshUnitIdx < 0 ? null : freshUnits[freshUnitIdx + direction]?.[0] ?? null
}
if (targetFor(useStore.getState().S.active) == null) return
update(s => {
const target = targetFor(s.active)
if (target != null) s.active.cur = target
})
}
const onSwipePointerDown = event => {
if (swipe.current || (event.pointerType && event.pointerType !== 'touch' && event.pointerType !== 'pen')) return
if (event.target.closest?.(SWIPE_IGNORED_TARGETS)) return
swipe.current = { id: event.pointerId, x: event.clientX, y: event.clientY }
event.currentTarget.setPointerCapture?.(event.pointerId)
}
const finishSwipe = (event, navigate) => {
const start = swipe.current
if (!start || start.id !== event.pointerId) return
swipe.current = null
event.currentTarget.releasePointerCapture?.(event.pointerId)
if (!navigate) return
const dx = event.clientX - start.x
const dy = event.clientY - start.y
if (Math.abs(dx) < SWIPE_MIN_DISTANCE || Math.abs(dx) < Math.abs(dy) * SWIPE_AXIS_RATIO) return
navigateUnit(dx < 0 ? 1 : -1)
}
const openProgressionSettings = idx => {
const state = useStore.getState().S
const entry = state.active?.entries?.[idx]
if (!entry) return
const routine = state.routines.find(r => r.id === state.active.routineId)
exConfigSheet(exOr(entry.id), entry.target, cfg => update(s => {
const activeEntry = s.active?.entries?.[idx]
if (!activeEntry) return
const full = { ...cfg, id: activeEntry.id }
const activeRoutine = s.routines.find(r => r.id === s.active.routineId)
const step = defaultIncrement(activeEntry.id, s.unit)
// A config without a set count keeps the rows the session already has.
if (!(full.sets > 0)) full.sets = activeEntry.sets.filter(x => !isWarmupRow(x)).length || 1
const plan = nextPrescription(s, full, activeRoutine)
// The sheet edits sets, reps, weight and warm-ups as well as the rule — so the rows are
// rebuilt from the new config the way the session was, and only what you already logged
// is kept in place (done warm-ups first, then done work sets, then the fresh remainder).
const fresh = applyIntensifierPlan(applyPrescription(buildSets(s, full, { step }), plan, step), full)
const doneWarm = activeEntry.sets.filter(x => x.done && isWarmupRow(x))
const doneWork = activeEntry.sets.filter(x => x.done && !isWarmupRow(x))
const freshWarm = fresh.filter(isWarmupRow)
const freshWork = fresh.filter(x => !isWarmupRow(x))
activeEntry.target = { ...cfg }
activeEntry.plan = plan
activeEntry.sets = [...doneWarm, ...freshWarm.slice(doneWarm.length), ...doneWork, ...freshWork.slice(doneWork.length)]
}), null, routine)
}
// Remove a whole exercise from the session. The confirmation always asks first; in a
// superset it asks WHICH exercise of the group to remove.
@@ -426,11 +549,15 @@ function ActiveWorkout() {
const restBeforeWarmup = nextUnit?.some(ui =>
fresh.entries[ui].sets.some(set => isWarmupRow(set) && !set.done),
)
// The rest this set has earned: the exercise's own restSec when it set one, the global
// timer when it did not, and the longest of the group's across a superset (issue #10).
// Resolved once here so every branch below times the same break.
const restSec = restSecFor(fresh.entries, freshUnit || [idx], S.restSec)
// A re-check of finished work must not navigate or reopen a sheet, but it may still owe
// you a rest — see restOnRecheck, and the other half of issue #3.
if (!progress.isNew) {
if (!restBeforeWarmup && restOnRecheck({ timerRunning: !!useUI.getState().timer, unitDone: freshUnitDone, lastUnit: freshWorkoutDone })) startRest(S.restSec, idx)
if (!restBeforeWarmup && restOnRecheck({ timerRunning: !!useUI.getState().timer, unitDone: freshUnitDone, lastUnit: freshWorkoutDone })) startRest(restSec, idx)
return
}
@@ -440,7 +567,7 @@ function ActiveWorkout() {
if (freshUnitDone) stopRest()
if (!freshUnit || freshUnit.length <= 1) {
if (freshUnitDone && !askTop && nextUnit?.length) update(s => { if (s.active) s.active.cur = nextUnit[0] })
if (!restBeforeWarmup && restAfterSet({ unitDone: freshUnitDone, lastUnit: freshWorkoutDone })) startRest(S.restSec, idx)
if (!restBeforeWarmup && restAfterSet({ unitDone: freshUnitDone, lastUnit: freshWorkoutDone })) startRest(restSec, idx)
return
}
@@ -450,11 +577,11 @@ function ActiveWorkout() {
if (nextUnit?.length) {
// The top-weight sheet's explicit "Just close" path owns the choice not to advance.
if (!askTop) update(s => { if (s.active) s.active.cur = nextUnit[0] })
if (!restBeforeWarmup) startRest(S.restSec, idx)
if (!restBeforeWarmup) startRest(restSec, idx)
}
} else {
if (step.nextIdx != null) update(s => { if (s.active) s.active.cur = step.nextIdx })
if (step.roundDone) startRest(S.restSec, idx)
if (step.roundDone) startRest(restSec, idx)
}
}
}
@@ -489,34 +616,46 @@ function ActiveWorkout() {
return <div className="narrow">
<div className="hdr">
<button className="iconbtn" aria-label={t('Discard')} onClick={() => confirmSheet({ title: t('Discard workout?'), message: t('The sets you logged in this session will be lost.'), confirmText: t('Discard'), danger: true, onConfirm: () => { update(s => { s.active = null }); stopRest(); stopWork(); nav('/home') } })}><Icon name="xmark" /></button>
<div style={{ textAlign: 'center' }}><div style={{ fontWeight: 600 }}>{A.name}</div><div className="sub"><Elapsed start={A.start} /> · {t('{0} sets', done + '/' + total)}</div></div>
<div style={{ textAlign: 'center' }}><div style={{ fontWeight: 600 }}>{A.name}</div><div className="sub">{A.backfill ? fmtDate(A.d, true) : <Elapsed start={A.start} />} · {t('{0} sets', done + '/' + total)}</div></div>
<button className="iconbtn" style={{ color: 'var(--acc)' }} aria-label={t('Finish')} onClick={finishWorkout}><Icon name="check" /></button>
</div>
<div className="wprog"><i style={{ width: (total ? done / total * 100 : 0) + '%' }} /></div>
{A.backfill && <div className="muted small" style={{ marginBottom: 8 }}>{t('Logging a past workout — no rest timers.')}</div>}
{A.entries.length ? <>
<div className="muted small" style={{ marginBottom: 6 }}>{isSuperset ? t('Superset {0} / {1}', unitIdx + 1, units.length) : t('Exercise {0} / {1}', unitIdx + 1, units.length)}</div>
<div className="workout-swipe-surface" data-testid="workout-swipe-surface"
onPointerDown={onSwipePointerDown}
onPointerUp={event => finishSwipe(event, true)}
onPointerCancel={event => finishSwipe(event, false)}
onLostPointerCapture={event => {
if (swipe.current?.id === event.pointerId) swipe.current = null
}}>
{isSuperset ? (
<div className="ss-card">
<div className="ss-hd" style={{ justifyContent: 'space-between' }}>
<span className="row" style={{ gap: 5 }}><Icon name="link" />{t('Superset · do these back-to-back, rest when done')}</span>
<Button size="xs" variant="ghost" icon="link" title={t('Unpair')} onClick={() => unpairAt(cur)}>{t('Unpair')}</Button>
</div>
{unit.map((idx, k) => <div key={idx} ref={el => { exRefs.current[idx] = el }} className="ss-ex" data-exidx={idx}>
{k > 0 && <div className="ss-amp">+</div>}
<ExerciseBlock entryIdx={idx} compact
onToggle={i => toggle(idx, i)} onField={(i, f, v) => setField(idx, i, f, v)} onAddSet={() => addSet(idx)} onRemoveSet={() => removeSet(idx)} onAddWarmup={() => addWarmup(idx)} onRemoveSetAt={i => removeSetAt(idx, i)} onStartTimed={i => startTimed(idx, i)} />
</div>)}
{unit.map((idx, k) => {
const entry = A.entries[idx]
return <div key={idx} ref={el => bindExRef(entry, el)} className="ss-ex" data-exidx={idx}>
{k > 0 && <div className="ss-amp">+</div>}
<ExerciseBlock entryIdx={idx} compact onSetRowRef={(setIdx, el) => bindSetRef(entry, setIdx, el)}
onToggle={i => toggle(idx, i)} onField={(i, f, v) => setField(idx, i, f, v)} onAddSet={() => addSet(idx)} onRemoveSet={() => removeSet(idx)} onAddWarmup={() => addWarmup(idx)} onRemoveSetAt={i => removeSetAt(idx, i)} onStartTimed={i => startTimed(idx, i)} onProgressionSettings={() => openProgressionSettings(idx)} />
</div>
})}
</div>
) : (
<ExerciseBlock entryIdx={cur} onToggle={i => toggle(cur, i)} onField={(i, f, v) => setField(cur, i, f, v)} onAddSet={() => addSet(cur)} onRemoveSet={() => removeSet(cur)} onAddWarmup={() => addWarmup(cur)} onRemoveSetAt={i => removeSetAt(cur, i)} onStartTimed={i => startTimed(cur, i)} onPairPrev={onPairPrev} onPairNext={onPairNext} />
<ExerciseBlock entryIdx={cur} onToggle={i => toggle(cur, i)} onField={(i, f, v) => setField(cur, i, f, v)} onAddSet={() => addSet(cur)} onRemoveSet={() => removeSet(cur)} onAddWarmup={() => addWarmup(cur)} onRemoveSetAt={i => removeSetAt(cur, i)} onStartTimed={i => startTimed(cur, i)} onPairPrev={onPairPrev} onPairNext={onPairNext} onProgressionSettings={() => openProgressionSettings(cur)} />
)}
</div>
</> : <div className="empty"><div className="ico"><Icon name="shuffle" /></div>{t('Freestyle workout — add your first exercise.')}</div>}
<div style={{ height: 12 }} />
<div className="row">
<Button icon="chevronLeft" disabled={unitIdx <= 0} onClick={() => update(s => { s.active.cur = units[unitIdx - 1][0] })}>{t('Prev')}</Button>
<Button trailingIcon="chevronRight" disabled={unitIdx < 0 || unitIdx >= units.length - 1} onClick={() => update(s => { s.active.cur = units[unitIdx + 1][0] })}>{t('Next')}</Button>
<Button icon="chevronLeft" disabled={unitIdx <= 0} onClick={() => navigateUnit(-1)}>{t('Prev')}</Button>
<Button trailingIcon="chevronRight" disabled={unitIdx < 0 || unitIdx >= units.length - 1} onClick={() => navigateUnit(1)}>{t('Next')}</Button>
</div>
<div style={{ height: 10 }} />
<Button onClick={() => exercisePicker(ex => {
@@ -537,6 +676,18 @@ function ActiveWorkout() {
}), null, routine, seed)
})} icon="plus">{t('Add exercise')}</Button>
{A.entries.length > 0 && <>
<div style={{ height: 6 }} />
<div className="row">
<Button size="sm" icon="chevronUp" aria-label={t('Move up')}
disabled={!!work || !canMoveActiveWorkoutUnit(A, cur, -1)} onClick={() => moveCurrentUnit(-1)}>{t('Move up')}</Button>
<Button size="sm" trailingIcon="chevronDown" aria-label={t('Move down')}
disabled={!!work || !canMoveActiveWorkoutUnit(A, cur, 1)} onClick={() => moveCurrentUnit(1)}>{t('Move down')}</Button>
</div>
<div style={{ height: 6 }} />
<div style={{ display: 'flex', justifyContent: 'center' }}>
<Button size="sm" icon="shuffle" aria-label={t('Swap exercise')} disabled={!!work}
onClick={() => swapActiveWorkoutExercise(cur)}>{t('Swap exercise')}</Button>
</div>
<div style={{ height: 6 }} />
<div style={{ display: 'flex', justifyContent: 'center' }}>
<Button size="sm" icon="minus" style={{ color: 'var(--red)' }} disabled={!!work} onClick={removeExerciseSheet}>{t('Remove exercise')}</Button>
+7 -2
View File
@@ -6,6 +6,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import Workout, { removeActiveExercise } from './Workout.jsx'
import { DEF, useStore } from '../store/useStore.js'
import { useUI } from '../store/useUI.js'
import { LANGS } from '../lib/i18n-core.js'
vi.mock('../lib/sound.js', () => ({ beep: vi.fn(), vibrate: vi.fn() }))
vi.mock('../lib/api.js', () => ({ api: vi.fn(() => Promise.resolve({})) }))
@@ -203,9 +204,13 @@ describe('remove-exercise locale coverage', () => {
'Which exercise in this superset do you want to remove?'
]
const packs = import.meta.glob('../locales/*.js', { eager: true, import: 'default' })
// Every non-English language has its own pack (English is the source, so it has none) —
// derived from LANGS rather than hardcoded so adding a language doesn't silently
// understate this test's own coverage.
const nonEnglishLangCount = Object.keys(LANGS).length - 1
it('defines every new prompt in all twelve locale packs', () => {
expect(Object.keys(packs)).toHaveLength(12)
it('defines every new prompt in every non-English locale pack', () => {
expect(Object.keys(packs)).toHaveLength(nonEnglishLangCount)
Object.entries(packs).forEach(([path, pack]) => {
required.forEach(key => expect(pack, `${path} is missing ${key}`).toHaveProperty(key))
})
+249
View File
@@ -18,6 +18,8 @@ const mocks = vi.hoisted(() => {
exercisePicker: vi.fn(),
exConfigSheet: vi.fn(),
toast: vi.fn(),
scrollCalls: [],
swapActiveWorkoutExercise: vi.fn(),
}
state.stopRest = vi.fn(() => { state.timer = null })
state.stopWork = vi.fn(() => { state.work = null })
@@ -63,6 +65,7 @@ vi.mock('../sheets.jsx', () => ({
finishWorkout: vi.fn(),
workoutCompleteSheet: mocks.workoutCompleteSheet,
confirmSheet: mocks.confirmSheet,
swapActiveWorkoutExercise: mocks.swapActiveWorkoutExercise,
// Both note sheets belong here even though the tests never open one: Workout.jsx reads
// sessionNoteSheet during render, so a missing export is a render crash, not a no-op.
exerciseNoteSheet: vi.fn(),
@@ -106,6 +109,9 @@ function installDom() {
globalThis.document = dom.document
Object.defineProperty(globalThis, 'navigator', { configurable: true, value: dom.navigator })
for (const key of ['HTMLElement', 'Node', 'Element', 'Event', 'Blob']) globalThis[key] = dom[key]
dom.Element.prototype.scrollIntoView = vi.fn(function (options) {
mocks.scrollCalls.push({ node: this, options })
})
globalThis.IS_REACT_ACT_ENVIRONMENT = true
container = document.getElementById('root')
root = createRoot(container)
@@ -131,6 +137,13 @@ async function toggleSet(index) {
await act(async () => { checkbox.dispatchEvent(new dom.Event('click', { bubbles: true })) })
}
async function pressProgression(index = 0) {
const button = container.querySelectorAll('.progline')[index]
expect(button).toBeTruthy()
await act(async () => { button.dispatchEvent(new dom.Event('click', { bubbles: true })) })
return button
}
async function requestDiscard() {
const button = container.querySelector('button[aria-label="Discard"]')
expect(button).toBeTruthy()
@@ -156,10 +169,16 @@ async function addExerciseThroughSheets(ex = { id: 'added-exercise' }, cfg = { m
await act(async () => { configCall[2](cfg) })
}
async function rerenderAt(cur) {
mocks.S.active.cur = cur
await act(async () => { root.render(React.createElement(Workout)) })
}
beforeEach(() => {
vi.clearAllMocks()
mocks.timer = null
mocks.work = null
mocks.scrollCalls.length = 0
})
afterEach(async () => {
@@ -416,6 +435,106 @@ describe('Workout discard timer lifecycle', () => {
})
})
describe('progression guidance', () => {
it('labels the visible outcome with the policy that calculated it', async () => {
await mount([exercise('plain-bench', [false, false, false], {
plan: {
policy: 'linear',
kind: 'up',
weight: 62.5,
why: ['Every rep last time — {0} {1} more.', 2.5, 'kg'],
},
})])
expect(container.querySelector('.progline')?.textContent)
.toContain('Linear progression · Every rep last time — 2.5 kg more.')
})
it('is a keyboard-accessible button that opens settings for the pressed grouped entry', async () => {
const plan = {
policy: 'linear', kind: 'up', weight: 62.5,
why: ['Every rep last time — {0} {1} more.', 2.5, 'kg'],
}
const first = exercise('plain-bench', [false], { sg: 'group', plan })
const second = exercise('plain-bench', [false], {
sg: 'group', plan, target: { mode: 'reps', reps: 8, weight: 80, bodyweight: false },
})
await mount([first, second])
const firstBefore = JSON.stringify(mocks.S.active.entries[0])
const button = await pressProgression(1)
expect(button.tagName).toBe('BUTTON')
expect(button.getAttribute('type')).toBe('button')
expect(button.getAttribute('aria-label')).toBe('Open progression settings')
expect(mocks.exConfigSheet).toHaveBeenCalledOnce()
expect(mocks.exConfigSheet.mock.calls[0][1]).toBe(second.target)
expect(mocks.exConfigSheet.mock.calls[0][4]).toBe(mocks.S.routines[0])
mocks.exConfigSheet.mock.calls[0][2]({ ...second.target, prog: 'double', repsMin: 6 })
expect(JSON.stringify(mocks.S.active.entries[0])).toBe(firstBefore)
expect(mocks.S.active.entries[1].target.prog).toBe('double')
expect(mocks.S.active.cur).toBe(0)
})
it('leaves the active entry unchanged when progression settings are cancelled', async () => {
const entry = exercise('plain-bench', [true, false], {
plan: {
policy: 'linear', kind: 'up', weight: 62.5,
why: ['Every rep last time — {0} {1} more.', 2.5, 'kg'],
},
})
await mount([entry])
const before = JSON.stringify(mocks.S.active.entries[0])
await pressProgression()
expect(JSON.stringify(mocks.S.active.entries[0])).toBe(before)
})
it('saves the active policy, preserves completed rows, and refreshes guidance immediately', async () => {
const entry = exercise('plain-bench', [true, false], {
plan: {
policy: 'linear', kind: 'up', weight: 62.5,
why: ['Every rep last time — {0} {1} more.', 2.5, 'kg'],
},
})
await mount([entry])
mocks.S.workouts = [{
d: '2026-08-27',
entries: [{
id: entry.id,
target: { sets: 2, reps: 5, weight: 60 },
sets: [{ w: 60, r: 5, done: true }, { w: 60, r: 5, done: true }],
}],
}]
const completed = mocks.S.active.entries[0].sets[0]
await pressProgression()
const save = mocks.exConfigSheet.mock.calls[0][2]
await act(async () => {
save({ ...entry.target, prog: 'double', repsMin: 3 })
root.render(React.createElement(Workout))
})
const saved = mocks.S.active.entries[0]
expect(saved.target.prog).toBe('double')
expect(saved.sets[0]).toEqual(completed)
expect(saved.sets[0]).toEqual({ w: 60, r: 5, done: true })
expect(saved.sets[1]).toEqual({ w: 62.5, r: 3, done: false })
expect(container.querySelector('.progline')?.textContent)
.toContain('Double progression · Top of the rep range in every set — 2.5 kg more, back to 3 reps.')
const persisted = JSON.parse(JSON.stringify(mocks.S))
await unmount()
mocks.S = persisted
installDom()
await act(async () => { root.render(React.createElement(Workout)) })
expect(container.querySelector('.progline')?.textContent)
.toContain('Double progression · Top of the rep range in every set — 2.5 kg more, back to 3 reps.')
})
})
describe('superset flow survives an exercise being removed mid-session', () => {
// removeActiveExercise splices A.entries, shifting every index above the removal down.
// The high-water marks are index-keyed, so without re-baselining the shifted exercise
@@ -448,3 +567,133 @@ describe('superset flow survives an exercise being removed mid-session', () => {
expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number))
})
})
describe('superset actionable-set centring', () => {
it('centres the newly active exercise first incomplete set row', async () => {
await mount([
exercise('bench', [true, false], { sg: 'g1' }),
exercise('row', [true, false, false], { sg: 'g1' }),
])
mocks.scrollCalls.length = 0
await rerenderAt(1)
const rows = container.querySelector('[data-exidx="1"]').querySelectorAll('.setrow')
expect(mocks.scrollCalls).toEqual([
{ node: rows[1], options: { behavior: 'smooth', block: 'center' } },
])
})
it('centres the last set row when the newly active exercise is complete', async () => {
await mount([
exercise('bench', [true, false], { sg: 'g1' }),
exercise('row', [true, true], { sg: 'g1' }),
])
mocks.scrollCalls.length = 0
await rerenderAt(1)
const rows = container.querySelector('[data-exidx="1"]').querySelectorAll('.setrow')
expect(mocks.scrollCalls).toEqual([
{ node: rows[1], options: { behavior: 'smooth', block: 'center' } },
])
})
it('centres the exercise wrapper when the newly active exercise has no set row', async () => {
await mount([
exercise('bench', [true, false], { sg: 'g1' }),
exercise('row', [], { sg: 'g1' }),
])
mocks.scrollCalls.length = 0
await rerenderAt(1)
const wrapper = container.querySelector('[data-exidx="1"]')
expect(mocks.scrollCalls).toEqual([
{ node: wrapper, options: { behavior: 'smooth', block: 'center' } },
])
})
it('does not auto-scroll set rows for ordinary exercise navigation', async () => {
await mount([
exercise('bench', [true, false]),
exercise('row', [false, false]),
])
mocks.scrollCalls.length = 0
await rerenderAt(1)
expect(mocks.scrollCalls).toEqual([])
})
})
describe('active workout whole-unit move controls', () => {
const action = label => container.querySelector(`button[aria-label="${label}"]`)
it('shows labelled controls and moves the selected standalone exercise one unit', async () => {
const selected = exercise('duplicate', [false], {
occurrenceId: 'duplicate#2',
target: { mode: 'reps', reps: 7, weight: 82.5, notes: 'Keep this target' },
sets: [{ w: 77.5, r: 6, done: true, rir: 2 }],
})
await mount([
exercise('duplicate', [false], { occurrenceId: 'duplicate#1' }),
exercise('middle', [false]),
selected,
], 2)
expect(action('Move up')?.textContent.trim()).toBe('Move up')
expect(action('Move down')?.textContent.trim()).toBe('Move down')
await act(async () => { action('Move up').dispatchEvent(new dom.Event('click', { bubbles: true })) })
expect(mocks.S.active.entries.map(entry => entry.occurrenceId || entry.id)).toEqual(['duplicate#1', 'duplicate#2', 'middle'])
expect(mocks.S.active.entries[1]).toEqual(selected)
expect(mocks.S.active.entries[1].target).toEqual({ mode: 'reps', reps: 7, weight: 82.5, notes: 'Keep this target' })
expect(mocks.S.active.entries[1].sets).toEqual([{ w: 77.5, r: 6, done: true, rir: 2 }])
expect(mocks.S.active.cur).toBe(1)
expect(mocks.stopWork).toHaveBeenCalledOnce()
expect(mocks.stopRest).not.toHaveBeenCalled()
})
it('moves the selected contiguous group as one unit without changing its metadata', async () => {
const first = exercise('group-a', [false], { sg: 'pair', occurrenceId: 'group-a#1' })
const selected = exercise('group-b', [true], { sg: 'pair', occurrenceId: 'group-b#1' })
const groupMeta = { pair: { kind: 'complex', label: 'Carry pair', cues: 'Stay braced.' } }
await mount([
exercise('before', [false]),
first,
selected,
exercise('after', [false]),
], 2)
mocks.S.active.groupMeta = groupMeta
await act(async () => { action('Move up').dispatchEvent(new dom.Event('click', { bubbles: true })) })
expect(mocks.S.active.entries.map(entry => entry.id)).toEqual(['group-a', 'group-b', 'before', 'after'])
expect(mocks.S.active.entries.slice(0, 2)).toEqual([first, selected])
expect(mocks.S.active.entries.slice(0, 2).map(entry => entry.sg)).toEqual(['pair', 'pair'])
expect(mocks.S.active.groupMeta).toEqual(groupMeta)
expect(mocks.S.active.entries[mocks.S.active.cur]).toEqual(selected)
})
it('disables both moves while a work timer can still write by index', async () => {
mocks.work = { left: 5, total: 5, endsAt: Date.now() + 5000 }
await mount([exercise('first', [false]), exercise('second', [false])], 1)
expect(action('Move up')?.disabled).toBe(true)
expect(action('Move down')?.disabled).toBe(true)
})
})
describe('active exercise swap control', () => {
it('opens the swap flow for the selected duplicate occurrence', async () => {
await mount([exercise('bench', [false]), exercise('bench', [false]), exercise('row', [false])], 1)
const swap = container.querySelector('button[aria-label="Swap exercise"]')
expect(swap).toBeTruthy()
await act(async () => { swap.dispatchEvent(new dom.Event('click', { bubbles: true })) })
expect(mocks.swapActiveWorkoutExercise).toHaveBeenCalledOnce()
expect(mocks.swapActiveWorkoutExercise).toHaveBeenCalledWith(1)
})
})
+44 -12
View File
@@ -9,16 +9,27 @@ import {
import {
modeOf, workoutVolume, setsDone, effectiveRoutine, effectiveRoutineId
} from '../../frontend/src/lib/history.js'
import { EXIDX, exOr } from '../../frontend/src/lib/exercises.js'
import { exOr } from '../../frontend/src/lib/exercises.js'
import { isWarmupRow } from '../../frontend/src/lib/workout-model.js'
import {
estimate1RM, best1RM, e1rmSeries, DEFAULT_FORMULA, REP_CAP
} from '../../frontend/src/lib/onerm.js'
import { loadOfWorkouts, rankOf, levelsOf } from '../../frontend/src/lib/muscles.js'
import { policyFor } from '../../frontend/src/lib/progression.js'
/* ---------- helpers ---------- */
// A custom exercise lives in S.customEx and is merged into EXIDX by registerCustom() at
// store load (useStore.js:54). The MCP server deliberately never calls it: http.js serves
// several profiles from one process behind withRemoteState, so mutating the module-global
// index would leak one profile's customs into another's reads.
const customOf = (id, S) => (S.customEx || []).find(ex => ex.id === id)
// exOr's miss is a placeholder object, not null — callers that only need a name are fine
// with it, callers feeding muscle resolution are NOT. Use customOf directly there.
const exerciseOf = (id, S) => customOf(id, S) || exOr(id)
function entryView(e, S) {
const ex = exOr(e.id)
const ex = exerciseOf(e.id, S)
// Spread id into the cfg the way every call site in the app does (Workout.jsx, Stats.jsx,
// progression.js) — the sheet saves a cardio target as {sets, min, speed} with no id and no
// mode, so modeOf needs the id to fall through to isCardio(id).
@@ -43,15 +54,17 @@ function entryView(e, S) {
}
// Best estimate per exercise, mirroring the UI's PR table: every eligible set across history, biggest wins.
// Warm-ups are skipped for the same reason bestSetOf() skips them (onerm.js): a heavy ramp row is not a
// record. Without this the coach's PR and the athlete's PR silently disagree for the same exercise.
function prTable(S, formula) {
const byId = new Map()
for (const w of (S.workouts || [])) {
for (const e of (w.entries || [])) {
const ex = exerciseOf(e.id, S)
for (const s of (e.sets || [])) {
if (!s.done) continue
if (!s.done || isWarmupRow(s)) continue
const est = estimate1RM(s.w, s.r, formula)
if (est == null) continue
const ex = exOr(e.id)
const prev = byId.get(e.id)
if (!prev || est > prev.est) {
// exId as well as exName: the consumer needs an id, not a name — exOr() treats any
@@ -82,7 +95,8 @@ export const listRoutines = {
emoji: r.emoji || null,
exercise_count: (r.ex || []).length,
superset_groups: [...new Set((r.ex || []).map(e => e.sg).filter(Boolean))].length || 0,
policy: r.policy || 'off'
policy: policyFor(null, r, 'reps'),
exclude_from_progression: r.excludeFromProgression === true
}))
}
}
@@ -102,11 +116,12 @@ export const getRoutine = {
id: r.id,
name: r.name,
emoji: r.emoji || null,
policy: r.policy || 'off',
policy_name: policyName(r.policy || 'off'),
policy: policyFor(null, r, 'reps'),
policy_name: policyName(policyFor(null, r, 'reps')),
exclude_from_progression: r.excludeFromProgression === true,
unit: S.unit || 'kg',
exercises: (r.ex || []).map((cfg, i) => {
const ex = exOr(cfg.id)
const ex = exerciseOf(cfg.id, S)
const mode = modeOf(cfg)
return {
position: i + 1,
@@ -117,12 +132,14 @@ export const getRoutine = {
sets: cfg.sets || 1,
reps: mode === 'reps' ? (cfg.reps || 0) : undefined,
reps_min: mode === 'reps' && cfg.repsMin != null ? cfg.repsMin : undefined,
reps_max: mode === 'reps' && cfg.repsMax != null ? cfg.repsMax : undefined,
sec: mode === 'time' ? (cfg.sec || 0) : undefined,
min: mode === 'cardio' ? (cfg.min || 0) : undefined,
speed: mode === 'cardio' ? (cfg.speed || 0) : undefined,
weight: cfg.weight != null ? cfg.weight : undefined,
increment: cfg.inc != null ? cfg.inc : undefined,
policy_override: cfg.policy || null,
policy: policyFor(cfg, r, mode),
policy_override: cfg.prog || null,
superset_group: cfg.sg || null,
summary: exLine(cfg, S.unit || 'kg')
}
@@ -266,7 +283,10 @@ export const getWorkout = {
sets_done: setsDone(w),
sets_planned: plannedSets(w),
duration: w.end && w.start ? friendlyDuration(w.end - w.start) : null,
prs: (w.prs || []).map(id => EXIDX[id]?.n || id),
prs: (w.prs || []).map(id => {
const ex = exerciseOf(id, S)
return ex.missing ? id : ex.n
}),
entries: (w.entries || []).map(e => entryView(e, S))
}
}
@@ -317,7 +337,7 @@ export const estimate1rm = {
if (!S) return noState()
const f = formula || DEFAULT_FORMULA
if (exercise_id) {
const ex = exOr(exercise_id)
const ex = exerciseOf(exercise_id, S)
const best = best1RM(S, exercise_id, f)
const series = e1rmSeries(S, exercise_id, f)
// A null best has two very different causes: never trained, or trained only above the
@@ -361,7 +381,19 @@ export const muscleBalance = {
: period === 'month' ? now - 30 * 86400000
: Number.NEGATIVE_INFINITY
const workouts = (S.workouts || []).filter(w => (w.start || new Date(w.d + 'T12:00:00').getTime()) >= cutoff)
const load = loadOfWorkouts(workouts)
// loadOf() resolves each entry through EXIDX, which holds the catalogue only, so a
// custom exercise's sets score zero here. Attaching the custom itself lets loadOf's own
// `historical` branch resolve it. Only a *found* custom: exOr's miss placeholder carries
// no muscle metadata and no muscleSnapshot, so attaching that would displace the entry
// and silently zero a *deleted* custom, whose snapshot loadOf reads off the entry
// (muscles.js:245 → metadataOf, snapshot written at sheets.jsx:421-426).
const load = loadOfWorkouts(workouts.map(w => ({
...w,
entries: (w.entries || []).map(e => {
const c = e.exercise ? null : customOf(e.id, S)
return c ? { ...e, exercise: c } : e
})
})))
const { worked, missed } = rankOf(load)
const levels = levelsOf(load)
return {
+130
View File
@@ -7,6 +7,7 @@ import { buildDemoState } from '../../frontend/src/lib/demoSeed.js'
import { EXDB } from '../../frontend/src/lib/exercises.js'
import { _seedStateForTests } from '../src/state.js'
import { TOOLS } from '../src/tools.js'
import { bestSetOf } from '../../frontend/src/lib/onerm.js'
// Re-stated here so the assertions stand alone without reaching into lib internals to learn
// the demo state's exact values.
@@ -70,6 +71,15 @@ describe('list_routines', () => {
})
})
test('reports progression exclusion in routine summaries and details', () => {
S.routines[0].excludeFromProgression = true
const summary = call('list_routines').routines.find(r => r.id === S.routines[0].id)
const detail = call('get_routine', { routine_id: S.routines[0].id })
expect(summary.exclude_from_progression).toBe(true)
expect(detail.exclude_from_progression).toBe(true)
})
test('list_routines entries line up with get_routine (no id drift)', () => {
const list = call('list_routines').routines
list.forEach(summary => {
@@ -98,6 +108,58 @@ describe('get_routine', () => {
})
})
test('resolves custom exercises from the current profile state', () => {
const custom = { id: 'cx-sled-drag', n: 'Sled drag', bp: 'upper legs' }
S.customEx = [custom]
S.routines[0].ex.push({ id: custom.id, sets: 3, reps: 20 })
const r = call('get_routine', { routine_id: S.routines[0].id })
expect(r.exercises.at(-1)).toMatchObject({
id: custom.id,
name: 'Sled drag',
body_part: 'upper legs'
})
})
test('returns both bounds of a reps range', () => {
const cfg = S.routines[0].ex[0]
Object.assign(cfg, { mode: 'reps', reps: 8, repsMin: 8, repsMax: 12 })
const r = call('get_routine', { routine_id: S.routines[0].id })
expect(r.exercises[0]).toMatchObject({ reps: 8, reps_min: 8, reps_max: 12 })
})
test('projects routine and exercise progression rules from prog', () => {
S.routines[0].prog = 'greyskull'
S.routines[0].ex[0].prog = 'double'
const r = call('get_routine', { routine_id: S.routines[0].id })
expect(r).toMatchObject({ policy: 'greyskull', policy_name: 'Greyskull LP' })
expect(r.exercises[0].policy_override).toBe('double')
})
test('a routine with no prog reports the policy the app actually runs, not off', () => {
delete S.routines[0].prog
delete S.routines[0].ex[0].prog
// policyFor defaults reps to linear (progression.js:73) and RoutineEdit.jsx:59 shows
// that same default, so reporting 'off' here would misdescribe every untouched routine.
const r = call('get_routine', { routine_id: S.routines[0].id })
expect(r.policy).toBe('linear')
expect(r.exercises[0].policy).toBe('linear')
expect(r.exercises[0].policy_override).toBeNull()
})
test('a policy the mode cannot run is clamped, not echoed back raw', () => {
S.routines[0].prog = 'greyskull' // reps-only policy
S.customEx = [{ id: 'cx-plank', n: 'Plank', bp: 'waist' }]
S.routines[0].ex.push({ id: 'cx-plank', mode: 'time', sets: 3, sec: 60 })
const view = call('get_routine', { routine_id: S.routines[0].id }).exercises.at(-1)
expect(view.mode).toBe('time')
expect(view.policy).toBe('off') // POLICIES_FOR.time excludes greyskull
})
test('throws ENOENT on a bogus routine id', () => {
expect(() => call('get_routine', { routine_id: 'bogus' })).toThrow()
})
@@ -423,6 +485,35 @@ describe('estimate_1rm', () => {
expect(table).toEqual([])
})
test('a heavy warm-up is never a PR — the table matches the app, which excludes warm-ups', () => {
// The app scans with bestSetOf(), which skips warm-ups (onerm.js). prTable used to gate on
// s.done alone, so a ramp row heavier than the work set became a record the coach reported
// and the athlete never saw — for the same exercise, from the same state.
S.workouts = [{
id: 'w-ramp', d: '2026-07-26', name: 'Legs', start: 1000, end: 1000 + 30 * 60000,
vol: 0, prs: [],
entries: [{
id: LEG_PRESS_ID, target: { sets: 2, reps: 5, mode: 'reps' },
sets: [
{ w: 200, r: 5, done: true, phase: 'warmup' }, // mistyped/greedy ramp row
{ w: 100, r: 5, done: true } // the only real work set
]
}]
}]
_seedStateForTests(S)
const app = bestSetOf(S.workouts[0].entries[0])
expect(app.w).toBe(100) // the app ignores the 200 kg warm-up
const best = call('estimate_1rm', { exercise_id: LEG_PRESS_ID }).best
expect(best.w).toBe(100)
expect(best.est).toBeCloseTo(app.est, 1)
const row = call('estimate_1rm', {}).pr_table.find(p => p.exId === LEG_PRESS_ID)
expect(row.w).toBe(100)
expect(row.est).toBeCloseTo(app.est, 1)
})
test('a null estimate says which kind of null it is', () => {
// "Never trained" and "trained, but always above the rep cap" are opposite facts that both
// arrive as best: null. Undistinguished, the second one reads as the first and an assistant
@@ -488,6 +579,45 @@ describe('muscle_balance', () => {
expect([...neg].every(s => all.has(s))).toBe(true)
})
test('counts custom exercises — they resolve from state, not from the catalogue', () => {
const total = r => r.worked.reduce((n, w) => n + w.effective_sets, 0)
const before = call('muscle_balance', { period: 'all' })
// A custom exercise is absent from EXIDX in this process: the app merges S.customEx in
// via registerCustom() at store load, the MCP server does not. Its sets used to vanish
// from the muscle map entirely.
S.customEx = [{ id: 'cx-hollow-hold', n: 'Hollow hold', bp: 'waist', tg: 'abs' }]
S.workouts[0].entries.push({
id: 'cx-hollow-hold',
sets: [{ sec: 45, done: true }, { sec: 45, done: true }]
})
const after = call('muscle_balance', { period: 'all' })
expect(total(after)).toBeGreaterThan(total(before))
expect(after.worked.find(w => w.slug === 'abs')?.effective_sets)
.toBeGreaterThan(before.worked.find(w => w.slug === 'abs')?.effective_sets || 0)
})
test('still counts a DELETED custom, from the snapshot left on the entry', () => {
const total = r => r.worked.reduce((n, w) => n + w.effective_sets, 0)
const before = total(call('muscle_balance', { period: 'all' }))
// Exactly what sheets.jsx:421-426 leaves behind when a custom exercise is deleted: the
// customEx row is gone, the history entry keeps `n` + `muscleSnapshot`. loadOf reads that
// snapshot off the entry — so nothing may be attached over the top of it.
S.customEx = []
S.workouts[0].entries.push({
id: 'cx-deleted-hold',
n: 'Hollow hold',
muscleSnapshot: { n: 'Hollow hold', bp: 'waist', muscleWeights: { abs: 1 } },
sets: [{ sec: 45, done: true }, { sec: 45, done: true }]
})
const after = call('muscle_balance', { period: 'all' })
expect(total(after)).toBeGreaterThan(before)
expect(after.worked.find(w => w.slug === 'abs')?.effective_sets).toBeGreaterThan(0)
})
test('period windows are inclusive: week ≤ month ≤ all', () => {
const all = call('muscle_balance', { period: 'all' }).workouts_in_period
const month = call('muscle_balance', { period: 'month' }).workouts_in_period
+259
View File
@@ -0,0 +1,259 @@
#!/usr/bin/env node
/**
* Build frontend/src/lib/hevy-id-map.js — a complete, deterministic
* Hevy template-id → openGym catalogue-id table.
*
* Usage:
* HEVY_API_KEY=… node scripts/build-hevy-id-map.mjs
* # or put HEVY_API_KEY in .env and run: node scripts/build-hevy-id-map.mjs
* # or: node scripts/build-hevy-id-map.mjs /path/to/templates.json
*
* Import resolution uses ONLY this table (lookup by template id). Titles are
* never guessed at runtime — regenerate this file when Hevy adds templates.
* End users paste their own key in Settings; this env var is only for regenerating
* the committed map.
*/
import { writeFileSync, readFileSync, existsSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { dirname, join } from 'node:path'
import { matchExercise } from '../frontend/src/lib/import-csv.js'
import { EXIDX } from '../frontend/src/lib/exercises.js'
const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..')
const OUT = join(ROOT, 'frontend/src/lib/hevy-id-map.js')
const HEVY_API = 'https://api.hevyapp.com'
/** Read HEVY_API_KEY from the environment, or from a local `.env` if present. */
function hevyApiKey() {
const fromEnv = (process.env.HEVY_API_KEY || '').trim()
if (fromEnv) return fromEnv
const envPath = join(ROOT, '.env')
if (!existsSync(envPath)) return ''
const m = readFileSync(envPath, 'utf8').match(/^HEVY_API_KEY\s*=\s*(.*)$/m)
if (!m) return ''
return m[1].trim().replace(/^['"]|['"]$/g, '')
}
/**
* Exact Hevy English title (lowercased) → catalogue id.
* Only entries we have verified against EXIDX. Gaps (hip thrust, rower, …)
* are intentionally omitted so they import as custom exercises.
*/
// Titles whose closest catalogue entry is a different movement — better a custom exercise than
// a wrong one. Keep in sync with the note at the top of the generated map.
const NEVER_BY_TITLE = new Set(['crunch', 'side plank', 'squat (machine)', 'triceps extension (cable)', 'rear delt reverse fly (cable)'])
const BY_TITLE = {
// Reported from a real import as customs — same lifts, Hevy vocabulary.
'bulgarian split squat (dumbbell)': '0410',
'bulgarian split squat (barbell)': '0099',
'chest supported incline row (dumbbell)': '0327',
'knee raise parallel bars': '0826',
'lat pulldown - close grip (cable)': '2616',
'rear delt reverse fly (dumbbell)': '0383',
'rear delt reverse fly (machine)': '0602',
'reverse lunge (dumbbell)': '0381',
'reverse lunge (barbell)': '0078',
'seated incline curl (dumbbell)': '0318',
'seated shoulder press (machine)': '0603',
'single leg standing calf raise (machine)': '0605',
// Shared with import-csv ALIAS_EX / cardio pins.
'ab wheel': '0857',
'elliptical trainer': '2141',
'treadmill': '3666',
'cycling': '2331',
'stationary bike': '2138',
'exercise bike': '2138',
'stair machine': '2311',
'stair machine (steps)': '2311',
'jumping jack': '3220',
'jumping jacks': '3220',
'battle ropes': '0128',
'pallof press': '0979',
'cable pallof press': '0979',
'face pull': '0203',
'hack squat (machine)': '0743',
'iso-lateral row (machine)': '0571',
'seated cable row - bar grip': '0218',
'reverse grip lat pulldown (cable)': '0673',
'single arm lateral raise (cable)': '0192',
'plate front raise': '0310',
'back extension (weighted hyperextension)': '0573',
'behind the back bicep wrist curl (barbell)': '0104',
'butterfly (pec deck)': '0596',
'chest fly (machine)': '0596',
'chest fly (dumbbell)': '0308',
'incline chest fly (dumbbell)': '0319',
'cable fly crossovers': '1269',
'bicep curl (dumbbell)': '0294',
'bicep curl (cable)': '0868',
'bicep curl (barbell)': '0031',
'chest supported reverse fly (dumbbell)': '0383',
'bench press (smith machine)': '0748',
'overhead press (smith machine)': '0766',
// Common Hevy titles → canonical catalogue entries (verified ids).
'bench press (barbell)': '0025',
'bench press (dumbbell)': '0289',
'incline bench press (barbell)': '0047',
'incline bench press (dumbbell)': '0314',
'overhead press (barbell)': '0091',
'overhead press (dumbbell)': '0405',
'shoulder press (machine)': '0603',
'shoulder press (dumbbell)': '0405',
'shoulder press (barbell)': '0091',
'squat (barbell)': '0043',
'front squat (barbell)': '0042',
'deadlift (barbell)': '0032',
'romanian deadlift (barbell)': '0085',
'romanian deadlift (dumbbell)': '1459',
'sumo deadlift (barbell)': '0117',
'bent over row (barbell)': '0027',
'bent over row (dumbbell)': '0292',
'lat pulldown (cable)': '2330',
'lat pulldown - wide grip (cable)': '2330',
'leg press (machine)': '0739',
'leg extension (machine)': '0585',
'seated leg curl (machine)': '0586',
'lying leg curl (machine)': '0586',
'goblet squat (dumbbell)': '1760',
'goblet squat (kettlebell)': '0534',
'lunge (dumbbell)': '0336',
'lunges (dumbbell)': '0336',
'pull up': '0652',
'pull-up': '0652',
'chin up': '1326',
'chin-up': '1326',
'push up': '0662',
'push-up': '0662',
'chest dip': '0251',
'plank': '2135',
'russian twist': '0687',
'hanging leg raise': '0472',
'hanging knee raise': '0472',
'cable crunch': '0175',
'standing calf raise (machine)': '0605',
'seated calf raise (machine)': '0594',
'standing calf raise (dumbbell)': '0417',
'shrug (barbell)': '0095',
'shrug (dumbbell)': '0406',
'hammer curl (dumbbell)': '0312',
'concentration curl (dumbbell)': '0297',
'preacher curl (barbell)': '0070',
'skullcrusher (barbell)': '0060',
'skull crusher (barbell)': '0060',
'tricep kickback (dumbbell)': '0333',
'kickback (dumbbell)': '0333',
'lateral raise (dumbbell)': '0334',
'good morning (barbell)': '0044',
}
const EQ_PAREN = {
barbell: 'Barbell', dumbbell: 'Dumbbell', kettlebell: 'Kettlebell',
machine: 'Machine', resistance_band: 'Band', none: null, other: null,
plate: 'Plate', suspension: null,
}
function resolve(t) {
const title = String(t.title || '').trim()
const key = title.toLowerCase()
if (Object.prototype.hasOwnProperty.call(BY_TITLE, key)) {
const v = BY_TITLE[key]
return v && EXIDX[v] ? v : null
}
const paren = EQ_PAREN[t.equipment]
const tries = []
if (paren) tries.push(`${title} (${paren})`)
tries.push(title)
const bare = title.replace(/\s*\([^)]*\)\s*$/, '').trim()
if (bare !== title) {
if (paren) tries.push(`${bare} (${paren})`)
tries.push(bare)
}
if (t.equipment === 'machine') tries.push(`lever ${bare}`)
for (const c of tries) {
const id = matchExercise(c)
if (id && EXIDX[id]) return id
}
return null
}
async function fetchTemplates(apiKey) {
const items = []
let page = 1, pageCount = 1
while (page <= pageCount) {
const url = `${HEVY_API}/v1/exercise_templates?page=${page}&pageSize=100`
const res = await fetch(url, { headers: { 'api-key': apiKey } })
if (!res.ok) throw new Error(`Hevy API ${res.status}`)
const data = await res.json()
pageCount = data.page_count || 1
items.push(...(data.exercise_templates || []))
page++
}
return items
}
async function main() {
for (const [title, id] of Object.entries(BY_TITLE)) {
if (id && !EXIDX[id]) throw new Error(`BY_TITLE "${title}" → missing catalogue id ${id}`)
}
const arg = process.argv[2]
let templates
if (arg && existsSync(arg)) {
templates = JSON.parse(readFileSync(arg, 'utf8'))
} else {
const key = hevyApiKey()
if (!key) {
throw new Error('Set HEVY_API_KEY (env or .env), or pass a templates JSON path')
}
templates = await fetchTemplates(key)
}
const map = {}
const titleMap = {}
const unmatched = []
for (const t of templates) {
if (!t?.id || t.is_custom) { if (t?.id && t.is_custom) unmatched.push(t); continue }
const id = resolve(t)
if (id) {
map[t.id] = id
const titleKey = String(t.title || '').trim().toLowerCase()
if (titleKey && !NEVER_BY_TITLE.has(titleKey) && !titleMap[titleKey]) titleMap[titleKey] = id
} else unmatched.push(t)
}
// Stable key order for readable diffs.
const keys = Object.keys(map).sort()
const lines = keys.map(k => ` ${JSON.stringify(k)}: ${JSON.stringify(map[k])},`)
const titleKeys = Object.keys(titleMap).sort()
const titleLines = titleKeys.map(k => ` ${JSON.stringify(k)}: ${JSON.stringify(titleMap[k])},`)
const body = `// AUTO-GENERATED by scripts/build-hevy-id-map.mjs — do not edit by hand.
// Hevy exercise_template id → openGym catalogue id, plus English title → id for CSV exports
// (Hevy CSV has titles, not template ids). Regenerated from the Hevy templates API +
// verified title aliases.
// ${keys.length} mapped · ${unmatched.length} left unmatched (import as custom).
// Source templates: ${templates.length} (built-in only).
export const HEVY_ID_MAP = {
${lines.join('\n')}
}
/** Lowercased Hevy English title → catalogue id (CSV / name path). */
export const HEVY_TITLE_MAP = {
${titleLines.join('\n')}
}
`
writeFileSync(OUT, body)
console.log(`Wrote ${OUT}`)
console.log(`Mapped ${keys.length} / ${templates.filter(t => !t.is_custom).length} (titles ${titleKeys.length})`)
console.log(`Unmatched ${unmatched.length} (become custom on import)`)
if (process.env.VERBOSE) {
unmatched.slice(0, 40).forEach(t => console.log(' -', t.title, `[${t.equipment}]`))
}
}
main().catch(e => { console.error(e); process.exit(1) })
+28
View File
@@ -0,0 +1,28 @@
#!/usr/bin/env node
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
import { dirname, join } from 'node:path'
import { fileURLToPath, pathToFileURL } from 'node:url'
const root = join(dirname(fileURLToPath(import.meta.url)), '..')
const sourcePath = join(root, 'scripts', 'exercise-name-sources', 'hu.json')
const outputPath = join(root, 'frontend', 'src', 'exercise-names', 'hu.js')
const exercisesPath = join(root, 'frontend', 'src', 'lib', 'exercises-data.js')
const source = JSON.parse(readFileSync(sourcePath, 'utf8'))
const { EXDB } = await import(pathToFileURL(exercisesPath))
const known = new Set(EXDB.map(exercise => exercise.id))
for (const id of Object.keys(source)) {
if (!known.has(id)) throw new Error(`Unknown exercise ID: ${id}`)
if (typeof source[id] !== 'string' || !source[id].trim()) throw new Error(`${id}: name must be a non-empty string`)
}
if (Object.keys(source).length !== EXDB.length) {
throw new Error(`Incomplete hu exercise names: ${Object.keys(source).length}/${EXDB.length}`)
}
const ordered = {}
for (const exercise of EXDB) ordered[exercise.id] = source[exercise.id].trim()
mkdirSync(dirname(outputPath), { recursive: true })
writeFileSync(outputPath, '// generated by scripts/build-hu-exercise-names.mjs — edit scripts/exercise-name-sources/hu.json\nexport default ' + JSON.stringify(ordered) + '\n')
console.log(`Generated ${EXDB.length}/${EXDB.length} hu exercise names.`)
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -344,7 +344,7 @@ try {
</ul>
<div class="push">
<a class="btn" href="openGym.apk" download>Download for Android</a>
<p class="meta">v1.2.13 · 4.4 MB · Android 6.0+ · signed APK. Your browser will ask
<p class="meta">v1.2.14 · 4.5 MB · Android 6.0+ · signed APK. Your browser will ask
before installing; that is normal outside the Play Store.</p>
<p class="meta">Every release is also built and signed by CI and attached to the
<a href="https://gitlab.com/DuarteSantos8/opengym/-/releases" rel="noopener">GitLab