import React, { forwardRef, useCallback, useImperativeHandle, useRef } from 'react'; import { NativeSyntheticEvent, Platform, StyleSheet, View } from 'react-native'; import { DeepPartial, DocumentDetectionResult, ImageRef, autorelease, createSBError, } from '../../types'; import NativeDocumentScannerView, { Commands, onNativeDocumentDetectionResult, onNativeDocumentScannerResult, onNativeError, } from '../spec/ScanbotDocumentScannerViewNativeComponent'; import { ScanbotDocumentScannerViewHandle, ScanbotDocumentScannerViewProperties, } from './ScanbotDocumentScannerViewProperties'; export const ScanbotDocumentScannerView = forwardRef< ScanbotDocumentScannerViewHandle, ScanbotDocumentScannerViewProperties >(({ onSnappedDocumentResult, onFrameDetectionResult, onError, ...props }, forwardedRef) => { const viewRef = useRef(null); useImperativeHandle(forwardedRef, () => { return { freezeCamera() { if (viewRef.current) { Commands.freezeCamera(viewRef.current); } }, unfreezeCamera() { if (viewRef.current) { Commands.unfreezeCamera(viewRef.current); } }, snapDocument(acquireFocus?: boolean) { if (viewRef.current) { Commands.snapDocument(viewRef.current, acquireFocus === true); } }, }; }, []); const _onSnappedDocumentResult = useCallback( (event: NativeSyntheticEvent) => { const originalImageUuid = event.nativeEvent.originalImage; if (originalImageUuid) { autorelease(async () => { try { const originalImage = ImageRef.from({ uniqueId: originalImageUuid, } as DeepPartial); const documentImage = event.nativeEvent.documentImage ? ImageRef.from({ uniqueId: event.nativeEvent.documentImage, } as DeepPartial) : undefined; const detectionResult = event.nativeEvent.detectionResult ? new DocumentDetectionResult( (Platform.OS === 'ios' ? JSON.parse(event.nativeEvent.detectionResult) : event.nativeEvent.detectionResult) as DeepPartial ) : undefined; await onSnappedDocumentResult(originalImage, documentImage, detectionResult); } catch (e) { onError && onError(createSBError(e)); } }); } }, [onSnappedDocumentResult, onError] ); const _onFrameDetectionResult = useCallback( (event: NativeSyntheticEvent) => { if (event.nativeEvent.result) { try { const detectionResult = new DocumentDetectionResult( (Platform.OS === 'ios' ? JSON.parse(event.nativeEvent.result) : event.nativeEvent.result) as DeepPartial ); onFrameDetectionResult && onFrameDetectionResult(detectionResult); } catch (e) { onError && onError(createSBError(e)); } } }, [onFrameDetectionResult, onError] ); const _onError = useCallback( (event: NativeSyntheticEvent) => { if (onError) { onError(createSBError(event.nativeEvent)); } }, [onError] ); return ( ); }); const styles = StyleSheet.create({ container: { flex: 1, }, });