Merge branch 'main' into feat/workout-list-view
This commit is contained in:
commit
98ed4ddcb1
51 files changed
+2652
-348
No files matched your search
@@ -27,11 +27,11 @@ describe('Brazilian Portuguese locale', () => {
|
||||
.sort(byCodeUnit)
|
||||
const fingerprint = createHash('sha256').update(JSON.stringify(inherited)).digest('hex')
|
||||
|
||||
expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(586)
|
||||
expect(inherited).toHaveLength(559)
|
||||
expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(603)
|
||||
expect(inherited).toHaveLength(571)
|
||||
// If this fails, review the changed keys and wording before accepting a new hash. From
|
||||
// frontend/: node scripts/pt-br-inheritance-fingerprint.mjs --list
|
||||
expect(fingerprint, 'pt-PT inheritance changed; review the inherited pt-BR wording').toBe('ae49ea702bb600947e67170a1ef61c0518a326724c83b8484ce7199f1393700b')
|
||||
expect(fingerprint, 'pt-PT inheritance changed; review the inherited pt-BR wording').toBe('1bc5c2825a8e797b2b8e129d1c06b6baca568e95ea9a1e43ae9dacae4bc98801')
|
||||
})
|
||||
|
||||
test('does not leak European Portuguese UI terms', () => {
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
// 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 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
|
||||
// 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]
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { normalizeFmt, canRenderFmt } from './qr.js'
|
||||
|
||||
// The QR helpers decide which scanned/typed codes the check-in feature will store: it can read
|
||||
// many symbologies but only redraw QR, so canRenderFmt is the gate, and normalizeFmt is what
|
||||
// folds every spelling mlkit might report into the single token everything else compares on.
|
||||
|
||||
describe('normalizeFmt', () => {
|
||||
it('folds every QR spelling to "qrcode"', () => {
|
||||
// mlkit's BarcodeFormat, the enum-ish casings, and the casual 'qr' all mean the same thing.
|
||||
expect(normalizeFmt('QR_CODE')).toBe('qrcode')
|
||||
expect(normalizeFmt('QrCode')).toBe('qrcode')
|
||||
expect(normalizeFmt('qrcode')).toBe('qrcode')
|
||||
expect(normalizeFmt('qr')).toBe('qrcode')
|
||||
expect(normalizeFmt('QR')).toBe('qrcode')
|
||||
})
|
||||
|
||||
it('lower-cases and strips separators for other formats', () => {
|
||||
expect(normalizeFmt('EAN_13')).toBe('ean13')
|
||||
expect(normalizeFmt('Code128')).toBe('code128')
|
||||
expect(normalizeFmt('CODE_128')).toBe('code128')
|
||||
})
|
||||
|
||||
it('treats empty / nullish as an empty token rather than throwing', () => {
|
||||
expect(normalizeFmt('')).toBe('')
|
||||
expect(normalizeFmt(null)).toBe('')
|
||||
expect(normalizeFmt(undefined)).toBe('')
|
||||
})
|
||||
})
|
||||
|
||||
describe('canRenderFmt', () => {
|
||||
it('accepts only QR, in any spelling', () => {
|
||||
expect(canRenderFmt('QR_CODE')).toBe(true)
|
||||
expect(canRenderFmt('QrCode')).toBe(true)
|
||||
expect(canRenderFmt('qr')).toBe(true)
|
||||
})
|
||||
|
||||
it('rejects 1D and other 2D symbologies we cannot faithfully redraw', () => {
|
||||
// These are readable by the scanner but lean-qr can't reproduce them, so a card in one of
|
||||
// these formats must never be stored — it would display as the wrong bars at the turnstile.
|
||||
for (const fmt of ['EAN_13', 'EAN_8', 'CODE_128', 'CODE_39', 'ITF', 'UPC_A', 'PDF_417', 'AZTEC', 'DATA_MATRIX']) {
|
||||
expect(canRenderFmt(fmt)).toBe(false)
|
||||
}
|
||||
})
|
||||
|
||||
it('rejects empty / unknown formats', () => {
|
||||
expect(canRenderFmt('')).toBe(false)
|
||||
expect(canRenderFmt(null)).toBe(false)
|
||||
expect(canRenderFmt('something-else')).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -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()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,112 @@
|
||||
// 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 (app build);
|
||||
// in a browser the view opens components/CameraScan.jsx instead
|
||||
//
|
||||
// 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
|
||||
// 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 (!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')
|
||||
|
||||
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'
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
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.
|
||||
// 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 off mobile', () => {
|
||||
it('scanCode rejects — the native scanner is app-only', async () => {
|
||||
await expect(scanCode()).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