diff --git a/CHANGELOG.md b/CHANGELOG.md index dde2037..540e018 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/README.md b/README.md index 43db947..b22c204 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/ROADMAP.md b/ROADMAP.md new file mode 100644 index 0000000..ce2a01c --- /dev/null +++ b/ROADMAP.md @@ -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. diff --git a/api/openapi.yaml b/api/openapi.yaml index d3db779..17841b8 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -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 diff --git a/api/package-lock.json b/api/package-lock.json index e32344a..462f251 100644 --- a/api/package-lock.json +++ b/api/package-lock.json @@ -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", diff --git a/api/package.json b/api/package.json index b25ce93..ea269f7 100644 --- a/api/package.json +++ b/api/package.json @@ -1,6 +1,6 @@ { "name": "gym-api", - "version": "1.3.2", + "version": "1.3.3", "private": true, "type": "module", "main": "server.js", diff --git a/frontend/android/app/build.gradle b/frontend/android/app/build.gradle index fb1f3c7..3882d10 100644 --- a/frontend/android/app/build.gradle +++ b/frontend/android/app/build.gradle @@ -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. diff --git a/frontend/android/app/src/main/AndroidManifest.xml b/frontend/android/app/src/main/AndroidManifest.xml index d84111a..4860b31 100644 --- a/frontend/android/app/src/main/AndroidManifest.xml +++ b/frontend/android/app/src/main/AndroidManifest.xml @@ -36,6 +36,7 @@ + diff --git a/frontend/android/app/src/main/java/ch/duartesantos/opengym/InstallPlugin.java b/frontend/android/app/src/main/java/ch/duartesantos/opengym/InstallPlugin.java new file mode 100644 index 0000000..3fdd7c7 --- /dev/null +++ b/frontend/android/app/src/main/java/ch/duartesantos/opengym/InstallPlugin.java @@ -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(); + } +} diff --git a/frontend/android/app/src/main/java/ch/duartesantos/opengym/MainActivity.java b/frontend/android/app/src/main/java/ch/duartesantos/opengym/MainActivity.java index 6b41bd5..67cacdb 100644 --- a/frontend/android/app/src/main/java/ch/duartesantos/opengym/MainActivity.java +++ b/frontend/android/app/src/main/java/ch/duartesantos/opengym/MainActivity.java @@ -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); + } +} diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 72e41b2..e3d6ae5 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -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", diff --git a/frontend/package.json b/frontend/package.json index b282830..b05ec24 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,7 +1,7 @@ { "name": "opengym-frontend", "private": true, - "version": "1.3.2", + "version": "1.3.3", "type": "module", "scripts": { "dev": "vite", diff --git a/frontend/src/components/Icon.jsx b/frontend/src/components/Icon.jsx index 033f3f1..065eb24 100644 --- a/frontend/src/components/Icon.jsx +++ b/frontend/src/components/Icon.jsx @@ -108,6 +108,7 @@ const P = { flag: <>, chartLine: , dot: , + more: <>, history: <>, signOut: <>, shuffle: <>, diff --git a/frontend/src/components/MuscleExplorer.jsx b/frontend/src/components/MuscleExplorer.jsx index e0cdfb6..9916377 100644 --- a/frontend/src/components/MuscleExplorer.jsx +++ b/frontend/src/components/MuscleExplorer.jsx @@ -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
choose(e))}> -
{exerciseNameFor(e)}
{t(primary ? 'Primary target' : 'Also trains')} · {t(e.tg || e.bp)} · {t(e.eq)}
+
{isFav(S, e.id) && }{exerciseNameFor(e)}
{t(primary ? 'Primary target' : 'Also trains')} · {t(e.tg || e.bp)} · {t(e.eq)}
{onPick ? : <> {best > 0 && {fmtNum(best)}} diff --git a/frontend/src/components/TabBar.jsx b/frontend/src/components/TabBar.jsx index d54e31c..97d27db 100644 --- a/frontend/src/components/TabBar.jsx +++ b/frontend/src/components/TabBar.jsx @@ -32,9 +32,12 @@ export default function TabBar({ onStart }) {
} +/* ============================ 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 &&

{title}

} + {subtitle &&
{subtitle}
} +
+ {items.filter(Boolean).map((it, i) =>
{ close(); it.onClick && it.onClick() })}> + {it.icon && } +
{it.label}
{it.sub &&
{it.sub}
}
+ {it.on != null && } +
)} +
+ +} +export function menuSheet(opts) { + ui().openSheet(close => ) +} + // Themed replacement for window.confirm — callback-based (no blocking). export function confirmSheet(opts) { ui().openSheet(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 <> -

{exerciseNameFor(ex)}

+
+

{exerciseNameFor(ex)}

+ +
{t(ex.bp)} @@ -605,6 +649,7 @@ function ExerciseDetail({ ex, close }) { {ex.desc &&
{ex.desc}
} {best > 0 &&
{t('Best:')} {fmtNum(best)} {st.unit}{last ? ` · ${t('last')} ${fmtDate(last.d)}: ${last.sets.map(s => setLabel(ex.id, s, last.target)).join(', ')}` : ''}
} + {last && } {ex.custom &&
@@ -619,6 +664,56 @@ function ExerciseDetail({ ex, close }) { } export const exerciseDetailSheet = ex => ui().openSheet(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 <> +

{exerciseNameFor(ex)}

+
{t('No sessions logged yet')}
+ + 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 <> +

{exerciseNameFor(ex)}

+
{t('Exercise history')} · {t(h.total === 1 ? '{0} session' : '{0} sessions', h.total)}
+ {/* Only reps work with a load produces an estimate, so the toggle is absent for the rest. */} + {h.e1rmPoints.length > 0 && h.metric === 'weight' && } +
+ +
+
+ + {t('Best:')} {fmtNum(onE1 ? e1Best : h.best)} {onE1 ? st.unit : unit} +
+

{h.sessions.length < h.total ? t('Last {0} sessions', h.sessions.length) : t('Sessions')}

+
+ {h.sessions.map(s =>
+
+
{fmtDate(s.d, true)} {s.pr && PR}
+
{s.sets.map(x => setLabel(exId, x, s.target)).join(' · ')}
+ {tail(s) &&
{tail(s)}
} +
+ {s.value != null && s.value > 0 && {fmtNum(s.value)} {unit}} +
)} +
+ +} +export const exerciseHistorySheet = exId => ui().openSheet(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 }) {
}
1 ? '10px 0 6px' : '10px 0' }}> + {favCount > 0 && } {chosenCount > 0 && } {BODYPARTS.map(b => )} @@ -813,12 +912,13 @@ function ExercisePicker({ onPick, close }) { {eqOpts.map(x => )}
}
- {bp !== '★' &&
customExSheet(null, ex => onPick(ex), q.trim()))}> + {!special &&
customExSheet(null, ex => onPick(ex), q.trim()))}>
{t('Create your own exercise')}
{t('name + body part, no animation')}
} {f.slice(0, shown).map(e =>
onPick(e))}> -
{exerciseNameFor(e)}
{t(e.tg || e.bp)} · {t(e.eq)}
+
{isFav(st, e.id) && }{exerciseNameFor(e)}
{t(e.tg || e.bp)} · {t(e.eq)}
+ {/* Accent tag = already in a routine/log ("Chosen"); the yellow star by the name = favourite. */} {usage[e.id] && } {/* 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) }}>
)} {f.length === 0 && bp === '★' &&
{t('Nothing chosen yet — add exercises and they’ll show up here.')}
} + {f.length === 0 && bp === '☆' &&
{t('No favourites here — tap the star on an exercise to add it.')}
}
{f.length > shown && <>
} @@ -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 <> +

{t('How hard was that set?')}

+
+ {t('Tap how many reps you had left, or type an exact {0}.', EFFORT[kind].hd)} +
+
+ {EFFORT_PRESETS.map(p => { + const label = fmtNum(toScale(kind, p.rir)) + (p.tail ? '+' : '') + const on = curRir != null && curRir === p.rir + return + })} +
+ {/* 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. */} +
+ {t('Exact {0}', EFFORT[kind].hd)} +
+ + set(capEffort(kind, nv))} /> + +
+ {EFFORT[kind].hd} +
+
+ {v != null && } +
+ +} +// 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 => ) + /* ============================ share / print / import a plan ============================ */ export const planToolsSheet = () => ui().openSheet(close => ) diff --git a/frontend/src/store/useStore.js b/frontend/src/store/useStore.js index 4c5f879..33dd4a7 100644 --- a/frontend/src/store/useStore.js +++ b/frontend/src/store/useStore.js @@ -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. diff --git a/frontend/src/views/CoachSetup.jsx b/frontend/src/views/CoachSetup.jsx index e5f8141..878d266 100644 --- a/frontend/src/views/CoachSetup.jsx +++ b/frontend/src/views/CoachSetup.jsx @@ -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) } } diff --git a/frontend/src/views/Library.jsx b/frontend/src/views/Library.jsx index b591abb..52eac47 100644 --- a/frontend/src/views/Library.jsx +++ b/frontend/src/views/Library.jsx @@ -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
exerciseDetailSheet(e))}> -
{exerciseNameFor(e)}
{t(e.tg || e.bp)} · {t(e.eq)}
+
{isFav(S, e.id) && }{exerciseNameFor(e)}
{t(e.tg || e.bp)} · {t(e.eq)}
{best > 0 && {fmtNum(best)}}
diff --git a/frontend/src/views/Library.test.jsx b/frontend/src/views/Library.test.jsx new file mode 100644 index 0000000..b4d9543 --- /dev/null +++ b/frontend/src/views/Library.test.jsx @@ -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()) + 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) + }) +}) diff --git a/frontend/src/views/Settings.gifsize.test.jsx b/frontend/src/views/Settings.gifsize.test.jsx index e3fa44d..a0d83d4 100644 --- a/frontend/src/views/Settings.gifsize.test.jsx +++ b/frontend/src/views/Settings.gifsize.test.jsx @@ -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(), diff --git a/frontend/src/views/Settings.jsx b/frontend/src/views/Settings.jsx index d349a96..f9e0bad 100644 --- a/frontend/src/views/Settings.jsx +++ b/frontend/src/views/Settings.jsx @@ -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 { 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() { } {/* ---------- general ---------- */} -
+
update(s => { s.lang = v })} @@ -131,7 +205,7 @@ export default function Settings() { update(s => { s.unit = v })} /> + value={S.unit} onChange={v => switchUnit(v)} /> {/* 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 })} /> + {/* 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. */} +