scandit-react-native-datacapture-core 8.5.2 → 8.6.0-beta.1

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.
Files changed (39) hide show
  1. package/android/build.gradle +1 -1
  2. package/android/src/main/kotlin/com/scandit/datacapture/reactnative/core/ui/ScanditViewGroupManager.kt +15 -0
  3. package/android/src/main/kotlin/com/scandit/datacapture/reactnative/core/utils/ViewWindowEvents.kt +32 -0
  4. package/android/src/main/newArch/kotlin/com/scandit/datacapture/reactnative/core/ScanditDataCaptureCoreModule.kt +4 -0
  5. package/android/src/main/oldArch/kotlin/com/scandit/datacapture/reactnative/core/ScanditDataCaptureCoreModule.kt +4 -0
  6. package/dist/core.js +471 -1
  7. package/dist/core.js.flow +2337 -0
  8. package/dist/core.js.map +1 -1
  9. package/dist/dts/core.d.ts +2151 -0
  10. package/dist/dts/experimental.d.ts +1 -9
  11. package/dist/dts/index.d.ts +672 -96
  12. package/dist/experimental.js.flow +3 -3
  13. package/dist/index.js +583 -143
  14. package/dist/index.js.flow +948 -96
  15. package/dist/index.js.map +1 -1
  16. package/ios/Sources/ScanditDataCaptureCore.swift +10 -1
  17. package/ios/Sources/Shared/DataCaptureViewWrapper.swift +7 -0
  18. package/package.json +9 -8
  19. package/scandit-react-native-datacapture-core.podspec +1 -1
  20. package/dist/dts/DataCaptureVersion.d.ts +0 -4
  21. package/dist/dts/DataCaptureView.d.ts +0 -61
  22. package/dist/dts/hooks/ScanditProvider.d.ts +0 -46
  23. package/dist/dts/hooks/index.d.ts +0 -5
  24. package/dist/dts/hooks/useCameraPermission.d.ts +0 -28
  25. package/dist/dts/hooks/useIsForeground.d.ts +0 -11
  26. package/dist/dts/hooks/useScanditContext.d.ts +0 -21
  27. package/dist/dts/native/CoreNativeCallerProvider.d.ts +0 -4
  28. package/dist/dts/native/RNNativeCaller.d.ts +0 -23
  29. package/dist/dts/native/ScanditNativeModule.d.ts +0 -6
  30. package/dist/dts/native/initProxy.d.ts +0 -1
  31. package/dist/dts/private/Defaults.d.ts +0 -1
  32. package/dist/dts/private/hooks/useMode.d.ts +0 -49
  33. package/dist/dts/private/hooks/useModeListener.d.ts +0 -40
  34. package/dist/dts/private/hooks/useNativeControl.d.ts +0 -14
  35. package/dist/dts/private/hooks/useOverlay.d.ts +0 -68
  36. package/dist/dts/private/hooks/useStableProp.d.ts +0 -22
  37. package/dist/dts/private/hooks/useViewHandle.d.ts +0 -41
  38. package/dist/dts/private/index.d.ts +0 -11
  39. package/dist/tsconfig.tsbuildinfo +0 -1
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
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';
1
+ import { CORE_PROXY_TYPE_NAMES, registerCoreProxies, loadCoreDefaults, setCoreDefaultsLoader, BaseDataCaptureView, DataCaptureContext, TorchState, CameraPosition, Camera, FrameSourceState } from './core.js';
2
+ export { AimerViewfinder, Anchor, Brush, CameraSettings, CameraSwitchControl, 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, SequenceFrameSource, Size, SizeWithAspect, SizeWithUnit, SizeWithUnitAndAspect, SizingMode, Sound, SwipeToZoom, TapToFocus, TextAlignment, TorchSwitchControl, Vibration, VibrationType, VideoResolution, WaveFormVibration, ZoomSwitchControl, ZoomSwitchOrientation } from './core.js';
3
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';
4
+ import React, { useState, useEffect, useCallback, useMemo, createContext, useContext, useRef, useLayoutEffect } 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.5.2';
141
+ return '8.6.0-beta.1';
142
142
  }
143
143
  static get sdkVersion() {
144
144
  return NativeModule.Version;
@@ -250,7 +250,8 @@ class DataCaptureView extends React.Component {
250
250
  cancelAnimationFrame(this._createViewRafHandle);
251
251
  this._createViewRafHandle = null;
252
252
  }
253
- this.view.dispose();
253
+ const teardown = Promise.resolve(this.view.dispose());
254
+ this.props.onNativeDispose?.(teardown);
254
255
  }
