@octane-xplat/barcode-scanner 0.18.0 → 0.20.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.
@@ -1,116 +1,135 @@
1
+ /** @jsxImportSource @octane-xplat/jsx/dom */
1
2
  import { useImperativeHandle, useEffect, useRef } from 'octane'
2
3
  import type { BarcodeScannerHandle, BarcodeScannerProps } from './props'
3
4
  import { fromDetectorFormat, toDetectorFormats } from './format-map.web'
5
+ import type { JSX } from 'octane/jsx-runtime'
4
6
 
5
7
  /** Live barcode/QR scanner — getUserMedia + the BarcodeDetector API
6
8
  * (Chromium/Safari 18.4+; Firefox lacks the detector). Polling runs on
7
9
  * requestVideoFrameCallback where available, else a 250ms interval. */
8
- export function BarcodeScanner(props: BarcodeScannerProps) @{
9
- const video = useRef<HTMLVideoElement | null>(null)
10
- const latest = useRef(props)
11
- latest.current = props
12
-
13
- const handle = (v: HTMLVideoElement | null): BarcodeScannerHandle => ({
14
- setPaused: () => {},
15
- toggleCamera: () => {},
16
- native: v,
17
- })
18
- useImperativeHandle(props.ref, () => handle(video.current), [])
19
-
20
- useEffect(() => {
21
- const Detector = (globalThis as any).BarcodeDetector
22
- const mediaDevices = (globalThis as any).navigator?.mediaDevices
23
- if (!Detector || typeof mediaDevices?.getUserMedia !== 'function') {
24
- props.onError?.({ message: 'unsupported: BarcodeDetector/getUserMedia is not available' })
25
- return
26
- }
27
- const el = video.current
28
- if (!el) {
29
- return
30
- }
31
-
32
- let detector: any
33
- try {
34
- detector = new Detector({ formats: toDetectorFormats(props.formats) })
35
- } catch {
36
- detector = new Detector()
37
- }
38
-
39
- let stream: MediaStream | null = null
40
- let timer: any = null
41
- let cancelled = false
42
- const pausedRef = { current: false }
43
-
44
- const poll = async () => {
45
- if (cancelled || !el || pausedRef.current) {
46
- return
47
- }
48
- try {
49
- const codes = await detector.detect(el)
50
- for (const code of codes ?? []) {
51
- const box = code.boundingBox
52
- latest.current.onCodeScanned?.({
53
- type: fromDetectorFormat(code.format),
54
- data: String(code.rawValue ?? ''),
55
- bounds: box ? { x: box.x, y: box.y, width: box.width, height: box.height } : undefined,
56
- })
57
- }
58
- } catch {
59
- // A transient frame failure ends detection for this tick only.
60
- }
61
- schedule()
62
- }
63
-
64
- const schedule = () => {
65
- if (cancelled) {
66
- return
67
- }
68
- const rvfc = (el as any).requestVideoFrameCallback
69
- if (typeof rvfc === 'function') {
70
- rvfc.call(el, () => poll())
71
- } else {
72
- timer = setTimeout(poll, 250)
73
- }
74
- }
75
-
76
- // props.paused is read through latest in the poll loop.
77
- Object.defineProperty(pausedRef, 'current', {
78
- get: () => latest.current.paused ?? false,
79
- })
80
-
81
- mediaDevices
82
- .getUserMedia({ video: { facingMode: props.facing === 'front' ? 'user' : 'environment' }, audio: false })
83
- .then((s: MediaStream) => {
84
- if (cancelled) {
85
- s.getTracks().forEach((t) => t.stop())
86
- return
87
- }
88
- stream = s
89
- el.srcObject = s
90
- el.play().catch(() => {})
91
- schedule()
92
- })
93
- .catch((e: any) => {
94
- latest.current.onError?.({ message: e?.message ?? 'camera unavailable' })
95
- })
96
-
97
- return () => {
98
- cancelled = true
99
- if (timer) {
100
- clearTimeout(timer)
101
- }
102
- stream?.getTracks().forEach((t) => t.stop())
103
- el.srcObject = null
104
- }
105
- }, [props.facing, JSON.stringify(props.formats)])
106
-
107
- <video
108
- ref={(el: HTMLVideoElement | null) => {
109
- video.current = el
110
- }}
111
- muted
112
- playsInline
113
- style={props.style}
114
- className={props.className}
115
- />
10
+ export function BarcodeScanner(props: BarcodeScannerProps): JSX.Element @{
11
+ const video = useRef<HTMLVideoElement | null>(null)
12
+ const latest = useRef(props)
13
+
14
+ latest.current = props
15
+
16
+ const handle = (v: HTMLVideoElement | null): BarcodeScannerHandle => ({
17
+ setPaused: () => {},
18
+ toggleCamera: () => {},
19
+ native: v,
20
+ })
21
+
22
+ useImperativeHandle(props.ref, () => handle(video.current), [])
23
+
24
+ useEffect(() => {
25
+ const Detector = (globalThis as any).BarcodeDetector
26
+ const mediaDevices = (globalThis as any).navigator?.mediaDevices
27
+
28
+ if (!Detector || typeof mediaDevices?.getUserMedia !== 'function') {
29
+ props.onError?.({ message: 'unsupported: BarcodeDetector/getUserMedia is not available' })
30
+ return
31
+ }
32
+
33
+ const el = video.current
34
+
35
+ if (!el) {
36
+ return
37
+ }
38
+
39
+ let detector: any
40
+
41
+ try {
42
+ detector = new Detector({ formats: toDetectorFormats(props.formats) })
43
+ } catch {
44
+ detector = new Detector()
45
+ }
46
+
47
+ let stream: MediaStream | null = null
48
+ let timer: any = null
49
+ let cancelled = false
50
+ const pausedRef = { current: false }
51
+
52
+ const poll = async () => {
53
+ if (cancelled || !el || pausedRef.current) {
54
+ return
55
+ }
56
+
57
+ try {
58
+ const codes = await detector.detect(el)
59
+
60
+ for (const code of codes ?? []) {
61
+ const box = code.boundingBox
62
+
63
+ latest.current.onCodeScanned?.({
64
+ type: fromDetectorFormat(code.format),
65
+ data: String(code.rawValue ?? ''),
66
+ bounds: box ? { x: box.x, y: box.y, width: box.width, height: box.height } : undefined,
67
+ })
68
+ }
69
+ } catch {
70
+ // A transient frame failure ends detection for this tick only.
71
+ }
72
+
73
+ schedule()
74
+ }
75
+
76
+ const schedule = () => {
77
+ if (cancelled) {
78
+ return
79
+ }
80
+
81
+ const rvfc = (el as any).requestVideoFrameCallback
82
+
83
+ if (typeof rvfc === 'function') {
84
+ rvfc.call(el, () => poll())
85
+ } else {
86
+ timer = setTimeout(poll, 250)
87
+ }
88
+ }
89
+
90
+ // props.paused is read through latest in the poll loop.
91
+ Object.defineProperty(pausedRef, 'current', {
92
+ get: () => latest.current.paused ?? false,
93
+ })
94
+
95
+ mediaDevices
96
+ .getUserMedia({
97
+ video: { facingMode: props.facing === 'front' ? 'user' : 'environment' },
98
+ audio: false,
99
+ })
100
+ .then((s: MediaStream) => {
101
+ if (cancelled) {
102
+ s.getTracks().forEach((t) => t.stop())
103
+ return
104
+ }
105
+
106
+ stream = s
107
+ el.srcObject = s
108
+ el.play().catch(() => {})
109
+ schedule()
110
+ })
111
+ .catch((e: any) => {
112
+ latest.current.onError?.({ message: e?.message ?? 'camera unavailable' })
113
+ })
114
+
115
+ return () => {
116
+ cancelled = true
117
+ if (timer) {
118
+ clearTimeout(timer)
119
+ }
120
+
121
+ stream?.getTracks().forEach((t) => t.stop())
122
+ el.srcObject = null
123
+ }
124
+ }, [props.facing, JSON.stringify(props.formats)])
125
+
126
+ <video
127
+ ref={(el: HTMLVideoElement | null) => {
128
+ video.current = el
129
+ }}
130
+ muted
131
+ playsInline
132
+ style={props.style}
133
+ className={props.className}
134
+ />
116
135
  }
@@ -1,12 +1,178 @@
1
- // Barcode scanner — macOS leaf. Vision's VNDetectBarcodesRequest is
2
- // bridgeable but not wired; report unsupported rather than leaving a hole.
3
- import type { BarcodeScannerService, PermissionResult } from './types'
1
+ // Barcode scanner — macOS leaf. Still images decode through Vision's
2
+ // VNDetectBarcodesRequest; live camera scanning is not available on macOS,
3
+ // so ensure() reports 'unsupported'.
4
+ import {
5
+ CGImageGetHeight,
6
+ CGImageGetWidth,
7
+ NSImage,
8
+ NSURL,
9
+ VNDetectBarcodesRequest,
10
+ VNImageRequestHandler,
11
+ } from '@octane-xplat/platform/macos'
4
12
 
5
- export const barcodeScanner: BarcodeScannerService = {
6
- supported: false,
7
- ensure: async (): Promise<PermissionResult> => 'unsupported',
8
- scanImage: () => Promise.reject(new Error('unsupported: barcode scanning is not wired on macOS')),
13
+ import type { BarcodeFormat, BarcodeScannerService, PermissionResult, ScannedCode } from './types'
14
+
15
+ // String literals, not the bound constants — the generated metadata targets
16
+ // macOS 11 and omits VNBarcodeSymbologyCodabar.
17
+ const VISION_PREFIX = 'VNBarcodeSymbology'
18
+ const SYMBOLOGIES: Record<BarcodeFormat, readonly string[]> = {
19
+ qr: ['QR'],
20
+ ean13: ['EAN13'],
21
+ ean8: ['EAN8'],
22
+ upc_a: ['EAN13'],
23
+ upc_e: ['UPCE'],
24
+ code128: ['Code128'],
25
+ code39: ['Code39', 'Code39Checksum', 'Code39FullASCII', 'Code39FullASCIIChecksum'],
26
+ code93: ['Code93', 'Code93i'],
27
+ codabar: ['Codabar'],
28
+ itf: ['I2of5', 'I2of5Checksum', 'ITF14'],
29
+ datamatrix: ['DataMatrix'],
30
+ pdf417: ['PDF417'],
31
+ aztec: ['Aztec'],
32
+ }
33
+
34
+ // Vision → our vocabulary. EAN13 resolves to ean13; UPC-A is an EAN-13 with
35
+ // a leading 0 and is rewritten on the payload (see below).
36
+ const FORMATS: Record<string, string> = {}
37
+
38
+ for (const [format, names] of Object.entries(SYMBOLOGIES)) {
39
+ for (const name of names) {
40
+ FORMATS[VISION_PREFIX + name] ??= format
41
+ }
42
+ }
43
+
44
+ /** The deduplicated, prefixed union for the requested formats — every entry
45
+ * when `formats` is missing or empty, so results stay inside our vocabulary. */
46
+ function symbologiesFor(formats?: BarcodeFormat[]): string[] {
47
+ const wanted = formats?.length ? formats : (Object.keys(SYMBOLOGIES) as BarcodeFormat[])
48
+ const out = new Set<string>()
49
+
50
+ for (const format of wanted) {
51
+ for (const name of SYMBOLOGIES[format] ?? []) {
52
+ out.add(VISION_PREFIX + name)
53
+ }
54
+ }
55
+
56
+ return [...out]
9
57
  }
10
58
 
11
- const permissionOwners = ((globalThis as any).__xplatPermissionOwners ??= {})
12
- permissionOwners.camera = () => barcodeScanner.ensure()
59
+ /** request.results may be a JS array or an NSArray — count/objectAtIndex. */
60
+ function observations(results: any): any[] {
61
+ if (!results) {
62
+ return []
63
+ }
64
+
65
+ if (Array.isArray(results)) {
66
+ return results
67
+ }
68
+
69
+ const out: any[] = []
70
+
71
+ for (let i = 0, count = Number(results.count ?? 0); i < count; i++) {
72
+ out.push(results.objectAtIndex(i))
73
+ }
74
+
75
+ return out
76
+ }
77
+
78
+ /** Headless barcode service — permission + still-image decode. See BarcodeScannerService. */
79
+ export const barcodeScanner: BarcodeScannerService = {
80
+ supported: true,
81
+ ensure: async (): Promise<PermissionResult> => 'unsupported',
82
+ scanImage: async (image: unknown, formats?: BarcodeFormat[]): Promise<ScannedCode[]> => {
83
+ let source: any
84
+
85
+ if (typeof image === 'string' || (image != null && typeof (image as any).uri === 'string')) {
86
+ const input = typeof image === 'string' ? image : (image as any).uri
87
+
88
+ if (/^file:/i.test(input)) {
89
+ source = NSImage.alloc().initWithContentsOfURL(NSURL.URLWithString(input))
90
+ } else if (/^[a-z][a-z0-9+.-]*:/i.test(input)) {
91
+ throw new Error(
92
+ 'barcodeScanner.scanImage: macOS decodes local files; download remote images first',
93
+ )
94
+ } else {
95
+ source = NSImage.alloc().initWithContentsOfURL(NSURL.fileURLWithPath(input))
96
+ }
97
+ } else if (
98
+ image != null &&
99
+ typeof (image as any).CGImageForProposedRectContextHints === 'function'
100
+ ) {
101
+ source = image
102
+ } else {
103
+ throw new Error(
104
+ 'barcodeScanner.scanImage: expected a file path, file URL, {uri} ref, or NSImage',
105
+ )
106
+ }
107
+
108
+ const cg = source?.CGImageForProposedRectContextHints?.(null, null, null)
109
+
110
+ if (!cg) {
111
+ throw new Error('barcodeScanner.scanImage: could not read the image')
112
+ }
113
+
114
+ const request = VNDetectBarcodesRequest.alloc().init()
115
+
116
+ request.symbologies = symbologiesFor(formats)
117
+
118
+ const handler = VNImageRequestHandler.alloc().initWithCGImageOptions(cg, {})
119
+
120
+ if (!handler.performRequestsError([request], null)) {
121
+ throw new Error('barcodeScanner.scanImage: Vision could not process the image')
122
+ }
123
+
124
+ // Vision reports UPC-A as EAN-13 with a leading 0.
125
+ const wantsUpcA = !formats?.length || formats.includes('upc_a')
126
+ const wantsEan13 = !formats?.length || formats.includes('ean13')
127
+ const W = Number(CGImageGetWidth(cg))
128
+ const H = Number(CGImageGetHeight(cg))
129
+ const codes: ScannedCode[] = []
130
+
131
+ for (const observation of observations(request.results)) {
132
+ const symbology = String(observation?.symbology ?? '')
133
+ let type =
134
+ FORMATS[symbology] ??
135
+ (symbology.startsWith(VISION_PREFIX) ? symbology.slice(VISION_PREFIX.length) : symbology)
136
+
137
+ let data = String(observation?.payloadStringValue ?? '')
138
+
139
+ if (type === 'ean13') {
140
+ if (data.length === 13 && data.startsWith('0') && wantsUpcA) {
141
+ type = 'upc_a'
142
+ data = data.slice(1)
143
+ } else if (!wantsEan13) {
144
+ continue
145
+ }
146
+ }
147
+
148
+ const code: ScannedCode = { type, data }
149
+ const box = observation?.boundingBox
150
+
151
+ if (box) {
152
+ const ox = Number(box.origin?.x)
153
+ const oy = Number(box.origin?.y)
154
+ const width = Number(box.size?.width)
155
+ const height = Number(box.size?.height)
156
+
157
+ if (
158
+ Number.isFinite(ox) &&
159
+ Number.isFinite(oy) &&
160
+ Number.isFinite(width) &&
161
+ Number.isFinite(height)
162
+ ) {
163
+ // Vision bounds are normalized with a bottom-left origin.
164
+ code.bounds = {
165
+ x: ox * W,
166
+ y: (1 - oy - height) * H,
167
+ width: width * W,
168
+ height: height * H,
169
+ }
170
+ }
171
+ }
172
+
173
+ codes.push(code)
174
+ }
175
+
176
+ return codes
177
+ },
178
+ }
@@ -10,110 +10,131 @@ import { fromNativeFormat, toNativeFormats } from './format-map'
10
10
  let scanRequestCode = 7723
11
11
 
12
12
  async function ensure(): Promise<PermissionResult> {
13
- try {
14
- if (Application.ios) {
15
- const av = (globalThis as any).AVCaptureDevice
16
- const video = (globalThis as any).AVMediaTypeVideo
17
- // 0=notDetermined 1=restricted 2=denied 3=authorized
18
- const status = av?.authorizationStatusForMediaType?.(video)
19
- if (status === 3) {
20
- return 'granted'
21
- }
22
- if (status === 1 || status === 2) {
23
- return 'denied'
24
- }
25
- if (typeof av?.requestAccessForMediaTypeCompletionHandler !== 'function') {
26
- return 'unsupported'
27
- }
28
- return await new Promise<PermissionResult>((resolve) => {
29
- av.requestAccessForMediaTypeCompletionHandler(video, (granted: boolean) =>
30
- resolve(granted ? 'granted' : 'denied'),
31
- )
32
- })
33
- }
34
-
35
- const perm = 'android.permission.CAMERA'
36
- const activity = Application.android.foregroundActivity ?? Application.android.startActivity
37
- if (
38
- activity?.checkSelfPermission?.(perm) === android.content.pm.PackageManager.PERMISSION_GRANTED
39
- ) {
40
- return 'granted'
41
- }
42
- if (!activity) {
43
- return 'denied'
44
- }
45
- return await new Promise<PermissionResult>((resolve) => {
46
- const requestCode = scanRequestCode++
47
- const event = Application.android.activityRequestPermissionsEvent
48
- const onResult = (args: any) => {
49
- if (args.requestCode !== requestCode) {
50
- return
51
- }
52
- Application.android.off(event, onResult)
53
- resolve(
54
- args.grantResults?.[0] === android.content.pm.PackageManager.PERMISSION_GRANTED
55
- ? 'granted'
56
- : 'denied',
57
- )
58
- }
59
- Application.android.on(event, onResult)
60
- try {
61
- activity.requestPermissions([perm], requestCode)
62
- } catch {
63
- Application.android.off(event, onResult)
64
- resolve('denied')
65
- }
66
- })
67
- } catch {
68
- return 'denied'
69
- }
13
+ try {
14
+ if (Application.ios) {
15
+ const av = (globalThis as any).AVCaptureDevice
16
+ const video = (globalThis as any).AVMediaTypeVideo
17
+ // 0=notDetermined 1=restricted 2=denied 3=authorized
18
+ const status = av?.authorizationStatusForMediaType?.(video)
19
+
20
+ if (status === 3) {
21
+ return 'granted'
22
+ }
23
+
24
+ if (status === 1 || status === 2) {
25
+ return 'denied'
26
+ }
27
+
28
+ if (typeof av?.requestAccessForMediaTypeCompletionHandler !== 'function') {
29
+ return 'unsupported'
30
+ }
31
+
32
+ return await new Promise<PermissionResult>((resolve) => {
33
+ av.requestAccessForMediaTypeCompletionHandler(video, (granted: boolean) =>
34
+ resolve(granted ? 'granted' : 'denied'),
35
+ )
36
+ })
37
+ }
38
+
39
+ const perm = 'android.permission.CAMERA'
40
+ const activity = Application.android.foregroundActivity ?? Application.android.startActivity
41
+
42
+ if (
43
+ activity?.checkSelfPermission?.(perm) === android.content.pm.PackageManager.PERMISSION_GRANTED
44
+ ) {
45
+ return 'granted'
46
+ }
47
+
48
+ if (!activity) {
49
+ return 'denied'
50
+ }
51
+
52
+ return await new Promise<PermissionResult>((resolve) => {
53
+ const requestCode = scanRequestCode++
54
+ const event = Application.android.activityRequestPermissionsEvent
55
+ const onResult = (args: any) => {
56
+ if (args.requestCode !== requestCode) {
57
+ return
58
+ }
59
+
60
+ Application.android.off(event, onResult)
61
+ resolve(
62
+ args.grantResults?.[0] === android.content.pm.PackageManager.PERMISSION_GRANTED
63
+ ? 'granted'
64
+ : 'denied',
65
+ )
66
+ }
67
+
68
+ Application.android.on(event, onResult)
69
+ try {
70
+ activity.requestPermissions([perm], requestCode)
71
+ } catch {
72
+ Application.android.off(event, onResult)
73
+ resolve('denied')
74
+ }
75
+ })
76
+ } catch {
77
+ return 'denied'
78
+ }
70
79
  }
71
80
 
72
81
  async function toImageSource(image: unknown): Promise<any> {
73
- if (image instanceof ImageSource) {
74
- return image
75
- }
76
- if (typeof image === 'string') {
77
- return ImageSource.fromFile(image)
78
- }
79
- if (image && typeof (image as { uri?: string }).uri === 'string') {
80
- return ImageSource.fromFile((image as { uri: string }).uri)
81
- }
82
- throw new Error('barcodeScanner.scanImage: expected an ImageSource, file path, or {uri} ref')
82
+ if (image instanceof ImageSource) {
83
+ return image
84
+ }
85
+
86
+ if (typeof image === 'string') {
87
+ return ImageSource.fromFile(image)
88
+ }
89
+
90
+ if (
91
+ typeof image === 'object' &&
92
+ image !== null &&
93
+ 'uri' in image &&
94
+ typeof image.uri === 'string'
95
+ ) {
96
+ return ImageSource.fromFile(image.uri)
97
+ }
98
+
99
+ throw new Error('barcodeScanner.scanImage: expected an ImageSource, file path, or {uri} ref')
83
100
  }
84
101
 
102
+ /** Headless barcode service — permission + still-image decode. See BarcodeScannerService. */
85
103
  export const barcodeScanner: BarcodeScannerService = {
86
- supported: true,
87
-
88
- ensure,
89
-
90
- async scanImage(image: unknown, formats?: BarcodeFormat[]): Promise<ScannedCode[]> {
91
- const source = await toImageSource(image)
92
- const result = await detectWithStillImage(source, {
93
- detectorType: DetectionType.Barcode,
94
- barcodeScanning: { barcodeFormat: toNativeFormats(formats) as [any] },
95
- })
96
- const list = Array.isArray(result) ? result : Object.values(result ?? {})
97
- return list
98
- .flat()
99
- .filter((item: any) => item && (item.rawValue !== undefined || item.format !== undefined))
100
- .map((item: any) => ({
101
- type: fromNativeFormat(item.format),
102
- data: String(item.rawValue ?? item.displayValue ?? ''),
103
- bounds: item.bounds
104
- ? {
105
- x: item.bounds.origin?.x ?? item.bounds.x ?? 0,
106
- y: item.bounds.origin?.y ?? item.bounds.y ?? 0,
107
- width: item.bounds.size?.width ?? item.bounds.width ?? 0,
108
- height: item.bounds.size?.height ?? item.bounds.height ?? 0,
109
- }
110
- : undefined,
111
- }))
112
- },
104
+ supported: true,
105
+
106
+ ensure,
107
+
108
+ async scanImage(image: unknown, formats?: BarcodeFormat[]): Promise<ScannedCode[]> {
109
+ const source = await toImageSource(image)
110
+ const result = await detectWithStillImage(source, {
111
+ detectorType: DetectionType.Barcode,
112
+ barcodeScanning: { barcodeFormat: toNativeFormats(formats) as [any] },
113
+ })
114
+
115
+ const list = Array.isArray(result) ? result : Object.values(result ?? {})
116
+
117
+ return list
118
+ .flat()
119
+ .filter((item: any) => item && (item.rawValue !== undefined || item.format !== undefined))
120
+ .map((item: any) => ({
121
+ type: fromNativeFormat(item.format),
122
+ data: String(item.rawValue ?? item.displayValue ?? ''),
123
+ bounds: item.bounds
124
+ ? {
125
+ x: item.bounds.origin?.x ?? item.bounds.x ?? 0,
126
+ y: item.bounds.origin?.y ?? item.bounds.y ?? 0,
127
+ width: item.bounds.size?.width ?? item.bounds.width ?? 0,
128
+ height: item.bounds.size?.height ?? item.bounds.height ?? 0,
129
+ }
130
+ : undefined,
131
+ }))
132
+ },
113
133
  }
114
134
 
115
135
  // Scanning needs camera access — register the kind this leaf owns for the
116
136
  // platform dispatcher (same 'camera' kind media registers; both leafs' owners
117
137
  // run identical ensure logic, and the leaf must work with media absent).
118
138
  const permissionOwners = ((globalThis as any).__xplatPermissionOwners ??= {})
139
+
119
140
  permissionOwners.camera = () => barcodeScanner.ensure()