1
1
import * as React from 'react'
2
- import { useState } from 'react'
3
- import { StyleSheet , View } from 'react-native'
4
- import { useCameraDevice , useCodeScanner } from 'react-native-vision-camera'
2
+ import { useCallback , useRef , useState } from 'react'
3
+ import { Alert , AlertButton , Linking , StyleSheet , View } from 'react-native'
4
+ import { Code , useCameraDevice , useCodeScanner } from 'react-native-vision-camera'
5
5
import { Camera } from 'react-native-vision-camera'
6
6
import { CONTENT_SPACING , CONTROL_BUTTON_SIZE , SAFE_AREA_PADDING } from './Constants'
7
7
import { useIsForeground } from './hooks/useIsForeground'
@@ -12,6 +12,26 @@ import type { Routes } from './Routes'
12
12
import type { NativeStackScreenProps } from '@react-navigation/native-stack'
13
13
import { useIsFocused } from '@react-navigation/core'
14
14
15
+ const showCodeAlert = ( value : string , onDismissed : ( ) => void ) : void => {
16
+ const buttons : AlertButton [ ] = [
17
+ {
18
+ text : 'Close' ,
19
+ style : 'cancel' ,
20
+ onPress : onDismissed ,
21
+ } ,
22
+ ]
23
+ if ( value . startsWith ( 'http' ) ) {
24
+ buttons . push ( {
25
+ text : 'Open URL' ,
26
+ onPress : ( ) => {
27
+ Linking . openURL ( value )
28
+ onDismissed ( )
29
+ } ,
30
+ } )
31
+ }
32
+ Alert . alert ( 'Scanned Code' , value , buttons )
33
+ }
34
+
15
35
type Props = NativeStackScreenProps < Routes , 'CodeScannerPage' >
16
36
export function CodeScannerPage ( { navigation } : Props ) : React . ReactElement {
17
37
// 1. Use a simple default back camera
@@ -25,12 +45,23 @@ export function CodeScannerPage({ navigation }: Props): React.ReactElement {
25
45
// 3. (Optional) enable a torch setting
26
46
const [ torch , setTorch ] = useState ( false )
27
47
28
- // 4. Initialize the Code Scanner to scan QR codes and Barcodes
48
+ // 4. On code scanned, we show an aler to the user
49
+ const isShowingAlert = useRef ( false )
50
+ const onCodeScanned = useCallback ( ( codes : Code [ ] ) => {
51
+ console . log ( `Scanned ${ codes . length } codes:` , codes )
52
+ const value = codes [ 0 ] ?. value
53
+ if ( value == null ) return
54
+ if ( isShowingAlert . current ) return
55
+ showCodeAlert ( value , ( ) => {
56
+ isShowingAlert . current = false
57
+ } )
58
+ isShowingAlert . current = true
59
+ } , [ ] )
60
+
61
+ // 5. Initialize the Code Scanner to scan QR codes and Barcodes
29
62
const codeScanner = useCodeScanner ( {
30
63
codeTypes : [ 'qr' , 'ean-13' ] ,
31
- onCodeScanned : ( codes , frame ) => {
32
- console . log ( codes , frame )
33
- } ,
64
+ onCodeScanned : onCodeScanned ,
34
65
} )
35
66
36
67
return (
0 commit comments