forked from StellarSplit/StellarSplit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCameraCapture.tsx
More file actions
430 lines (386 loc) · 13.2 KB
/
Copy pathCameraCapture.tsx
File metadata and controls
430 lines (386 loc) · 13.2 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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
import { useEffect, useRef, useState } from 'react';
import { Camera, Repeat2, X, Check } from 'lucide-react';
import {
requestCameraPermission,
stopCameraStream,
checkCameraPermission,
getUserFriendlyErrorMessage,
} from '../../utils/cameraPermissions';
import {
compressImage,
blobToFile,
formatFileSize,
isValidImageType,
} from '../../utils/imageCompression';
export interface CameraCaptureProps {
onCapture: (file: File) => void;
onError?: (error: Error) => void;
maxFileSize?: number; // in bytes
compressionQuality?: number; // 0-1
}
interface CameraState {
status: 'idle' | 'requesting' | 'active' | 'captured' | 'error';
error?: string;
isFrontCamera: boolean;
originalFile?: File;
compressedFile?: File;
capturedImageUrl?: string;
}
/**
* CameraCapture Component
* Allows users to capture photos of receipts on mobile and desktop
* Features:
* - Access device camera using HTML5 API
* - Show camera preview
* - Capture button with visual feedback
* - Switch between front/back camera (mobile)
* - Image preview after capture
* - Retake option
* - Image compression before upload
* - Graceful permission handling
*/
export const CameraCapture = ({
onCapture,
onError,
maxFileSize = 5242880, // 5MB default
compressionQuality = 0.8,
}: CameraCaptureProps) => {
const videoRef = useRef<HTMLVideoElement>(null);
const canvasRef = useRef<HTMLCanvasElement>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
const [cameraState, setCameraState] = useState<CameraState>({
status: 'idle',
isFrontCamera: false,
});
const [stream, setStream] = useState<MediaStream | null>(null);
const [isCompressing, setIsCompressing] = useState(false);
// Initialize camera on mount
useEffect(() => {
const initializeCamera = async () => {
try {
const permissionStatus = await checkCameraPermission();
if (permissionStatus === 'denied') {
setCameraState((prev) => ({
...prev,
status: 'error',
error: 'Camera permission was previously denied. Please enable it in browser settings.',
}));
return;
}
setCameraState((prev) => ({ ...prev, status: 'requesting' }));
const mediaStream = await requestCameraPermission({
video: {
facingMode: cameraState.isFrontCamera ? 'user' : 'environment',
width: { ideal: 1920 },
height: { ideal: 1440 },
},
audio: false,
});
setStream(mediaStream);
setCameraState((prev) => ({ ...prev, status: 'active', error: undefined }));
if (videoRef.current) {
videoRef.current.srcObject = mediaStream;
}
} catch (error) {
const err = error as Error;
const errorMessage = getUserFriendlyErrorMessage(err);
setCameraState((prev) => ({
...prev,
status: 'error',
error: errorMessage,
}));
onError?.(err);
}
};
initializeCamera();
return () => {
if (stream) {
stopCameraStream(stream);
}
};
}, [cameraState.isFrontCamera, onError]);
// Switch camera
const handleSwitchCamera = async () => {
if (stream) {
stopCameraStream(stream);
setStream(null);
}
setCameraState((prev) => ({
...prev,
isFrontCamera: !prev.isFrontCamera,
status: 'requesting',
error: undefined,
}));
};
// Capture image from camera
const handleCapture = async () => {
if (!videoRef.current || !canvasRef.current) {
return;
}
try {
const canvas = canvasRef.current;
const video = videoRef.current;
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
const ctx = canvas.getContext('2d');
if (!ctx) {
throw new Error('Failed to get canvas context');
}
ctx.drawImage(video, 0, 0);
canvas.toBlob(async (blob) => {
if (!blob) {
throw new Error('Failed to capture image');
}
try {
const originalFile = new File([blob], 'receipt.jpg', {
type: 'image/jpeg',
});
// Create preview URL
const previewUrl = URL.createObjectURL(blob);
setCameraState((prev) => ({
...prev,
status: 'captured',
capturedImageUrl: previewUrl,
originalFile,
}));
} catch (error) {
const err = error as Error;
setCameraState((prev) => ({
...prev,
status: 'error',
error: 'Failed to capture image',
}));
onError?.(err);
}
}, 'image/jpeg');
} catch (error) {
const err = error as Error;
setCameraState((prev) => ({
...prev,
status: 'error',
error: err.message || 'Failed to capture image',
}));
onError?.(err);
}
};
// Compress and submit image
const handleConfirmCapture = async () => {
if (!cameraState.originalFile) {
return;
}
setIsCompressing(true);
try {
let fileToSubmit = cameraState.originalFile;
let compressedBlob = await compressImage(cameraState.originalFile, {
quality: compressionQuality,
});
// Check file size
if (compressedBlob.size > maxFileSize) {
// Try more aggressive compression
compressedBlob = await compressImage(cameraState.originalFile, {
quality: Math.max(0.5, compressionQuality - 0.2),
});
}
fileToSubmit = blobToFile(compressedBlob, 'receipt.jpg');
setCameraState((prev) => ({
...prev,
compressedFile: fileToSubmit,
}));
onCapture(fileToSubmit);
} catch (error) {
const err = error as Error;
setCameraState((prev) => ({
...prev,
status: 'error',
error: err.message || 'Failed to compress image',
}));
onError?.(err);
} finally {
setIsCompressing(false);
}
};
// Retake photo
const handleRetake = () => {
if (cameraState.capturedImageUrl) {
URL.revokeObjectURL(cameraState.capturedImageUrl);
}
setCameraState((prev) => ({
...prev,
status: 'active',
capturedImageUrl: undefined,
originalFile: undefined,
compressedFile: undefined,
error: undefined,
}));
};
// Upload from file (fallback for desktop)
const handleFileUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
if (!isValidImageType(file)) {
setCameraState((prev) => ({
...prev,
error: 'Please select a valid image file (JPEG, PNG, or WebP)',
}));
return;
}
try {
setIsCompressing(true);
const compressedBlob = await compressImage(file, {
quality: compressionQuality,
});
if (compressedBlob.size > maxFileSize) {
const moreCompressed = await compressImage(file, {
quality: Math.max(0.5, compressionQuality - 0.2),
});
const compressedFile = blobToFile(moreCompressed, 'receipt.jpg');
onCapture(compressedFile);
} else {
const compressedFile = blobToFile(compressedBlob, 'receipt.jpg');
onCapture(compressedFile);
}
} catch (error) {
const err = error as Error;
setCameraState((prev) => ({
...prev,
error: err.message || 'Failed to process image',
}));
onError?.(err);
} finally {
setIsCompressing(false);
}
};
return (
<div className="w-full max-w-2xl mx-auto">
{/* Camera Preview or Captured Image */}
<div className="relative bg-black rounded-xl overflow-hidden shadow-lg">
{cameraState.status === 'active' ? (
<>
{/* Video Preview */}
<video
ref={videoRef}
autoPlay
playsInline
className="w-full aspect-video object-cover"
/>
{/* Camera Controls Overlay */}
<div className="absolute inset-0 flex flex-col justify-between p-4">
{/* Top - Camera Switch Button */}
{cameraState.status === 'active' && (
<div className="flex justify-end">
<button
onClick={handleSwitchCamera}
aria-label="Switch camera"
className="p-2 bg-black/50 rounded-full text-white hover:bg-black/70 transition-colors focus:outline-none focus:ring-2 focus:ring-purple-500"
>
<Repeat2 size={24} />
</button>
</div>
)}
{/* Bottom - Capture Controls */}
<div className="flex justify-center gap-4">
{/* File Upload Fallback */}
<label className="px-6 py-3 bg-gray-700/50 text-white rounded-full cursor-pointer hover:bg-gray-700 transition-colors flex items-center gap-2 focus-within:ring-2 focus-within:ring-purple-500">
<input
ref={fileInputRef}
type="file"
accept="image/*"
className="hidden"
onChange={handleFileUpload}
aria-label="Upload image file"
/>
Upload
</label>
{/* Capture Button */}
<button
onClick={handleCapture}
aria-label="Take photo"
className="p-4 bg-purple-500 text-white rounded-full hover:bg-purple-600 transition-all active:scale-95 shadow-lg focus:outline-none focus:ring-2 focus:ring-purple-500 focus:ring-offset-2"
>
<Camera size={28} />
</button>
</div>
</div>
</>
) : cameraState.status === 'captured' && cameraState.capturedImageUrl ? (
<>
{/* Captured Image Preview */}
<img
src={cameraState.capturedImageUrl}
alt="Captured receipt"
className="w-full aspect-video object-cover"
/>
{/* Image Review Controls */}
<div className="absolute inset-0 flex items-end justify-center p-4 bg-gradient-to-t from-black/50 to-transparent">
<div className="flex gap-4">
{/* Retake Button */}
<button
onClick={handleRetake}
disabled={isCompressing}
aria-label="Retake photo"
className="px-6 py-3 bg-gray-600 text-white rounded-full hover:bg-gray-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed focus:outline-none focus:ring-2 focus:ring-purple-500 flex items-center gap-2"
>
<Repeat2 size={20} />
Retake
</button>
{/* Confirm Button */}
<button
onClick={handleConfirmCapture}
disabled={isCompressing}
aria-label="Confirm and upload photo"
className="px-6 py-3 bg-purple-500 text-white rounded-full hover:bg-purple-600 transition-all active:scale-95 disabled:opacity-50 disabled:cursor-not-allowed focus:outline-none focus:ring-2 focus:ring-purple-500 flex items-center gap-2"
>
{isCompressing ? (
<>
<span className="animate-spin">⏳</span>
Compressing...
</>
) : (
<>
<Check size={20} />
Confirm
</>
)}
</button>
</div>
</div>
</>
) : cameraState.status === 'requesting' ? (
<div className="w-full aspect-video flex items-center justify-center">
<div className="text-center text-white">
<div className="animate-spin mb-4">
<Camera size={48} />
</div>
<p>Requesting camera access...</p>
</div>
</div>
) : cameraState.status === 'error' ? (
<div className="w-full aspect-video flex items-center justify-center bg-red-900/20">
<div className="text-center text-white p-4">
<X size={48} className="mx-auto mb-4 text-red-400" />
<p className="font-semibold mb-2">Camera Error</p>
<p className="text-sm text-gray-300">{cameraState.error}</p>
</div>
</div>
) : null}
</div>
{/* Hidden Canvas for Image Capture */}
<canvas ref={canvasRef} className="hidden" />
{/* File Size Info */}
{cameraState.compressedFile && (
<div className="mt-4 p-3 bg-blue-50 rounded-lg text-sm text-blue-800">
<p>
Image compressed: {formatFileSize(cameraState.compressedFile.size)}
</p>
</div>
)}
{/* Error Message */}
{cameraState.error && cameraState.status !== 'error' && (
<div className="mt-4 p-3 bg-red-50 rounded-lg text-sm text-red-800 flex items-start gap-2">
<X size={16} className="mt-0.5 flex-shrink-0" />
<div>{cameraState.error}</div>
</div>
)}
</div>
);
};