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

Add a mobile-only gym check-in screen: saved membership codes shown as
QR codes in a swipeable carousel, reached from a 'Check in' card on Home.
Cards are added by typing the code, importing a photo, or scanning with
the camera. Only the code value + symbology are stored — never a photo;
the QR is regenerated from the value on every display.

Rendering uses lean-qr (MIT); camera scan and photo decode use
@capacitor-mlkit/barcode-scanning (Apache-2.0), pinned to the 7.x line
for Capacitor 7. Both are documented in NOTICE.md and bundled only in the
mobile build — the whole feature folds away in web/demo builds via MOBILE,
so nothing new lands in the web bundle. No backend/schema change: gymCards
rides the existing state sync and backup like every other field.

Non-QR symbologies are readable but not reproducible, so capture refuses
them rather than storing a code that would display wrong bars.

Native wiring: CAMERA permission + ML Kit barcode_ui meta-data
(AndroidManifest), NSCameraUsageDescription (iOS Info.plist), mlkit plugin
registered via cap sync. Debug builds get an applicationIdSuffix '.test'
and an 'OpenGymTest' label so a test build installs alongside the real app.
This commit is contained in:
Sebastian G committed 2026-09-03 11:10:58 +02:00
1 parent 272bf785ee
commit a797729dd0
19 files changed
+587

No files matched your search

+67
View File
@@ -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]
}
+109
View File
@@ -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'
}