scandit-react-native-datacapture-core 8.4.1 → 8.5.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/THIRD_PARTY.txt +0 -5
- package/android/build.gradle +3 -3
- package/android/generated/jni/CMakeLists.txt +21 -1
- package/dist/core.js +1581 -1545
- package/dist/core.js.map +1 -1
- package/dist/dts/hooks/ScanditProvider.d.ts +46 -0
- package/dist/dts/hooks/index.d.ts +5 -0
- package/dist/dts/hooks/useCameraPermission.d.ts +28 -0
- package/dist/dts/hooks/useIsForeground.d.ts +11 -0
- package/dist/dts/hooks/useScanditContext.d.ts +21 -0
- package/dist/dts/index.d.ts +4 -0
- package/dist/dts/native/ScanditNativeModule.d.ts +1 -1
- package/dist/dts/private/hooks/useMode.d.ts +49 -0
- package/dist/dts/private/hooks/useModeListener.d.ts +40 -0
- package/dist/dts/private/hooks/useNativeControl.d.ts +14 -0
- package/dist/dts/private/hooks/useOverlay.d.ts +68 -0
- package/dist/dts/private/hooks/useStableProp.d.ts +22 -0
- package/dist/dts/private/hooks/useViewHandle.d.ts +41 -0
- package/dist/dts/private/index.d.ts +11 -0
- package/dist/index.js +737 -6
- package/dist/index.js.flow +4 -0
- package/dist/index.js.map +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/package.json +2 -2
- package/scandit-react-native-datacapture-core.podspec +1 -1
- package/specs/NativeScanditDataCaptureCore.ts +2 -3
- package/specs/RNTDataCaptureViewNativeComponent.ts +1 -4
- package/THIRD_PARTY_ID.txt +0 -545
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { CORE_PROXY_TYPE_NAMES, registerCoreProxies, loadCoreDefaults, setCoreDefaultsLoader, BaseDataCaptureView } from './core.js';
|
|
2
|
-
export { AimerViewfinder, Anchor, Brush,
|
|
3
|
-
import { NativeEventEmitter, Platform, NativeModules, TurboModuleRegistry, findNodeHandle, requireNativeComponent } from 'react-native';
|
|
4
|
-
import React from 'react';
|
|
1
|
+
import { CORE_PROXY_TYPE_NAMES, registerCoreProxies, loadCoreDefaults, setCoreDefaultsLoader, BaseDataCaptureView, DataCaptureContext, TorchState, CameraPosition, FrameSourceState, Camera } from './core.js';
|
|
2
|
+
export { AimerViewfinder, Anchor, Brush, CameraSettings, ClusteringMode, Color, ContextStatus, DataCaptureContextSettings, Direction, Expiration, Feedback, FocusGestureStrategy, FocusRange, FontFamily, FrameDataSettings, FrameDataSettingsBuilder, ImageBuffer, ImageFrameSource, LaserlineViewfinder, LicenseInfo, LogoStyle, MacroMode, MarginsWithUnit, MeasureUnit, NoViewfinder, NoneLocationSelection, NumberWithUnit, OpenSourceSoftwareLicenseInfo, Orientation, PinchToZoom, Point, PointWithUnit, Quadrilateral, RadiusLocationSelection, Rect, RectWithUnit, RectangularLocationSelection, RectangularViewfinder, RectangularViewfinderAnimation, RectangularViewfinderLineStyle, RectangularViewfinderStyle, ScanIntention, ScanditIcon, ScanditIconBuilder, ScanditIconShape, ScanditIconType, SelectionMode, Size, SizeWithAspect, SizeWithUnit, SizeWithUnitAndAspect, SizingMode, Sound, SwipeToZoom, TapToFocus, TextAlignment, TorchSwitchControl, Vibration, VideoResolution, WaveFormVibration, ZoomSwitchControl, ZoomSwitchOrientation } from './core.js';
|
|
3
|
+
import { NativeEventEmitter, Platform, NativeModules, TurboModuleRegistry, findNodeHandle, requireNativeComponent, AppState, PermissionsAndroid } from 'react-native';
|
|
4
|
+
import React, { useState, useEffect, useCallback, useMemo, createContext, useContext, useRef } from 'react';
|
|
5
5
|
|
|
6
6
|
class RNNativeCaller {
|
|
7
7
|
nativeModule;
|
|
@@ -138,7 +138,7 @@ setCoreDefaultsLoader(initCoreDefaults);
|
|
|
138
138
|
const NativeModule = getNativeModule('ScanditDataCaptureCore');
|
|
139
139
|
class DataCaptureVersion {
|
|
140
140
|
static get pluginVersion() {
|
|
141
|
-
return '8.
|
|
141
|
+
return '8.5.0';
|
|
142
142
|
}
|
|
143
143
|
static get sdkVersion() {
|
|
144
144
|
return NativeModule.Version;
|
|
@@ -279,8 +279,739 @@ class DataCaptureView extends React.Component {
|
|
|
279
279
|
}
|
|
280
280
|
const RNTDataCaptureView = requireNativeComponent('RNTDataCaptureView');
|
|
281
281
|
|
|
282
|
+
/**
|
|
283
|
+
* Returns whether the app is currently in the foreground.
|
|
284
|
+
* Useful for composing the `isActive` prop on scanning views:
|
|
285
|
+
*
|
|
286
|
+
* ```tsx
|
|
287
|
+
* const isForeground = useIsForeground();
|
|
288
|
+
* const isFocused = useIsFocused(); // from @react-navigation/native
|
|
289
|
+
* <BarcodeCaptureView isActive={isFocused && isForeground} ... />
|
|
290
|
+
* ```
|
|
291
|
+
*/
|
|
292
|
+
function useIsForeground() {
|
|
293
|
+
const [isForeground, setIsForeground] = useState(() => AppState.currentState === 'active');
|
|
294
|
+
useEffect(() => {
|
|
295
|
+
const onChange = (state) => {
|
|
296
|
+
setIsForeground(state === 'active');
|
|
297
|
+
};
|
|
298
|
+
const subscription = AppState.addEventListener('change', onChange);
|
|
299
|
+
return () => subscription.remove();
|
|
300
|
+
}, []);
|
|
301
|
+
return isForeground;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
function mapAndroidResult(result) {
|
|
305
|
+
switch (result) {
|
|
306
|
+
case PermissionsAndroid.RESULTS.GRANTED:
|
|
307
|
+
return 'granted';
|
|
308
|
+
case PermissionsAndroid.RESULTS.DENIED:
|
|
309
|
+
return 'denied';
|
|
310
|
+
case PermissionsAndroid.RESULTS.NEVER_ASK_AGAIN:
|
|
311
|
+
return 'restricted';
|
|
312
|
+
default:
|
|
313
|
+
return 'not-determined';
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
async function checkAndroidPermission() {
|
|
317
|
+
const granted = await PermissionsAndroid.check(PermissionsAndroid.PERMISSIONS.CAMERA);
|
|
318
|
+
return granted ? 'granted' : 'not-determined';
|
|
319
|
+
}
|
|
320
|
+
async function requestAndroidPermission() {
|
|
321
|
+
const result = await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.CAMERA);
|
|
322
|
+
return mapAndroidResult(result);
|
|
323
|
+
}
|
|
324
|
+
/**
|
|
325
|
+
* Manages camera permission status.
|
|
326
|
+
*
|
|
327
|
+
* **Android**: real status via `PermissionsAndroid`; `requestPermission()` shows the native
|
|
328
|
+
* prompt; status re-checked when the app returns to the foreground (e.g. user flipped it
|
|
329
|
+
* in Settings).
|
|
330
|
+
*
|
|
331
|
+
* **iOS**: limited. Without a platform-specific native module we can't query
|
|
332
|
+
* `AVCaptureDevice.authorizationStatus` or drive the system prompt directly — iOS
|
|
333
|
+
* handles the permission dialog automatically the first time the camera is accessed.
|
|
334
|
+
* On iOS this hook returns `permissionStatus: 'not-determined'` initially and
|
|
335
|
+
* optimistically flips to `'granted'` after `requestPermission()` is called.
|
|
336
|
+
* It cannot detect denials after-the-fact; consumers should treat the iOS camera-start
|
|
337
|
+
* flow as the authoritative signal (surfaced via `<BarcodeCaptureView onError={...} />`).
|
|
338
|
+
*
|
|
339
|
+
* ```tsx
|
|
340
|
+
* const { hasPermission, requestPermission } = useCameraPermission();
|
|
341
|
+
* if (!hasPermission) return <Button onPress={requestPermission} title="Grant Camera Access" />;
|
|
342
|
+
* ```
|
|
343
|
+
*/
|
|
344
|
+
function useCameraPermission() {
|
|
345
|
+
const [status, setStatus] = useState(Platform.OS === 'android' ? 'not-determined' : 'not-determined');
|
|
346
|
+
const refresh = useCallback(async () => {
|
|
347
|
+
if (Platform.OS !== 'android')
|
|
348
|
+
return;
|
|
349
|
+
setStatus(await checkAndroidPermission());
|
|
350
|
+
}, []);
|
|
351
|
+
useEffect(() => {
|
|
352
|
+
void refresh();
|
|
353
|
+
}, [refresh]);
|
|
354
|
+
// Re-check when returning from Settings (Android only — iOS can't be introspected).
|
|
355
|
+
useEffect(() => {
|
|
356
|
+
if (Platform.OS !== 'android')
|
|
357
|
+
return;
|
|
358
|
+
const onChange = (state) => {
|
|
359
|
+
if (state === 'active') {
|
|
360
|
+
void refresh();
|
|
361
|
+
}
|
|
362
|
+
};
|
|
363
|
+
const subscription = AppState.addEventListener('change', onChange);
|
|
364
|
+
return () => subscription.remove();
|
|
365
|
+
}, [refresh]);
|
|
366
|
+
const requestPermission = useCallback(async () => {
|
|
367
|
+
if (Platform.OS === 'android') {
|
|
368
|
+
const result = await requestAndroidPermission();
|
|
369
|
+
setStatus(result);
|
|
370
|
+
return result === 'granted';
|
|
371
|
+
}
|
|
372
|
+
// iOS: we can't drive the prompt from JS. Flip optimistically to 'granted';
|
|
373
|
+
// the native camera access triggers the iOS dialog automatically, and denial
|
|
374
|
+
// surfaces as a camera-start failure (hook into `BarcodeCaptureView.onError`).
|
|
375
|
+
setStatus('granted');
|
|
376
|
+
return true;
|
|
377
|
+
}, []);
|
|
378
|
+
return {
|
|
379
|
+
hasPermission: status === 'granted',
|
|
380
|
+
permissionStatus: status,
|
|
381
|
+
requestPermission,
|
|
382
|
+
};
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
/**
|
|
386
|
+
* Initializes (or retrieves) the DataCaptureContext singleton.
|
|
387
|
+
*
|
|
388
|
+
* ```tsx
|
|
389
|
+
* const settings = useMemo(() => new DataCaptureContextSettings(), []);
|
|
390
|
+
* const context = useScanditContext('YOUR_LICENSE_KEY', { settings });
|
|
391
|
+
* ```
|
|
392
|
+
*/
|
|
393
|
+
function useScanditContext(licenseKey, options) {
|
|
394
|
+
const context = useMemo(() => DataCaptureContext.initialize(licenseKey, options?.creationOptions ?? null, options?.settings ?? null),
|
|
395
|
+
// The context is a singleton; init runs once per license key. `settings`
|
|
396
|
+
// and `creationOptions` are intentionally excluded — settings are pushed
|
|
397
|
+
// by the effect below, creationOptions are init-only.
|
|
398
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
399
|
+
[licenseKey]);
|
|
400
|
+
// Re-apply settings whenever the consumer hands us a new instance. The
|
|
401
|
+
// first call here is redundant with the init above (same instance) — it's
|
|
402
|
+
// a no-op in native. Subsequent changes propagate to the running context.
|
|
403
|
+
useEffect(() => {
|
|
404
|
+
if (options?.settings)
|
|
405
|
+
void context.applySettings(options.settings);
|
|
406
|
+
}, [context, options?.settings]);
|
|
407
|
+
return context;
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
const DEFAULT_TORCH = TorchState.Off;
|
|
411
|
+
const DEFAULT_POSITION = CameraPosition.WorldFacing;
|
|
412
|
+
const DEFAULT_FRAME_SOURCE_STATE = FrameSourceState.On;
|
|
413
|
+
function createCameraOwner(context) {
|
|
414
|
+
let camera = null;
|
|
415
|
+
let position = null;
|
|
416
|
+
let desiredTorch = DEFAULT_TORCH;
|
|
417
|
+
let desiredState = DEFAULT_FRAME_SOURCE_STATE;
|
|
418
|
+
let queue = Promise.resolve();
|
|
419
|
+
const enqueue = (op) => {
|
|
420
|
+
queue = queue.then(op).catch(err => console.warn('ScanditProvider: camera operation failed', err));
|
|
421
|
+
return queue;
|
|
422
|
+
};
|
|
423
|
+
// `Camera.atPosition` is a process-wide singleton, so any other
|
|
424
|
+
// DataCaptureContext can grab it via `setFrameSource(...)` while we're idle.
|
|
425
|
+
// Rebind only when the camera isn't ours anymore — otherwise a no-op.
|
|
426
|
+
const isOurs = (cam) => cam.context === context;
|
|
427
|
+
// Bind `camera` to our context and push our cached desired state.
|
|
428
|
+
// Used after a fresh `Camera.atPosition(...)` and to reclaim a stolen camera.
|
|
429
|
+
const bind = async () => {
|
|
430
|
+
if (camera === null)
|
|
431
|
+
return;
|
|
432
|
+
camera.desiredTorchState = desiredTorch;
|
|
433
|
+
await context.setFrameSource(camera);
|
|
434
|
+
await camera.switchToDesiredState(desiredState);
|
|
435
|
+
};
|
|
436
|
+
const reclaimIfNeeded = async () => {
|
|
437
|
+
if (camera !== null && !isOurs(camera))
|
|
438
|
+
await bind();
|
|
439
|
+
};
|
|
440
|
+
return {
|
|
441
|
+
setPosition(next) {
|
|
442
|
+
void enqueue(async () => {
|
|
443
|
+
if (camera !== null && position === next) {
|
|
444
|
+
await reclaimIfNeeded();
|
|
445
|
+
return;
|
|
446
|
+
}
|
|
447
|
+
if (camera !== null)
|
|
448
|
+
await camera.switchToDesiredState(FrameSourceState.Off);
|
|
449
|
+
camera = Camera.atPosition(next);
|
|
450
|
+
position = next;
|
|
451
|
+
await bind();
|
|
452
|
+
});
|
|
453
|
+
},
|
|
454
|
+
setTorch(next) {
|
|
455
|
+
void enqueue(async () => {
|
|
456
|
+
desiredTorch = next;
|
|
457
|
+
await reclaimIfNeeded();
|
|
458
|
+
if (camera !== null)
|
|
459
|
+
camera.desiredTorchState = next;
|
|
460
|
+
});
|
|
461
|
+
},
|
|
462
|
+
setFrameSourceState(next) {
|
|
463
|
+
void enqueue(async () => {
|
|
464
|
+
desiredState = next;
|
|
465
|
+
await reclaimIfNeeded();
|
|
466
|
+
if (camera !== null)
|
|
467
|
+
await camera.switchToDesiredState(next);
|
|
468
|
+
});
|
|
469
|
+
},
|
|
470
|
+
reclaimIfNeeded() {
|
|
471
|
+
void enqueue(reclaimIfNeeded);
|
|
472
|
+
},
|
|
473
|
+
dispose() {
|
|
474
|
+
return enqueue(async () => {
|
|
475
|
+
const cam = camera;
|
|
476
|
+
camera = null;
|
|
477
|
+
// Skip `setFrameSource(null)` if we don't own the camera — it would
|
|
478
|
+
// yank it away from whichever context holds it now.
|
|
479
|
+
if (cam !== null && isOurs(cam)) {
|
|
480
|
+
await cam.switchToDesiredState(FrameSourceState.Off);
|
|
481
|
+
await context.setFrameSource(null);
|
|
482
|
+
}
|
|
483
|
+
await context.dispose();
|
|
484
|
+
});
|
|
485
|
+
},
|
|
486
|
+
};
|
|
487
|
+
}
|
|
488
|
+
const ScanditInternalContext = createContext(null);
|
|
489
|
+
/** Reflects a provider's camera-related props onto the singleton camera. */
|
|
490
|
+
function useApplyCameraProps(owner, props) {
|
|
491
|
+
const { frameSourceState, torchState, cameraPosition } = props;
|
|
492
|
+
useEffect(() => {
|
|
493
|
+
if (cameraPosition !== undefined)
|
|
494
|
+
owner.setPosition(cameraPosition);
|
|
495
|
+
}, [owner, cameraPosition]);
|
|
496
|
+
useEffect(() => {
|
|
497
|
+
if (torchState !== undefined)
|
|
498
|
+
owner.setTorch(torchState);
|
|
499
|
+
}, [owner, torchState]);
|
|
500
|
+
useEffect(() => {
|
|
501
|
+
if (frameSourceState !== undefined)
|
|
502
|
+
owner.setFrameSourceState(frameSourceState);
|
|
503
|
+
}, [owner, frameSourceState]);
|
|
504
|
+
}
|
|
505
|
+
/**
|
|
506
|
+
* Provides a `DataCaptureContext` and a singleton `Camera` to descendant AIO views.
|
|
507
|
+
*
|
|
508
|
+
* - **Root** (no parent `<ScanditProvider>` above): creates the context + camera,
|
|
509
|
+
* disposes them on unmount.
|
|
510
|
+
* - **Nested**: applies its own `frameSourceState` / `torchState` / `cameraPosition`
|
|
511
|
+
* props to the same singleton camera. Last writer wins; values are not reverted
|
|
512
|
+
* when a nested provider unmounts.
|
|
513
|
+
*
|
|
514
|
+
* The camera is recreated only when `cameraPosition` flips; torch and
|
|
515
|
+
* `frameSourceState` are applied directly to the live camera.
|
|
516
|
+
*
|
|
517
|
+
* ```tsx
|
|
518
|
+
* <ScanditProvider licenseKey={KEY}>
|
|
519
|
+
* <NavigationContainer> ... </NavigationContainer>
|
|
520
|
+
* </ScanditProvider>
|
|
521
|
+
*
|
|
522
|
+
* // Screen-local control:
|
|
523
|
+
* <ScanditProvider
|
|
524
|
+
* frameSourceState={isFocused ? FrameSourceState.On : FrameSourceState.Off}
|
|
525
|
+
* torchState={torch}
|
|
526
|
+
* cameraPosition={position}>
|
|
527
|
+
* <BarcodeCaptureView state="enabled" ... />
|
|
528
|
+
* </ScanditProvider>
|
|
529
|
+
* ```
|
|
530
|
+
*/
|
|
531
|
+
function ScanditProvider(props) {
|
|
532
|
+
const parent = useContext(ScanditInternalContext);
|
|
533
|
+
if (parent !== null) {
|
|
534
|
+
return React.createElement(NestedScanditProvider, { ...props, parent: parent });
|
|
535
|
+
}
|
|
536
|
+
if (!props.licenseKey) {
|
|
537
|
+
throw new Error('<ScanditProvider> requires a `licenseKey` prop when used as the root provider.');
|
|
538
|
+
}
|
|
539
|
+
return React.createElement(RootScanditProvider, { ...props, licenseKey: props.licenseKey });
|
|
540
|
+
}
|
|
541
|
+
function NestedScanditProvider({ parent, frameSourceState, torchState, cameraPosition, licenseKey, settings, options, children, }) {
|
|
542
|
+
if (licenseKey || settings || options) {
|
|
543
|
+
console.warn('ScanditProvider: licenseKey/settings/options are ignored on nested providers.');
|
|
544
|
+
}
|
|
545
|
+
useApplyCameraProps(parent.owner, { frameSourceState, torchState, cameraPosition });
|
|
546
|
+
return React.createElement(ScanditInternalContext.Provider, { value: parent }, children);
|
|
547
|
+
}
|
|
548
|
+
function RootScanditProvider({ licenseKey, options, settings, frameSourceState, torchState, cameraPosition, children, }) {
|
|
549
|
+
const context = useMemo(() => DataCaptureContext.initialize(licenseKey, options ?? null, settings ?? null),
|
|
550
|
+
// The context is a singleton keyed on licenseKey.
|
|
551
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
552
|
+
[licenseKey]);
|
|
553
|
+
const owner = useMemo(() => createCameraOwner(context), [context]);
|
|
554
|
+
// Apply our own props to the singleton, falling back to defaults so the
|
|
555
|
+
// camera is always created and in a known state.
|
|
556
|
+
useApplyCameraProps(owner, {
|
|
557
|
+
frameSourceState: frameSourceState ?? DEFAULT_FRAME_SOURCE_STATE,
|
|
558
|
+
torchState: torchState ?? DEFAULT_TORCH,
|
|
559
|
+
cameraPosition: cameraPosition ?? DEFAULT_POSITION,
|
|
560
|
+
});
|
|
561
|
+
// Dispose context + camera on unmount. Chained onto the owner's queue so
|
|
562
|
+
// any in-flight mutation finishes first.
|
|
563
|
+
useEffect(() => {
|
|
564
|
+
return () => {
|
|
565
|
+
void owner.dispose();
|
|
566
|
+
};
|
|
567
|
+
}, [owner]);
|
|
568
|
+
const internal = useMemo(() => ({ context, owner }), [context, owner]);
|
|
569
|
+
return React.createElement(ScanditInternalContext.Provider, { value: internal }, children);
|
|
570
|
+
}
|
|
571
|
+
// ─── Internal hook consumed by AIO view packages ─────────────────────────────
|
|
572
|
+
/** Internal — used by AIO views to attach modes to the shared context. */
|
|
573
|
+
function useDataCaptureContextInternal() {
|
|
574
|
+
const internal = useContext(ScanditInternalContext);
|
|
575
|
+
if (!internal) {
|
|
576
|
+
throw new Error('This component must be rendered inside a <ScanditProvider>.');
|
|
577
|
+
}
|
|
578
|
+
// Reclaim the singleton camera on (re)mount: anything else in the app that
|
|
579
|
+
// touched `Camera.atPosition` while we were unmounted may have stolen it.
|
|
580
|
+
useEffect(() => internal.owner.reclaimIfNeeded(), [internal]);
|
|
581
|
+
return internal.context;
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
function isSerializable(v) {
|
|
585
|
+
return typeof v === 'object' && v !== null && typeof v.toJson === 'function';
|
|
586
|
+
}
|
|
587
|
+
function signature(v) {
|
|
588
|
+
try {
|
|
589
|
+
return JSON.stringify(isSerializable(v) ? v.toJson() : v) ?? '';
|
|
590
|
+
}
|
|
591
|
+
catch {
|
|
592
|
+
// Cyclic / un-serializable values fall through to `''` so the caller sees
|
|
593
|
+
// a "changed" signature and uses the new value. Better safe than wrong.
|
|
594
|
+
return '';
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
/**
|
|
598
|
+
* Returns a referentially-stable copy of `value` as long as the structural
|
|
599
|
+
* content stays the same. Lets consumers pass inline SDK class instances
|
|
600
|
+
* (`new Brush(...)`, `new TorchSwitchControl()`) or plain options objects
|
|
601
|
+
* without memoizing — the effect deps array sees the same reference until
|
|
602
|
+
* the underlying content actually changes.
|
|
603
|
+
*
|
|
604
|
+
* SDK classes that extend `DefaultSerializeable` are compared via their
|
|
605
|
+
* `toJson()` output (which respects `@ignoreFromSerialization`), so private
|
|
606
|
+
* back-refs like `view` don't cause spurious diffs. Plain objects and arrays
|
|
607
|
+
* are compared via direct `JSON.stringify`.
|
|
608
|
+
*
|
|
609
|
+
* ```tsx
|
|
610
|
+
* function MyView({ brush }: { brush?: Brush | null }) {
|
|
611
|
+
* const stableBrush = useStableProp(brush);
|
|
612
|
+
* useEffect(() => {
|
|
613
|
+
* if (stableBrush) overlay.brush = stableBrush;
|
|
614
|
+
* }, [stableBrush]);
|
|
615
|
+
* }
|
|
616
|
+
* ```
|
|
617
|
+
*/
|
|
618
|
+
function useStableProp(value) {
|
|
619
|
+
const ref = useRef(null);
|
|
620
|
+
const sig = signature(value);
|
|
621
|
+
if (ref.current && ref.current.sig === sig)
|
|
622
|
+
return ref.current.value;
|
|
623
|
+
ref.current = { value, sig };
|
|
624
|
+
return value;
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
/**
|
|
628
|
+
* Registers a listener on a Scandit mode or view and keeps it up to date.
|
|
629
|
+
*
|
|
630
|
+
* Pass `listenerFns` with the callbacks you care about and leave the rest
|
|
631
|
+
* `undefined`. The hook only registers when `mode` is non-null and at least
|
|
632
|
+
* one callback is set; it unregisters automatically on unmount or when those
|
|
633
|
+
* conditions stop being true.
|
|
634
|
+
*
|
|
635
|
+
* The proxy installed on the target contains methods **only for keys whose
|
|
636
|
+
* values are currently defined**. This matters because some shared
|
|
637
|
+
* controllers do `if (listener.foo)` truthy checks (e.g.
|
|
638
|
+
* `BarcodeBatchBasicOverlayController.handleBrushForTrackedBarcode`) and a
|
|
639
|
+
* proxy method that returns `undefined` is interpreted as a real `null`
|
|
640
|
+
* response by the bridge — which wipes the configured default brush. When
|
|
641
|
+
* the set of defined keys changes (a callback flips between defined and
|
|
642
|
+
* undefined across renders), the proxy is rebuilt and the listener is
|
|
643
|
+
* unregistered + re-registered.
|
|
644
|
+
*
|
|
645
|
+
* Inline functions are fine — within the "defined" set, the registered
|
|
646
|
+
* listener is a stable proxy that always dispatches to the latest version of
|
|
647
|
+
* each callback without re-registering.
|
|
648
|
+
*
|
|
649
|
+
* ```tsx
|
|
650
|
+
* useModeListener<BarcodeCapture, BarcodeCaptureListener>({
|
|
651
|
+
* mode,
|
|
652
|
+
* listenerFns: {
|
|
653
|
+
* didScan: onScan ? async (_c, session, getFD) => onScan(session, getFD) : undefined,
|
|
654
|
+
* },
|
|
655
|
+
* addListener: (m, l) => m.addListener(l),
|
|
656
|
+
* removeListener: (m, l) => m.removeListener(l),
|
|
657
|
+
* });
|
|
658
|
+
* ```
|
|
659
|
+
*/
|
|
660
|
+
function useModeListener({ mode, listenerFns, addListener, removeListener, }) {
|
|
661
|
+
const definedKeysSig = currentDefinedKeysSig(listenerFns);
|
|
662
|
+
const isActive = mode != null && definedKeysSig !== '';
|
|
663
|
+
const listenerRef = useRef(listenerFns);
|
|
664
|
+
listenerRef.current = listenerFns;
|
|
665
|
+
const addRef = useRef(addListener);
|
|
666
|
+
addRef.current = addListener;
|
|
667
|
+
const removeRef = useRef(removeListener);
|
|
668
|
+
removeRef.current = removeListener;
|
|
669
|
+
// Rebuild the proxy whenever the set of defined keys changes. Within the
|
|
670
|
+
// same set, callback-identity changes are absorbed via `listenerRef`.
|
|
671
|
+
const stableListenerRef = useRef(null);
|
|
672
|
+
const stableListenerSigRef = useRef('');
|
|
673
|
+
if (definedKeysSig !== stableListenerSigRef.current) {
|
|
674
|
+
stableListenerSigRef.current = definedKeysSig;
|
|
675
|
+
if (definedKeysSig === '') {
|
|
676
|
+
stableListenerRef.current = null;
|
|
677
|
+
}
|
|
678
|
+
else {
|
|
679
|
+
const proxy = {};
|
|
680
|
+
for (const key of definedKeysSig.split(',')) {
|
|
681
|
+
proxy[key] = (...args) => listenerRef.current[key]?.(...args);
|
|
682
|
+
}
|
|
683
|
+
stableListenerRef.current = proxy;
|
|
684
|
+
}
|
|
685
|
+
}
|
|
686
|
+
useEffect(() => {
|
|
687
|
+
if (!isActive)
|
|
688
|
+
return;
|
|
689
|
+
const proxy = stableListenerRef.current;
|
|
690
|
+
if (!proxy)
|
|
691
|
+
return;
|
|
692
|
+
addRef.current(mode, proxy);
|
|
693
|
+
return () => removeRef.current(mode, proxy);
|
|
694
|
+
// The proxy identity changes only when `definedKeysSig` changes, which is
|
|
695
|
+
// already in the deps.
|
|
696
|
+
}, [mode, isActive, definedKeysSig]);
|
|
697
|
+
}
|
|
698
|
+
function currentDefinedKeysSig(listenerFns) {
|
|
699
|
+
const keys = [];
|
|
700
|
+
for (const k of Object.keys(listenerFns)) {
|
|
701
|
+
if (listenerFns[k] != null)
|
|
702
|
+
keys.push(k);
|
|
703
|
+
}
|
|
704
|
+
keys.sort();
|
|
705
|
+
return keys.join(',');
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
/**
|
|
709
|
+
* Bundles the `ref + viewState + viewId` pattern that AIO views share.
|
|
710
|
+
*
|
|
711
|
+
* - The returned `ref` is stable across renders.
|
|
712
|
+
* - `current` is a reactive snapshot — effects keyed on it re-run when the
|
|
713
|
+
* view mounts/unmounts. `mutableRef` exposes the same value for imperative
|
|
714
|
+
* reads that must not trigger re-renders.
|
|
715
|
+
* - `id` is generated once per hook instance and stays stable for the lifetime
|
|
716
|
+
* of the component, suitable for `parentId` serialization.
|
|
717
|
+
*/
|
|
718
|
+
function useViewHandle() {
|
|
719
|
+
const mutableRef = useRef(null);
|
|
720
|
+
const [current, setCurrent] = useState(null);
|
|
721
|
+
const ref = useCallback((v) => {
|
|
722
|
+
mutableRef.current = v;
|
|
723
|
+
setCurrent(v);
|
|
724
|
+
}, []);
|
|
725
|
+
const id = useRef(Math.floor(Math.random() * 1_000_000)).current;
|
|
726
|
+
// Readiness promise resolved on the first `onLayout`. Created lazily once per
|
|
727
|
+
// hook instance so `whenReady()` returns a stable promise across renders.
|
|
728
|
+
const readyRef = useRef(undefined);
|
|
729
|
+
const resolveReadyRef = useRef(undefined);
|
|
730
|
+
if (!readyRef.current) {
|
|
731
|
+
readyRef.current = new Promise(resolve => {
|
|
732
|
+
resolveReadyRef.current = resolve;
|
|
733
|
+
});
|
|
734
|
+
}
|
|
735
|
+
const onLayout = useCallback(() => {
|
|
736
|
+
resolveReadyRef.current?.();
|
|
737
|
+
}, []);
|
|
738
|
+
const whenReady = useCallback(() => readyRef.current, []);
|
|
739
|
+
return { ref, current, mutableRef, id, onLayout, whenReady };
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
/**
|
|
743
|
+
* Adds `control` to `view` while both are present and the control reference is
|
|
744
|
+
* stable. Removes the control on unmount or when either reference changes.
|
|
745
|
+
*
|
|
746
|
+
* The view is typically a `DataCaptureView` and the control is a Scandit
|
|
747
|
+
* `Control` (e.g. `TorchSwitchControl`, `ZoomSwitchControl`). Pair this with
|
|
748
|
+
* `useStableProp(control)` at the call site so inline `new XControl()`
|
|
749
|
+
* instantiation doesn't churn add/remove.
|
|
750
|
+
*/
|
|
751
|
+
function useNativeControl(view, control) {
|
|
752
|
+
useEffect(() => {
|
|
753
|
+
if (!view || !control)
|
|
754
|
+
return;
|
|
755
|
+
void view.addControl(control);
|
|
756
|
+
return () => void view.removeControl(control);
|
|
757
|
+
}, [view, control]);
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
/**
|
|
761
|
+
* Mode-lifetime state machine shared by SDK view components.
|
|
762
|
+
*
|
|
763
|
+
* Owns: lazy mode creation, attach/detach transitions driven by `state`,
|
|
764
|
+
* `isEnabled` flips on `enabled`↔`disabled`, settings reapply on dep change,
|
|
765
|
+
* and detach-on-unmount.
|
|
766
|
+
*
|
|
767
|
+
* Side-effecting callbacks (`attach`, `detach`, `applySettings`, `setEnabled`,
|
|
768
|
+
* `createMode`) are read through a ref, so callers can pass closures without
|
|
769
|
+
* memoizing — only `state`, `canAttach`, and `settingsDeps` drive effects.
|
|
770
|
+
*/
|
|
771
|
+
function useMode(options) {
|
|
772
|
+
const { state, canAttach = true, settingsDeps } = options;
|
|
773
|
+
const optsRef = useRef(options);
|
|
774
|
+
optsRef.current = options;
|
|
775
|
+
const modeRef = useRef(null);
|
|
776
|
+
const attachedRef = useRef(false);
|
|
777
|
+
const prevStateRef = useRef('detached');
|
|
778
|
+
const getMode = useCallback(() => {
|
|
779
|
+
if (modeRef.current)
|
|
780
|
+
return modeRef.current;
|
|
781
|
+
console.debug('[useMode] create mode');
|
|
782
|
+
modeRef.current = optsRef.current.createMode();
|
|
783
|
+
return modeRef.current;
|
|
784
|
+
}, []);
|
|
785
|
+
const isAttached = useCallback(() => attachedRef.current, []);
|
|
786
|
+
// State machine: attach/detach + enabled flip.
|
|
787
|
+
useEffect(() => {
|
|
788
|
+
const prev = prevStateRef.current;
|
|
789
|
+
if (state === 'detached') {
|
|
790
|
+
prevStateRef.current = state;
|
|
791
|
+
if (!attachedRef.current) {
|
|
792
|
+
console.debug(`[useMode] state ${prev} -> detached (no-op, not attached)`);
|
|
793
|
+
return;
|
|
794
|
+
}
|
|
795
|
+
const mode = modeRef.current;
|
|
796
|
+
attachedRef.current = false;
|
|
797
|
+
console.debug(`[useMode] state ${prev} -> detached: detaching`);
|
|
798
|
+
if (mode) {
|
|
799
|
+
void detachAttachablesThen(optsRef.current.attachables, () => optsRef.current.detach(mode)).then(() => {
|
|
800
|
+
console.debug('[useMode] detach complete');
|
|
801
|
+
if (modeRef.current === mode)
|
|
802
|
+
modeRef.current = null;
|
|
803
|
+
});
|
|
804
|
+
}
|
|
805
|
+
return;
|
|
806
|
+
}
|
|
807
|
+
const enabled = state === 'enabled';
|
|
808
|
+
if (attachedRef.current) {
|
|
809
|
+
prevStateRef.current = state;
|
|
810
|
+
console.debug(`[useMode] state ${prev} -> ${state}: flip isEnabled=${enabled}`);
|
|
811
|
+
if (modeRef.current)
|
|
812
|
+
optsRef.current.setEnabled(modeRef.current, enabled);
|
|
813
|
+
return;
|
|
814
|
+
}
|
|
815
|
+
if (!canAttach) {
|
|
816
|
+
console.debug(`[useMode] state ${prev} -> ${state}: parked (canAttach=false)`);
|
|
817
|
+
return;
|
|
818
|
+
}
|
|
819
|
+
prevStateRef.current = state;
|
|
820
|
+
const mode = getMode();
|
|
821
|
+
let cancelled = false;
|
|
822
|
+
console.debug(`[useMode] state ${prev} -> ${state}: attaching`);
|
|
823
|
+
void attachThenAttachables(() => optsRef.current.attach(mode), optsRef.current.attachables).then(() => {
|
|
824
|
+
if (cancelled) {
|
|
825
|
+
console.debug('[useMode] attach resolved but cancelled');
|
|
826
|
+
return;
|
|
827
|
+
}
|
|
828
|
+
attachedRef.current = true;
|
|
829
|
+
console.debug(`[useMode] attach complete, isEnabled=${enabled}`);
|
|
830
|
+
if (modeRef.current)
|
|
831
|
+
optsRef.current.setEnabled(modeRef.current, enabled);
|
|
832
|
+
});
|
|
833
|
+
return () => {
|
|
834
|
+
cancelled = true;
|
|
835
|
+
};
|
|
836
|
+
}, [state, canAttach, getMode]);
|
|
837
|
+
// Settings reapply. Only meaningful when a mode exists.
|
|
838
|
+
useEffect(() => {
|
|
839
|
+
if (state === 'detached')
|
|
840
|
+
return;
|
|
841
|
+
if (!modeRef.current)
|
|
842
|
+
return;
|
|
843
|
+
console.debug('[useMode] reapply settings');
|
|
844
|
+
void Promise.resolve(optsRef.current.applySettings(modeRef.current));
|
|
845
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
846
|
+
}, [state, ...settingsDeps]);
|
|
847
|
+
// Detach on unmount.
|
|
848
|
+
useEffect(() => {
|
|
849
|
+
return () => {
|
|
850
|
+
if (!attachedRef.current) {
|
|
851
|
+
console.debug('[useMode] unmount (not attached)');
|
|
852
|
+
modeRef.current = null;
|
|
853
|
+
return;
|
|
854
|
+
}
|
|
855
|
+
const mode = modeRef.current;
|
|
856
|
+
attachedRef.current = false;
|
|
857
|
+
console.debug('[useMode] unmount: detaching');
|
|
858
|
+
if (mode)
|
|
859
|
+
void detachAttachablesThen(optsRef.current.attachables, () => optsRef.current.detach(mode));
|
|
860
|
+
modeRef.current = null;
|
|
861
|
+
};
|
|
862
|
+
}, []);
|
|
863
|
+
return { getMode, modeRef, isAttached };
|
|
864
|
+
}
|
|
865
|
+
async function attachThenAttachables(attachMode, attachables) {
|
|
866
|
+
await attachMode();
|
|
867
|
+
if (!attachables)
|
|
868
|
+
return;
|
|
869
|
+
for (const a of attachables)
|
|
870
|
+
await a.attach();
|
|
871
|
+
}
|
|
872
|
+
async function detachAttachablesThen(attachables, detachMode) {
|
|
873
|
+
if (attachables) {
|
|
874
|
+
for (let i = attachables.length - 1; i >= 0; i--)
|
|
875
|
+
await attachables[i].detach();
|
|
876
|
+
}
|
|
877
|
+
await detachMode();
|
|
878
|
+
}
|
|
879
|
+
|
|
880
|
+
/**
|
|
881
|
+
* Wait until the underlying `BaseDataCaptureView` has finished
|
|
882
|
+
* `createNativeView` (which sets `viewId` to a non-negative value). Calling
|
|
883
|
+
* `addOverlay` before this is a silent no-op — the controller's `updateView`
|
|
884
|
+
* bails out when `!isViewCreated()`, so the overlay JSON never reaches native.
|
|
885
|
+
*
|
|
886
|
+
* The native-view creation is itself driven by `DataCaptureView`'s `onLayout`
|
|
887
|
+
* (see SDC-32208), so we just poll `viewId` until it flips to a non-negative
|
|
888
|
+
* value. This avoids the previous dependency on
|
|
889
|
+
* `InteractionManager.runAfterInteractions`, whose queue can be starved
|
|
890
|
+
* indefinitely by a looping JS animation, leaving the overlay never attached.
|
|
891
|
+
*/
|
|
892
|
+
async function waitForDataCaptureViewReady(view) {
|
|
893
|
+
const baseView = view.view;
|
|
894
|
+
for (let i = 0; baseView && baseView.viewId === -1 && i < 100; i++) {
|
|
895
|
+
await new Promise(r => setTimeout(r, 10));
|
|
896
|
+
}
|
|
897
|
+
}
|
|
898
|
+
/**
|
|
899
|
+
* Lifecycle helper for `DataCaptureView` overlays. Pass the returned value into
|
|
900
|
+
* `useMode({ attachables: [...] })` — `useMode` orders `attach()` after the
|
|
901
|
+
* mode is added to the context and `detach()` before it's removed.
|
|
902
|
+
*
|
|
903
|
+
* Listener registration is not handled here; pair with `useModeListener`
|
|
904
|
+
* keyed on the reactive `overlay` snapshot:
|
|
905
|
+
*
|
|
906
|
+
* ```tsx
|
|
907
|
+
* const basicOverlay = useOverlay<BarcodeBatchBasicOverlay>({ ... });
|
|
908
|
+
*
|
|
909
|
+
* useModeListener<BarcodeBatchBasicOverlay, BarcodeBatchBasicOverlayListener>({
|
|
910
|
+
* mode: basicOverlay.overlay,
|
|
911
|
+
* listenerFns: { brushForTrackedBarcode, didTapTrackedBarcode },
|
|
912
|
+
* addListener: (o, l) => { o.listener = l; },
|
|
913
|
+
* removeListener: o => { o.listener = null; },
|
|
914
|
+
* });
|
|
915
|
+
* ```
|
|
916
|
+
*/
|
|
917
|
+
function useOverlay(opts) {
|
|
918
|
+
const { view, enabled = true, factoryDeps = [], updateDeps = [] } = opts;
|
|
919
|
+
const optsRef = useRef(opts);
|
|
920
|
+
optsRef.current = opts;
|
|
921
|
+
const overlayRef = useRef(null);
|
|
922
|
+
const [overlay, setOverlay] = useState(null);
|
|
923
|
+
// Tracks whether `useMode` currently considers us "mode-attached" — set by
|
|
924
|
+
// the `attach`/`detach` callbacks it invokes via `attachables`. Used by the
|
|
925
|
+
// `enabled`-flip effect to gate self-driven attach/detach.
|
|
926
|
+
const modeAttachedRef = useRef(false);
|
|
927
|
+
const doAttach = useCallback(async () => {
|
|
928
|
+
if (overlayRef.current)
|
|
929
|
+
return;
|
|
930
|
+
const v = view.current;
|
|
931
|
+
if (!v)
|
|
932
|
+
return;
|
|
933
|
+
// The native view is created asynchronously when `DataCaptureView` lays out
|
|
934
|
+
// (see SDC-32208). Calling `addOverlay` before it's ready is a silent no-op
|
|
935
|
+
// (the view controller's `updateView` bails out on `!isViewCreated()`), so
|
|
936
|
+
// wait for the view to report a valid `viewId` first.
|
|
937
|
+
await waitForDataCaptureViewReady(v);
|
|
938
|
+
const created = optsRef.current.factory();
|
|
939
|
+
optsRef.current.update?.(created);
|
|
940
|
+
overlayRef.current = created;
|
|
941
|
+
await v.addOverlay(created);
|
|
942
|
+
setOverlay(created);
|
|
943
|
+
}, [view]);
|
|
944
|
+
const doDetach = useCallback(async () => {
|
|
945
|
+
const o = overlayRef.current;
|
|
946
|
+
overlayRef.current = null;
|
|
947
|
+
setOverlay(null);
|
|
948
|
+
if (!o)
|
|
949
|
+
return;
|
|
950
|
+
const v = view.current;
|
|
951
|
+
if (v)
|
|
952
|
+
await v.removeOverlay(o);
|
|
953
|
+
}, [view]);
|
|
954
|
+
const attach = useCallback(async () => {
|
|
955
|
+
modeAttachedRef.current = true;
|
|
956
|
+
if (optsRef.current.enabled === false)
|
|
957
|
+
return;
|
|
958
|
+
await doAttach();
|
|
959
|
+
}, [doAttach]);
|
|
960
|
+
const detach = useCallback(async () => {
|
|
961
|
+
modeAttachedRef.current = false;
|
|
962
|
+
await doDetach();
|
|
963
|
+
}, [doDetach]);
|
|
964
|
+
const getOverlay = useCallback(() => overlayRef.current, []);
|
|
965
|
+
// Enabled toggle handling while the mode is attached.
|
|
966
|
+
useEffect(() => {
|
|
967
|
+
if (!modeAttachedRef.current)
|
|
968
|
+
return;
|
|
969
|
+
if (enabled && !overlayRef.current) {
|
|
970
|
+
void doAttach();
|
|
971
|
+
}
|
|
972
|
+
else if (!enabled && overlayRef.current) {
|
|
973
|
+
void doDetach();
|
|
974
|
+
}
|
|
975
|
+
}, [enabled, doAttach, doDetach]);
|
|
976
|
+
// Recreate on factoryDeps change while attached. Skips the initial render
|
|
977
|
+
// (first attach is driven by useMode's attachables, not this effect).
|
|
978
|
+
const isFirstFactoryEffect = useRef(true);
|
|
979
|
+
useEffect(() => {
|
|
980
|
+
if (isFirstFactoryEffect.current) {
|
|
981
|
+
isFirstFactoryEffect.current = false;
|
|
982
|
+
return;
|
|
983
|
+
}
|
|
984
|
+
if (!overlayRef.current)
|
|
985
|
+
return;
|
|
986
|
+
void (async () => {
|
|
987
|
+
await doDetach();
|
|
988
|
+
await doAttach();
|
|
989
|
+
})();
|
|
990
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
991
|
+
}, factoryDeps);
|
|
992
|
+
// Re-run `update` on updateDeps change while attached.
|
|
993
|
+
useEffect(() => {
|
|
994
|
+
if (!overlay)
|
|
995
|
+
return;
|
|
996
|
+
optsRef.current.update?.(overlay);
|
|
997
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
998
|
+
}, [overlay, ...updateDeps]);
|
|
999
|
+
return { overlay, getOverlay, attach, detach };
|
|
1000
|
+
}
|
|
1001
|
+
|
|
1002
|
+
var index = /*#__PURE__*/Object.freeze({
|
|
1003
|
+
__proto__: null,
|
|
1004
|
+
useDataCaptureContextInternal: useDataCaptureContextInternal,
|
|
1005
|
+
useMode: useMode,
|
|
1006
|
+
useModeListener: useModeListener,
|
|
1007
|
+
useNativeControl: useNativeControl,
|
|
1008
|
+
useOverlay: useOverlay,
|
|
1009
|
+
useStableProp: useStableProp,
|
|
1010
|
+
useViewHandle: useViewHandle
|
|
1011
|
+
});
|
|
1012
|
+
|
|
282
1013
|
initCoreDefaults();
|
|
283
1014
|
initCoreProxy();
|
|
284
1015
|
|
|
285
|
-
export { DataCaptureVersion, DataCaptureView, RNNativeCaller, createRNNativeCaller, getModuleDefaults, getNativeModule, initCoreDefaults, initCoreProxy };
|
|
1016
|
+
export { Camera, CameraPosition, DataCaptureContext, DataCaptureVersion, DataCaptureView, FrameSourceState, RNNativeCaller, ScanditProvider, TorchState, index as _internal, createRNNativeCaller, getModuleDefaults, getNativeModule, initCoreDefaults, initCoreProxy, useCameraPermission, useIsForeground, useScanditContext };
|
|
286
1017
|
//# sourceMappingURL=index.js.map
|