255
256
  componentDidMount() {
256
257
  this._isMounted = true;
@@ -381,7 +382,7 @@ async function requestAndroidPermission() {
381
382
  * ```
382
383
  */
383
384
  function useCameraPermission() {
384
- const [status, setStatus] = useState(Platform.OS === 'android' ? 'not-determined' : 'not-determined');
385
+ const [status, setStatus] = useState('not-determined');
385
386
  const refresh = useCallback(async () => {
386
387
  if (Platform.OS !== 'android')
387
388
  return;
@@ -448,80 +449,221 @@ function useScanditContext(licenseKey, options) {
448
449
 
449
450
  const DEFAULT_TORCH = TorchState.Off;
450
451
  const DEFAULT_POSITION = CameraPosition.WorldFacing;
451
- const DEFAULT_FRAME_SOURCE_STATE = FrameSourceState.On;
452
- function createCameraOwner(context) {
452
+ function createCameraOwner(context, cameraFactory = position => Camera.atPosition(position), onError) {
453
453
  let camera = null;
454
- let position = null;
454
+ // The position the live `camera` was created for; recreate only when it flips.
455
+ let createdPosition = null;
456
+ let position = DEFAULT_POSITION;
455
457
  let desiredTorch = DEFAULT_TORCH;
456
- let desiredState = DEFAULT_FRAME_SOURCE_STATE;
457
- let queue = Promise.resolve();
458
+ let applied = 'off';
459
+ // True only after a FULLY successful acquire (both native calls confirmed).
460
+ // Lets the apply pass skip re-issuing setFrameSource/switchOn when nothing
461
+ // changed - every claim burst re-applies, and redundant re-acquires showed
462
+ // up on device as 2-3 pointless native calls per navigation.
463
+ let acquireSucceeded = false;
464
+ let disposed = false;
465
+ // The single owner slot. Last claim wins; superseded owners' operations
466
+ // no-op because every queued op re-checks this slot when it runs.
467
+ let owner = null;
468
+ let chain = Promise.resolve();
458
469
  const enqueue = (op) => {
459
- queue = queue.then(op).catch(err => console.warn('ScanditProvider: camera operation failed', err));
460
- return queue;
470
+ chain = chain.then(op).catch(err => {
471
+ console.warn('ScanditProvider: camera operation failed', err);
472
+ onError?.(err);
473
+ });
474
+ return chain;
461
475
  };
462
- // `Camera.atPosition` is a process-wide singleton, so any other
463
- // DataCaptureContext can grab it via `setFrameSource(...)` while we're idle.
464
- // Rebind only when the camera isn't ours anymore — otherwise a no-op.
465
- const isOurs = (cam) => cam.context === context;
466
- // Bind `camera` to our context and push our cached desired state.
467
- // Used after a fresh `Camera.atPosition(...)` and to reclaim a stolen camera.
468
- const bind = async () => {
469
- if (camera === null)
476
+ /** Turn the provider camera on for a shared owner. Retries once: switching
477
+ * on can fail transiently when it races an exclusive owner's async native
478
+ * teardown (iOS nulls/steals the context frame source after our resume —
479
+ * SDC-32484). The chain is serialized, so the retry only buys the native
480
+ * side time to settle. */
481
+ const acquireSharedCamera = async (retriesLeft = 1) => {
482
+ if (acquireSucceeded && applied === 'on' && camera !== null && createdPosition === position) {
483
+ // Already on for this camera/position - just keep the torch in sync.
484
+ camera.desiredTorchState = desiredTorch;
470
485
  return;
486
+ }
487
+ if (camera === null || createdPosition !== position) {
488
+ // `Camera.atPosition` returns null when the position is unavailable on
489
+ // the device. Don't crash the chain — warn and leave the camera off; a
490
+ // later position change can retry.
491
+ camera = cameraFactory(position);
492
+ if (camera === null) {
493
+ console.warn('ScanditProvider: no camera available at position', position);
494
+ return;
495
+ }
496
+ createdPosition = position;
497
+ }
471
498
  camera.desiredTorchState = desiredTorch;
472
- await context.setFrameSource(camera);
473
- await camera.switchToDesiredState(desiredState);
499
+ // Mark before the awaits: a partial failure leaves applied='on' so a
500
+ // later release fully unwinds the half-attached camera.
501
+ applied = 'on';
502
+ acquireSucceeded = false;
503
+ try {
504
+ await context.setFrameSource(camera);
505
+ await camera.switchToDesiredState(FrameSourceState.On);
506
+ acquireSucceeded = true;
507
+ }
508
+ catch (err) {
509
+ if (retriesLeft > 0) {
510
+ console.warn('ScanditProvider: switching the camera on failed, retrying once', err);
511
+ await acquireSharedCamera(retriesLeft - 1);
512
+ return;
513
+ }
514
+ throw err;
515
+ }
516
+ };
517
+ /** Between-screens release: put the camera in native Standby. Capture input
518
+ * is disabled immediately (sensor released, no frames) and the NATIVE staged
519
+ * standby completes the full shutdown after ~30s if no screen resumes -
520
+ * we never run a JS timer. Resuming from standby is near-instant, so
521
+ * navigation hand-offs don't blink. The frame source stays attached; only a
522
+ * hard release (exclusive hand-over / dispose) detaches it. */
523
+ const standbySharedCamera = async () => {
524
+ if (camera === null || applied !== 'on')
525
+ return;
526
+ applied = 'standby';
527
+ acquireSucceeded = false;
528
+ await camera.switchToDesiredState(FrameSourceState.Standby);
529
+ };
530
+ /** Hard release: full Off + frame source detached. Required when the device
531
+ * must be free immediately - an exclusive (own-camera) owner taking camera 0,
532
+ * or provider dispose. Standby is not enough there: it keeps the capture
533
+ * session (and the context's frame source) alive. */
534
+ const releaseSharedCamera = async () => {
535
+ if (camera === null || applied === 'off')
536
+ return;
537
+ applied = 'off';
538
+ acquireSucceeded = false;
539
+ await camera.switchToDesiredState(FrameSourceState.Off);
540
+ await context.setFrameSource(null);
541
+ };
542
+ const releaseManagedCamera = releaseSharedCamera;
543
+ /** Apply the state the CURRENT owner implies. Called at op-run time so a
544
+ * superseded claim's op naturally applies the latest truth. */
545
+ const applyOwnerState = async () => {
546
+ if (disposed)
547
+ return;
548
+ if (owner === null) {
549
+ await standbySharedCamera();
550
+ }
551
+ else if (owner.mode === 'shared') {
552
+ await acquireSharedCamera();
553
+ }
554
+ else {
555
+ await releaseManagedCamera();
556
+ }
474
557
  };
475
- const reclaimIfNeeded = async () => {
476
- if (camera !== null && !isOurs(camera))
477
- await bind();
558
+ /** Timeout-raced await of a dying view's native teardown: it must settle
559
+ * before ANY later camera op, or the dispose can stop camera 0 underneath
560
+ * the next owner's freshly-started camera (SDC-32484). Safety valve: a hung
561
+ * dispose must not wedge the chain forever. */
562
+ const awaitTeardown = async (teardown) => {
563
+ let timer;
564
+ const timeout = new Promise(resolve => (timer = setTimeout(resolve, 10000)));
565
+ const settled = teardown.then(() => undefined, () => undefined);
566
+ void settled.then(() => clearTimeout(timer));
567
+ await Promise.race([settled, timeout]);
568
+ };
569
+ const pendingSteps = [];
570
+ let applyScheduled = false;
571
+ const scheduleApply = () => {
572
+ if (applyScheduled)
573
+ return;
574
+ applyScheduled = true;
575
+ void enqueue(async () => {
576
+ // Reset FIRST: a step pushed while this op is mid-drain is picked up by
577
+ // the loop below AND may schedule a follow-up apply-op — which then
578
+ // finds an empty list and runs one harmless no-op apply. The
579
+ // alternative (reset after the drain) can drop a step entirely.
580
+ applyScheduled = false;
581
+ while (pendingSteps.length > 0) {
582
+ const step = pendingSteps.shift();
583
+ if (step)
584
+ await step();
585
+ }
586
+ await applyOwnerState();
587
+ });
588
+ };
589
+ const mutate = (step) => {
590
+ if (disposed)
591
+ return;
592
+ pendingSteps.push(step);
593
+ scheduleApply();
594
+ };
595
+ const addClaim = (claim) => {
596
+ mutate(() => {
597
+ console.debug(`[cameraOwner] claim add: mode=${claim.mode} active=${claim.active}`);
598
+ if (claim.active)
599
+ owner = claim;
600
+ });
601
+ };
602
+ const updateClaim = (claim, patch) => {
603
+ mutate(() => {
604
+ Object.assign(claim, patch);
605
+ console.debug(`[cameraOwner] claim update: mode=${claim.mode} active=${claim.active}`);
606
+ if (claim.active) {
607
+ // Claim ownership: last writer wins, the previous owner is superseded.
608
+ owner = claim;
609
+ }
610
+ else if (owner === claim) {
611
+ // Deactivating while owner: release. Deactivations from superseded
612
+ // owners are ignored.
613
+ owner = null;
614
+ }
615
+ });
616
+ };
617
+ const removeClaim = (claim, teardown) => {
618
+ mutate(async () => {
619
+ // The teardown barrier holds even for a superseded owner: its native
620
+ // dispose still touches camera 0, so later ops must wait for it.
621
+ if (teardown)
622
+ await awaitTeardown(teardown);
623
+ console.debug(`[cameraOwner] claim remove: mode=${claim.mode} owner=${owner === claim}`);
624
+ if (owner === claim)
625
+ owner = null;
626
+ });
627
+ };
628
+ const whenGranted = (claim) => {
629
+ return enqueue(() => Promise.resolve());
478
630
  };
479
631
  return {
480
- setPosition(next) {
481
- void enqueue(async () => {
482
- if (camera !== null && position === next) {
483
- await reclaimIfNeeded();
484
- return;
485
- }
486
- if (camera !== null)
487
- await camera.switchToDesiredState(FrameSourceState.Off);
488
- camera = Camera.atPosition(next);
489
- position = next;
490
- await bind();
491
- });
492
- },
493
632
  setTorch(next) {
494
- void enqueue(async () => {
633
+ return enqueue(() => {
495
634
  desiredTorch = next;
496
- await reclaimIfNeeded();
497
635
  if (camera !== null)
498
636
  camera.desiredTorchState = next;
637
+ return Promise.resolve();
499
638
  });
500
639
  },
501
- setFrameSourceState(next) {
502
- void enqueue(async () => {
503
- desiredState = next;
504
- await reclaimIfNeeded();
505
- if (camera !== null)
506
- await camera.switchToDesiredState(next);
640
+ setPosition(next) {
641
+ return enqueue(async () => {
642
+ position = next;
643
+ await applyOwnerState();
507
644
  });
508
645
  },
509
- reclaimIfNeeded() {
510
- void enqueue(reclaimIfNeeded);
646
+ idle() {
647
+ return chain.then(() => undefined, () => undefined);
511
648
  },
512
649
  dispose() {
513
650
  return enqueue(async () => {
514
- const cam = camera;
515
- camera = null;
516
- // Skip `setFrameSource(null)` if we don't own the camera — it would
517
- // yank it away from whichever context holds it now.
518
- if (cam !== null && isOurs(cam)) {
519
- await cam.switchToDesiredState(FrameSourceState.Off);
651
+ if (disposed)
652
+ return;
653
+ disposed = true;
654
+ owner = null;
655
+ if (camera !== null) {
656
+ await camera.switchToDesiredState(FrameSourceState.Off);
520
657
  await context.setFrameSource(null);
521
658
  }
522
659
  await context.dispose();
523
660
  });
524
661
  },
662
+ // ─── Ownership surface (backs `useCameraClaim`) ─────────────────────────
663
+ addClaim,
664
+ updateClaim,
665
+ removeClaim,
666
+ whenGranted,
525
667
  };
526
668
  }
527
669
  const ScanditInternalContext = createContext(null);
@@ -530,15 +672,24 @@ function useApplyCameraProps(owner, props) {
530
672
  const { frameSourceState, torchState, cameraPosition } = props;
531
673
  useEffect(() => {
532
674
  if (cameraPosition !== undefined)
533
- owner.setPosition(cameraPosition);
675
+ void owner.setPosition(cameraPosition);
534
676
  }, [owner, cameraPosition]);
535
677
  useEffect(() => {
536
678
  if (torchState !== undefined)
537
- owner.setTorch(torchState);
679
+ void owner.setTorch(torchState);
538
680
  }, [owner, torchState]);
681
+ // The camera is ownership-driven: it is only turned on when a view (or an
682
+ // explicit `frameSourceState={On}`) claims it.
683
+ // - undefined → do nothing (let views drive the camera).
684
+ // - Off → do nothing (no claim).
685
+ // - On → claim ownership for as long as this prop stays On. A view
686
+ // claiming later supersedes this (last writer wins).
539
687
  useEffect(() => {
540
- if (frameSourceState !== undefined)
541
- owner.setFrameSourceState(frameSourceState);
688
+ if (frameSourceState !== FrameSourceState.On)
689
+ return;
690
+ const claim = { mode: 'shared', active: true };
691
+ owner.addClaim(claim);
692
+ return () => owner.removeClaim(claim);
542
693
  }, [owner, frameSourceState]);
543
694
  }
544
695
  /**
@@ -550,8 +701,11 @@ function useApplyCameraProps(owner, props) {
550
701
  * props to the same singleton camera. Last writer wins; values are not reverted
551
702
  * when a nested provider unmounts.
552
703
  *
553
- * The camera is recreated only when `cameraPosition` flips; torch and
554
- * `frameSourceState` are applied directly to the live camera.
704
+ * The camera is ownership-driven: exactly one view owns it at a time (last
705
+ * claim wins), and it is only on while the owner is a provider-camera view (or
706
+ * `frameSourceState={On}` is set). Torch and position are applied to the
707
+ * coordinator; the camera instance is recreated only when `cameraPosition`
708
+ * flips.
555
709
  *
556
710
  * ```tsx
557
711
  * <ScanditProvider licenseKey={KEY}>
@@ -584,21 +738,28 @@ function NestedScanditProvider({ parent, frameSourceState, torchState, cameraPos
584
738
  useApplyCameraProps(parent.owner, { frameSourceState, torchState, cameraPosition });
585
739
  return React.createElement(ScanditInternalContext.Provider, { value: parent }, children);
586
740
  }
587
- function RootScanditProvider({ licenseKey, options, settings, frameSourceState, torchState, cameraPosition, children, }) {
741
+ function RootScanditProvider({ licenseKey, options, settings, frameSourceState, torchState, cameraPosition, onError, children, }) {
588
742
  const context = useMemo(() => DataCaptureContext.initialize(licenseKey, options ?? null, settings ?? null),
589
743
  // The context is a singleton keyed on licenseKey.
590
744
  // eslint-disable-next-line react-hooks/exhaustive-deps
591
745
  [licenseKey]);
592
- const owner = useMemo(() => createCameraOwner(context), [context]);
593
- // Apply our own props to the singleton, falling back to defaults so the
594
- // camera is always created and in a known state.
746
+ // Keep the latest `onError` in a ref so the owner — memoized on `[context]`,
747
+ // and intentionally NOT recreated when `onError` changes — always calls the
748
+ // current callback through a stable wrapper.
749
+ const onErrorRef = useRef(onError);
750
+ onErrorRef.current = onError;
751
+ const owner = useMemo(() => createCameraOwner(context, undefined, e => onErrorRef.current?.(e)), [context]);
752
+ // Apply our own props to the singleton. The provider must NOT claim the
753
+ // camera on its own — only an explicit `frameSourceState={On}` from a
754
+ // consumer does. Position/torch defaults are still applied so the camera has
755
+ // a known configuration once something claims it.
595
756
  useApplyCameraProps(owner, {
596
- frameSourceState: frameSourceState ?? DEFAULT_FRAME_SOURCE_STATE,
757
+ frameSourceState,
597
758
  torchState: torchState ?? DEFAULT_TORCH,
598
759
  cameraPosition: cameraPosition ?? DEFAULT_POSITION,
599
760
  });
600
- // Dispose context + camera on unmount. Chained onto the owner's queue so
601
- // any in-flight mutation finishes first.
761
+ // Dispose context + camera on unmount. Chained onto the owner's chain so
762
+ // any in-flight operation finishes first.
602
763
  useEffect(() => {
603
764
  return () => {
604
765
  void owner.dispose();
@@ -607,17 +768,18 @@ function RootScanditProvider({ licenseKey, options, settings, frameSourceState,
607
768
  const internal = useMemo(() => ({ context, owner }), [context, owner]);
608
769
  return React.createElement(ScanditInternalContext.Provider, { value: internal }, children);
609
770
  }
610
- // ─── Internal hook consumed by AIO view packages ─────────────────────────────
611
- /** Internal — used by AIO views to attach modes to the shared context. */
612
- function useDataCaptureContextInternal() {
771
+ // ─── Internal hooks consumed by AIO view packages ────────────────────────────
772
+ /** Internal — exposes the shared context + camera coordinator to AIO views. */
773
+ function useScanditInternal() {
613
774
  const internal = useContext(ScanditInternalContext);
614
775
  if (!internal) {
615
776
  throw new Error('This component must be rendered inside a <ScanditProvider>.');
616
777
  }
617
- // Reclaim the singleton camera on (re)mount: anything else in the app that
618
- // touched `Camera.atPosition` while we were unmounted may have stolen it.
619
- useEffect(() => internal.owner.reclaimIfNeeded(), [internal]);
620
- return internal.context;
778
+ return internal;
779
+ }
780
+ /** Internal — used by AIO views to attach modes to the shared context. */
781
+ function useDataCaptureContextInternal() {
782
+ return useScanditInternal().context;
621
783
  }
622
784
 
623
785
  function isSerializable(v) {
@@ -663,6 +825,46 @@ function useStableProp(value) {
663
825
  return value;
664
826
  }
665
827
 
828
+ /**
829
+ * Mirrors a fixed set of prop values onto a live native-view instance via
830
+ * direct property assignment.
831
+ *
832
+ * `keys` is constrained to `keyof Props & keyof Target` and combined with an
833
+ * `as const satisfies ReadonlyArray<...>` at the call site, so a rename on
834
+ * either side — prop interface or native view — is a compile error.
835
+ *
836
+ * `undefined` values are skipped to preserve SDK defaults. The effect is
837
+ * gated on `target` so setter RPCs only fire after the native view is
838
+ * attached.
839
+ *
840
+ * For batched-update layers that expose an `updateWithProps(prev, next)`
841
+ * method, keep their own diff effect rather than using this hook — it would
842
+ * fire one RPC per key instead of one per render.
843
+ *
844
+ * ```ts
845
+ * const KEYS = ['shouldShowTorchControl', 'torchControlPosition'] as const
846
+ * satisfies ReadonlyArray<keyof MyProps & keyof BaseView>;
847
+ *
848
+ * usePassThroughProps(baseView, props, KEYS);
849
+ * ```
850
+ */
851
+ function usePassThroughProps(target, props, keys) {
852
+ useEffect(() => {
853
+ if (!target)
854
+ return;
855
+ for (const key of keys) {
856
+ const value = props[key];
857
+ if (value === undefined)
858
+ continue;
859
+ target[key] = value;
860
+ }
861
+ // `keys` is `as const` at the call site — its identity and length are
862
+ // stable across renders, so the spread produces a same-length,
863
+ // positionally-stable dep array, which is what useEffect requires.
864
+ // eslint-disable-next-line react-hooks/exhaustive-deps
865
+ }, [target, ...keys.map(k => props[k])]);
866
+ }
867
+
666
868
  /**
667
869
  * Registers a listener on a Scandit mode or view and keeps it up to date.
668
870
  *
@@ -830,23 +1032,48 @@ function useNativeControl(view, control) {
830
1032
  }
831
1033
 
832
1034
  /**
833
- * Mode-lifetime state machine shared by SDK view components.
1035
+ * Mode-lifetime helper shared by SDK view components.
1036
+ *
1037
+ * Owns: lazy mode creation, attach-on-mount / detach-on-unmount, settings
1038
+ * reapply on dep change, and the mode's `isEnabled` via the returned
1039
+ * `enable()` / `disable()`. The first `setEnabled` after attach honors the
1040
+ * `disabled` veto, so a view declared `disabled` comes up off.
834
1041
  *
835
- * Owns: lazy mode creation, attach/detach transitions driven by `state`,
836
- * `isEnabled` flips on `enabled`↔`disabled`, settings reapply on dep change,
837
- * and detach-on-unmount.
1042
+ * Enable/disable intent is tracked in a ref (not React state) and applied as
1043
+ * soon as the mode is attached — calling `enable()`/`disable()` before attach
1044
+ * completes is fine; the pending value is flushed on attach.
838
1045
  *
839
1046
  * Side-effecting callbacks (`attach`, `detach`, `applySettings`, `setEnabled`,
840
1047
  * `createMode`) are read through a ref, so callers can pass closures without
841
- * memoizing — only `state`, `canAttach`, and `settingsDeps` drive effects.
1048
+ * memoizing — only `canAttach` and `settingsDeps` drive effects.
842
1049
  */
843
1050
  function useMode(options) {
844
- const { state, canAttach = true, settingsDeps } = options;
1051
+ const { canAttach = true, settingsDeps } = options;
845
1052
  const optsRef = useRef(options);
846
1053
  optsRef.current = options;
847
1054
  const modeRef = useRef(null);
848
1055
  const attachedRef = useRef(false);
849
- const prevStateRef = useRef('detached');
1056
+ // Desired enabled state, seeded from `disabled` at first render. Updated by
1057
+ // enable()/disable() and flushed to the mode once attached.
1058
+ const desiredEnabledRef = useRef(!options.disabled);
1059
+ // Serializes attach()/detach() so focus toggling can't interleave add/remove
1060
+ // on the shared context (which is single-active-mode).
1061
+ const opChainRef = useRef(Promise.resolve());
1062
+ // Bumped *synchronously* by detach(). An in-flight attach op captures the
1063
+ // value when it starts and re-checks after its awaits: a detach() issued
1064
+ // mid-attach makes the attach roll itself back instead of completing on a
1065
+ // dead screen (SDC-32484 — the device trace `attaching → detaching →
1066
+ // attach complete, setEnabled=true` re-enabled a mode after teardown).
1067
+ const detachEpochRef = useRef(0);
1068
+ // Chain an op onto the serialized queue. The `.catch` keeps the chain alive:
1069
+ // a failed attach/detach must not poison the queue and silently drop every
1070
+ // later lifecycle op.
1071
+ const enqueue = useCallback((op) => {
1072
+ opChainRef.current = opChainRef.current.then(op).catch(err => {
1073
+ console.warn('[useMode] lifecycle operation failed', err);
1074
+ });
1075
+ return opChainRef.current;
1076
+ }, []);
850
1077
  const getMode = useCallback(() => {
851
1078
  if (modeRef.current)
852
1079
  return modeRef.current;
@@ -855,84 +1082,90 @@ function useMode(options) {
855
1082
  return modeRef.current;
856
1083
  }, []);
857
1084
  const isAttached = useCallback(() => attachedRef.current, []);
858
- // State machine: attach/detach + enabled flip.
859
- useEffect(() => {
860
- const prev = prevStateRef.current;
861
- if (state === 'detached') {
862
- prevStateRef.current = state;
863
- if (!attachedRef.current) {
864
- console.debug(`[useMode] state ${prev} -> detached (no-op, not attached)`);
865
- return;
866
- }
867
- const mode = modeRef.current;
868
- attachedRef.current = false;
869
- console.debug(`[useMode] state ${prev} -> detached: detaching`);
870
- if (mode) {
871
- void detachAttachablesThen(optsRef.current.attachables, () => optsRef.current.detach(mode)).then(() => {
872
- console.debug('[useMode] detach complete');
873
- if (modeRef.current === mode)
874
- modeRef.current = null;
875
- });
876
- }
1085
+ // Debug tag: identifies WHICH mode instance logs (SDC-32484 interim instrumentation).
1086
+ const tag = () => (modeRef.current ? modeRef.current.constructor.name : 'unattached');
1087
+ // Attach (add to context) + attachables, then flush desired enabled state.
1088
+ // Idempotent (no-op while already attached). Reuses the same mode instance so
1089
+ // its listener survives across detach→attach.
1090
+ const attach = useCallback(() => enqueue(async () => {
1091
+ if (attachedRef.current)
877
1092
  return;
878
- }
879
- const enabled = state === 'enabled';
880
- if (attachedRef.current) {
881
- prevStateRef.current = state;
882
- console.debug(`[useMode] state ${prev} -> ${state}: flip isEnabled=${enabled}`);
883
- if (modeRef.current)
884
- optsRef.current.setEnabled(modeRef.current, enabled);
1093
+ // Respect the readiness gate (e.g. BarcodeCount waits for its native view).
1094
+ // A focus-driven attach() before the gate opens is skipped; the mount
1095
+ // effect re-runs attach() once `canAttach` flips true.
1096
+ if (optsRef.current.canAttach === false) {
1097
+ console.debug('[useMode] attach parked (canAttach=false)');
885
1098
  return;
886
1099
  }
887
- if (!canAttach) {
888
- console.debug(`[useMode] state ${prev} -> ${state}: parked (canAttach=false)`);
889
- return;
890
- }
891
- prevStateRef.current = state;
1100
+ const epoch = detachEpochRef.current;
892
1101
  const mode = getMode();
893
- let cancelled = false;
894
- console.debug(`[useMode] state ${prev} -> ${state}: attaching`);
895
- void attachThenAttachables(() => optsRef.current.attach(mode), optsRef.current.attachables).then(() => {
896
- if (cancelled) {
897
- console.debug('[useMode] attach resolved but cancelled');
1102
+ console.debug(`[useMode:${tag()}] attaching`);
1103
+ await attachThenAttachables(() => optsRef.current.attach(mode), optsRef.current.attachables);
1104
+ attachedRef.current = true;
1105
+ // detach() may have been requested while the async attach was in
1106
+ // flight (unmount / blur / `disabled` mid-attach). The attach still
1107
+ // completes — the queued detach op right behind us needs a symmetric
1108
+ // attached state to tear down — but it must NOT enable the mode: the
1109
+ // screen is dead or vetoed, and enabling here re-opens the camera on
1110
+ // it (SDC-32484 — device trace `attaching → detaching → attach
1111
+ // complete, setEnabled=true`).
1112
+ const detachPending = detachEpochRef.current !== epoch;
1113
+ const enabled = detachPending ? false : desiredEnabledRef.current;
1114
+ if (detachPending)
1115
+ console.debug('[useMode] detach requested mid-attach — forcing disabled');
1116
+ console.debug(`[useMode:${tag()}] attach complete, setEnabled=${enabled}`);
1117
+ await optsRef.current.setEnabled(mode, enabled);
1118
+ }), [enqueue, getMode]);
1119
+ // Detach attachables + the mode (remove from context). Idempotent. Keeps the
1120
+ // instance so a later attach() re-adds the same object.
1121
+ const detach = useCallback(() => {
1122
+ // Synchronous bump so an attach op already past its idempotency check
1123
+ // observes the detach request and cancels itself (see attach()).
1124
+ detachEpochRef.current++;
1125
+ return enqueue(async () => {
1126
+ if (!attachedRef.current)
898
1127
  return;
899
- }
900
- attachedRef.current = true;
901
- console.debug(`[useMode] attach complete, isEnabled=${enabled}`);
902
- if (modeRef.current)
903
- optsRef.current.setEnabled(modeRef.current, enabled);
1128
+ const mode = modeRef.current;
1129
+ attachedRef.current = false;
1130
+ console.debug(`[useMode:${tag()}] detaching`);
1131
+ if (mode)
1132
+ await detachAttachablesThen(optsRef.current.attachables, () => optsRef.current.detach(mode));
904
1133
  });
905
- return () => {
906
- cancelled = true;
907
- };
908
- }, [state, canAttach, getMode]);
909
- // Settings reapply. Only meaningful when a mode exists.
1134
+ }, [enqueue]);
1135
+ const applyEnabled = useCallback(async (enabled) => {
1136
+ desiredEnabledRef.current = enabled;
1137
+ if (modeRef.current && attachedRef.current) {
1138
+ console.debug(`[useMode:${tag()}] setEnabled=${enabled}`);
1139
+ await optsRef.current.setEnabled(modeRef.current, enabled);
1140
+ }
1141
+ else {
1142
+ console.debug(`[useMode] enable=${enabled} deferred (not attached)`);
1143
+ }
1144
+ }, []);
1145
+ const enable = useCallback(() => applyEnabled(true), [applyEnabled]);
1146
+ const disable = useCallback(() => applyEnabled(false), [applyEnabled]);
1147
+ // Attach on mount once `canAttach`. attach() honors the desired enabled state
1148
+ // (seeded from `!disabled`), so a disabled view never auto-enables.
910
1149
  useEffect(() => {
911
- if (state === 'detached')
1150
+ if (!canAttach)
912
1151
  return;
1152
+ void attach();
1153
+ }, [canAttach, attach]);
1154
+ // Settings reapply. Only meaningful when a mode exists.
1155
+ useEffect(() => {
913
1156
  if (!modeRef.current)
914
1157
  return;
915
1158
  console.debug('[useMode] reapply settings');
916
1159
  void Promise.resolve(optsRef.current.applySettings(modeRef.current));
917
1160
  // eslint-disable-next-line react-hooks/exhaustive-deps
918
- }, [state, ...settingsDeps]);
1161
+ }, settingsDeps);
919
1162
  // Detach on unmount.
920
1163
  useEffect(() => {
921
1164
  return () => {
922
- if (!attachedRef.current) {
923
- console.debug('[useMode] unmount (not attached)');
924
- modeRef.current = null;
925
- return;
926
- }
927
- const mode = modeRef.current;
928
- attachedRef.current = false;
929
- console.debug('[useMode] unmount: detaching');
930
- if (mode)
931
- void detachAttachablesThen(optsRef.current.attachables, () => optsRef.current.detach(mode));
932
- modeRef.current = null;
1165
+ void detach();
933
1166
  };
934
- }, []);
935
- return { getMode, modeRef, isAttached };
1167
+ }, [detach]);
1168
+ return { getMode, modeRef, isAttached, enable, disable, attach, detach };
936
1169
  }
937
1170
  async function attachThenAttachables(attachMode, attachables) {
938
1171
  await attachMode();
@@ -1071,13 +1304,220 @@ function useOverlay(opts) {
1071
1304
  return { overlay, getOverlay, attach, detach };
1072
1305
  }
1073
1306
 
1307
+ /**
1308
+ * Handle modes lifetime by calling `onEnable` / `onDisable` when the navigation focus or blur event happens or AppState changes to not active.
1309
+ */
1310
+ function useLifecycleHook({ navigation, disabled = false, appStateHandlingDisabled = false, onEnable, onDisable, }) {
1311
+ // Latest-ref so effects/listeners read current callbacks and `disabled`
1312
+ // without depending on them (which would re-run / re-subscribe).
1313
+ const latest = useRef({ onEnable, onDisable, disabled, appStateHandlingDisabled });
1314
+ latest.current = { onEnable, onDisable, disabled, appStateHandlingDisabled };
1315
+ // We track focus so the AppState listener won't enable a blurred screen.
1316
+ const focusedRef = useRef(true);
1317
+ useEffect(() => {
1318
+ if (navigation === undefined || navigation.addListener === undefined) {
1319
+ return;
1320
+ }
1321
+ console.debug('[useLifecycleHook] subscribing to focus/blur');
1322
+ const offFocus = navigation.addListener('focus', () => {
1323
+ focusedRef.current = true;
1324
+ if (!latest.current.disabled && AppState.currentState === 'active') {
1325
+ console.debug('[useLifecycleHook] enable');
1326
+ void latest.current.onEnable();
1327
+ }
1328
+ });
1329
+ const offBlur = navigation.addListener('blur', () => {
1330
+ focusedRef.current = false;
1331
+ console.debug('[useLifecycleHook] disable');
1332
+ void latest.current.onDisable();
1333
+ });
1334
+ return () => {
1335
+ console.debug('[useLifecycleHook] unsubscribing from focus/blur');
1336
+ offFocus();
1337
+ offBlur();
1338
+ };
1339
+ }, [navigation]);
1340
+ useEffect(() => {
1341
+ const subscription = AppState.addEventListener('change', next => {
1342
+ if (latest.current.appStateHandlingDisabled) {
1343
+ return;
1344
+ }
1345
+ console.debug(`[useLifecycleHook] app state -> ${next}`);
1346
+ if (next === 'active') {
1347
+ if (!latest.current.disabled && focusedRef.current) {
1348
+ void latest.current.onEnable();
1349
+ }
1350
+ }
1351
+ else {
1352
+ void latest.current.onDisable();
1353
+ }
1354
+ });
1355
+ return () => subscription.remove();
1356
+ }, []);
1357
+ // React to `disabled` flips.
1358
+ useEffect(() => {
1359
+ if (disabled) {
1360
+ void latest.current.onDisable();
1361
+ }
1362
+ else if (focusedRef.current && AppState.currentState === 'active') {
1363
+ void latest.current.onEnable();
1364
+ }
1365
+ }, [disabled]);
1366
+ }
1367
+
1368
+ // Native per-view window lifecycle events (emitted by the view containers on
1369
+ // both platforms — see ViewWindowEventsRelay / ViewWindowEvents). They drive
1370
+ // the single-owner camera model without any navigation-library coupling:
1371
+ // attach → claim, detach → release.
1372
+ const WINDOW_ATTACHED_EVENT = 'NativeView.onWindowAttached';
1373
+ const WINDOW_DETACHED_EVENT = 'NativeView.onWindowDetached';
1374
+ let windowEventsCaller = null;
1375
+ function getWindowEventsCaller() {
1376
+ if (windowEventsCaller === null) {
1377
+ windowEventsCaller = createRNNativeCaller(NativeModules.ScanditDataCaptureCore);
1378
+ }
1379
+ return windowEventsCaller;
1380
+ }
1381
+ function eventViewId(event) {
1382
+ const ev = event;
1383
+ if (typeof ev.viewId === 'number')
1384
+ return ev.viewId;
1385
+ if (typeof ev.data === 'string') {
1386
+ try {
1387
+ const parsed = JSON.parse(ev.data);
1388
+ if (typeof parsed.viewId === 'number')
1389
+ return parsed.viewId;
1390
+ }
1391
+ catch {
1392
+ return null;
1393
+ }
1394
+ }
1395
+ return null;
1396
+ }
1397
+ /**
1398
+ * The entire camera-ownership contract a view wrapper needs to learn. Register
1399
+ * a claim and drive it declaratively via `active`; the coordinator in
1400
+ * `ScanditProvider.tsx` derives the actual camera state from the full set of
1401
+ * currently-registered claims (see its module doc for the derivation rules)
1402
+ * and coalesces rapid changes into a single native transition.
1403
+ */
1404
+ function useCameraClaim({ mode, active, nativeViewRef }) {
1405
+ const { owner } = useScanditInternal();
1406
+ // Stable identity for the lifetime of this hook instance — the coordinator
1407
+ // keys its claim Set (and `granted()` waiters) on object identity, not
1408
+ // value equality.
1409
+ const claimRef = useRef(null);
1410
+ if (claimRef.current === null) {
1411
+ claimRef.current = { mode, active };
1412
+ }
1413
+ const registeredRef = useRef(false);
1414
+ const releasedRef = useRef(false);
1415
+ // `useLayoutEffect`, not `useEffect`: a caller that flips `active` via
1416
+ // `setState` and then immediately calls `granted()` relies on the claim
1417
+ // being synced to the coordinator within the SAME commit that applied the
1418
+ // state change, before `granted()`'s (microtask-deferred) check runs —
1419
+ // `useEffect`'s passive-effect scheduling can lag a tick behind that.
1420
+ useLayoutEffect(() => {
1421
+ const claim = claimRef.current;
1422
+ if (!registeredRef.current) {
1423
+ registeredRef.current = true;
1424
+ releasedRef.current = false;
1425
+ owner.addClaim(claim);
1426
+ return;
1427
+ }
1428
+ if (claim.mode !== mode || claim.active !== active) {
1429
+ owner.updateClaim(claim, { mode, active });
1430
+ }
1431
+ // eslint-disable-next-line react-hooks/exhaustive-deps
1432
+ }, [owner, mode, active]);
1433
+ // Native window lifecycle → ownership (SDC-32484 single-owner model):
1434
+ // attach → (re-)claim if the wrapper currently wants the camera, detach →
1435
+ // release. Superseded/stale flips are harmless: the coordinator ignores
1436
+ // deactivations from non-owners and claims are idempotent.
1437
+ const desiredActiveRef = useRef(active);
1438
+ desiredActiveRef.current = active;
1439
+ useEffect(() => {
1440
+ if (!nativeViewRef)
1441
+ return;
1442
+ const caller = getWindowEventsCaller();
1443
+ let disposed = false;
1444
+ const subscriptions = [];
1445
+ const matchesOwnView = (event) => {
1446
+ const id = eventViewId(event);
1447
+ if (id === null || nativeViewRef.current == null)
1448
+ return false;
1449
+ // Resolved lazily at event time: the ref is typically still null when
1450
+ // this effect first runs (the child component mounts later).
1451
+ const tag = findNodeHandle(nativeViewRef.current);
1452
+ return tag !== null && id === tag;
1453
+ };
1454
+ const subscribe = (eventName, onEvent) => {
1455
+ void caller
1456
+ .registerEvent(eventName, event => {
1457
+ if (!disposed && matchesOwnView(event))
1458
+ onEvent();
1459
+ return Promise.resolve();
1460
+ })
1461
+ .then(subscription => {
1462
+ if (disposed)
1463
+ void caller.unregisterEvent(eventName, subscription);
1464
+ else
1465
+ subscriptions.push([eventName, subscription]);
1466
+ });
1467
+ };
1468
+ subscribe(WINDOW_ATTACHED_EVENT, () => {
1469
+ if (desiredActiveRef.current && !releasedRef.current) {
1470
+ owner.updateClaim(claimRef.current, { active: true });
1471
+ }
1472
+ });
1473
+ subscribe(WINDOW_DETACHED_EVENT, () => {
1474
+ if (!releasedRef.current) {
1475
+ owner.updateClaim(claimRef.current, { active: false });
1476
+ }
1477
+ });
1478
+ return () => {
1479
+ disposed = true;
1480
+ for (const [eventName, subscription] of subscriptions) {
1481
+ void caller.unregisterEvent(eventName, subscription);
1482
+ }
1483
+ };
1484
+ }, [owner, nativeViewRef]);
1485
+ // Safety-net release on unmount for a caller that never explicitly calls
1486
+ // `release()` — mirrors the old `useApplyCameraProps` cleanup pattern.
1487
+ useEffect(() => {
1488
+ return () => {
1489
+ if (!releasedRef.current) {
1490
+ releasedRef.current = true;
1491
+ owner.removeClaim(claimRef.current);
1492
+ }
1493
+ };
1494
+ }, [owner]);
1495
+ return useMemo(() => ({
1496
+ granted: () =>
1497
+ // Deferred by one microtask: lets a same-turn `setState` (that a
1498
+ // caller just issued right before calling `granted()`) reach the
1499
+ // layout effect above first, so this doesn't read a stale `active`.
1500
+ Promise.resolve().then(() => owner.whenGranted(claimRef.current)),
1501
+ release: teardown => {
1502
+ if (releasedRef.current)
1503
+ return;
1504
+ releasedRef.current = true;
1505
+ owner.removeClaim(claimRef.current, teardown);
1506
+ },
1507
+ }), [owner]);
1508
+ }
1509
+
1074
1510
  var index = /*#__PURE__*/Object.freeze({
1075
1511
  __proto__: null,
1512
+ useCameraClaim: useCameraClaim,
1076
1513
  useDataCaptureContextInternal: useDataCaptureContextInternal,
1514
+ useLifecycleHook: useLifecycleHook,
1077
1515
  useMode: useMode,
1078
1516
  useModeListener: useModeListener,
1079
1517
  useNativeControl: useNativeControl,
1080
1518
  useOverlay: useOverlay,
1519
+ usePassThroughProps: usePassThroughProps,
1520
+ useScanditInternal: useScanditInternal,
1081
1521
  useStableProp: useStableProp,
1082
1522
  useViewHandle: useViewHandle
1083
1523
  });