Repository navigation
Expand file tree
/
Copy pathmpx-camera.tsx
More file actions
391 lines (365 loc) · 11.7 KB
/
Copy pathmpx-camera.tsx
File metadata and controls
391 lines (365 loc) · 11.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
import { createElement, forwardRef, useRef, useCallback, useContext, useState, useEffect, useMemo } from 'react'
import { getCurrentPage, useTransformStyle, useLayout, extendObject } from './utils'
import useInnerProps, { getCustomEvent } from './getInnerListeners'
import { Camera, useCameraDevice, useCodeScanner, useCameraFormat } from 'react-native-vision-camera'
import { noop, warn, hasOwn } from '@mpxjs/utils'
import { RouteContext } from './context'
import { watch, WatchOptions } from '@mpxjs/core'
const qualityValue = {
high: 90,
normal: 75,
low: 50,
original: 100
}
interface CameraProps {
mode?: 'normal' | 'scanCode'
resolution?: 'low' | 'medium' | 'high'
'device-position'?: 'front' | 'back'
flash?: 'auto' | 'on' | 'off'
'frame-size'?: 'small' | 'medium' | 'large'
style?: Record<string, any>
bindstop?: (event: Record<string, any>) => void
binderror?: (error: { message: string }) => void
bindinitdone?: (result: { type: string, data: string }) => void
bindscancode?: (result: { type: string, data: string }) => void
'parent-width'?: number
'parent-height'?: number
'enable-var'?: boolean
}
interface TakePhotoOptions {
quality?: 'high' | 'normal' | 'low' | 'original'
success?: (result: { errMsg: string, tempImagePath: string }) => void
fail?: (result: { errMsg: string }) => void
complete?: (result: { errMsg: string, tempImagePath?: string }) => void
}
interface RecordOptions {
timeout?: number
success?: (result: { errMsg: string }) => void
fail?: (result: { errMsg: string, error?: any }) => void
complete?: (result: { errMsg: string }) => void
timeoutCallback?: (result: { errMsg: string, error?: any }) => void
}
interface StopRecordOptions {
success?: (result: { errMsg: string, tempVideoPath: string, duration: number }) => void
fail?: (result: { errMsg: string }) => void
complete?: (result: { errMsg: string, tempVideoPath?: string, duration?: number }) => void
}
interface CameraRef {
setZoom: (zoom: number) => void
takePhoto: (options?: TakePhotoOptions) => void
startRecord: (options?: RecordOptions) => void
stopRecord: (options?: StopRecordOptions) => void
}
interface CameraPermissionCache {
promise?: Promise<any>
result?: boolean
}
type HandlerRef<T, P> = {
current: T | null
}
let RecordRes: any = null
const cameraPermissionCacheMap = new Map<number, CameraPermissionCache>()
function getCameraPermissionCache (pageId: number | undefined) {
if (pageId == null) return
let cache = cameraPermissionCacheMap.get(pageId)
if (!cache) {
cache = {}
cameraPermissionCacheMap.set(pageId, cache)
}
return cache
}
const _camera = forwardRef<HandlerRef<any, CameraProps>, CameraProps>((props: CameraProps, ref): JSX.Element | null => {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const cameraRef = useRef<any>(null)
const {
mode = 'normal',
resolution = 'medium',
'device-position': devicePosition = 'back',
flash = 'auto',
'frame-size': frameSize = 'medium',
bindinitdone,
bindstop,
bindscancode,
'parent-width': parentWidth,
'parent-height': parentHeight,
'enable-var': enableVar,
style = {}
} = props
const styleObj = extendObject(
{},
style
)
const {
normalStyle,
hasSelfPercent,
setWidth,
setHeight
} = useTransformStyle(styleObj, {
enableVar,
parentWidth,
parentHeight
})
const { layoutRef, layoutStyle, layoutProps } = useLayout({ props, hasSelfPercent, setWidth, setHeight, nodeRef: cameraRef })
const isPhoto = useRef<boolean>(false)
isPhoto.current = mode === 'normal'
const device = useCameraDevice(devicePosition || 'back')
const { navigation, pageId } = useContext(RouteContext) || {}
const [zoomValue, setZoomValue] = useState<number>(1)
const [isActive, setIsActive] = useState<boolean>(true)
const [hasPermission, setHasPermission] = useState<boolean | null>(null)
const page = getCurrentPage(pageId)
// 先定义常量,避免在条件判断后使用
const maxZoom = device?.maxZoom || 1
const RESOLUTION_MAPPING: Record<string, { width: number, height: number } | 'max'> = {
low: { width: 1280, height: 720 },
medium: { width: 1920, height: 1080 },
high: 'max'
}
const FRAME_SIZE_MAPPING: Record<string, { width: number, height: number } | 'max'> = {
small: { width: 1280, height: 720 },
medium: { width: 1920, height: 1080 },
large: 'max'
}
const format = useCameraFormat(device, [
{
photoResolution: RESOLUTION_MAPPING[resolution],
videoResolution: FRAME_SIZE_MAPPING[frameSize] || RESOLUTION_MAPPING[resolution]
}
])
const isScancode = useCallback((fail: (res: { errMsg: string }) => void, complete: (res: { errMsg: string }) => void) => {
if (!isPhoto.current) {
const result = {
errMsg: 'Not allow to invoke takePhoto in \'scanCode\' mode.'
}
fail(result)
complete(result)
return true
}
return false
}, [])
const codeScanner = useCodeScanner({
codeTypes: ['qr'],
onCodeScanned: (codes: any[]) => {
codes.forEach(code => {
const type = code.type === 'qr' ? 'QR_CODE' : code.type?.toUpperCase()
const frame = code.frame || {}
bindscancode && bindscancode(getCustomEvent('scancode', {}, {
detail: {
result: code.value,
type,
scanArea: [parseInt(frame.x) || 0, parseInt(frame.y) || 0, parseInt(frame.width) || 0, parseInt(frame.height) || 0]
}
}))
})
}
})
const onInitialized = useCallback(() => {
bindinitdone && bindinitdone(getCustomEvent('initdone', {}, {
detail: {
maxZoom
}
}))
}, [bindinitdone, maxZoom])
const onStopped = useCallback(() => {
bindstop && bindstop(getCustomEvent('stop', {}, { layoutRef }))
}, [bindstop])
const camera: CameraRef = useMemo(() => ({
setZoom: (zoom: number) => {
setZoomValue(zoom)
},
takePhoto: (options: TakePhotoOptions = {}) => {
const { success = noop, fail = noop, complete = noop } = options
if (isScancode(fail, complete)) return
cameraRef.current?.takePhoto?.({
quality: qualityValue[options.quality || 'normal'] as number
} as any).then((res: { path: any }) => {
const result = {
errMsg: 'takePhoto:ok',
tempImagePath: res.path
}
success(result)
complete(result)
}).catch(() => {
const result = {
errMsg: 'takePhoto:fail'
}
fail(result)
complete(result)
})
},
startRecord: (options: RecordOptions = {}) => {
let { timeout = 30, success = noop, fail = noop, complete = noop, timeoutCallback = noop } = options
timeout = timeout > 300 ? 300 : timeout
let recordTimer: NodeJS.Timeout | null = null
if (isScancode(fail, complete)) return
try {
const result = {
errMsg: 'startRecord:ok'
}
success(result)
complete(result)
cameraRef.current?.startRecording?.({
onRecordingError: (error: any) => {
if (recordTimer) clearTimeout(recordTimer)
const errorResult = {
errMsg: 'startRecord:fail during recording',
error: error
}
timeoutCallback(errorResult)
},
onRecordingFinished: (video: any) => {
RecordRes = video
if (recordTimer) clearTimeout(recordTimer)
}
})
recordTimer = setTimeout(() => { // 超时自动停止
cameraRef.current?.stopRecording().catch(() => {
// 忽略停止录制时的错误
})
}, timeout * 1000)
} catch (error: any) {
if (recordTimer) clearTimeout(recordTimer)
const result = {
errMsg: 'startRecord:fail ' + (error.message || 'unknown error')
}
fail(result)
complete(result)
}
},
stopRecord: (options: StopRecordOptions = {}) => {
const { success = noop, fail = noop, complete = noop } = options
if (isScancode(fail, complete)) return
try {
cameraRef.current?.stopRecording().then(() => {
setTimeout(() => {
if (RecordRes) {
const result = {
errMsg: 'stopRecord:ok',
tempVideoPath: RecordRes?.path,
duration: RecordRes.duration * 1000 // 转成ms
}
RecordRes = null
success(result)
complete(result)
}
}, 200) // 延时200ms,确保录制结果已准备好
}).catch((e: any) => {
const result = {
errMsg: 'stopRecord:fail ' + (e.message || 'promise rejected')
}
fail(result)
complete(result)
})
} catch (error: any) {
const result = {
errMsg: 'stopRecord:fail ' + (error.message || 'unknown error')
}
fail(result)
complete(result)
}
}
}), [])
useEffect(() => {
let unWatch: any
if (pageId && hasOwn(global.__mpxPageStatusMap, String(pageId))) {
unWatch = watch(() => global.__mpxPageStatusMap[pageId], (newVal: string) => {
if (newVal === 'show') {
if (page.id === pageId) {
setIsActive(true)
}
}
if (newVal === 'hide') {
setIsActive(false)
}
}, { sync: true } as WatchOptions)
}
const checkCameraPermission = async () => {
try {
const cameraPermission = global?.__mpx?.config?.rnConfig?.cameraPermission
if (typeof cameraPermission === 'function') {
const permissionCache = getCameraPermissionCache(pageId)
if (permissionCache && hasOwn(permissionCache, 'result')) {
setHasPermission(permissionCache.result === true)
return
}
let permissionResult
if (permissionCache) {
if (!permissionCache.promise) {
permissionCache.promise = cameraPermission()
}
permissionResult = await permissionCache.promise
} else {
permissionResult = await cameraPermission()
}
const granted = permissionResult === true
if (permissionCache) {
permissionCache.result = granted
}
setHasPermission(granted)
} else {
setHasPermission(true)
}
} catch (error) {
const permissionCache = getCameraPermissionCache(pageId)
if (permissionCache) {
permissionCache.result = false
}
setHasPermission(false)
}
}
checkCameraPermission()
return () => {
if (navigation?.camera === camera) {
delete navigation.camera
}
unWatch && unWatch()
}
}, [])
const innerProps:any = useInnerProps(
extendObject(
{},
props,
layoutProps,
{
ref: cameraRef,
style: extendObject({}, normalStyle, layoutStyle),
isActive,
photo: true,
video: true,
onInitialized,
onStopped,
device,
format,
codeScanner: !isPhoto.current ? codeScanner : undefined,
zoom: zoomValue,
torch: flash
}
),
[
'mode',
'resolution',
'frame-size',
'device-position',
'bindinitdone',
'bindstop',
'flash',
'bindscancode',
'binderror'
],
{
layoutRef
}
)
if (navigation && navigation.camera && navigation.camera !== camera) {
warn('<camera>: 一个页面只能插入一个')
return null
} else if (navigation) {
navigation.camera = camera
}
if (!hasPermission || !device) {
return null
}
return createElement(Camera, innerProps)
})
_camera.displayName = 'MpxCamera'
export default _camera