Просмотр исходного кода

Keep the barcode scanner from crashing on a small camera view (#662)

Bernt Christian Egeland 5 дней назад
Родитель
Сommit
d9970b22ab

+ 19 - 0
src/__tests__/components/barcode-scanner-dialog.test.tsx

@@ -150,6 +150,25 @@ describe('BarcodeScannerDialog', () => {
     expect(start.mock.calls[1][0]).toBe('usb-cam')
   })
 
+  it('shows the camera error, not a crash, when the scanner fails to start', async () => {
+    start.mockRejectedValue(new Error('NotReadableError: Could not start video source'))
+    getCameras.mockRejectedValue(new Error('NotReadableError: Could not start video source'))
+    renderDialog()
+
+    expect(await screen.findByText('The camera could not start')).toBeInTheDocument()
+    expect(screen.getByRole('button', { name: 'Try again' })).toBeInTheDocument()
+    expect(screen.getByRole('textbox', { name: 'Enter barcode...' })).toBeInTheDocument()
+  })
+
+  it('hands the scanner a box that fits a short viewfinder', async () => {
+    start.mockResolvedValue(null)
+    renderDialog()
+
+    await vi.waitFor(() => expect(start).toHaveBeenCalledTimes(1))
+    const { qrbox } = start.mock.calls[0][1]
+    expect(qrbox(382, 150)).toEqual({ width: 120, height: 50 })
+  })
+
   it('explains HTTPS without asking for the camera on an insecure page', async () => {
     setSecure(false)
     renderDialog()

+ 81 - 0
src/__tests__/lib/barcode-scan-box.test.ts

@@ -0,0 +1,81 @@
+/**
+ * The barcode scanner's scan box never makes html5-qrcode throw, whatever
+ * size the camera picture turns out to be. A phone once reported a short
+ * viewfinder and the scanner crashed with "minimum size of 'config.qrbox'
+ * dimension value is 50px".
+ */
+
+import { describe, it, expect } from 'vitest'
+import { libraryScanBox, MIN_SCAN_BOX, scanBoxFor } from '@/lib/barcode-scan-box'
+
+/**
+ * html5-qrcode 2.3.8's own checks in `setupUi`: both sides at least 50 px;
+ * a box no taller than the viewfinder is shaded and must then fit inside it,
+ * a taller one is ignored and the whole frame scanned.
+ */
+function libraryAccepts(viewfinderWidth: number, viewfinderHeight: number) {
+  const box = libraryScanBox(viewfinderWidth, viewfinderHeight)
+  if (box.width < MIN_SCAN_BOX || box.height < MIN_SCAN_BOX) return false
+  const shaded = box.height <= viewfinderHeight
+  if (shaded && (box.width > viewfinderWidth || box.height > viewfinderHeight)) return false
+  return true
+}
+
+const sizes: Array<[string, number, number]> = [
+  ['very small', 20, 30],
+  ['49 px square', 49, 49],
+  ['narrow and tall', 40, 300],
+  ['wide and flat', 300, 40],
+  ['50 px square', 50, 50],
+  ['100x100', 100, 100],
+  ['166x300', 166, 300],
+  ['300x166', 300, 166],
+  ['Safari before the video has a size', 382, 150],
+  ['430x320', 430, 320],
+  ['1280x720', 1280, 720],
+  ['fractional', 333.7, 187.4],
+  ['zero', 0, 0],
+  ['NaN', Number.NaN, Number.NaN],
+  ['NaN height', 400, Number.NaN],
+]
+
+describe('scanBoxFor', () => {
+  it.each(
+    sizes
+  )('%s (%s x %s) gives a box of at least 50 px inside the viewfinder, or none', (_, w, h) => {
+    const box = scanBoxFor(w, h)
+    const fits = Number.isFinite(w) && Number.isFinite(h) && w >= MIN_SCAN_BOX && h >= MIN_SCAN_BOX
+    if (!fits) {
+      expect(box).toBeNull()
+      return
+    }
+    expect(box).not.toBeNull()
+    const { width, height } = box!
+    expect(Number.isInteger(width) && Number.isInteger(height)).toBe(true)
+    expect(width).toBeGreaterThanOrEqual(MIN_SCAN_BOX)
+    expect(height).toBeGreaterThanOrEqual(MIN_SCAN_BOX)
+    expect(width).toBeLessThanOrEqual(w)
+    expect(height).toBeLessThanOrEqual(h)
+  })
+
+  it('keeps the wide barcode shape on a normal camera picture', () => {
+    expect(scanBoxFor(1280, 720)).toEqual({ width: 576, height: 216 })
+    expect(scanBoxFor(430, 320)).toEqual({ width: 256, height: 96 })
+  })
+
+  it('raises a short box to the minimum instead of going under it', () => {
+    expect(scanBoxFor(166, 300)).toEqual({ width: 132, height: 50 })
+    expect(scanBoxFor(382, 150)).toEqual({ width: 120, height: 50 })
+  })
+})
+
+describe('libraryScanBox', () => {
+  it.each(sizes)('%s (%s x %s) passes the library checks', (_, w, h) => {
+    expect(libraryAccepts(w, h)).toBe(true)
+  })
+
+  it('asks for the whole frame when the viewfinder is under 50 px', () => {
+    const box = libraryScanBox(300, 40)
+    expect(box.height).toBeGreaterThan(40)
+  })
+})

+ 2 - 4
src/components/barcode-scanner-dialog.tsx

@@ -12,6 +12,7 @@ import { Button } from '@/components/ui/button'
 import { Input } from '@/components/ui/input'
 import { Camera, CameraOff, Keyboard, RotateCcw } from 'lucide-react'
 import { useTranslations } from 'next-intl'
+import { libraryScanBox } from '@/lib/barcode-scan-box'
 
 interface BarcodeScannerDialogProps {
   open: boolean
@@ -144,10 +145,7 @@ export function BarcodeScannerDialog({
 
         const scanConfig = {
           fps: 10,
-          qrbox: (viewfinderWidth: number, viewfinderHeight: number) => ({
-            width: Math.floor(Math.min(viewfinderWidth, viewfinderHeight) * 0.8),
-            height: Math.floor(Math.min(viewfinderWidth, viewfinderHeight) * 0.3),
-          }),
+          qrbox: libraryScanBox,
         }
         const onSuccess = (decodedText: string) => {
           if (mounted) handleScan(decodedText)

+ 57 - 0
src/lib/barcode-scan-box.ts

@@ -0,0 +1,57 @@
+/**
+ * The scan box the barcode scanner draws over the camera picture.
+ *
+ * html5-qrcode (2.3.8) asks for the box once the video plays, from a
+ * `playing` listener, and throws there (uncaught, after `start()` has
+ * resolved) when either side is under 50 px. It also throws when a box that
+ * fits in height is wider than the viewfinder. Safari can report a small
+ * viewfinder at that moment (a video with no size yet is 150 px tall), so the
+ * box is clamped to the library's minimum and to the viewfinder itself.
+ */
+
+/** The library's `Constants.MIN_QR_BOX_SIZE`. */
+export const MIN_SCAN_BOX = 50
+
+export interface ScanBox {
+  width: number
+  height: number
+}
+
+function wholePixels(value: number): number {
+  return Number.isFinite(value) && value > 0 ? Math.floor(value) : 0
+}
+
+function clamp(value: number, min: number, max: number): number {
+  return Math.min(Math.max(value, min), max)
+}
+
+/**
+ * A wide, short box for one-dimensional barcodes, in whole pixels, at least
+ * 50 px on each side and never larger than the viewfinder. `null` when the
+ * viewfinder is too small for any box: then the whole frame is scanned.
+ */
+export function scanBoxFor(viewfinderWidth: number, viewfinderHeight: number): ScanBox | null {
+  const width = wholePixels(viewfinderWidth)
+  const height = wholePixels(viewfinderHeight)
+  if (width < MIN_SCAN_BOX || height < MIN_SCAN_BOX) return null
+  const side = Math.min(width, height)
+  return {
+    width: clamp(Math.floor(side * 0.8), MIN_SCAN_BOX, width),
+    height: clamp(Math.floor(side * 0.3), MIN_SCAN_BOX, height),
+  }
+}
+
+/**
+ * What to hand html5-qrcode's `qrbox` function. The function has to return a
+ * box once the config is set, so "no box" is said the way the library
+ * understands it: a box of the minimum size that is taller than the
+ * viewfinder, which makes it skip the shading and scan the whole frame.
+ */
+export function libraryScanBox(viewfinderWidth: number, viewfinderHeight: number): ScanBox {
+  return (
+    scanBoxFor(viewfinderWidth, viewfinderHeight) ?? {
+      width: MIN_SCAN_BOX,
+      height: Math.max(MIN_SCAN_BOX, wholePixels(viewfinderHeight) + 1),
+    }
+  )
+}