Skip to content

Open-source gym & body-weight tracker, now in the App Store (iPhone + Apple Watch) and as an Android APK. Plan routines, log workouts, see which muscles are trained, import from Strong/Hevy/FitNotes. Self-host it or use it on the phone alone.

feat(checkin): gym membership QR check-in (mobile-only)

Sebastian Ga797729dd081
diff --git a/NOTICE.md b/NOTICE.md
index a6a1cf2e6..0ae5a0a34 100644
--- a/NOTICE.md
+++ b/NOTICE.md
@@ -123,3 +123,49 @@ English source produced with OpenAI Codex and Anthropic Claude Code
language-model assistance. They are not copied from a separate Portuguese
dataset. Their review status and translation policy are documented alongside
the source files.
+
+## Gym check-in QR codes
+
+The mobile-only gym check-in feature (a saved membership code shown as a QR/barcode on the phone,
+added by typing, importing a photo, or scanning with the camera) uses two third-party packages.
+Both are permissively licensed and compatible with openGym's AGPL, and both are bundled only in
+the mobile build — the web and demo builds never ship them.
+
+### QR/barcode rendering — `lean-qr`
+
+openGym renders each saved code on the phone with [**lean-qr**](https://github.com/davidje13/lean-qr)
+by David Evans, used under the **MIT License** and reproduced below. Only the code's stored value
+is kept; the picture is generated fresh from that value each time it is shown, never stored.
+
+```
+MIT License
+
+Copyright (c) 2021-2025 David Evans
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+```
+
+### Camera scan & photo decode — `@capacitor-mlkit/barcode-scanning`
+
+Reading a code — from the camera or from an imported photo — uses the
+[**@capacitor-mlkit/barcode-scanning**](https://github.com/capawesome-team/capacitor-mlkit) plugin
+by the Capawesome Team (Robin Genz), a Capacitor wrapper around Google's ML Kit, used under the
+**Apache License 2.0**. openGym pins the `7.x` line to stay on Capacitor 7. The full license text is
+available at <https://www.apache.org/licenses/LICENSE-2.0> and in the package's own `LICENSE` file.
+The decoded string is what openGym keeps; the photo itself is never stored.
diff --git a/frontend/android/app/build.gradle b/frontend/android/app/build.gradle
index 98868cd41..f47759508 100644
--- a/frontend/android/app/build.gradle
+++ b/frontend/android/app/build.gradle
@@ -21,6 +21,12 @@ android {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
+ debug {
+ // Test build installs side-by-side with the real app: its own applicationId, so both
+ // can live on one device. The name/icon label is overridden by the debug resource
+ // overlay in src/debug/res. The release build (the "real" app) is untouched.
+ applicationIdSuffix ".test"
+ }
}
}
diff --git a/frontend/android/app/capacitor.build.gradle b/frontend/android/app/capacitor.build.gradle
index af1bea981..815aa6bab 100644
--- a/frontend/android/app/capacitor.build.gradle
+++ b/frontend/android/app/capacitor.build.gradle
@@ -9,6 +9,7 @@ android {
apply from: "../capacitor-cordova-android-plugins/cordova.variables.gradle"
dependencies {
+ implementation project(':capacitor-mlkit-barcode-scanning')
implementation project(':capacitor-app')
implementation project(':capacitor-filesystem')
implementation project(':capacitor-local-notifications')
diff --git a/frontend/android/app/src/debug/res/values/strings.xml b/frontend/android/app/src/debug/res/values/strings.xml
new file mode 100644
index 000000000..eff2a584f
--- /dev/null
+++ b/frontend/android/app/src/debug/res/values/strings.xml
@@ -0,0 +1,7 @@
+<?xml version='1.0' encoding='utf-8'?>
+<resources>
+ <!-- Debug-only overrides so the test build shows a distinct name next to the real app.
+ Merged over src/main/res for the debug variant only; the release build keeps openGym. -->
+ <string name="app_name">OpenGymTest</string>
+ <string name="title_activity_main">OpenGymTest</string>
+</resources>
diff --git a/frontend/android/app/src/main/AndroidManifest.xml b/frontend/android/app/src/main/AndroidManifest.xml
index d137fe653..d84111ae0 100644
--- a/frontend/android/app/src/main/AndroidManifest.xml
+++ b/frontend/android/app/src/main/AndroidManifest.xml
@@ -27,6 +27,10 @@
android:grantUriPermissions="true">
<meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths" />
</provider>
+
+ <!-- Gym check-in scanner (@capacitor-mlkit/barcode-scanning): pre-fetch the ML Kit
+ barcode model at install time so the first scan doesn't wait on a download. -->
+ <meta-data android:name="com.google.mlkit.vision.DEPENDENCIES" android:value="barcode_ui" />
</application>
<!-- Permissions -->
@@ -36,4 +40,6 @@
on Android 12+. Where it isn't granted, scheduling silently falls back to inexact
alarms — the reminder still arrives, just not to the minute. -->
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />
+ <!-- Gym check-in: scanning a membership QR/barcode with the camera. -->
+ <uses-permission android:name="android.permission.CAMERA" />
</manifest>
diff --git a/frontend/android/capacitor.settings.gradle b/frontend/android/capacitor.settings.gradle
index d757f12e5..90dbbe8a1 100644
--- a/frontend/android/capacitor.settings.gradle
+++ b/frontend/android/capacitor.settings.gradle
@@ -2,6 +2,9 @@
include ':capacitor-android'
project(':capacitor-android').projectDir = new File('../node_modules/@capacitor/android/capacitor')
+include ':capacitor-mlkit-barcode-scanning'
+project(':capacitor-mlkit-barcode-scanning').projectDir = new File('../node_modules/@capacitor-mlkit/barcode-scanning/android')
+
include ':capacitor-app'
project(':capacitor-app').projectDir = new File('../node_modules/@capacitor/app/android')
diff --git a/frontend/ios/App/App/Info.plist b/frontend/ios/App/App/Info.plist
index 8e81fcd38..198730746 100644
--- a/frontend/ios/App/App/Info.plist
+++ b/frontend/ios/App/App/Info.plist
@@ -45,5 +45,7 @@
</array>
<key>UIViewControllerBasedStatusBarAppearance</key>
<true/>
+ <key>NSCameraUsageDescription</key>
+ <string>Used to scan your gym membership QR code so you can check in from the app.</string>
</dict>
</plist>
diff --git a/frontend/package-lock.json b/frontend/package-lock.json
index a4e04ce3e..57d6a3c61 100644
--- a/frontend/package-lock.json
+++ b/frontend/package-lock.json
@@ -9,11 +9,13 @@
"version": "1.2.14",
"license": "AGPL-3.0-or-later",
"dependencies": {
+ "@capacitor-mlkit/barcode-scanning": "^7.5.0",
"@capacitor/app": "^7.1.2",
"@capacitor/core": "^7.6.8",
"@capacitor/filesystem": "^7.1.8",
"@capacitor/local-notifications": "^7.0.7",
"@capacitor/share": "^7.0.4",
+ "lean-qr": "^2.7.3",
"react": "^19.2.7",
"react-dom": "^19.2.7",
"react-router-dom": "^7.18.2",
@@ -54,6 +56,25 @@
"node": ">=6.9.0"
}
},
+ "node_modules/@capacitor-mlkit/barcode-scanning": {
+ "version": "7.5.0",
+ "resolved": "https://registry.npmjs.org/@capacitor-mlkit/barcode-scanning/-/barcode-scanning-7.5.0.tgz",
+ "integrity": "sha512-DBWRykYYLW0YMj/UzlQ0sVGn83mwGAJsbZVxFsd44pppEEy88OO04lxy9Esv5QpnNBIKPjSIqLWmSLuhoFGPaQ==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/capawesome-team/"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/capawesome"
+ }
+ ],
+ "license": "Apache-2.0",
+ "peerDependencies": {
+ "@capacitor/core": ">=7.0.0"
+ }
+ },
"node_modules/@capacitor/android": {
"version": "7.6.8",
"resolved": "https://registry.npmjs.org/@capacitor/android/-/android-7.6.8.tgz",
@@ -3742,6 +3763,15 @@
"node": ">=6"
}
},
+ "node_modules/lean-qr": {
+ "version": "2.7.3",
+ "resolved": "https://registry.npmjs.org/lean-qr/-/lean-qr-2.7.3.tgz",
+ "integrity": "sha512-/eQryMvYyTL3dSMK/IlvSjUYG0ShQv62owXiFbGkSH+lFZzf4VOsPP+UInAgeUH/rPIyz59uQE9XHRbn9o8SyQ==",
+ "license": "MIT",
+ "bin": {
+ "lean-qr": "cli.mjs"
+ }
+ },
"node_modules/lightningcss": {
"version": "1.32.0",
"resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.32.0.tgz",
diff --git a/frontend/package.json b/frontend/package.json
index 7ee96e5de..dded90664 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -14,11 +14,13 @@
},
"license": "AGPL-3.0-or-later",
"dependencies": {
+ "@capacitor-mlkit/barcode-scanning": "^7.5.0",
"@capacitor/app": "^7.1.2",
"@capacitor/core": "^7.6.8",
"@capacitor/filesystem": "^7.1.8",
"@capacitor/local-notifications": "^7.0.7",
"@capacitor/share": "^7.0.4",
+ "lean-qr": "^2.7.3",
"react": "^19.2.7",
"react-dom": "^19.2.7",
"react-router-dom": "^7.18.2",
diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx
index b30af2f81..bd0f340b4 100644
--- a/frontend/src/App.jsx
+++ b/frontend/src/App.jsx
@@ -5,6 +5,7 @@ import { useUI } from './store/useUI.js'
import { bindUI } from './components/ui.jsx'
import { ACCENTS } from './lib/format.js'
import { setLang, useLang } from './lib/i18n.js'
+import { MOBILE } from './lib/mobile.js'
import { setNav } from './lib/nav.js'
import { initBackButton } from './lib/back.js'
import { useWakeLock } from './lib/wakelock.js'
@@ -19,6 +20,7 @@ import TimerFlash from './components/TimerFlash.jsx'
import Login from './views/Login.jsx'
import MobileOnboarding from './views/MobileOnboarding.jsx'
import Home from './views/Home.jsx'
+import CheckIn from './views/CheckIn.jsx'
import Plan from './views/Plan.jsx'
import RoutineEdit from './views/RoutineEdit.jsx'
import Workout from './views/Workout.jsx'
@@ -110,6 +112,10 @@ function Shell() {
{!authed ? <Login /> : needsMobileOnboarding ? <MobileOnboarding /> : (
<Routes>
<Route path="/home" element={<Home />} />
+ {/* Gym check-in is mobile-only — it needs the native scanner and showing a QR to
+ a turnstile makes no sense in a browser tab. Off mobile the route falls through
+ to the catch-all redirect below. */}
+ {MOBILE && <Route path="/checkin" element={<CheckIn />} />}
<Route path="/plan" element={<Plan />} />
<Route path="/plan/r/:id" element={<RoutineEdit />} />
<Route path="/workout" element={<Workout />} />
diff --git a/frontend/src/components/Icon.jsx b/frontend/src/components/Icon.jsx
index b270cd343..033f3f13b 100644
--- a/frontend/src/components/Icon.jsx
+++ b/frontend/src/components/Icon.jsx
@@ -112,6 +112,11 @@ const P = {
signOut: <><path d="M14.2 4.6H7a1.9 1.9 0 0 0-1.9 1.9v11a1.9 1.9 0 0 0 1.9 1.9h7.2" /><path d="m16.8 8.4 3.6 3.6-3.6 3.6M20.4 12H10.2" /></>,
shuffle: <><path d="M3.6 7.2h2.9c1.6 0 2.8.9 3.8 2.4l3 4.8c1 1.5 2.2 2.4 3.8 2.4h2.9M3.6 16.8h2.9c1.6 0 2.8-.9 3.8-2.4l.7-1.1M15.6 9.9l.7-1.1c1-1.5 2.2-2.4 3.8-2.4h1.9" /><path d="m17.9 4.3 2.8 2.1-2.8 2.1M17.9 14.7l2.8 2.1-2.8 2.1" /></>,
info: <><circle cx="12" cy="12" r="8.2" /><path d="M12 11v5.4" /><circle cx="12" cy="7.9" r=".9" fill="currentColor" stroke="none" /></>,
+ // Three position-detection squares plus a scatter of modules — reads as "QR / scan this"
+ // at tab-bar size without trying to draw a real (unscannable) code.
+ qr: <><rect x="3.6" y="3.6" width="6" height="6" rx="1.2" /><rect x="14.4" y="3.6" width="6" height="6" rx="1.2" /><rect x="3.6" y="14.4" width="6" height="6" rx="1.2" /><path d="M14.4 14.4h2.4v2.4M20.4 14.4v.01M14.4 20.4h.01M17.4 17.4h3M17.4 20.4h3" /></>,
+ camera: <><path d="M3.6 8.8a2 2 0 0 1 2-2h1.9l1.3-2.1h6.4l1.3 2.1h1.9a2 2 0 0 1 2 2v8.4a2 2 0 0 1-2 2H5.6a2 2 0 0 1-2-2Z" /><circle cx="12" cy="12.8" r="3.3" /></>,
+ image: <><rect x="3.6" y="4.8" width="16.8" height="14.4" rx="2.6" /><circle cx="8.6" cy="9.6" r="1.7" /><path d="m4.4 17.4 4.8-4.6 3.3 3 3-2.6 4.1 4" /></>,
warning: <><path d="M12 3.4 21.2 19.4H2.8Z" /><path d="M12 9.6v4.4" /><circle cx="12" cy="16.6" r=".9" fill="currentColor" stroke="none" /></>,
}
diff --git a/frontend/src/components/QrCanvas.jsx b/frontend/src/components/QrCanvas.jsx
new file mode 100644
index 000000000..543e0527d
--- /dev/null
+++ b/frontend/src/components/QrCanvas.jsx
@@ -0,0 +1,33 @@
+import { useEffect, useRef, useState } from 'react'
+import { renderQrToCanvas } from '../lib/qr.js'
+
+// Renders a gym check-in code as a QR image on a <canvas>. lean-qr draws one module per pixel;
+// CSS (.qr-canvas) scales it up with image-rendering: pixelated so it stays razor-sharp at any
+// display size without re-generating. Regenerated from `value` on every change — we never store
+// the picture (see lib/qr.js).
+//
+// The lib loads via dynamic import, so the first paint is a frame behind; a plain box holds the
+// space until then. A render failure (empty value, lib load error) shows nothing rather than a
+// broken canvas — the caller decides what an unusable card looks like.
+export default function QrCanvas({ value, size = 240, className = '' }) {
+ const ref = useRef(null)
+ const [ok, setOk] = useState(false)
+
+ useEffect(() => {
+ let alive = true
+ setOk(false)
+ renderQrToCanvas(ref.current, value)
+ .then(mods => { if (alive) setOk(mods > 0) })
+ .catch(() => { if (alive) setOk(false) })
+ return () => { alive = false }
+ }, [value])
+
+ return (
+ <canvas
+ ref={ref}
+ className={'qr-canvas ' + className}
+ style={{ width: size, height: size, opacity: ok ? 1 : 0 }}
+ aria-label="QR code"
+ />
+ )
+}
diff --git a/frontend/src/index.css b/frontend/src/index.css
index ca0528eea..cfbb5420e 100644
--- a/frontend/src/index.css
+++ b/frontend/src/index.css
@@ -1056,3 +1056,40 @@ h4.sec{
.exmedia img{height:380px}
.hm-wrap{display:flex;flex-direction:column;align-items:center}
}
+
+/* ------------------------------------------------------- gym check-in -- */
+/* Mobile-only feature (views/CheckIn.jsx): saved membership codes shown as QR, swiped
+ through horizontally. The rail is a scroll-snap track — one card per viewport, no JS
+ carousel — with a trailing "+" card to add another. */
+.ci-rail{
+ display:flex;gap:14px;overflow-x:auto;scroll-snap-type:x mandatory;
+ -webkit-overflow-scrolling:touch;scrollbar-width:none;
+ padding:4px 0 8px;margin:0 -16px;padding-left:16px;padding-right:16px;
+}
+.ci-rail::-webkit-scrollbar{display:none}
+.ci-card{
+ scroll-snap-align:center;flex:0 0 100%;box-sizing:border-box;
+ background:var(--surface);border-radius:var(--r-xl);padding:22px 18px;
+ display:flex;flex-direction:column;align-items:center;gap:14px;
+}
+.ci-card .ci-label{font-size:19px;font-weight:600;letter-spacing:-.014em;text-align:center}
+.ci-card .ci-value{font-size:14px;color:var(--label-2);word-break:break-all;text-align:center;font-variant-numeric:tabular-nums}
+/* The QR itself: lean-qr paints 1 module per pixel, so scale it up with the browser's
+ nearest-neighbour so every module stays a crisp square instead of a blurred blob. White
+ quiet-zone padding is baked in by the renderer; the plate underneath just frames it. */
+.ci-qr-plate{background:#fff;border-radius:var(--r-lg);padding:16px}
+.qr-canvas{display:block;image-rendering:pixelated;image-rendering:crisp-edges;transition:opacity var(--fast)}
+/* the trailing add card — a big + on a dashed outline, same footprint as a real card */
+.ci-add{
+ scroll-snap-align:center;flex:0 0 100%;box-sizing:border-box;
+ min-height:280px;border-radius:var(--r-xl);
+ border:2px dashed var(--surface-3);background:none;color:var(--label-2);
+ display:flex;flex-direction:column;align-items:center;justify-content:center;gap:10px;
+}
+.ci-add:active{background:var(--surface);transform:scale(.99)}
+.ci-add .icn{font-size:40px;--icon-stroke:1.8}
+.ci-add .ci-add-t{font-size:16px;font-weight:500}
+/* dots under the rail — which card you're on. Purely a hint; the rail itself is the control. */
+.ci-dots{display:flex;justify-content:center;gap:7px;margin-top:4px}
+.ci-dot{width:7px;height:7px;border-radius:50%;background:var(--surface-3);transition:background var(--fast),transform var(--fast)}
+.ci-dot.on{background:var(--acc);transform:scale(1.15)}
diff --git a/frontend/src/lib/qr.js b/frontend/src/lib/qr.js
new file mode 100644
index 000000000..a3af848b9
--- /dev/null
+++ b/frontend/src/lib/qr.js
@@ -0,0 +1,67 @@
+// QR rendering for the gym check-in cards (mobile-only feature — see views/CheckIn.jsx).
+//
+// We never store a photo of a membership card, only its decoded value (+ its symbology in
+// `fmt`). The picture a turnstile scanner reads is regenerated from that value every time the
+// card is shown, here.
+//
+// lean-qr (MIT, see NOTICE.md) is loaded with a dynamic import so its ~4kB never lands in the
+// web bundle — the whole feature is gated behind MOBILE, but the library itself is plain JS a
+// static import would otherwise pull into every build.
+//
+// Scope: lean-qr generates QR codes only. A gym card is virtually always a QR code, and the
+// capture flow (lib/scan.js) refuses any symbology we cannot faithfully reproduce, so a stored
+// card is guaranteed renderable here — canRenderFmt() is the single source of that truth, shared
+// by both sides.
+
+let _leanqr = null
+
+// Cached loader for lean-qr. Resolves once; every card after the first reuses the same module.
+async function loadLeanQr() {
+ if (!_leanqr) _leanqr = await import('lean-qr')
+ return _leanqr
+}
+
+// The symbologies we can both read (mlkit) AND redraw (lean-qr). Stored `fmt` is a lower-cased
+// BarcodeFormat. Only QR qualifies: reproducing an EAN/Code128/etc. would need a 1D renderer we
+// deliberately did not add, and a code we can't redraw faithfully is worse than not storing it —
+// it would look scannable but carry the wrong bars.
+export function canRenderFmt(fmt) {
+ return normalizeFmt(fmt) === 'qrcode'
+}
+
+// mlkit reports BarcodeFormat as e.g. 'QR_CODE' | 'QrCode'; older callers may pass 'qr'. Fold
+// them all to a stable lower-case token we store and compare on.
+export function normalizeFmt(fmt) {
+ const s = String(fmt || '').toLowerCase().replace(/[^a-z0-9]/g, '')
+ if (s === 'qr' || s === 'qrcode') return 'qrcode'
+ return s
+}
+
+// Draw `value` as a QR code onto `canvas` at 1 module per pixel; CSS scales it up with
+// image-rendering: pixelated (see .qr-canvas in index.css) so it stays crisp at any size.
+// `on`/`off` default to solid black on white — turnstile scanners want maximum contrast, not
+// the app's theme colours, and a themed (e.g. lime-on-black) code fails to read on many
+// readers. Returns the module count (QR size) so the caller can react if it wants.
+export async function renderQrToCanvas(canvas, value, { on = '#000000', off = '#ffffff' } = {}) {
+ if (!canvas || !value) return 0
+ const { generate, correction } = await loadLeanQr()
+ // Medium error correction: a good default that survives a scratched or partly-obscured phone
+ // screen without inflating the code so much it gets dense on small screens.
+ const code = generate(value, { minCorrectionLevel: correction.M })
+ code.toCanvas(canvas, {
+ on: hexToRgba(on),
+ off: hexToRgba(off),
+ padX: 2,
+ padY: 2,
+ })
+ return code.size
+}
+
+// lean-qr wants colours as [r,g,b,a]. Accept a #rrggbb (or #rgb) string; anything else is
+// treated as opaque black/white by the caller's defaults, so this only has to handle hex.
+function hexToRgba(hex) {
+ let h = String(hex).replace('#', '')
+ if (h.length === 3) h = h.split('').map(c => c + c).join('')
+ const n = parseInt(h, 16)
+ return [(n >> 16) & 255, (n >> 8) & 255, n & 255, 255]
+}
diff --git a/frontend/src/lib/scan.js b/frontend/src/lib/scan.js
new file mode 100644
index 000000000..f7bb9f8a7
--- /dev/null
+++ b/frontend/src/lib/scan.js
@@ -0,0 +1,109 @@
+// Capturing a gym check-in code (mobile-only — see views/CheckIn.jsx). Three ways in:
+// 1. type it — no plugin, handled entirely in the view
+// 2. import a photo — importCodeFromImage(file): decode a picture the user already has
+// 3. scan with camera — scanCode(): live camera via ML Kit's own scanner UI
+//
+// Both plugin paths dynamic-import @capacitor-mlkit/barcode-scanning (Apache-2.0, see NOTICE.md)
+// so it never lands in the web bundle — the whole feature is behind MOBILE, and every entry point
+// here throws a plain Error off mobile rather than importing a native module that isn't there.
+//
+// What comes back is a normalized { value, fmt } (or null when the user cancels / nothing was
+// found). `value` is the code's machine-readable content; `fmt` is a lower-cased symbology token
+// matching lib/qr.js's normalizeFmt. The caller checks canRenderFmt(fmt) before saving — we can
+// read many barcode kinds but only redraw QR, so a non-QR code is reported and refused there, not
+// silently stored.
+import { MOBILE } from './mobile.js'
+import { normalizeFmt } from './qr.js'
+
+// A found barcode from either path → our stored shape. mlkit gives rawValue (machine-readable,
+// what a turnstile actually reads) and a BarcodeFormat; we keep rawValue and fold the format.
+function toCode(barcode) {
+ if (!barcode) return null
+ const value = barcode.rawValue || barcode.displayValue || ''
+ if (!value) return null
+ return { value, fmt: normalizeFmt(barcode.format) }
+}
+
+// Live camera scan. On Android this opens Google's own full-screen scanner UI (no camera view we
+// have to host); on iOS the plugin's native scanner. Returns the first barcode found, or null if
+// the user backed out without scanning. Throws if scanning isn't supported or permission is hard-
+// denied so the caller can explain why.
+export async function scanCode() {
+ if (!MOBILE) throw new Error('Scanning is only available in the app')
+ const { BarcodeScanner } = await import('@capacitor-mlkit/barcode-scanning')
+
+ const { supported } = await BarcodeScanner.isSupported()
+ if (!supported) throw new Error('unsupported')
+
+ await ensureCameraPermission(BarcodeScanner)
+ await ensureScannerModule(BarcodeScanner)
+
+ const { barcodes } = await BarcodeScanner.scan()
+ return barcodes && barcodes.length ? toCode(barcodes[0]) : null
+}
+
+// Decode a barcode out of an image the user picked. mlkit's readBarcodesFromImage wants a local
+// file PATH, and a browser <input type=file> only hands us a File/blob — so we bounce the bytes
+// through the app's cache dir (reusing @capacitor/filesystem, already a dependency) to get a real
+// path, decode, then delete the temp file. Returns the first barcode, or null if none was found.
+export async function importCodeFromImage(file) {
+ if (!MOBILE) throw new Error('Importing is only available in the app')
+ if (!file) return null
+ const { BarcodeScanner } = await import('@capacitor-mlkit/barcode-scanning')
+ const { Filesystem, Directory } = await import('@capacitor/filesystem')
+
+ const base64 = await fileToBase64(file)
+ const name = `checkin-import-${Date.now()}.${extOf(file.name)}`
+ let uri = null
+ try {
+ const w = await Filesystem.writeFile({ path: name, directory: Directory.Cache, data: base64 })
+ uri = w.uri
+ const { barcodes } = await BarcodeScanner.readBarcodesFromImage({ path: uri })
+ return barcodes && barcodes.length ? toCode(barcodes[0]) : null
+ } finally {
+ // Best effort — a leftover temp image in the cache dir is harmless, but tidy up anyway.
+ try { await Filesystem.deleteFile({ path: name, directory: Directory.Cache }) } catch (e) { /* */ }
+ }
+}
+
+// Camera permission for the live scanner. checkPermissions first so an already-granted user never
+// sees a prompt; request only when needed. A hard denial throws so the caller can point the user
+// at Settings rather than silently doing nothing.
+async function ensureCameraPermission(BarcodeScanner) {
+ let { camera } = await BarcodeScanner.checkPermissions()
+ if (camera !== 'granted' && camera !== 'limited') {
+ ({ camera } = await BarcodeScanner.requestPermissions())
+ }
+ if (camera !== 'granted' && camera !== 'limited') throw new Error('permission-denied')
+}
+
+// On Android the ML Kit scanner ships as an on-demand Google Play module, absent on first use.
+// Install it (once) before scanning; a no-op / not-applicable on iOS, where the check simply
+// reports available. Failures here are non-fatal — scan() will surface a clearer error if it
+// truly can't proceed.
+async function ensureScannerModule(BarcodeScanner) {
+ try {
+ if (!BarcodeScanner.isGoogleBarcodeScannerModuleAvailable) return
+ const { available } = await BarcodeScanner.isGoogleBarcodeScannerModuleAvailable()
+ if (!available) await BarcodeScanner.installGoogleBarcodeScannerModule()
+ } catch (e) { /* let scan() decide whether it can still run */ }
+}
+
+// A File/Blob → bare base64 (no data: prefix), which Filesystem.writeFile expects.
+function fileToBase64(file) {
+ return new Promise((resolve, reject) => {
+ const r = new FileReader()
+ r.onerror = () => reject(r.error || new Error('read failed'))
+ r.onload = () => {
+ const s = String(r.result || '')
+ const comma = s.indexOf(',')
+ resolve(comma === -1 ? s : s.slice(comma + 1))
+ }
+ r.readAsDataURL(file)
+ })
+}
+
+function extOf(filename) {
+ const m = /\.([a-z0-9]+)$/i.exec(filename || '')
+ return m ? m[1].toLowerCase() : 'jpg'
+}
diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js
index 116779290..ec7dbfd84 100644
--- a/frontend/src/locales/es.js
+++ b/frontend/src/locales/es.js
@@ -743,4 +743,29 @@ export default {
'Set to 0 to go back to the default ({0}).': 'Pon 0 para volver al valor por defecto ({0}).',
'Applies to this exercise everywhere, not just this plan.': 'Se aplica a este ejercicio en todas partes, no solo en este plan.',
'You still log the total weight — the bar only feeds the per-side plate math.': 'Sigues registrando el peso total — la barra solo se usa para calcular los discos por lado.',
+ // Gym check-in (mobile-only)
+ 'Check in': 'Registrarse',
+ 'At the gym': 'En el gimnasio',
+ 'Show this at the gym': 'Muestra esto en el gimnasio',
+ 'Add your gym card': 'Añade tu tarjeta del gimnasio',
+ 'Add a card': 'Añadir una tarjeta',
+ 'Type the number on your membership card, import a photo of it, or scan it with the camera. No extra app needed at the gym — just open this screen.': 'Escribe el número de tu tarjeta de socio, importa una foto o escanéala con la cámara. No hace falta otra app en el gimnasio — solo abre esta pantalla.',
+ 'Remove this card?': '¿Eliminar esta tarjeta?',
+ 'Scan it, import a photo, or type the code by hand.': 'Escanéala, importa una foto o escribe el código a mano.',
+ 'Scan': 'Escanear',
+ 'Import photo': 'Importar foto',
+ 'Label': 'Etiqueta',
+ 'e.g. FitZone downtown': 'p. ej. FitZone centro',
+ 'Code': 'Código',
+ 'Membership number or code': 'Número de socio o código',
+ 'Save card': 'Guardar tarjeta',
+ 'Gym card': 'Tarjeta del gimnasio',
+ 'Card added': 'Tarjeta añadida',
+ 'Nothing to save yet': 'Nada que guardar todavía',
+ "That's not a QR code — only QR cards can be shown here": 'Eso no es un código QR — aquí solo se pueden mostrar tarjetas QR',
+ 'No QR code found in that image': 'No se encontró ningún código QR en esa imagen',
+ 'Could not read that image': 'No se pudo leer esa imagen',
+ 'Camera permission is needed to scan. Enable it in Settings.': 'Se necesita permiso de cámara para escanear. Actívalo en Ajustes.',
+ 'Scanning is not available on this device.': 'El escaneo no está disponible en este dispositivo.',
+ 'Could not start the scanner': 'No se pudo iniciar el escáner',
}
diff --git a/frontend/src/store/useStore.js b/frontend/src/store/useStore.js
index c86f7a83d..2476cb7b2 100644
--- a/frontend/src/store/useStore.js
+++ b/frontend/src/store/useStore.js
@@ -29,6 +29,14 @@ export const DEF = {
// lib/bar.js). Personal equipment, so it syncs with the account but never travels in a
// shared plan. Logged weights stay the total — this only feeds the plate math.
barWeights: {},
+ // Gym check-in cards (mobile-only feature, see views/CheckIn.jsx). Each is a membership
+ // code shown as a QR/barcode at the gym's turnstile — added by typing it, importing a photo
+ // of the card, or scanning it. We only ever keep the code's VALUE, never a photo: the image
+ // is regenerated from `value` every time it's shown (lib/qr.js). `fmt` is the barcode symbology
+ // ('qrcode' | 'ean13' | 'code128' | … — lower-cased BarcodeFormat) so it renders as the same
+ // kind of code the gym issued. Just data, so it syncs and backs up like everything else.
+ // [{ id, label, value, fmt }]
+ gymCards: [],
}
const clone = o => JSON.parse(JSON.stringify(o))
diff --git a/frontend/src/views/CheckIn.jsx b/frontend/src/views/CheckIn.jsx
new file mode 100644
index 000000000..6083f83e1
--- /dev/null
+++ b/frontend/src/views/CheckIn.jsx
@@ -0,0 +1,176 @@
+import { useEffect, useRef, useState } from 'react'
+import { useNavigate } from 'react-router-dom'
+import { useStore } from '../store/useStore.js'
+import { useUI } from '../store/useUI.js'
+import { uid } from '../lib/format.js'
+import { t } from '../lib/i18n.js'
+import { canRenderFmt } from '../lib/qr.js'
+import { scanCode, importCodeFromImage } from '../lib/scan.js'
+import Icon from '../components/Icon.jsx'
+import QrCanvas from '../components/QrCanvas.jsx'
+import { Button, TextField } from '../components/ui.jsx'
+import { confirmSheet } from '../sheets.jsx'
+import { tappable } from '../lib/use-sheet-keyboard.js'
+
+// Gym check-in (mobile-only, reached from the Home "Check in" card). Shows each saved membership
+// code as a QR the turnstile can read, swiped through horizontally, with a trailing "+" to add
+// another. We only ever store the code's value + symbology; the QR is regenerated from it here
+// every time (see lib/qr.js), so nothing sensitive is kept as an image.
+export default function CheckIn() {
+ const nav = useNavigate()
+ const cards = useStore(s => s.S.gymCards) || []
+ const railRef = useRef(null)
+ const [active, setActive] = useState(0)
+
+ // Which card the horizontal scroll has settled on — drives the little dots. Reading it off the
+ // scroll position keeps the rail itself the single control; no separate paging state to sync.
+ const onScroll = () => {
+ const rail = railRef.current
+ if (!rail) return
+ const i = Math.round(rail.scrollLeft / rail.clientWidth)
+ setActive(i)
+ }
+
+ return <div className="narrow">
+ <div className="hdr">
+ <button className="iconbtn" onClick={() => nav('/home')} aria-label={t('Home')}><Icon name="chevronLeft" /></button>
+ <div style={{ flex: 1 }}>
+ <h1 style={{ fontSize: 28 }}>{t('Check in')}</h1>
+ <div className="sub">{cards.length ? t('Show this at the gym') : t('Add your gym card')}</div>
+ </div>
+ </div>
+
+ <div className="ci-rail" ref={railRef} onScroll={onScroll}>
+ {cards.map(card => <CardFace key={card.id} card={card} />)}
+ <button className="ci-add" onClick={openAddCard}>
+ <Icon name="plus" />
+ <span className="ci-add-t">{t('Add a card')}</span>
+ </button>
+ </div>
+
+ {(cards.length > 0) && <div className="ci-dots">
+ {cards.map((c, i) => <span key={c.id} className={'ci-dot' + (i === active ? ' on' : '')} />)}
+ {/* the add card is a slide too, so it gets a dot */}
+ <span className={'ci-dot' + (active >= cards.length ? ' on' : '')} />
+ </div>}
+
+ {!cards.length && <div className="muted small" style={{ textAlign: 'center', marginTop: 18, lineHeight: 1.5 }}>
+ {t('Type the number on your membership card, import a photo of it, or scan it with the camera. No extra app needed at the gym — just open this screen.')}
+ </div>}
+ </div>
+}
+
+// One saved card: its label, the QR, and the raw value underneath (handy when a reader is fussy
+// and a staff member types it in). Long-press / the trash button removes it.
+function CardFace({ card }) {
+ const update = useStore(s => s.update)
+ const remove = () => confirmSheet({
+ title: t('Remove this card?'),
+ message: card.label,
+ confirmText: t('Remove'),
+ danger: true,
+ onConfirm: () => update(s => { s.gymCards = (s.gymCards || []).filter(c => c.id !== card.id) }),
+ })
+ return <div className="ci-card">
+ <div className="row between" style={{ width: '100%', alignItems: 'flex-start' }}>
+ <div className="ci-label" style={{ flex: 1 }}>{card.label}</div>
+ <button className="iconbtn" style={{ width: 30, height: 30, fontSize: 14, color: 'var(--red)' }} onClick={remove} aria-label={t('Remove')}><Icon name="trash" /></button>
+ </div>
+ <div className="ci-qr-plate"><QrCanvas value={card.value} size={230} /></div>
+ <div className="ci-value">{card.value}</div>
+ </div>
+}
+
+/* ------------------------------------------------------------- add-card sheet -- */
+
+// Opens the add-card sheet. Co-located with the view (not sheets.jsx) because the whole feature
+// is mobile-only and pulls in the native scanner — keeping it here keeps that out of the shared,
+// web-bundled sheets module.
+export function openAddCard() {
+ useUI.getState().openSheet(close => <AddCard close={close} />)
+}
+
+function saveCard({ label, value, fmt }) {
+ const update = useStore.getState().update
+ const toast = useUI.getState().toast
+ const trimmed = (value || '').trim()
+ if (!trimmed) { toast(t('Nothing to save yet')); return false }
+ // We can read many barcode kinds but only redraw QR faithfully — refuse anything else rather
+ // than store a code that would display as the wrong bars at the turnstile.
+ if (fmt && !canRenderFmt(fmt)) { toast(t("That's not a QR code — only QR cards can be shown here")); return false }
+ update(s => {
+ if (!Array.isArray(s.gymCards)) s.gymCards = []
+ s.gymCards.push({ id: uid(), label: (label || '').trim() || t('Gym card'), value: trimmed, fmt: 'qrcode' })
+ })
+ toast(t('Card added'))
+ return true
+}
+
+function AddCard({ close }) {
+ const [label, setLabel] = useState('')
+ const [value, setValue] = useState('')
+ const [busy, setBusy] = useState(false)
+ const fileRef = useRef(null)
+ const toast = useUI(s => s.toast)
+
+ const commitTyped = () => { if (saveCard({ label, value, fmt: 'qrcode' })) close() }
+
+ // Camera scan: hands off to the native scanner, comes back with a value we drop straight into
+ // the form so the user can still name it before saving.
+ const doScan = async () => {
+ setBusy(true)
+ try {
+ const code = await scanCode()
+ if (!code) return // user backed out
+ if (!canRenderFmt(code.fmt)) { toast(t("That's not a QR code — only QR cards can be shown here")); return }
+ setValue(code.value)
+ } catch (e) {
+ toast(scanErrorMessage(e))
+ } finally { setBusy(false) }
+ }
+
+ const onFile = async ev => {
+ const file = ev.target.files && ev.target.files[0]
+ ev.target.value = '' // let the same file be picked again later
+ if (!file) return
+ setBusy(true)
+ try {
+ const code = await importCodeFromImage(file)
+ if (!code) { toast(t('No QR code found in that image')); return }
+ if (!canRenderFmt(code.fmt)) { toast(t("That's not a QR code — only QR cards can be shown here")); return }
+ setValue(code.value)
+ } catch (e) {
+ toast(t('Could not read that image'))
+ } finally { setBusy(false) }
+ }
+
+ return <>
+ <h3>{t('Add a card')}</h3>
+ <div className="muted small" style={{ marginBottom: 14 }}>{t('Scan it, import a photo, or type the code by hand.')}</div>
+
+ <div className="row" style={{ gap: 8, marginBottom: 16 }}>
+ <Button variant="tinted" icon="camera" onClick={doScan} disabled={busy}>{t('Scan')}</Button>
+ <Button variant="tinted" icon="image" onClick={() => fileRef.current?.click()} disabled={busy}>{t('Import photo')}</Button>
+ </div>
+
+ <label className="sect-t">{t('Label')}</label>
+ <TextField value={label} onChange={e => setLabel(e.target.value)} placeholder={t('e.g. FitZone downtown')} style={{ marginBottom: 12 }} />
+
+ <label className="sect-t">{t('Code')}</label>
+ <TextField value={value} onChange={e => setValue(e.target.value)} placeholder={t('Membership number or code')} inputMode="text" style={{ marginBottom: 16 }} />
+
+ {value.trim() && <div className="ci-qr-plate" style={{ alignSelf: 'center', marginBottom: 16 }}><QrCanvas value={value.trim()} size={150} /></div>}
+
+ <Button variant="primary" onClick={commitTyped} disabled={busy || !value.trim()}>{t('Save card')}</Button>
+
+ <input ref={fileRef} type="file" accept="image/*" hidden onChange={onFile} />
+ </>
+}
+
+// Map the thrown reasons from lib/scan.js to something a person can act on.
+function scanErrorMessage(e) {
+ const m = String(e && e.message)
+ if (m === 'permission-denied') return t('Camera permission is needed to scan. Enable it in Settings.')
+ if (m === 'unsupported') return t('Scanning is not available on this device.')
+ return t('Could not start the scanner')
+}
diff --git a/frontend/src/views/Home.jsx b/frontend/src/views/Home.jsx
index 158a45960..c597218f2 100644
--- a/frontend/src/views/Home.jsx
+++ b/frontend/src/views/Home.jsx
@@ -10,6 +10,7 @@ import Icon from '../components/Icon.jsx'
import { Button } from '../components/ui.jsx'
import { tappable } from '../lib/use-sheet-keyboard.js'
import { glyphOf } from '../lib/glyphs.js'
+import { MOBILE } from '../lib/mobile.js'
// Home = what to do now + a quick glance. Deep charts & history live in Stats.
export default function Home() {
@@ -94,6 +95,23 @@ export default function Home() {
</div>
</div>
+ {/* Mobile-only: jump to the gym check-in cards (QR membership codes). Shown here as a quick
+ tap on arrival at the gym; the whole feature folds away in web/demo builds via MOBILE. */}
+ {MOBILE && (
+ <div className="card tappable" style={{ cursor: 'pointer' }} {...tappable(() => nav('/checkin'))}>
+ <div className="row between">
+ <div className="row" style={{ gap: 9 }}>
+ <span className="lrow-i" style={{ background: 'var(--blue)' }}><Icon name="qr" /></span>
+ <div>
+ <div className="lbl2">{t('At the gym')}</div>
+ <div className="ttl">{t('Check in')}</div>
+ </div>
+ </div>
+ <Icon name="chevronRight" className="chev" />
+ </div>
+ </div>
+ )}
+
{!S.routines.length && !S.active && (
<div className="card">
<div className="row" style={{ gap: 10, marginBottom: 6 }}>