-
Notifications
You must be signed in to change notification settings - Fork 0
fix: improve barcode scanner compatibility #3
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,147 @@ | ||
| import type { IScannerProps } from "@yudiel/react-qr-scanner"; | ||
|
|
||
| type BarcodeScannerFormatList = NonNullable<IScannerProps["formats"]>; | ||
|
|
||
| type BarcodeScannerCameraOptions = { | ||
| deviceId: string | null; | ||
| usesCompatibleCamera: boolean; | ||
| }; | ||
|
|
||
| type BarcodeScannerFocusPoint = { | ||
| x: number; | ||
| y: number; | ||
| }; | ||
|
|
||
| type BarcodeScannerConstraintSet = MediaTrackConstraintSet & { | ||
| focusMode?: string; | ||
| pointsOfInterest?: BarcodeScannerFocusPoint[]; | ||
| zoom?: number; | ||
| }; | ||
|
|
||
| const BARCODE_SCANNER_FOCUS_CONSTRAINTS: BarcodeScannerConstraintSet = { | ||
| focusMode: "continuous", | ||
| pointsOfInterest: [{ x: 0.5, y: 0.5 }], | ||
| zoom: 2, | ||
| }; | ||
|
|
||
| export const barcodeScannerFormats: BarcodeScannerFormatList = [ | ||
| "codabar", | ||
| "code_128", | ||
| "code_39", | ||
| "code_93", | ||
| "databar", | ||
| "databar_expanded", | ||
| "databar_limited", | ||
| "ean_13", | ||
| "ean_8", | ||
| "itf", | ||
| "upc_a", | ||
| "upc_e", | ||
| ]; | ||
|
|
||
| export const barcodeScannerCameraConstraints: MediaTrackConstraints = { | ||
| facingMode: { ideal: "environment" }, | ||
| width: { ideal: 1280 }, | ||
| height: { ideal: 720 }, | ||
| advanced: [BARCODE_SCANNER_FOCUS_CONSTRAINTS], | ||
| }; | ||
|
|
||
| export const barcodeScannerCompatibleCameraConstraints: MediaTrackConstraints = { | ||
| facingMode: { ideal: "environment" }, | ||
| }; | ||
|
|
||
| const BARCODE_SCANNER_FRONT_CAMERA_PATTERN = | ||
| /front|frontal|selfie|user|frente/i; | ||
|
|
||
| const BARCODE_SCANNER_BACK_CAMERA_PATTERN = | ||
| /back|rear|environment|traseira|trasera|facing back/i; | ||
|
|
||
| const BARCODE_SCANNER_LOW_FOCUS_CAMERA_PATTERN = | ||
| /depth|macro|tele|ultra|wide|0\.5/i; | ||
|
|
||
| const BARCODE_SCANNER_CAMERA_RETRY_ERROR_NAMES = new Set([ | ||
| "AbortError", | ||
| "ConstraintNotSatisfiedError", | ||
| "NotFoundError", | ||
| "NotReadableError", | ||
| "OverconstrainedError", | ||
| ]); | ||
|
|
||
| type BarcodeScannerNamedError = { | ||
| message?: string; | ||
| name: string; | ||
| }; | ||
|
|
||
| const removeFacingModeFromConstraints = ( | ||
| constraints: MediaTrackConstraints, | ||
| ): MediaTrackConstraints => { | ||
| const nextConstraints = { ...constraints }; | ||
| delete nextConstraints.facingMode; | ||
| return nextConstraints; | ||
| }; | ||
|
|
||
| const isBarcodeScannerNamedError = ( | ||
| error: unknown, | ||
| ): error is BarcodeScannerNamedError => { | ||
| if (typeof error !== "object" || error === null) return false; | ||
|
|
||
| const errorCandidate = error as { message?: unknown; name?: unknown }; | ||
| return typeof errorCandidate.name === "string"; | ||
| }; | ||
|
|
||
| const getBarcodeScannerDeviceScore = ( | ||
| device: MediaDeviceInfo, | ||
| index: number, | ||
| ): number => { | ||
| const label = device.label.toLowerCase(); | ||
| let score = 100 - index; | ||
|
|
||
| if (BARCODE_SCANNER_BACK_CAMERA_PATTERN.test(label)) score += 50; | ||
| if (BARCODE_SCANNER_FRONT_CAMERA_PATTERN.test(label)) score -= 100; | ||
| if (BARCODE_SCANNER_LOW_FOCUS_CAMERA_PATTERN.test(label)) score -= 25; | ||
|
|
||
| return score; | ||
| }; | ||
|
|
||
| export const createBarcodeScannerCameraConstraints = ({ | ||
| deviceId, | ||
| usesCompatibleCamera, | ||
| }: BarcodeScannerCameraOptions): MediaTrackConstraints => { | ||
| const baseConstraints = usesCompatibleCamera | ||
| ? barcodeScannerCompatibleCameraConstraints | ||
| : barcodeScannerCameraConstraints; | ||
|
|
||
| if (!deviceId) return baseConstraints; | ||
|
|
||
| return { | ||
| ...removeFacingModeFromConstraints(baseConstraints), | ||
| deviceId: { exact: deviceId }, | ||
| }; | ||
| }; | ||
|
|
||
| export const getBarcodeScannerDeviceIds = ( | ||
| devices: MediaDeviceInfo[], | ||
| ): string[] => { | ||
| const videoDevices = devices.filter((device) => device.kind === "videoinput"); | ||
| const labeledDevices = videoDevices.filter((device) => device.label.length > 0); | ||
| const candidateDevices = labeledDevices.filter( | ||
| (device) => !BARCODE_SCANNER_FRONT_CAMERA_PATTERN.test(device.label), | ||
| ); | ||
|
|
||
| return candidateDevices | ||
| .sort( | ||
| (firstDevice, secondDevice) => | ||
| getBarcodeScannerDeviceScore(secondDevice, videoDevices.indexOf(secondDevice)) - | ||
| getBarcodeScannerDeviceScore(firstDevice, videoDevices.indexOf(firstDevice)), | ||
| ) | ||
| .map((device) => device.deviceId) | ||
| .filter((deviceId) => deviceId.length > 0); | ||
| }; | ||
|
|
||
| export const shouldRetryBarcodeScannerCamera = (error: unknown): boolean => { | ||
| if (!isBarcodeScannerNamedError(error)) return false; | ||
|
|
||
| if (BARCODE_SCANNER_CAMERA_RETRY_ERROR_NAMES.has(error.name)) return true; | ||
|
|
||
| return error.message?.toLowerCase().includes("timed out") ?? false; | ||
| }; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,96 @@ | ||
| "use client"; | ||
|
|
||
| import { useCallback, useEffect, useMemo, useState } from "react"; | ||
| import { | ||
| Scanner, | ||
| type IScannerProps, | ||
| } from "@yudiel/react-qr-scanner"; | ||
| import { | ||
| barcodeScannerFormats, | ||
| createBarcodeScannerCameraConstraints, | ||
| getBarcodeScannerDeviceIds, | ||
| shouldRetryBarcodeScannerCamera, | ||
| } from "@/components/product/barcode-scanner-camera"; | ||
|
|
||
| type BarcodeScannerProps = Omit<IScannerProps, "constraints" | "formats">; | ||
|
|
||
| const BARCODE_SCANNER_DEVICE_REFRESH_DELAYS_MS = [750, 2500] as const; | ||
|
|
||
| export const BarcodeScanner = ({ | ||
| onError, | ||
| onScan, | ||
| ...scannerProps | ||
| }: BarcodeScannerProps) => { | ||
| const [usesCompatibleCamera, setUsesCompatibleCamera] = useState(false); | ||
| const [cameraDeviceIds, setCameraDeviceIds] = useState<string[]>([]); | ||
| const [cameraDeviceIndex, setCameraDeviceIndex] = useState(0); | ||
|
|
||
| const selectedCameraDeviceId = cameraDeviceIds[cameraDeviceIndex] ?? null; | ||
| const cameraConstraints = useMemo( | ||
| () => | ||
| createBarcodeScannerCameraConstraints({ | ||
| deviceId: selectedCameraDeviceId, | ||
| usesCompatibleCamera, | ||
| }), | ||
| [selectedCameraDeviceId, usesCompatibleCamera], | ||
| ); | ||
|
|
||
| const scannerKey = `${selectedCameraDeviceId ?? "environment"}:${ | ||
| usesCompatibleCamera ? "compatible" : "preferred" | ||
| }`; | ||
|
|
||
| const refreshCameraDevices = useCallback(async (): Promise<void> => { | ||
| if (!navigator.mediaDevices?.enumerateDevices) return; | ||
|
|
||
| const devices = await navigator.mediaDevices.enumerateDevices(); | ||
| setCameraDeviceIds(getBarcodeScannerDeviceIds(devices)); | ||
| }, []); | ||
|
|
||
| const selectNextCameraConfiguration = useCallback(() => { | ||
| setUsesCompatibleCamera(true); | ||
| setCameraDeviceIndex((currentIndex) => { | ||
| if (cameraDeviceIds.length < 2) return currentIndex; | ||
| return (currentIndex + 1) % cameraDeviceIds.length; | ||
| }); | ||
| }, [cameraDeviceIds.length]); | ||
|
|
||
| const handleScannerError = useCallback( | ||
| (error: unknown) => { | ||
| if (shouldRetryBarcodeScannerCamera(error)) { | ||
| selectNextCameraConfiguration(); | ||
| } | ||
|
|
||
| void refreshCameraDevices(); | ||
| onError?.(error); | ||
| }, | ||
| [onError, refreshCameraDevices, selectNextCameraConfiguration], | ||
| ); | ||
|
|
||
| useEffect(() => { | ||
| void refreshCameraDevices(); | ||
|
|
||
| const timeoutIds = BARCODE_SCANNER_DEVICE_REFRESH_DELAYS_MS.map((delay) => | ||
| window.setTimeout(() => void refreshCameraDevices(), delay), | ||
| ); | ||
|
|
||
| return () => timeoutIds.forEach((timeoutId) => window.clearTimeout(timeoutId)); | ||
| }, [refreshCameraDevices]); | ||
|
|
||
| useEffect(() => { | ||
| setCameraDeviceIndex((currentIndex) => { | ||
| if (currentIndex < cameraDeviceIds.length) return currentIndex; | ||
| return 0; | ||
| }); | ||
| }, [cameraDeviceIds.length]); | ||
|
|
||
| return ( | ||
| <Scanner | ||
| key={scannerKey} | ||
| {...scannerProps} | ||
| constraints={cameraConstraints} | ||
| formats={barcodeScannerFormats} | ||
| onScan={onScan} | ||
| onError={handleScannerError} | ||
| /> | ||
| ); | ||
| }; |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The new shared
barcodeScannerFormatslist no longer includes"qr_code", but every replaced call site previously passed"qr_code"explicitly. This changes runtime behavior across PDV, transfer validation, and modal scanners: QR labels that worked before this commit now never triggeronScan. If operators use QR-encoded product/transfer labels, scanning is a hard regression rather than a compatibility improvement.Useful? React with 👍 / 👎.