All files / app/(tabs)/scanner/components/camera ExpoCameraView.tsx

77.61% Statements 52/67
75.86% Branches 22/29
75% Functions 9/12
79.68% Lines 51/64

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                      1x                     1x     1x 5x       1x 6x   6x 1x     5x 1x     4x                                                                             13x 13x 13x           13x           13x     13x 13x     13x 13x     13x     13x 1x     1x                                                           13x 4x 4x     13x 1x 1x   1x                                                           1x 1x         13x   6x   6x 6x   6x   4x 1x     3x 3x 3x         13x 1x 1x 1x     13x             13x           13x                   13x                                                                                                        
/**
 * ExpoCameraView - 相机视图主组件
 */
 
import React, { useCallback, useRef, useState } from 'react';
import { Animated, LayoutChangeEvent, StyleSheet, View } from 'react-native';
import { CameraType, CameraView } from 'expo-camera';
import * as Haptics from 'expo-haptics';
import { YStack } from 'tamagui';
 
import { ScanType } from '@/src/types/camera';
import type { ExpoBarcodeResult } from '@/src/types/camera';
 
import { CameraBottomBar } from './components/CameraBottomBar';
import { CameraControls } from './components/CameraControls';
import { ScanFrame } from './components/ScanFrame';
import { useZoomGesture } from './hooks/useZoomGesture';
 
// 支持的条码类型(与组件配置一致)
export const SUPPORTED_BARCODE_TYPES = [
  'qr',
  'ean13',
  'ean8',
  'code128',
  'code39',
  'upc_e',
  'upc_a',
] as const;
 
// 防抖间隔(毫秒)
const SCAN_DEBOUNCE_TIME = 1000;
 
// EAN13格式校验(13位纯数字)
const isValidEAN13 = (data: string): boolean => {
  return /^\d{13}$/.test(data);
};
 
// 通用条码数据校验
const isValidBarcodeData = (data: string | null | undefined, type: string): boolean => {
  Iif (!data || data.trim() === '') return false;
 
  if (!SUPPORTED_BARCODE_TYPES.includes(type as (typeof SUPPORTED_BARCODE_TYPES)[number])) {
    return false;
  }
 
  if (type === 'ean13' && !isValidEAN13(data)) {
    return false;
  }
 
  return true;
};
 
interface ExpoCameraViewProps {
  cameraRef: React.RefObject<CameraView | null>;
  facing: 'front' | 'back';
  scanType: ScanType;
  onClose: () => void;
  onToggleCamera: () => void;
  onToggleScanType: () => void;
  onCameraReady: () => void;
  onBarCodeScanned: (result: ExpoBarcodeResult) => void;
  onTakePhoto: (
    zoom?: number,
    frameLayout?: { x: number; y: number; width: number; height: number } | null
  ) => void;
  takePicture: (options?: {
    quality?: number;
    cropToScanFrame?: boolean;
    zoom?: number;
    frameLayout?: { x: number; y: number; width: number; height: number };
  }) => Promise<{ uri: string } | null>;
  debounceTime?: number;
}
 
