Merge workout-clean: schlanker Workout-Screen, Farb-RIR (!91), Historie im Workout, Favoriten, In-App-Update (!40), Bugfix-Runde — v1.3.3

This commit is contained in:
Duarte Santos committed 2026-09-05 14:28:12 +02:00
commit 078f091cfb
65 files changed
+3082 -148

No files matched your search

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