modern-barcode-scanner 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Sumit Sahoo
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,291 @@
1
+ <div align="center">
2
+ <h1>📷 Modern Barcode Scanner</h1>
3
+ <p>A high-performance barcode scanner React component with optimized detection, camera switching, torch control, and automatic phone detection.</p>
4
+
5
+ [![npm version](https://badge.fury.io/js/modern-barcode-scanner.svg)](https://www.npmjs.com/package/modern-barcode-scanner)
6
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
7
+ </div>
8
+
9
+ ---
10
+
11
+ ## ✨ Features
12
+
13
+ - 🚀 **High Performance**: Web Worker-based scanning with optimized grayscale conversion.
14
+ - 📱 **Mobile Optimized**: Automatic phone detection with appropriate camera selection.
15
+ - đŸ”Ļ **Torch Control**: Built-in torch/flash support for low-light scanning.
16
+ - 🔄 **Camera Switching**: Easy switching between front and back cameras.
17
+ - 📷 **Smart Camera Selection**: Automatically selects the best rear camera (avoids ultra-wide/telephoto).
18
+ - đŸŽ¯ **Session Management**: Prevents stale results with session-based tracking.
19
+ - 🎨 **Customizable UI**: CSS-based styling with sensible defaults and CSS variables.
20
+ - đŸ“Ļ **TypeScript Support**: Full type definitions included out of the box.
21
+ - đŸ“ŗ **Haptic Feedback**: Standard [Web Vibration API](https://developer.mozilla.org/en-US/docs/Web/API/Vibration_API) support for successful scans (Android/Desktop).
22
+ - 🔊 **Sound Feedback**: Optional audio cues on successful scans.
23
+
24
+ ---
25
+
26
+ ## đŸˇī¸ Supported Barcode Formats
27
+
28
+ - **2D Codes**: QR Code, PDF417
29
+ - **Retail Codes**: EAN-13, EAN-8, UPC-A, UPC-E
30
+ - **Industrial/Standard Codes**: Code 128, Code 39, Code 93, Codabar, ITF (Interleaved 2 of 5)
31
+ - **Books**: ISBN-10, ISBN-13
32
+ - **DataBar (GS1)**
33
+ - *And more! (Powered by ZBar)*
34
+
35
+ ---
36
+
37
+ ## đŸ“Ļ Installation
38
+
39
+ Choose your preferred package manager:
40
+
41
+ ```bash
42
+ # npm
43
+ npm install modern-barcode-scanner
44
+
45
+ # yarn
46
+ yarn add modern-barcode-scanner
47
+
48
+ # pnpm
49
+ pnpm add modern-barcode-scanner
50
+ ```
51
+
52
+ ---
53
+
54
+ ## 🚀 Quick Start
55
+
56
+ Here's a minimal example to get the scanner up and running in your React application:
57
+
58
+ ```tsx
59
+ import { useRef, useEffect } from 'react';
60
+ import { BarcodeScanner, BarcodeScannerRef, ScanResult } from 'modern-barcode-scanner';
61
+
62
+ // Styles are auto-imported, but you can also import manually if needed:
63
+ // import 'modern-barcode-scanner/styles.css';
64
+
65
+ function App() {
66
+ const scannerRef = useRef<BarcodeScannerRef>(null);
67
+
68
+ const handleScan = (result: ScanResult) => {
69
+ console.log('đŸ“Ļ Barcode type:', result.typeName);
70
+ console.log('📄 Barcode data:', result.scanData);
71
+
72
+ // Scanner automatically stops after detection.
73
+ // Call scannerRef.current?.start() to scan again!
74
+ };
75
+
76
+ const handleError = (error: Error) => {
77
+ console.error('❌ Scanner error:', error.message);
78
+ };
79
+
80
+ useEffect(() => {
81
+ // Start scanning when component mounts
82
+ scannerRef.current?.start();
83
+ }, []);
84
+
85
+ return (
86
+ <div style={{ width: '100vw', height: '100vh' }}>
87
+ <BarcodeScanner
88
+ ref={scannerRef}
89
+ onScan={handleScan}
90
+ onError={handleError}
91
+ themeColor="#4db8a8" // Customize the primary UI color!
92
+ />
93
+ </div>
94
+ );
95
+ }
96
+ ```
97
+
98
+ ---
99
+
100
+ ## 📖 API Reference
101
+
102
+ ### `<BarcodeScanner />` Component
103
+
104
+ #### Props
105
+
106
+ | Prop | Type | Default | Description |
107
+ |------|------|---------|-------------|
108
+ | `onScan` | `(result: ScanResult) => void` | **Required** | Callback fired when a barcode is detected. |
109
+ | `onError` | `(error: Error) => void` | `undefined` | Callback fired when an error occurs. |
110
+ | `onStateChange` | `(state: ScannerState) => void` | `undefined` | Callback fired when scanner state changes. |
111
+ | `themeColor` | `string` | `'#4db8a8'` | Primary theme color for UI elements and scan line. |
112
+ | `scanInterval` | `number` | `100` | Time between scan attempts (in ms). |
113
+ | `enableVibration` | `boolean` | `true` | Enable haptic feedback on scan (uses `navigator.vibrate`). |
114
+ | `vibrationDuration`| `number` | `200` | Vibration duration (in ms). |
115
+ | `enableSound` | `boolean` | `false` | Enable sound feedback on scan. |
116
+ | `initialFacingMode`| `'user' \| 'environment'` | `'environment'`| Initial camera to use. |
117
+ | `showScanLine` | `boolean` | `true` | Show scanning animation line. |
118
+ | `showCameraSwitch` | `boolean` | `true` | Show camera switch button. |
119
+ | `showTorchButton` | `boolean` | `true` | Show torch button (if supported). |
120
+ | `className` | `string` | `''` | Custom CSS class for the container. |
121
+ | `style` | `React.CSSProperties` | `undefined` | Custom inline styles for the container. |
122
+
123
+ #### Ref Methods
124
+
125
+ Exposed via `useImperativeHandle` for direct control:
126
+
127
+ ```tsx
128
+ interface BarcodeScannerRef {
129
+ start: () => Promise<void>; // Starts the camera and scanning
130
+ stop: () => void; // Stops the camera and scanning
131
+ switchCamera: () => Promise<void>; // Toggles between front and back camera
132
+ toggleTorch: () => Promise<void>; // Toggles the torch/flash (if supported)
133
+ getState: () => ScannerState; // Returns current state
134
+ }
135
+ ```
136
+
137
+ ### TypeScript Types
138
+
139
+ ```tsx
140
+ interface ScanResult {
141
+ typeName: string; // e.g., 'QRCODE', 'EAN13', 'CODE128'
142
+ scanData: string; // The decoded barcode string
143
+ }
144
+
145
+ interface ScannerState {
146
+ isScanning: boolean;
147
+ facingMode: 'user' | 'environment';
148
+ isTorchOn: boolean;
149
+ }
150
+ ```
151
+
152
+ ---
153
+
154
+ ## đŸ› ī¸ Advanced Usage
155
+
156
+ ### Using the `useScanner` Hook
157
+
158
+ If you need complete control over the UI, you can use the internal hook directly:
159
+
160
+ ```tsx
161
+ import { useScanner } from 'modern-barcode-scanner';
162
+
163
+ function CustomScanner() {
164
+ const {
165
+ scannerState,
166
+ videoRef,
167
+ canvasRef,
168
+ handleScan,
169
+ handleStopScan,
170
+ handleSwitchCamera,
171
+ handleToggleTorch,
172
+ } = useScanner({
173
+ onScan: (result) => console.log('Scanned:', result),
174
+ onError: (error) => console.error('Error:', error),
175
+ enableVibration: true,
176
+ });
177
+
178
+ return (
179
+ <div>
180
+ <video ref={videoRef} autoPlay muted playsInline />
181
+ <canvas ref={canvasRef} hidden />
182
+
183
+ <div className="controls">
184
+ <button onClick={handleScan}>â–ļī¸ Start</button>
185
+ <button onClick={handleStopScan}>âšī¸ Stop</button>
186
+ <button onClick={handleSwitchCamera}>🔄 Switch</button>
187
+ {scannerState.isTorchOn ? 'đŸ”Ļ On' : 'đŸ”Ļ Off'}
188
+ </div>
189
+ </div>
190
+ );
191
+ }
192
+ ```
193
+
194
+ ### Helper Utilities
195
+
196
+ The library exports several useful utilities:
197
+
198
+ ```tsx
199
+ import {
200
+ isPhone,
201
+ getBestRearCamera,
202
+ getMediaConstraints
203
+ } from 'modern-barcode-scanner';
204
+
205
+ // 📱 Check if device is a phone/tablet
206
+ const isMobile = isPhone();
207
+
208
+ // 📷 Get the optimal rear camera device ID (avoids ultra-wide lenses)
209
+ const cameraId = await getBestRearCamera();
210
+
211
+ // âš™ī¸ Get optimized media constraints based on facing mode
212
+ const constraints = await getMediaConstraints('environment');
213
+ ```
214
+
215
+ ---
216
+
217
+ ## 🎨 Styling
218
+
219
+ The component uses CSS prefix `mbs-` (Modern Barcode Scanner) and supports native CSS variables for easy theming.
220
+
221
+ ### CSS Variables
222
+
223
+ You can easily override the primary color globally or via the `themeColor` prop:
224
+ ```css
225
+ :root {
226
+ --mbs-primary: #ff0055; /* Changes scan line and active icon colors */
227
+ }
228
+ ```
229
+
230
+ ### Overriding Classes
231
+
232
+ ```css
233
+ /* Custom container styling */
234
+ .mbs-container {
235
+ border-radius: 1rem;
236
+ box-shadow: 0 4px 6px rgba(0,0,0,0.1);
237
+ }
238
+
239
+ /* Custom scan line */
240
+ .mbs-scan-line {
241
+ height: 3px;
242
+ box-shadow: 0 0 15px 3px var(--mbs-primary);
243
+ }
244
+
245
+ /* Custom control buttons */
246
+ .mbs-control-btn {
247
+ background-color: rgba(255, 255, 255, 0.2);
248
+ backdrop-filter: blur(4px);
249
+ }
250
+ ```
251
+
252
+ ---
253
+
254
+ ## 🌐 Browser Support
255
+
256
+ | Browser / OS | Version |
257
+ |--------------|---------|
258
+ | đŸŸĸ Google Chrome | 79+ |
259
+ | đŸ”ĩ Microsoft Edge | 79+ |
260
+ | 🟠 Mozilla Firefox | 79+ |
261
+ | 🧭 Safari (macOS) | 14.1+ |
262
+ | 📱 Chrome for Android | Supported |
263
+ | 🍎 Safari on iOS | 14.5+ |
264
+
265
+ > **âš ī¸ Note**: Camera access requires a secure context (**HTTPS**) in production environments!
266
+
267
+ ---
268
+
269
+ ## ⚡ Performance Optimizations
270
+
271
+ This library is built for speed and reliability:
272
+ 1. **Web Worker Processing**: Barcode detection runs entirely off the main thread.
273
+ 2. **Grayscale Conversion**: Uses bitwise operations for incredibly fast image matrix processing.
274
+ 3. **Frame Throttling**: Configurable `scanInterval` perfectly balances detection speed with device battery/CPU usage.
275
+ 4. **Session Management**: Strictly prevents processing out-of-date or stale video frames.
276
+ 5. **Smart Downscaling**: Intelligently reduces image resolution for faster processing while maintaining read quality.
277
+ 6. **Canvas Optimizations**: Utilizes `willReadFrequently` and `desynchronized` rendering hints where supported.
278
+
279
+ ---
280
+
281
+ ## 📝 License
282
+
283
+ MIT Š [Sumit Sahoo](https://github.com/sumitsahoo)
284
+
285
+ Please refer to the [LICENSE](./LICENSE) file for the full text.
286
+
287
+ ---
288
+
289
+ ## 🤝 Credits
290
+
291
+ - Powerful barcode detection engine powered by [ZBar WASM](https://github.com/nickinchern/nickinchern-undecaf-zbar-wasm).