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:
1 parent
0af9f55528
commit
aa487d29f4
30 files changed
+315
-47
No files matched your search
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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() }
|
||||
}
|
||||
@@ -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()
|
||||
})
|
||||
})
|
||||
@@ -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')
|
||||
|
||||
|
||||
@@ -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()
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user