### Local Project Setup Source: https://github.com/yudielcurbelo/react-qr-scanner/blob/main/CONTRIBUTING.md Clone the repository, navigate to the project directory, and install dependencies to set up the project locally. The `prepare` script automatically installs Husky hooks for pre-commit checks. ```bash git clone https://github.com/yudielcurbelo/react-qr-scanner.git cd react-qr-scanner npm install ``` -------------------------------- ### Install React QR Scanner with pnpm Source: https://github.com/yudielcurbelo/react-qr-scanner/blob/main/README.md Install the library using pnpm. ```bash pnpm add @yudiel/react-qr-scanner ``` -------------------------------- ### Install React QR Scanner with yarn Source: https://github.com/yudielcurbelo/react-qr-scanner/blob/main/README.md Install the library using yarn. ```bash yarn add @yudiel/react-qr-scanner ``` -------------------------------- ### Install React QR Scanner with npm Source: https://github.com/yudielcurbelo/react-qr-scanner/blob/main/README.md Install the library using npm. ```bash npm install @yudiel/react-qr-scanner ``` -------------------------------- ### Basic QR Scanner Setup Source: https://github.com/yudielcurbelo/react-qr-scanner/blob/main/_autodocs/README.md This is the most basic setup for the QR scanner. It requires importing the Scanner component and providing `onScan` and `onError` callback functions. ```typescript import { Scanner } from '@yudiel/react-qr-scanner'; export function App() { return ( console.log(result)} onError={(error) => console.error(error)} /> ); } ``` -------------------------------- ### Basic React QR Scanner Setup Source: https://github.com/yudielcurbelo/react-qr-scanner/blob/main/README.md A minimal setup for the QR scanner component. It logs the scan result and any errors encountered. ```jsx import { Scanner } from '@yudiel/react-qr-scanner'; function App() { return ( console.log(result)} onError={(error) => console.log(error?.message)} /> ); } ``` -------------------------------- ### Example: Full UI Configuration Source: https://github.com/yudielcurbelo/react-qr-scanner/blob/main/_autodocs/configuration.md Renders the scanner with all available UI components enabled: finder, torch, zoom, and on/off toggle. ```typescript ``` -------------------------------- ### Camera Start Options (TypeScript) Source: https://github.com/yudielcurbelo/react-qr-scanner/blob/main/_autodocs/types.md Configure camera initialization with this interface. Specify media track constraints and whether to restart the camera if it's already active. ```typescript interface IStartCamera { constraints: MediaTrackConstraints; restart?: boolean; } ``` -------------------------------- ### Minimal Configuration Source: https://github.com/yudielcurbelo/react-qr-scanner/blob/main/_autodocs/configuration.md A minimal setup where most UI components like the finder, torch, and zoom are disabled. ```typescript ``` -------------------------------- ### Capture Frame Example Source: https://github.com/yudielcurbelo/react-qr-scanner/blob/main/_autodocs/types.md Example of how to capture a frame from the scanner's video feed using the IScannerHandle. Requires importing useRef and Scanner. ```typescript import { useRef } from 'react'; import { Scanner, type IScannerHandle } from '@yudiel/react-qr-scanner'; export function SnapshotCapture() { const scannerRef = useRef(null); function captureFrame() { const video = scannerRef.current?.getVideoElement(); if (!video) return; const canvas = document.createElement('canvas'); canvas.width = video.videoWidth; canvas.height = video.videoHeight; const ctx = canvas.getContext('2d'); if (ctx) { ctx.drawImage(video, 0, 0); console.log(canvas.toDataURL('image/png')); } } return ( <> ); } ``` -------------------------------- ### Custom Scanner Styles Example Source: https://github.com/yudielcurbelo/react-qr-scanner/blob/main/_autodocs/types.md Example demonstrating how to override default styles for the Scanner component's container and video elements using the 'styles' prop. ```jsx ``` -------------------------------- ### Example: Minimal UI Configuration Source: https://github.com/yudielcurbelo/react-qr-scanner/blob/main/_autodocs/configuration.md Renders the scanner with only the essential UI components disabled, providing a minimal interface. ```typescript ``` -------------------------------- ### Quick Timeout Configuration (Strict) Source: https://github.com/yudielcurbelo/react-qr-scanner/blob/main/_autodocs/configuration.md Use a short `startTimeoutMs` to fail quickly if the camera doesn't start. `settleDelayMs` is set low to avoid waiting for capabilities. ```typescript ``` -------------------------------- ### Basic Camera Startup with useCamera Source: https://github.com/yudielcurbelo/react-qr-scanner/blob/main/_autodocs/api-reference/useCamera.md Demonstrates how to start the camera and attach it to a video element. Ensure the component is mounted and the videoRef is available before calling startCamera. The hook handles camera initialization and provides a ready state. ```typescript import { useRef, useEffect, useState } from 'react'; import useCamera from '@yudiel/react-qr-scanner/hooks/useCamera'; export function CameraComponent() { const videoRef = useRef(null); const camera = useCamera({ startTimeoutMs: 5000 }); const [cameraReady, setCameraReady] = useState(false); useEffect(() => { const startCamera = async () => { try { if (!videoRef.current) return; await camera.startCamera(videoRef.current, { constraints: { facingMode: 'environment' }, }); setCameraReady(true); } catch (error) { console.error('Camera failed:', error); } }; startCamera(); }, [camera]); return (
); } ``` -------------------------------- ### Start Camera Stream Source: https://github.com/yudielcurbelo/react-qr-scanner/blob/main/_autodocs/api-reference/useCamera.md Acquires a camera stream and attaches it to a video element. Requires a secure context (HTTPS or localhost). ```typescript const videoEl = document.querySelector('video')!; const camera = useCamera(); try { await camera.startCamera(videoEl, { constraints: { facingMode: 'environment', width: { ideal: 1280 }, height: { ideal: 720 }, }, }); console.log('Camera started. Torch supported:', camera.capabilities.torch); } catch (error) { console.error('Failed to start camera:', error); } ``` -------------------------------- ### Example Detection Flow Source: https://github.com/yudielcurbelo/react-qr-scanner/blob/main/_autodocs/api-reference/useScanner.md Illustrates the sequence of events and state changes during barcode detection across multiple frames. ```text Frame 1: Detect QR code "ABC" - contentBefore = {} - anyNewCodesDetected = true - onScan([{rawValue: "ABC", ...}]) - contentBefore = {"ABC"} Frame 2: Same QR code "ABC" visible - contentBefore = {"ABC"} - anyNewCodesDetected = false (ABC already in contentBefore) - onScan is NOT called - onFound([{ rawValue: "ABC", ...}]) called anyway for tracking Frame 3: QR code "ABC" disappears, new code "DEF" detected - contentBefore = {"ABC"} - anyNewCodesDetected = true (DEF is new) - onScan([{ rawValue: "DEF", ...}]) - onFound([{ rawValue: "DEF", ...}]) - contentBefore = {"DEF"} Frame 4: Code "DEF" gone, nothing detected - contentBefore = {"DEF"} - anyNewCodesDetected = false - onScan is NOT called - onFound([]) called because lastScanHadContent = true - contentBefore = {} (cleared because nothing detected) ``` -------------------------------- ### Render Camera List using useDevices Hook Source: https://github.com/yudielcurbelo/react-qr-scanner/blob/main/README.md This example demonstrates how to use the `useDevices` hook to fetch available cameras and render them as a list. Each device is displayed with its label or a fallback identifier. ```jsx import { useDevices } from '@yudiel/react-qr-scanner'; function CameraList() { const devices = useDevices(); return (
    {devices.map((device) => (
  • {device.label || `Camera ${device.deviceId}`}
  • ))}
); } ``` -------------------------------- ### startCamera Source: https://github.com/yudielcurbelo/react-qr-scanner/blob/main/_autodocs/api-reference/useCamera.md Acquires a camera stream and attaches it to a video element. It handles secure context checks, user permissions, and stream setup, returning a promise that resolves on success or rejects on failure. ```APIDOC ## startCamera(videoEl, { constraints, restart }): Promise ### Description Acquires a camera stream and attaches it to a video element. ### Parameters #### Path Parameters - **videoEl** (HTMLVideoElement) - Required - The video element to attach the stream to. - **constraints** (MediaTrackConstraints) - Required - Media track constraints (e.g., `facingMode`, `deviceId`, `width`, `height`, `advanced: [{ zoom, torch }]`). - **restart** (boolean) - Optional - If `true`, stops the current camera before starting a new one, even if constraints are identical. Default: `false`. ### Behavior - Checks for secure context (HTTPS or localhost) before calling `getUserMedia`. - Calls `navigator.mediaDevices.getUserMedia({ audio: false, video: constraints })`. - Sets the stream as the `srcObject` of the video element. - Waits for `play()` with a timeout. - Waits `settleDelayMs` before reading capabilities and settings. - Returns a promise that rejects if the browser lacks the Stream API, the user denies permission, or the camera is unavailable. ### Throws - `Error` if not in a secure context - `Error` if the Stream API is not supported - `DOMException` (e.g., `NotAllowedError`, `NotFoundError`, `NotReadableError`, `OverconstrainedError`) mapped by `createScannerError` into an `IScannerError` - `Error` if `play()` times out ### Example ```typescript const videoEl = document.querySelector('video')!; const camera = useCamera(); try { await camera.startCamera(videoEl, { constraints: { facingMode: 'environment', width: { ideal: 1280 }, height: { ideal: 720 }, }, }); console.log('Camera started. Torch supported:', camera.capabilities.torch); } catch (error) { console.error('Failed to start camera:', error); } ``` ``` -------------------------------- ### Start Scanning with useScanner Source: https://github.com/yudielcurbelo/react-qr-scanner/blob/main/_autodocs/api-reference/useScanner.md Initiates the barcode detection loop. Ensure you have a video element reference and define callbacks for scan results. ```typescript const { startScanning, stopScanning } = useScanner({ videoElementRef: videoRef, onScan: (codes) => console.log('Detected:', codes), onFound: (codes) => drawOverlay(codes), }); startScanning(); // Begin detection ``` -------------------------------- ### useCamera Hook Options Example Source: https://github.com/yudielcurbelo/react-qr-scanner/blob/main/_autodocs/configuration.md Customizes the behavior of the useCamera hook by adjusting timeouts for camera startup and capability settling. ```typescript const camera = useCamera({ startTimeoutMs: 5000, // Allow 5 seconds for camera to start settleDelayMs: 1000, // Wait longer for capabilities to settle }); ``` -------------------------------- ### Configure ZXing Module Overrides Source: https://github.com/yudielcurbelo/react-qr-scanner/blob/main/_autodocs/api-reference/utilities.md Use `prepareZXingModule` for configuration. The `setZXingModuleOverrides` function is deprecated. This example shows how to specify a custom path for locating module files. ```typescript // Old way (deprecated) import { setZXingModuleOverrides } from '@yudiel/react-qr-scanner'; setZXingModuleOverrides({ locateFile: (p) => `/static/${p}` }); // New way (recommended) import { prepareZXingModule } from '@yudiel/react-qr-scanner'; prepareZXingModule({ overrides: { locateFile: (p) => `/static/${p}` }, }); ``` -------------------------------- ### Conventional Commit Message Examples Source: https://github.com/yudielcurbelo/react-qr-scanner/blob/main/CONTRIBUTING.md Follow the Conventional Commits style for commit messages. Examples include 'fix:', 'feat:', and 'test:' prefixes to categorize changes. ```git fix: clone merged constraints before deleting facingMode feat: forward ref on Scanner to expose video element and stream test: cover useDevices devicechange refresh ``` -------------------------------- ### Storybook Setup Source: https://github.com/yudielcurbelo/react-qr-scanner/blob/main/CLAUDE.md Configuration for Storybook, used for interactive component development. Stories are located in the `stories/` directory, utilizing React, Webpack 5, and the SWC compiler. ```javascript // stories/ directory // Uses React + Webpack 5 + SWC compiler // Accessible at `http://localhost:6006` during development ``` -------------------------------- ### Basic Barcode Detection with useScanner Source: https://github.com/yudielcurbelo/react-qr-scanner/blob/main/_autodocs/api-reference/useScanner.md Demonstrates the basic usage of the useScanner hook for detecting barcodes. It initializes the scanner, starts detection on component mount, and stops it on unmount. The detected codes are logged to the console. ```typescript import { useRef, useEffect } from 'react'; import useScanner from '@yudiel/react-qr-scanner/hooks/useScanner'; export function BarcodeDetector() { const videoRef = useRef(null); const { startScanning, stopScanning } = useScanner({ videoElementRef: videoRef, onScan: (detectedCodes) => { console.log('Detected:', detectedCodes); detectedCodes.forEach((code) => { console.log(`Format: ${code.format}, Value: ${code.rawValue}`); }); }, onFound: (detectedCodes) => { // Called every frame when codes are visible // Useful for updating tracking overlays }, }); useEffect(() => { startScanning(); return () => stopScanning(); }, []); return