Gym check-in in the browser/PWA too

The feature was gated behind MOBILE because scanning went through the native ML Kit
plugin. iPhone users only have the PWA, so: route, Home card and Settings switch on
every platform; photo import and a live camera sheet decode in the browser with
BarcodeDetector where it exists and jsQR (Apache-2.0, lazy chunk) otherwise. The app
build keeps ML Kit. Round-trip test lean-qr -> jsQR.
This commit is contained in:
Duarte Santos committed 2026-09-04 15:15:31 +02:00
1 parent 0af9f55528
commit aa487d29f4
30 files changed
+315 -47

No files matched your search

+3 -5
View File
@@ -5,7 +5,6 @@ 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'
@@ -115,10 +114,9 @@ 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 (or switched off in
Settings) the route falls through to the catch-all redirect below. */}
{MOBILE && S.checkIn !== false && <Route path="/checkin" element={<CheckIn />} />}
{/* Gym check-in — switched off in Settings, the route falls through to the
catch-all redirect below. */}
{S.checkIn !== false && <Route path="/checkin" element={<CheckIn />} />}
<Route path="/plan" element={<Plan />} />
<Route path="/plan/r/:id" element={<RoutineEdit />} />
<Route path="/workout" element={<Workout />} />
+69
View File
@@ -0,0 +1,69 @@
import { useEffect, useRef, useState } from 'react'
import { t } from '../lib/i18n.js'
import { decodeSource } from '../lib/scan-web.js'
import { Button } from '../components/ui.jsx'
// Live camera scanner for the browser/PWA (the app build uses ML Kit's own UI instead — see
// lib/scan.js). Opens the rear camera into a <video>, decodes a frame every ~150 ms until a QR
// shows up, then hands { value, fmt } to onFound. Cancel (or unmount) stops the camera.
//
// Errors are shown in place rather than thrown: a denied permission or a browser without
// getUserMedia leaves the sheet up with a message, and the add-card form underneath still offers
// photo import and typing.
export default function CameraScan({ onFound, onCancel }) {
const videoRef = useRef(null)
const [error, setError] = useState(null)
useEffect(() => {
let stream = null, timer = null, done = false
const stop = () => {
done = true
if (timer) clearTimeout(timer)
if (stream) stream.getTracks().forEach(tr => tr.stop())
}
;(async () => {
if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) { setError('unavailable'); return }
try {
stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: { ideal: 'environment' } }, audio: false })
} catch (e) {
setError(e && (e.name === 'NotAllowedError' || e.name === 'SecurityError') ? 'denied' : 'unavailable')
return
}
if (done) { stream.getTracks().forEach(tr => tr.stop()); return }
const v = videoRef.current
if (!v) return
v.srcObject = stream
try { await v.play() } catch (e) { /* autoplay policies; the loop below waits for frames */ }
const tick = async () => {
if (done) return
if (v.readyState >= 2) {
let code = null
try { code = await decodeSource(v) } catch (e) { /* keep trying */ }
if (code && !done) { stop(); onFound(code); return }
}
timer = setTimeout(tick, 150)
}
tick()
})()
return stop
}, [onFound])
return <>
<h3>{t('Scan')}</h3>
{error
? <div className="muted small" style={{ marginBottom: 16, lineHeight: 1.5 }}>
{error === 'denied'
? t('Camera access was denied — allow it in your browser and try again.')
: t('Camera is not available here — import a photo or type the code instead.')}
</div>
: <>
<div className="cam-wrap">
{/* playsInline keeps iOS from going full-screen; muted satisfies autoplay rules. */}
<video ref={videoRef} playsInline muted autoPlay />
<div className="cam-frame" aria-hidden="true" />
</div>
<div className="muted small" style={{ textAlign: 'center', margin: '12px 0 16px' }}>{t('Point the camera at the QR code')}</div>
</>}
<Button variant="tinted" onClick={onCancel}>{t('Cancel')}</Button>
</>
}
+5
View File
@@ -1093,6 +1093,11 @@ h4.sec{
.ci-dots{display:flex;justify-content:center;gap:7px;margin-top:4px}
.ci-dot{width:7px;height:7px;border-radius:50%;background:var(--surface-3);transition:background var(--fast),transform var(--fast)}
.ci-dot.on{background:var(--acc);transform:scale(1.15)}
/* browser camera sheet (components/CameraScan.jsx): the video fills a portrait plate, a dashed
square in the middle says "put the code here" — decoding reads the whole frame regardless. */
.cam-wrap{position:relative;width:100%;aspect-ratio:3/4;max-height:58vh;border-radius:var(--r-lg);overflow:hidden;background:#000}
.cam-wrap video{width:100%;height:100%;object-fit:cover;display:block}
.cam-frame{position:absolute;inset:0;margin:auto;width:62%;aspect-ratio:1;border:2px dashed rgba(255,255,255,.75);border-radius:14px;pointer-events:none}
/* ------------------------------------------------- the Coach entry on Plan -- */
.coach-cta{
display:flex;align-items:center;gap:13px;width:100%;text-align:left;
+1 -1
View File
@@ -27,7 +27,7 @@ describe('Brazilian Portuguese locale', () => {
.sort(byCodeUnit)
const fingerprint = createHash('sha256').update(JSON.stringify(inherited)).digest('hex')
expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(600)
expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(603)
expect(inherited).toHaveLength(565)
// If this fails, review the changed keys and wording before accepting a new hash. From
// frontend/: node scripts/pt-br-inheritance-fingerprint.mjs --list
+3 -4
View File
@@ -1,12 +1,11 @@
// QR rendering for the gym check-in cards (mobile-only feature — see views/CheckIn.jsx).
// QR rendering for the gym check-in cards (see views/CheckIn.jsx).
//
// We never store a photo of a membership card, only its decoded value (+ its symbology in
// `fmt`). The picture a turnstile scanner reads is regenerated from that value every time the
// card is shown, here.
//
// lean-qr (MIT, see NOTICE.md) is loaded with a dynamic import so its ~4kB 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.
// lean-qr (MIT, see NOTICE.md) is loaded with a dynamic import so its ~4kB only loads when a
// card is actually shown, on every platform — the PWA renders the same code as the app.
//
// Scope: lean-qr generates QR codes only. A gym card is virtually always a QR code, and the
// capture flow (lib/scan.js) refuses any symbology we cannot faithfully reproduce, so a stored
+83
View File
@@ -0,0 +1,83 @@
// Browser-side QR decoding for the gym check-in — the PWA half of lib/scan.js. The app build
// hands scanning to ML Kit; here in a browser tab (installed PWA on a phone, most often) we do
// it ourselves: draw the source — an uploaded photo or a live <video> frame — onto an offscreen
// canvas and decode the pixels.
//
// Two decoders, tried in order:
// 1. BarcodeDetector — the browser's own (Chrome/Edge on Android, Samsung Internet). Native
// speed and quality when it exists; asked for QR only.
// 2. jsQR (Apache-2.0, see NOTICE.md) — pure JS, works everywhere including iOS Safari, which
// has no BarcodeDetector. Loaded with a dynamic import so it only ships when someone scans.
//
// decodeImageData is the pure core (pixels in, string out) and is what the unit test exercises;
// decodeSource wraps it with the canvas plumbing the browser paths need.
import { normalizeFmt } from './qr.js'
let _jsqr = null
async function loadJsQr() {
if (!_jsqr) _jsqr = (await import('jsqr')).default
return _jsqr
}
let _detector = null
function nativeDetector() {
if (_detector !== null) return _detector
try {
_detector = (typeof BarcodeDetector === 'function') ? new BarcodeDetector({ formats: ['qr_code'] }) : false
} catch (e) { _detector = false }
return _detector
}
// { data, width, height } (an ImageData or anything shaped like one) → { value, fmt } | null.
// jsQR only; the native detector wants a drawable, not raw pixels, so it lives in decodeSource.
export async function decodeImageData(img) {
if (!img || !img.data || !img.width || !img.height) return null
const jsQR = await loadJsQr()
const hit = jsQR(img.data, img.width, img.height, { inversionAttempts: 'attemptBoth' })
return hit && hit.data ? { value: hit.data, fmt: 'qrcode' } : null
}
// Decode from anything drawImage accepts: <video>, <img>, ImageBitmap, canvas. The source is
// scaled down to at most MAX px on its long edge — plenty for a QR, and it keeps jsQR fast enough
// to run on every few video frames on a phone. Reuses one canvas across calls.
const MAX = 800
let _canvas = null
export async function decodeSource(source) {
const sw = source.videoWidth || source.naturalWidth || source.width || 0
const sh = source.videoHeight || source.naturalHeight || source.height || 0
if (!sw || !sh) return null
const k = Math.min(1, MAX / Math.max(sw, sh))
const w = Math.max(1, Math.round(sw * k)), h = Math.max(1, Math.round(sh * k))
if (!_canvas) _canvas = document.createElement('canvas')
_canvas.width = w; _canvas.height = h
const ctx = _canvas.getContext('2d', { willReadFrequently: true })
ctx.drawImage(source, 0, 0, w, h)
const det = nativeDetector()
if (det) {
try {
const found = await det.detect(_canvas)
const b = found && found.find(x => x.rawValue)
if (b) return { value: b.rawValue, fmt: normalizeFmt(b.format) || 'qrcode' }
} catch (e) { /* fall through to jsQR */ }
}
return decodeImageData(ctx.getImageData(0, 0, w, h))
}
// A picked File → { value, fmt } | null. createImageBitmap honours EXIF orientation where the
// browser supports it, which matters for photos of a card taken in portrait.
export async function importCodeFromImageWeb(file) {
if (!file) return null
let bmp
if (typeof createImageBitmap === 'function') {
bmp = await createImageBitmap(file)
} else {
bmp = await new Promise((resolve, reject) => {
const img = new Image()
img.onload = () => resolve(img)
img.onerror = () => reject(new Error('bad image'))
img.src = URL.createObjectURL(file)
})
}
try { return await decodeSource(bmp) } finally { if (bmp.close) bmp.close() }
}
+44
View File
@@ -0,0 +1,44 @@
import { describe, it, expect } from 'vitest'
import { generate } from 'lean-qr'
import { decodeImageData } from './scan-web.js'
// Round trip through the two libraries the browser path relies on: lean-qr draws a code (the
// same renderer the card view uses), jsQR reads it back. Pixels are built by hand from
// code.get(x, y) — no canvas in this environment — scaled 4× with a 4-module quiet zone, which
// is what a phone camera would roughly see.
function rasterize(code, scale = 4, quiet = 4) {
const n = code.size + quiet * 2
const w = n * scale
const data = new Uint8ClampedArray(w * w * 4)
for (let y = 0; y < w; y++) {
for (let x = 0; x < w; x++) {
const mx = Math.floor(x / scale) - quiet, my = Math.floor(y / scale) - quiet
const dark = mx >= 0 && my >= 0 && mx < code.size && my < code.size && code.get(mx, my)
const v = dark ? 0 : 255
const i = (y * w + x) * 4
data[i] = v; data[i + 1] = v; data[i + 2] = v; data[i + 3] = 255
}
}
return { data, width: w, height: w }
}
describe('decodeImageData', () => {
it('reads back a code lean-qr generated', async () => {
const value = 'MEMBER-0042-FITZONE'
const hit = await decodeImageData(rasterize(generate(value)))
expect(hit).toEqual({ value, fmt: 'qrcode' })
})
it('reads a URL-shaped code, the other common gym format', async () => {
const value = 'https://checkin.example.com/m/8f3a1c?v=2'
const hit = await decodeImageData(rasterize(generate(value)))
expect(hit?.value).toBe(value)
})
it('returns null for blank pixels and for junk input', async () => {
const blank = { data: new Uint8ClampedArray(64 * 64 * 4).fill(255), width: 64, height: 64 }
expect(await decodeImageData(blank)).toBeNull()
expect(await decodeImageData(null)).toBeNull()
expect(await decodeImageData({ data: null, width: 1, height: 1 })).toBeNull()
})
})
+9 -6
View File
@@ -1,11 +1,14 @@
// Capturing a gym check-in code (mobile-only — see views/CheckIn.jsx). Three ways in:
// Capturing a gym check-in code (see views/CheckIn.jsx). Three ways in:
// 1. type it — no plugin, handled entirely in the view
// 2. import a photo — importCodeFromImage(file): decode a picture the user already has
// 3. scan with camera — scanCode(): live camera via ML Kit's own scanner UI
// 3. scan with camera — scanCode(): live camera via ML Kit's own scanner UI (app build);
// in a browser the view opens components/CameraScan.jsx instead
//
// 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.
// The app build (MOBILE) decodes with @capacitor-mlkit/barcode-scanning (Apache-2.0, see
// NOTICE.md), dynamic-imported so it never lands in the web bundle. In a browser — the PWA on a
// phone is the common case — photo import goes through lib/scan-web.js (BarcodeDetector where the
// browser has one, jsQR otherwise). scanCode() itself is app-only: ML Kit brings its own camera
// UI, the browser path is a React sheet and lives with the view.
//
// What comes back is a normalized { value, fmt } (or null when the user cancels / nothing was
// found). `value` is the code's machine-readable content; `fmt` is a lower-cased symbology token
@@ -47,8 +50,8 @@ export async function scanCode() {
// 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
if (!MOBILE) return (await import('./scan-web.js')).importCodeFromImageWeb(file)
const { BarcodeScanner } = await import('@capacitor-mlkit/barcode-scanning')
const { Filesystem, Directory } = await import('@capacitor/filesystem')
+7 -8
View File
@@ -2,17 +2,16 @@ import { describe, it, expect } from 'vitest'
import { scanCode, importCodeFromImage } from './scan.js'
// In the test environment VITE_MOBILE is unset, so MOBILE is false — the same as a web build.
// Both capture paths must refuse to run there rather than reach for a native plugin that isn't
// present. (The happy-path decoding is exercised on-device; here we pin the guard that keeps the
// scanner out of every non-mobile build.)
// The native ML Kit scanner must refuse to run there rather than reach for a plugin that isn't
// present; the view opens the browser camera sheet instead. (On-device decoding is exercised by
// hand; the browser decoder has its own round-trip test in scan-web.test.js.)
describe('scan guards off mobile', () => {
it('scanCode rejects when not in the mobile build', async () => {
describe('scan off mobile', () => {
it('scanCode rejects — the native scanner is app-only', async () => {
await expect(scanCode()).rejects.toThrow(/only available in the app/)
})
it('importCodeFromImage rejects when not in the mobile build', async () => {
const fakeFile = new Blob(['x'], { type: 'image/png' })
await expect(importCodeFromImage(fakeFile)).rejects.toThrow(/only available in the app/)
it('importCodeFromImage takes the browser path and is a no-op without a file', async () => {
expect(await importCodeFromImage(null)).toBeNull()
})
})
+3
View File
@@ -1126,4 +1126,7 @@ export default {
'Could not start the scanner': 'Scanner konnte nicht gestartet werden',
'Gym check-in': 'Gym-Check-in',
'Show a card on Home with your membership QR codes.': 'Zeigt auf Start eine Karte mit deinen Mitglieds-QR-Codes.',
'Point the camera at the QR code': 'Richte die Kamera auf den QR-Code',
'Camera is not available here — import a photo or type the code instead.': 'Die Kamera ist hier nicht verfügbar — importiere ein Foto oder tippe den Code ein.',
'Camera access was denied — allow it in your browser and try again.': 'Kamerazugriff wurde verweigert — erlaube ihn im Browser und versuche es erneut.',
}
+3
View File
@@ -1107,4 +1107,7 @@ export default {
'Could not start the scanner': 'No se pudo iniciar el escáner',
'Gym check-in': 'Check-in del gimnasio',
'Show a card on Home with your membership QR codes.': 'Muestra en Inicio una tarjeta con tus códigos QR de socio.',
'Point the camera at the QR code': 'Apunta la cámara al código QR',
'Camera is not available here — import a photo or type the code instead.': 'La cámara no está disponible aquí — importa una foto o escribe el código.',
'Camera access was denied — allow it in your browser and try again.': 'Se denegó el acceso a la cámara — permítelo en el navegador e inténtalo de nuevo.',
}
+3
View File
@@ -1107,4 +1107,7 @@ export default {
'Could not start the scanner': 'Impossible de démarrer le scanner',
'Gym check-in': 'Enregistrement à la salle',
'Show a card on Home with your membership QR codes.': 'Affiche sur l’Accueil une carte avec vos codes QR d’abonné.',
'Point the camera at the QR code': 'Pointez la caméra vers le code QR',
'Camera is not available here — import a photo or type the code instead.': 'La caméra n’est pas disponible ici — importez une photo ou saisissez le code.',
'Camera access was denied — allow it in your browser and try again.': 'L’accès à la caméra a été refusé — autorisez-le dans le navigateur et réessayez.',
}
+3
View File
@@ -1107,4 +1107,7 @@ export default {
'Could not start the scanner': 'स्कैनर शुरू नहीं हो सका',
'Gym check-in': 'जिम चेक-इन',
'Show a card on Home with your membership QR codes.': 'होम पर आपके सदस्यता QR कोड वाला कार्ड दिखाता है।',
'Point the camera at the QR code': 'कैमरे को QR कोड पर रखें',
'Camera is not available here — import a photo or type the code instead.': 'कैमरा यहाँ उपलब्ध नहीं है — फ़ोटो इंपोर्ट करें या कोड टाइप करें।',
'Camera access was denied — allow it in your browser and try again.': 'कैमरे की अनुमति नहीं मिली — ब्राउज़र में अनुमति दें और फिर कोशिश करें।',
}
+3
View File
@@ -1110,4 +1110,7 @@ export default {
'Message the Coach…': 'Üzenet az Edzőnek…',
'Gym check-in': 'Bejelentkezés a teremben',
'Show a card on Home with your membership QR codes.': 'A Kezdőlapon egy kártyát mutat a tagsági QR-kódjaiddal.',
'Point the camera at the QR code': 'Irányítsd a kamerát a QR-kódra',
'Camera is not available here — import a photo or type the code instead.': 'A kamera itt nem elérhető — importálj egy fotót vagy írd be a kódot.',
'Camera access was denied — allow it in your browser and try again.': 'A kamera-hozzáférés elutasítva — engedélyezd a böngészőben, és próbáld újra.',
}
+3
View File
@@ -1107,4 +1107,7 @@ export default {
'Could not start the scanner': 'Impossibile avviare lo scanner',
'Gym check-in': 'Check-in in palestra',
'Show a card on Home with your membership QR codes.': 'Mostra nella Home una scheda con i tuoi codici QR di iscrizione.',
'Point the camera at the QR code': 'Inquadra il codice QR con la fotocamera',
'Camera is not available here — import a photo or type the code instead.': 'La fotocamera non è disponibile qui — importa una foto o digita il codice.',
'Camera access was denied — allow it in your browser and try again.': 'Accesso alla fotocamera negato — consentilo nel browser e riprova.',
}
+3
View File
@@ -1107,4 +1107,7 @@ export default {
'Could not start the scanner': '스캐너를 시작할 수 없습니다',
'Gym check-in': '헬스장 체크인',
'Show a card on Home with your membership QR codes.': '홈 화면에 회원 QR 코드 카드를 표시합니다.',
'Point the camera at the QR code': '카메라를 QR 코드에 맞추세요',
'Camera is not available here — import a photo or type the code instead.': '여기서는 카메라를 사용할 수 없습니다 — 사진을 가져오거나 코드를 입력하세요.',
'Camera access was denied — allow it in your browser and try again.': '카메라 접근이 거부되었습니다 — 브라우저에서 허용한 뒤 다시 시도하세요.',
}
+3
View File
@@ -1107,4 +1107,7 @@ export default {
'Could not start the scanner': 'Nie udało się uruchomić skanera',
'Gym check-in': 'Zameldowanie na siłowni',
'Show a card on Home with your membership QR codes.': 'Pokazuje na Starcie kartę z Twoimi kodami QR członkowskimi.',
'Point the camera at the QR code': 'Skieruj aparat na kod QR',
'Camera is not available here — import a photo or type the code instead.': 'Aparat nie jest tu dostępny — zaimportuj zdjęcie lub wpisz kod.',
'Camera access was denied — allow it in your browser and try again.': 'Odmówiono dostępu do aparatu — zezwól w przeglądarce i spróbuj ponownie.',
}
+3
View File
@@ -624,6 +624,9 @@ export const PT_BR_OVERRIDES = {
'Could not start the scanner': 'Não foi possível iniciar o scanner',
'Gym check-in': 'Check-in na academia',
'Show a card on Home with your membership QR codes.': 'Mostra no Início um cartão com seus códigos QR de sócio.',
'Point the camera at the QR code': 'Aponte a câmera para o código QR',
'Camera is not available here — import a photo or type the code instead.': 'A câmera não está disponível aqui — importe uma foto ou digite o código.',
'Camera access was denied — allow it in your browser and try again.': 'O acesso à câmera foi negado — permita-o no navegador e tente de novo.',
}
export default { ...pt, ...PT_BR_OVERRIDES }
+3
View File
@@ -1107,4 +1107,7 @@ export default {
'Could not start the scanner': 'Não foi possível iniciar o scanner',
'Gym check-in': 'Check-in no ginásio',
'Show a card on Home with your membership QR codes.': 'Mostra no Início um cartão com os teus códigos QR de sócio.',
'Point the camera at the QR code': 'Aponta a câmara para o código QR',
'Camera is not available here — import a photo or type the code instead.': 'A câmara não está disponível aqui — importa uma foto ou escreve o código.',
'Camera access was denied — allow it in your browser and try again.': 'O acesso à câmara foi recusado — permite-o no navegador e tenta de novo.',
}
+3
View File
@@ -1107,4 +1107,7 @@ export default {
'Could not start the scanner': 'Не удалось запустить сканер',
'Gym check-in': 'Отметка в зале',
'Show a card on Home with your membership QR codes.': 'Показывает на Главной карточку с вашими QR-кодами абонемента.',
'Point the camera at the QR code': 'Наведите камеру на QR-код',
'Camera is not available here — import a photo or type the code instead.': 'Камера здесь недоступна — импортируйте фото или введите код.',
'Camera access was denied — allow it in your browser and try again.': 'Доступ к камере запрещён — разрешите его в браузере и попробуйте снова.',
}
+3
View File
@@ -1118,4 +1118,7 @@ export default {
'Message the Coach…': 'ส่งข้อความถึงโค้ช…',
'Gym check-in': 'เช็คอินที่ยิม',
'Show a card on Home with your membership QR codes.': 'แสดงการ์ดพร้อม QR โค้ดสมาชิกของคุณบนหน้าหลัก',
'Point the camera at the QR code': 'เล็งกล้องไปที่ QR โค้ด',
'Camera is not available here — import a photo or type the code instead.': 'ใช้กล้องที่นี่ไม่ได้ — นำเข้ารูปภาพหรือพิมพ์รหัสแทน',
'Camera access was denied — allow it in your browser and try again.': 'การเข้าถึงกล้องถูกปฏิเสธ — อนุญาตในเบราว์เซอร์แล้วลองอีกครั้ง',
}
+3
View File
@@ -1107,4 +1107,7 @@ export default {
'Could not start the scanner': 'Tarayıcı başlatılamadı',
'Gym check-in': 'Salon girişi',
'Show a card on Home with your membership QR codes.': 'Ana sayfada üyelik QR kodlarınızı içeren bir kart gösterir.',
'Point the camera at the QR code': 'Kamerayı QR koda tutun',
'Camera is not available here — import a photo or type the code instead.': 'Kamera burada kullanılamıyor — bir fotoğraf içe aktarın veya kodu yazın.',
'Camera access was denied — allow it in your browser and try again.': 'Kamera erişimi reddedildi — tarayıcıda izin verip tekrar deneyin.',
}
+3
View File
@@ -1107,4 +1107,7 @@ export default {
'Could not start the scanner': '无法启动扫描器',
'Gym check-in': '健身房签到',
'Show a card on Home with your membership QR codes.': '在首页显示一张包含会员二维码的卡片。',
'Point the camera at the QR code': '将摄像头对准二维码',
'Camera is not available here — import a photo or type the code instead.': '此处无法使用摄像头 — 请导入照片或手动输入代码。',
'Camera access was denied — allow it in your browser and try again.': '摄像头访问被拒绝 — 请在浏览器中允许后重试。',
}
+2 -2
View File
@@ -34,7 +34,7 @@ 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
// Gym check-in cards (see views/CheckIn.jsx). Each is a membership
// code shown as a QR/barcode at the gym's turnstile — added by typing it, importing a photo
// of the card, or scanning it. We only ever keep the code's VALUE, never a photo: the image
// is regenerated from `value` every time it's shown (lib/qr.js). `fmt` is the barcode symbology
@@ -42,7 +42,7 @@ export const DEF = {
// kind of code the gym issued. Just data, so it syncs and backs up like everything else.
// [{ id, label, value, fmt }]
gymCards: [],
// Whether the check-in feature is on at all (Settings toggle, mobile-only). Off hides the Home
// Whether the check-in feature is on at all (Settings toggle). Off hides the Home
// card and the /checkin route; the saved gymCards stay so turning it back on restores them.
// Defaults on; an older profile without the key reads as on (`!== false`).
checkIn: true,
+18 -6
View File
@@ -6,13 +6,15 @@ import { uid } from '../lib/format.js'
import { t } from '../lib/i18n.js'
import { canRenderFmt } from '../lib/qr.js'
import { scanCode, importCodeFromImage } from '../lib/scan.js'
import { MOBILE } from '../lib/mobile.js'
import Icon from '../components/Icon.jsx'
import QrCanvas from '../components/QrCanvas.jsx'
import CameraScan from '../components/CameraScan.jsx'
import { Button, TextField } from '../components/ui.jsx'
import { confirmSheet } from '../sheets.jsx'
import { tappable } from '../lib/use-sheet-keyboard.js'
// Gym check-in (mobile-only, reached from the Home "Check in" card). Shows each saved membership
// Gym check-in (reached from the Home "Check in" card; app and PWA alike). Shows each saved membership
// code as a QR the turnstile can read, swiped through horizontally, with a trailing "+" to add
// another. We only ever store the code's value + symbology; the QR is regenerated from it here
// every time (see lib/qr.js), so nothing sensitive is kept as an image.
@@ -83,9 +85,8 @@ function CardFace({ card }) {
/* ------------------------------------------------------------- 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.
// Opens the add-card sheet. Co-located with the view (not sheets.jsx) because it pulls in the
// scanner paths — keeping it here keeps them out of the shared sheets module.
export function openAddCard() {
useUI.getState().openSheet(close => <AddCard close={close} />)
}
@@ -115,9 +116,20 @@ function AddCard({ close }) {
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.
// Camera scan: in the app, hands off to the native scanner; in a browser, opens our own camera
// sheet on top of this one. Either way the value drops straight into the form so the user can
// still name it before saving.
const doScan = async () => {
if (!MOBILE) {
useUI.getState().openSheet(close => <CameraScan
onCancel={close}
onFound={code => {
close()
if (!canRenderFmt(code.fmt)) { toast(t("That's not a QR code — only QR cards can be shown here")); return }
setValue(code.value)
}} />)
return
}
setBusy(true)
try {
const code = await scanCode()
+3 -5
View File
@@ -10,7 +10,6 @@ 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() {
@@ -95,10 +94,9 @@ 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,
and per user via the "Gym check-in" switch in Settings. */}
{MOBILE && S.checkIn !== false && (
{/* Jump to the gym check-in cards (QR membership codes). Shown here as a quick tap on
arrival at the gym; folds away per user via the "Gym check-in" switch in Settings. */}
{S.checkIn !== false && (
<div className="card tappable" style={{ cursor: 'pointer' }} {...tappable(() => nav('/checkin'))}>
<div className="row between">
<div className="row" style={{ gap: 9 }}>
+3 -4
View File
@@ -140,12 +140,11 @@ export default function Settings() {
options={[{ value: MONDAY, label: t('Monday') }, { value: SUNDAY, label: t('Sunday') }]}
value={weekStartOf(S)} onChange={v => update(s => { s.weekStart = v })} />
</Row>
{/* Membership QR codes on Home (views/CheckIn.jsx). Only the app can scan and show them
at a turnstile, so the switch exists only there; off = no Home card, no route. */}
{MOBILE && <Row icon="qr" iconTint="var(--blue)" title={t('Gym check-in')}
{/* Membership QR codes on Home (views/CheckIn.jsx); off = no Home card, no route. */}
<Row icon="qr" iconTint="var(--blue)" title={t('Gym check-in')}
subtitle={t('Show a card on Home with your membership QR codes.')}>
<Switch checked={S.checkIn !== false} onChange={v => update(s => { s.checkIn = v })} />
</Row>}
</Row>
</Section>
{/* ---------- during a workout ---------- */}