export function ExpoCameraView({
  cameraRef,
  facing,
  scanType,
  onClose,
  onToggleCamera,
  onToggleScanType,
  onCameraReady,
  onBarCodeScanned,
  onTakePhoto,
  takePicture,
  debounceTime = SCAN_DEBOUNCE_TIME,
}: ExpoCameraViewProps) {
  // ============ 状态管理 ============
  const [isCameraReady, setIsCameraReady] = useState(false);
  const [zoom, setZoom] = useState(0);
  const [scanFrameLayout, setScanFrameLayout] = useState<{
    x: number;
    y: number;
    width: number;
    height: number;
  } | null>(null);
  const [cameraViewLayout, setCameraViewLayout] = useState<{
    x: number;
    y: number;
    width: number;
    height: number;
  } | null>(null);
  const cameraViewRef = useRef<View>(null);
 
  // 防抖相关
  const lastScannedData = useRef<string | null>(null);
  const lastScanTime = useRef<number>(0);
 
  // 动画相关
  const frameScale = useRef(new Animated.Value(1)).current;
  const frameBorderWidth = useRef(new Animated.Value(2)).current;
 
  // ============ Hooks ============
  const { panResponder } = useZoomGesture({ zoom, setZoom });
 
  // ============ 动画效果 ============
  const playShutterAnimation = useCallback(() => {
    Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Medium);
 
    // 扫描框收缩动画
    Animated.parallel([
      Animated.sequence([
        Animated.timing(frameScale, {
          toValue: 0.85,
          duration: 150,
          useNativeDriver: true,
        }),
        Animated.spring(frameScale, {
          toValue: 1,
          friction: 5,
          tension: 100,
          useNativeDriver: true,
        }),
      ]),
      Animated.sequence([
        Animated.timing(frameBorderWidth, {
          toValue: 6,
          duration: 150,
          useNativeDriver: false,
        }),
        Animated.timing(frameBorderWidth, {
          toValue: 2,
          duration: 150,
          useNativeDriver: false,
        }),
      ]),
    ]).start();
  }, [frameScale, frameBorderWidth]);
 
  // ============ 事件处理 ============
  const handleCameraReady = useCallback(() => {
    setIsCameraReady(true);
    onCameraReady();
  }, [onCameraReady]);
 
  const handleTakePhotoWithAnimation = useCallback(() => {
    playShutterAnimation();
    setTimeout(() => {
      // 计算扫描框相对于相机视图的位置
      Iif (scanFrameLayout && cameraViewLayout) {
        console.log('\n🎬 拍照参数计算:');
        console.log('  扫描框(屏幕坐标):', {
          x: scanFrameLayout.x.toFixed(1),
          y: scanFrameLayout.y.toFixed(1),
          w: scanFrameLayout.width.toFixed(1),
          h: scanFrameLayout.height.toFixed(1),
        });
        console.log('  相机视图(屏幕坐标):', {
          x: cameraViewLayout.x.toFixed(1),
          y: cameraViewLayout.y.toFixed(1),
          w: cameraViewLayout.width.toFixed(1),
          h: cameraViewLayout.height.toFixed(1),
        });
 
        const relativeLayout = {
          x: scanFrameLayout.x - cameraViewLayout.x,
          y: scanFrameLayout.y - cameraViewLayout.y,
          width: scanFrameLayout.width,
          height: scanFrameLayout.height,
        };
        console.log('  📐 扫描框(相对相机):', {
          x: relativeLayout.x.toFixed(1),
          y: relativeLayout.y.toFixed(1),
          w: relativeLayout.width.toFixed(1),
          h: relativeLayout.height.toFixed(1),
        });
 
        onTakePhoto(zoom, relativeLayout);
      } else {
        console.warn('⚠️ 缺少布局信息:', { scanFrameLayout, cameraViewLayout });
        onTakePhoto(zoom, scanFrameLayout);
      }
    }, 50);
  }, [onTakePhoto, playShutterAnimation, zoom, scanFrameLayout, cameraViewLayout]);
 
  const handleBarCodeScanned = useCallback(
    (result: ExpoBarcodeResult) => {
      Iif (scanType !== ScanType.BARCODE || !isCameraReady) return;
 
      const { data, type } = result;
      const currentTime = Date.now();
 
      if (!isValidBarcodeData(data, type)) return;
 
      if (lastScannedData.current === data && currentTime - lastScanTime.current < debounceTime) {
        return;
      }
 
      lastScannedData.current = data;
      lastScanTime.current = currentTime;
      onBarCodeScanned(result);
    },
    [scanType, isCameraReady, onBarCodeScanned, debounceTime]
  );
 
  const handleZoomIn = useCallback(() => {
    const newZoom = Math.min(1, zoom + 0.2);
    setZoom(newZoom);
    Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light);
  }, [zoom]);
 
  const handleZoomOut = useCallback(() => {
    const newZoom = Math.max(0, zoom - 0.2);
    setZoom(newZoom);
    Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light);
  }, [zoom]);
 
  // ============ 动画插值 ============
  const frameBorderWidthInterpolated = frameBorderWidth.interpolate({
    inputRange: [2, 6],
    outputRange: [2, 6],
  });
 
  // 测量相机视图的位置
  const handleCameraViewLayout = useCallback((event: LayoutChangeEvent) => {
    if (cameraViewRef.current) {
      cameraViewRef.current.measureInWindow((x, y, width, height) => {
        console.log('📹 相机视图位置:', { x, y, width, height });
        setCameraViewLayout({ x, y, width, height });
      });
    }
  }, []);
 
  // ============ 渲染 ============
  return (
    <YStack flex={1} backgroundColor="black">
      <YStack
        ref={cameraViewRef}
        flex={1}
        position="relative"
        {...panResponder.panHandlers}
        onLayout={handleCameraViewLayout}
      >
        {/* 相机视图 */}
        <CameraView
          ref={cameraRef}
          style={StyleSheet.absoluteFill}
          facing={facing as CameraType}
          zoom={zoom}
          autofocus="on"
          onCameraReady={handleCameraReady}
          barcodeScannerSettings={{
            barcodeTypes: [...SUPPORTED_BARCODE_TYPES],
          }}
          onBarcodeScanned={scanType === ScanType.BARCODE ? handleBarCodeScanned : undefined}
        />
 
        {/* 顶部控制栏 */}
        <CameraControls
          scanType={scanType}
          zoom={zoom}
          onClose={onClose}
          onToggleCamera={onToggleCamera}
          onZoomIn={handleZoomIn}
          onZoomOut={handleZoomOut}
          setZoom={setZoom}
        />
 
        {/* 扫描框 */}
        <ScanFrame
          scanType={scanType}
          frameScale={frameScale}
          frameBorderWidth={frameBorderWidthInterpolated}
          onLayout={setScanFrameLayout}
        />
 
        {/* 底部操作栏 */}
        <CameraBottomBar
          scanType={scanType}
          onToggleScanType={onToggleScanType}
          onTakePhoto={handleTakePhotoWithAnimation}
        />
      </YStack>
    </YStack>
  );
}