@smileid/web-components 10.0.6 → 11.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (142) hide show
  1. package/README.md +15 -15
  2. package/dist/README.md +15 -0
  3. package/dist/components/README.md +14 -0
  4. package/dist/components/document/src/README.md +111 -0
  5. package/dist/components/document/src/document-capture/README.md +90 -0
  6. package/dist/components/document/src/document-capture-instructions/README.md +56 -0
  7. package/dist/components/document/src/document-capture-review/README.md +79 -0
  8. package/dist/components/selfie/README.md +225 -0
  9. package/dist/components/smart-camera-web/src/README.md +207 -0
  10. package/dist/domain/camera/src/README.md +38 -0
  11. package/dist/domain/file-upload/README.md +35 -0
  12. package/dist/esm/{DocumentCaptureScreens-BjATTDqu.js → DocumentCaptureScreens-DmH2JZDA.js} +3 -3
  13. package/dist/esm/DocumentCaptureScreens-DmH2JZDA.js.map +1 -0
  14. package/dist/esm/EndUserConsent-D4fd1ovG.js.map +1 -1
  15. package/dist/esm/Navigation-CTjK6tLU.js.map +1 -1
  16. package/dist/esm/PoweredBySmileId-CxbaihMu.js.map +1 -1
  17. package/dist/esm/SelfieCaptureScreens-DbdN2zNk.js +7901 -0
  18. package/dist/esm/SelfieCaptureScreens-DbdN2zNk.js.map +1 -0
  19. package/dist/esm/SignaturePad-C7MtmT8m.js.map +1 -1
  20. package/dist/esm/TotpConsent-CQU5jQi4.js.map +1 -1
  21. package/dist/esm/combobox.js.map +1 -1
  22. package/dist/esm/document.js +1 -1
  23. package/dist/esm/main.js +2 -2
  24. package/dist/esm/{package-CZlW6BZn.js → package-bgeQiff6.js} +2 -2
  25. package/dist/esm/package-bgeQiff6.js.map +1 -0
  26. package/dist/esm/selfie.js +1 -1
  27. package/dist/esm/smart-camera-web.js +3 -3
  28. package/dist/esm/smart-camera-web.js.map +1 -1
  29. package/dist/esm/styles-BOEZtbuc.js.map +1 -1
  30. package/dist/package-lock.json +4948 -0
  31. package/dist/package.json +59 -0
  32. package/dist/smart-camera-web.js +72 -98
  33. package/dist/smart-camera-web.js.gz +0 -0
  34. package/dist/smart-camera-web.js.map +1 -1
  35. package/dist/src/components/combobox/src/index.js +2 -0
  36. package/dist/src/components/combobox/src/index.js.map +7 -0
  37. package/dist/src/components/document/src/index.js +2 -0
  38. package/dist/src/components/document/src/index.js.map +7 -0
  39. package/dist/src/components/end-user-consent/src/index.js +14 -0
  40. package/dist/src/components/end-user-consent/src/index.js.map +7 -0
  41. package/dist/src/components/selfie/src/index.js +2 -0
  42. package/dist/src/components/selfie/src/index.js.map +7 -0
  43. package/dist/src/components/signature-pad/src/index.js +10 -0
  44. package/dist/src/components/signature-pad/src/index.js.map +7 -0
  45. package/dist/src/components/smart-camera-web/src/SmartCameraWeb.js +2 -0
  46. package/dist/src/components/smart-camera-web/src/SmartCameraWeb.js.map +7 -0
  47. package/dist/src/components/totp-consent/src/index.js +14 -0
  48. package/dist/src/components/totp-consent/src/index.js.map +7 -0
  49. package/dist/src/index.js.map +7 -0
  50. package/dist/styles/README.md +3 -0
  51. package/dist/types/combobox.d.ts +19 -19
  52. package/dist/types/document.d.ts +19 -19
  53. package/dist/types/end-user-consent.d.ts +19 -19
  54. package/dist/types/main.d.ts +24 -20
  55. package/dist/types/navigation.d.ts +19 -19
  56. package/dist/types/selfie.d.ts +19 -19
  57. package/dist/types/signature-pad.d.ts +19 -19
  58. package/dist/types/smart-camera-web.d.ts +19 -19
  59. package/dist/types/totp-consent.d.ts +19 -19
  60. package/lib/components/README.md +14 -14
  61. package/lib/components/attribution/PoweredBySmileId.js +42 -42
  62. package/lib/components/camera-permission/CameraPermission.js +139 -139
  63. package/lib/components/camera-permission/CameraPermission.stories.js +27 -27
  64. package/lib/components/combobox/src/Combobox.js +589 -589
  65. package/lib/components/combobox/src/index.js +1 -1
  66. package/lib/components/document/src/DocumentCaptureScreens.js +410 -409
  67. package/lib/components/document/src/DocumentCaptureScreens.stories.js +57 -57
  68. package/lib/components/document/src/README.md +111 -111
  69. package/lib/components/document/src/document-capture/DocumentCapture.js +760 -760
  70. package/lib/components/document/src/document-capture/DocumentCapture.stories.js +78 -78
  71. package/lib/components/document/src/document-capture/README.md +90 -90
  72. package/lib/components/document/src/document-capture/index.js +3 -3
  73. package/lib/components/document/src/document-capture-instructions/DocumentCaptureInstructions.js +545 -545
  74. package/lib/components/document/src/document-capture-instructions/DocumentCaptureInstructions.stories.js +24 -24
  75. package/lib/components/document/src/document-capture-instructions/README.md +56 -56
  76. package/lib/components/document/src/document-capture-instructions/index.js +3 -3
  77. package/lib/components/document/src/document-capture-review/DocumentCaptureReview.js +360 -360
  78. package/lib/components/document/src/document-capture-review/DocumentCaptureReview.stories.js +24 -24
  79. package/lib/components/document/src/document-capture-review/README.md +79 -79
  80. package/lib/components/document/src/document-capture-review/index.js +3 -3
  81. package/lib/components/document/src/index.js +3 -3
  82. package/lib/components/end-user-consent/src/EndUserConsent.js +795 -795
  83. package/lib/components/end-user-consent/src/EndUserConsent.stories.js +29 -29
  84. package/lib/components/end-user-consent/src/index.js +4 -4
  85. package/lib/components/navigation/src/Navigation.js +171 -171
  86. package/lib/components/navigation/src/Navigation.stories.js +24 -24
  87. package/lib/components/navigation/src/index.js +3 -3
  88. package/lib/components/selfie/README.md +225 -225
  89. package/lib/components/selfie/src/SelfieCaptureScreens.js +420 -431
  90. package/lib/components/selfie/src/SelfieCaptureScreens.stories.js +29 -29
  91. package/lib/components/selfie/src/index.js +3 -3
  92. package/lib/components/selfie/src/selfie-capture/SelfieCapture.js +1099 -1084
  93. package/lib/components/selfie/src/selfie-capture/SelfieCapture.stories.js +36 -36
  94. package/lib/components/selfie/src/selfie-capture/index.js +3 -3
  95. package/lib/components/selfie/src/selfie-capture-instructions/SelfieCaptureInstructions.js +689 -689
  96. package/lib/components/selfie/src/selfie-capture-instructions/SelfieCaptureInstructions.stories.js +23 -23
  97. package/lib/components/selfie/src/selfie-capture-instructions/index.js +3 -3
  98. package/lib/components/selfie/src/selfie-capture-review/SelfieCaptureReview.js +209 -209
  99. package/lib/components/selfie/src/selfie-capture-review/SelfieCaptureReview.stories.js +24 -24
  100. package/lib/components/selfie/src/selfie-capture-review/index.js +3 -3
  101. package/lib/components/selfie/src/selfie-capture-wrapper/SelfieCaptureWrapper.tsx +256 -239
  102. package/lib/components/selfie/src/selfie-capture-wrapper/index.ts +1 -1
  103. package/lib/components/selfie/src/smartselfie-capture/OvalProgress.tsx +81 -81
  104. package/lib/components/selfie/src/smartselfie-capture/SmartSelfieCapture.tsx +265 -283
  105. package/lib/components/selfie/src/smartselfie-capture/components/AlertDisplay.tsx +34 -34
  106. package/lib/components/selfie/src/smartselfie-capture/components/CameraPreview.tsx +97 -97
  107. package/lib/components/selfie/src/smartselfie-capture/components/CaptureControls.tsx +78 -76
  108. package/lib/components/selfie/src/smartselfie-capture/components/index.ts +3 -3
  109. package/lib/components/selfie/src/smartselfie-capture/constants.ts +23 -23
  110. package/lib/components/selfie/src/smartselfie-capture/hooks/index.ts +2 -2
  111. package/lib/components/selfie/src/smartselfie-capture/hooks/useCamera.ts +238 -238
  112. package/lib/components/selfie/src/smartselfie-capture/hooks/useFaceCapture.ts +618 -617
  113. package/lib/components/selfie/src/smartselfie-capture/index.ts +1 -1
  114. package/lib/components/selfie/src/smartselfie-capture/utils/alertMessages.ts +13 -13
  115. package/lib/components/selfie/src/smartselfie-capture/utils/canvas.ts +105 -105
  116. package/lib/components/selfie/src/smartselfie-capture/utils/faceDetection.ts +129 -129
  117. package/lib/components/selfie/src/smartselfie-capture/utils/imageCapture.ts +64 -64
  118. package/lib/components/selfie/src/smartselfie-capture/utils/index.ts +4 -4
  119. package/lib/components/selfie/src/smartselfie-capture/utils/mediapipeManager.ts +77 -77
  120. package/lib/components/signature-pad/package-lock.json +3009 -3009
  121. package/lib/components/signature-pad/package.json +30 -30
  122. package/lib/components/signature-pad/src/SignaturePad.js +484 -484
  123. package/lib/components/signature-pad/src/SignaturePad.stories.js +32 -32
  124. package/lib/components/signature-pad/src/index.js +3 -3
  125. package/lib/components/smart-camera-web/src/README.md +206 -206
  126. package/lib/components/smart-camera-web/src/SmartCameraWeb.js +305 -305
  127. package/lib/components/smart-camera-web/src/SmartCameraWeb.stories.js +57 -57
  128. package/lib/components/totp-consent/src/TotpConsent.js +949 -949
  129. package/lib/components/totp-consent/src/index.js +4 -4
  130. package/lib/domain/camera/src/README.md +38 -38
  131. package/lib/domain/camera/src/SmartCamera.js +109 -109
  132. package/lib/domain/constants/src/Constants.js +27 -27
  133. package/lib/domain/file-upload/README.md +35 -35
  134. package/lib/domain/file-upload/src/SmartFileUpload.js +65 -65
  135. package/lib/styles/README.md +3 -3
  136. package/lib/styles/src/styles.js +372 -372
  137. package/lib/styles/src/typography.js +52 -52
  138. package/package.json +111 -112
  139. package/dist/esm/DocumentCaptureScreens-BjATTDqu.js.map +0 -1
  140. package/dist/esm/SelfieCaptureScreens-UUzZzl1A.js +0 -11361
  141. package/dist/esm/SelfieCaptureScreens-UUzZzl1A.js.map +0 -1
  142. package/dist/esm/package-CZlW6BZn.js.map +0 -1
@@ -1,617 +1,618 @@
1
- import { useRef } from 'preact/hooks';
2
- import { useSignal, useComputed } from '@preact/signals';
3
- import { FaceLandmarker } from '@mediapipe/tasks-vision';
4
- import { throttle } from 'lodash';
5
- import {
6
- calculateFaceSize,
7
- isFaceInBounds,
8
- calculateMouthOpening,
9
- } from '../utils/faceDetection';
10
- import {
11
- createCroppedVideoFrame,
12
- drawFaceMesh,
13
- clearCanvas,
14
- } from '../utils/canvas';
15
- import { captureImageFromVideo } from '../utils/imageCapture';
16
- import { ImageType } from '../constants';
17
- import { MESSAGES, type MessageKey } from '../utils/alertMessages';
18
- import { getMediapipeInstance } from '../utils/mediapipeManager';
19
- import packageJson from '../../../../../../package.json';
20
-
21
- const COMPONENTS_VERSION = packageJson.version;
22
-
23
- interface UseFaceCaptureProps {
24
- videoRef: React.RefObject<HTMLVideoElement>;
25
- canvasRef: React.RefObject<HTMLCanvasElement>;
26
- interval: number;
27
- duration: number;
28
- smileThreshold: number;
29
- mouthOpenThreshold: number;
30
- minFaceSize: number;
31
- maxFaceSize: number;
32
- smileCooldown: number;
33
- getFacingMode: () => CameraFacingMode;
34
- }
35
-
36
- export const useFaceCapture = ({
37
- videoRef,
38
- canvasRef,
39
- interval,
40
- duration,
41
- smileThreshold,
42
- mouthOpenThreshold,
43
- minFaceSize,
44
- maxFaceSize,
45
- smileCooldown,
46
- getFacingMode,
47
- }: UseFaceCaptureProps) => {
48
- const faceLandmarkerRef = useRef<FaceLandmarker | null>(null);
49
- const animationFrameRef = useRef<number | null>(null);
50
- const captureTimerRef = useRef<NodeJS.Timeout | null>(null);
51
- const resumeCaptureRef = useRef<(() => void) | null>(null);
52
-
53
- const faceDetected = useSignal(false);
54
- const faceInBounds = useSignal(false);
55
- const faceProximity = useSignal<'too-close' | 'too-far' | 'good'>('good');
56
- const multipleFaces = useSignal(false);
57
- const videoAspectRatio = useSignal(16 / 9);
58
- const faceLandmarks = useSignal<any[]>([]);
59
- const currentSmileScore = useSignal(0);
60
- const currentFaceSize = useSignal(0);
61
- const currentMouthOpen = useSignal(0);
62
- const lastSmileTime = useSignal(0);
63
- const alertTitle = useSignal('');
64
- const isInitializing = useSignal(true);
65
-
66
- const isCapturing = useSignal(false);
67
- const isPaused = useSignal(false);
68
- const countdown = useSignal(0);
69
- const capturedImages = useSignal<string[]>([]);
70
- const referencePhoto = useSignal<string | null>(null);
71
- const totalCaptures = useSignal(1);
72
- const capturesTaken = useSignal(0);
73
- const hasFinishedCapture = useSignal(false);
74
-
75
- const smileCheckpoint = useComputed(() =>
76
- Math.floor(totalCaptures.value * 0.4),
77
- );
78
- const neutralZone = useComputed(() => Math.floor(totalCaptures.value * 0.2));
79
-
80
- const isReadyToCapture = useComputed(
81
- () =>
82
- faceDetected.value &&
83
- faceInBounds.value &&
84
- faceProximity.value === 'good' &&
85
- !multipleFaces.value,
86
- );
87
-
88
- const updateAlertImmediate = (messageKey: MessageKey | null) => {
89
- if (messageKey && MESSAGES[messageKey]) {
90
- alertTitle.value = MESSAGES[messageKey];
91
- } else {
92
- alertTitle.value = '';
93
- }
94
- };
95
-
96
- const updateAlert = useRef(
97
- throttle((messageKey: MessageKey | null) => {
98
- updateAlertImmediate(messageKey);
99
- }, 600),
100
- ).current;
101
-
102
- const initializeFaceLandmarker = async () => {
103
- try {
104
- const isAlreadyLoaded =
105
- window.__smileIdentityMediapipe?.loaded &&
106
- window.__smileIdentityMediapipe?.instance;
107
-
108
- if (!isAlreadyLoaded) {
109
- isInitializing.value = true;
110
- updateAlertImmediate('initializing');
111
- }
112
-
113
- faceLandmarkerRef.current = await getMediapipeInstance();
114
- isInitializing.value = false;
115
- } catch (error) {
116
- console.error('Failed to initialize MediaPipe:', error);
117
- isInitializing.value = false;
118
- }
119
- };
120
-
121
- const setupCanvas = () => {
122
- if (videoRef.current && canvasRef.current) {
123
- const { videoWidth, videoHeight } = videoRef.current;
124
-
125
- videoAspectRatio.value = videoWidth / videoHeight;
126
-
127
- canvasRef.current.width = videoWidth;
128
- canvasRef.current.height = videoHeight;
129
-
130
- const container = videoRef.current.parentElement;
131
- if (container) {
132
- canvasRef.current.style.left = '50%';
133
- canvasRef.current.style.top = '50%';
134
- }
135
- }
136
- };
137
-
138
- const updateCaptureAlerts = () => {
139
- const isInNeutralZone = capturesTaken.value < neutralZone.value;
140
- const isInSmileZone = capturesTaken.value >= smileCheckpoint.value;
141
-
142
- if (isInNeutralZone) {
143
- alertTitle.value = 'Capturing...';
144
- } else if (isInSmileZone) {
145
- const timeSinceSmile = Date.now() - lastSmileTime.value;
146
- if (timeSinceSmile > smileCooldown) {
147
- if (
148
- currentSmileScore.value >= smileThreshold &&
149
- currentMouthOpen.value < mouthOpenThreshold
150
- ) {
151
- updateAlert('open-mouth-smile');
152
- } else {
153
- updateAlert('smile-required');
154
- }
155
- } else {
156
- alertTitle.value = 'Keep smiling!';
157
- }
158
- } else {
159
- updateAlert(null);
160
- }
161
- };
162
-
163
- const updateAlerts = () => {
164
- if (isInitializing.value) {
165
- updateAlertImmediate('initializing');
166
- } else if (multipleFaces.value) {
167
- updateAlert('multiple-faces');
168
- } else if (!faceDetected.value) {
169
- updateAlert('no-face');
170
- } else if (faceProximity.value === 'too-close') {
171
- updateAlert('too-close');
172
- } else if (faceProximity.value === 'too-far') {
173
- updateAlert('too-far');
174
- } else if (!faceInBounds.value) {
175
- updateAlert('out-of-bounds');
176
- } else if (isCapturing.value) {
177
- updateCaptureAlerts();
178
- } else {
179
- alertTitle.value = 'Ready to capture';
180
- }
181
- };
182
-
183
- const stopDetectionLoop = () => {
184
- if (animationFrameRef.current) {
185
- cancelAnimationFrame(animationFrameRef.current);
186
- animationFrameRef.current = null;
187
- }
188
- };
189
-
190
- const detectFace = async () => {
191
- if (!faceLandmarkerRef.current || !videoRef.current) {
192
- stopDetectionLoop();
193
- return;
194
- }
195
-
196
- // ensure video has valid dimensions before processing
197
- if (
198
- videoRef.current.videoWidth <= 0 ||
199
- videoRef.current.videoHeight <= 0 ||
200
- videoRef.current.readyState < 2
201
- ) {
202
- animationFrameRef.current = requestAnimationFrame(detectFace);
203
- return;
204
- }
205
-
206
- try {
207
- if (isInitializing.value) {
208
- isInitializing.value = false;
209
- }
210
-
211
- const croppedCanvas = createCroppedVideoFrame(videoRef.current);
212
- const detectionSource = croppedCanvas || videoRef.current;
213
-
214
- const results = faceLandmarkerRef.current.detectForVideo(
215
- detectionSource,
216
- performance.now(),
217
- );
218
-
219
- faceLandmarks.value = results.faceLandmarks || [];
220
-
221
- if (results.faceLandmarks && canvasRef.current && videoRef.current) {
222
- // we run detection on a cropped video frame
223
- // adjust landmark coordinates back to full video space
224
- if (croppedCanvas) {
225
- const sourceWidth = videoRef.current.videoWidth;
226
- const sourceHeight = videoRef.current.videoHeight;
227
- const squareSize = Math.min(sourceWidth, sourceHeight);
228
- const offsetX = (sourceWidth - squareSize) / (2 * sourceWidth);
229
- const offsetY = (sourceHeight - squareSize) / (2 * sourceHeight);
230
- const scaleFactor = squareSize / sourceWidth;
231
- const scaleFactorY = squareSize / sourceHeight;
232
-
233
- const adjustedLandmarks = results.faceLandmarks.map((face) =>
234
- face.map((landmark: any) => ({
235
- x: landmark.x * scaleFactor + offsetX,
236
- y: landmark.y * scaleFactorY + offsetY,
237
- z: landmark.z,
238
- })),
239
- );
240
-
241
- drawFaceMesh(
242
- canvasRef.current,
243
- adjustedLandmarks,
244
- capturesTaken.value,
245
- smileCheckpoint.value,
246
- );
247
- } else {
248
- drawFaceMesh(
249
- canvasRef.current,
250
- results.faceLandmarks,
251
- capturesTaken.value,
252
- smileCheckpoint.value,
253
- );
254
- }
255
- } else if (canvasRef.current) {
256
- clearCanvas(canvasRef.current);
257
- }
258
-
259
- // Check number of faces
260
- const numFaces = results.faceLandmarks ? results.faceLandmarks.length : 0;
261
- multipleFaces.value = numFaces > 1;
262
-
263
- // Check if face is detected
264
- const hasFace =
265
- results.faceBlendshapes &&
266
- results.faceBlendshapes.length > 0 &&
267
- numFaces === 1;
268
- faceDetected.value = hasFace;
269
-
270
- if (hasFace && results.faceLandmarks) {
271
- // Calculate face size and position
272
- const faceSize = calculateFaceSize(results.faceLandmarks);
273
- currentFaceSize.value = faceSize;
274
-
275
- // Check face proximity
276
- if (faceSize > maxFaceSize) {
277
- faceProximity.value = 'too-close';
278
- } else if (faceSize < minFaceSize) {
279
- faceProximity.value = 'too-far';
280
- } else {
281
- faceProximity.value = 'good';
282
- }
283
-
284
- // Check face position
285
- faceInBounds.value = isFaceInBounds(
286
- results.faceLandmarks,
287
- videoAspectRatio.value,
288
- );
289
-
290
- // Get smile and mouth open data
291
- const blendshapes = results.faceBlendshapes[0].categories;
292
- const smileLeft =
293
- blendshapes.find((b) => b.categoryName === 'mouthSmileLeft')?.score ||
294
- 0;
295
- const smileRight =
296
- blendshapes.find((b) => b.categoryName === 'mouthSmileRight')
297
- ?.score || 0;
298
- const mouthOpen = calculateMouthOpening(results.faceLandmarks);
299
- const smileScore = (smileLeft + smileRight) / 2;
300
-
301
- currentSmileScore.value = smileScore;
302
- currentMouthOpen.value = mouthOpen;
303
-
304
- if (smileScore >= smileThreshold && mouthOpen >= mouthOpenThreshold) {
305
- lastSmileTime.value = Date.now();
306
-
307
- if (isPaused.value && isCapturing.value && resumeCaptureRef.current) {
308
- // defer execution
309
- setTimeout(() => {
310
- const stillSmiling = Date.now() - lastSmileTime.value <= 100;
311
- if (
312
- stillSmiling &&
313
- isPaused.value &&
314
- isCapturing.value &&
315
- resumeCaptureRef.current
316
- ) {
317
- resumeCaptureRef.current();
318
- }
319
- }, 0);
320
- }
321
- }
322
- } else {
323
- // No face detected or multiple faces - reset values
324
- currentSmileScore.value = 0;
325
- currentFaceSize.value = 0;
326
- currentMouthOpen.value = 0;
327
- faceInBounds.value = false;
328
- faceProximity.value = 'good';
329
- }
330
-
331
- updateAlerts();
332
- } catch (error) {
333
- faceDetected.value = false;
334
- faceInBounds.value = false;
335
- multipleFaces.value = false;
336
- faceProximity.value = 'good';
337
- currentMouthOpen.value = 0;
338
-
339
- if (isCapturing.value) {
340
- updateAlert('no-face');
341
- }
342
- }
343
-
344
- animationFrameRef.current = requestAnimationFrame(detectFace);
345
- };
346
-
347
- const startDetectionLoop = () => {
348
- if (animationFrameRef.current) {
349
- cancelAnimationFrame(animationFrameRef.current);
350
- }
351
- animationFrameRef.current = requestAnimationFrame(detectFace);
352
- };
353
-
354
- const captureImage = () => {
355
- if (!videoRef.current) return;
356
-
357
- const isReference = capturesTaken.value === totalCaptures.value - 1;
358
- const imageData = captureImageFromVideo(videoRef.current, isReference);
359
-
360
- if (!imageData) return;
361
-
362
- if (isReference) {
363
- referencePhoto.value = imageData;
364
- } else {
365
- capturedImages.value = [...capturedImages.value, imageData];
366
- }
367
-
368
- capturesTaken.value++;
369
- countdown.value = totalCaptures.value - capturesTaken.value;
370
- };
371
-
372
- const stopCapture = () => {
373
- if (captureTimerRef.current) {
374
- clearInterval(captureTimerRef.current);
375
- captureTimerRef.current = null;
376
- }
377
-
378
- isCapturing.value = false;
379
- isPaused.value = false;
380
-
381
- if (capturesTaken.value >= totalCaptures.value && referencePhoto.value) {
382
- const livenessImages = capturedImages.value.map((img) => ({
383
- image: img.split(',')[1],
384
- image_type_id: ImageType.LIVENESS_IMAGE_BASE64,
385
- }));
386
-
387
- const referenceImage = {
388
- image: referencePhoto.value.split(',')[1],
389
- image_type_id: ImageType.SELFIE_IMAGE_BASE64,
390
- };
391
-
392
- const eventDetail = {
393
- images: [...livenessImages, referenceImage],
394
- referenceImage: referencePhoto.value,
395
- previewImage: referencePhoto.value,
396
- facingMode: getFacingMode(),
397
- meta: { libraryVersion: COMPONENTS_VERSION },
398
- };
399
-
400
- window.dispatchEvent(
401
- new CustomEvent('selfie-capture.publish', {
402
- detail: eventDetail,
403
- }),
404
- );
405
-
406
- hasFinishedCapture.value = true;
407
- }
408
- };
409
-
410
- const pauseCapture = () => {
411
- if (captureTimerRef.current) {
412
- clearInterval(captureTimerRef.current);
413
- captureTimerRef.current = null;
414
- }
415
- isPaused.value = true;
416
-
417
- if (
418
- !multipleFaces.value &&
419
- faceDetected.value &&
420
- faceInBounds.value &&
421
- faceProximity.value === 'good'
422
- ) {
423
- updateAlert('smile-required');
424
- }
425
- };
426
-
427
- const startCaptureInterval = () => {
428
- if (captureTimerRef.current) {
429
- clearInterval(captureTimerRef.current);
430
- }
431
-
432
- captureTimerRef.current = setInterval(() => {
433
- if (capturesTaken.value >= totalCaptures.value) {
434
- stopCapture();
435
- return;
436
- }
437
-
438
- if (multipleFaces.value) {
439
- pauseCapture();
440
- return;
441
- }
442
-
443
- if (!faceDetected.value) {
444
- return;
445
- }
446
-
447
- if (!faceInBounds.value) {
448
- pauseCapture();
449
- return;
450
- }
451
-
452
- if (faceProximity.value !== 'good') {
453
- pauseCapture();
454
- return;
455
- }
456
-
457
- const isInSmileZone = capturesTaken.value >= smileCheckpoint.value;
458
-
459
- if (isInSmileZone) {
460
- const timeSinceSmile = Date.now() - lastSmileTime.value;
461
- if (timeSinceSmile > smileCooldown) {
462
- pauseCapture();
463
- return;
464
- }
465
- }
466
-
467
- captureImage();
468
- }, interval);
469
- };
470
-
471
- const resumeCapture = () => {
472
- if (
473
- faceDetected.value &&
474
- faceProximity.value === 'good' &&
475
- faceInBounds.value &&
476
- !multipleFaces.value
477
- ) {
478
- const isInSmileZone = capturesTaken.value >= smileCheckpoint.value;
479
- if (isInSmileZone) {
480
- const timeSinceSmile = Date.now() - lastSmileTime.value;
481
- if (timeSinceSmile > smileCooldown) {
482
- return;
483
- }
484
- }
485
-
486
- isPaused.value = false;
487
- updateAlert(null);
488
- startCaptureInterval();
489
- }
490
- };
491
-
492
- resumeCaptureRef.current = resumeCapture;
493
-
494
- const startCapture = async () => {
495
- capturedImages.value = [];
496
- isCapturing.value = true;
497
- isPaused.value = false;
498
- totalCaptures.value = Math.ceil(duration / interval);
499
- capturesTaken.value = 0;
500
- countdown.value = totalCaptures.value;
501
-
502
- const smartCameraWeb = document.querySelector('smart-camera-web');
503
- smartCameraWeb?.dispatchEvent(
504
- new CustomEvent('metadata.selfie-capture-start'),
505
- );
506
- smartCameraWeb?.dispatchEvent(
507
- new CustomEvent('metadata.selfie-origin', {
508
- detail: {
509
- imageOrigin: {
510
- environment: 'back_camera',
511
- user: 'front_camera',
512
- }[getFacingMode()],
513
- },
514
- }),
515
- );
516
-
517
- startCaptureInterval();
518
- };
519
-
520
- const handleCancel = () => {
521
- stopCapture();
522
- window.dispatchEvent(
523
- new CustomEvent('selfie-capture.cancelled', {
524
- detail: { meta: { libraryVersion: COMPONENTS_VERSION } },
525
- }),
526
- );
527
-
528
- // TODO: remove - for backwards compatibility
529
- window.dispatchEvent(
530
- new CustomEvent('selfie-capture-screens.cancelled', {
531
- detail: { meta: { libraryVersion: COMPONENTS_VERSION } },
532
- }),
533
- );
534
- };
535
-
536
- const handleClose = () => {
537
- stopCapture();
538
-
539
- window.dispatchEvent(
540
- new CustomEvent('selfie-capture.close', {
541
- detail: { meta: { libraryVersion: COMPONENTS_VERSION } },
542
- }),
543
- );
544
-
545
- // TODO: remove - backwards compatibility
546
- window.dispatchEvent(
547
- new CustomEvent('selfie-capture-screens.close', {
548
- detail: { meta: { libraryVersion: COMPONENTS_VERSION } },
549
- }),
550
- );
551
- };
552
-
553
- const cleanup = () => {
554
- if (captureTimerRef.current) {
555
- clearInterval(captureTimerRef.current);
556
- }
557
- stopDetectionLoop();
558
- updateAlert.cancel();
559
- };
560
-
561
- const resetFaceDetectionState = () => {
562
- faceDetected.value = false;
563
- faceInBounds.value = false;
564
- faceProximity.value = 'good';
565
- multipleFaces.value = false;
566
- faceLandmarks.value = [];
567
- currentSmileScore.value = 0;
568
- currentFaceSize.value = 0;
569
- currentMouthOpen.value = 0;
570
- lastSmileTime.value = 0;
571
-
572
- if (canvasRef.current) {
573
- clearCanvas(canvasRef.current);
574
- }
575
- };
576
-
577
- return {
578
- faceDetected,
579
- faceInBounds,
580
- faceProximity,
581
- multipleFaces,
582
- videoAspectRatio,
583
- faceLandmarks,
584
- currentSmileScore,
585
- currentFaceSize,
586
- currentMouthOpen,
587
- lastSmileTime,
588
- alertTitle,
589
- isInitializing,
590
- isReadyToCapture,
591
-
592
- isCapturing,
593
- isPaused,
594
- countdown,
595
- capturedImages,
596
- referencePhoto,
597
- totalCaptures,
598
- capturesTaken,
599
- hasFinishedCapture,
600
- smileCheckpoint,
601
- neutralZone,
602
-
603
- initializeFaceLandmarker,
604
- setupCanvas,
605
- startDetectionLoop,
606
- stopDetectionLoop,
607
- updateAlert,
608
- startCapture,
609
- stopCapture,
610
- pauseCapture,
611
- resumeCapture,
612
- handleCancel,
613
- handleClose,
614
- cleanup,
615
- resetFaceDetectionState,
616
- };
617
- };
1
+ import { useRef } from 'preact/hooks';
2
+ import { useSignal, useComputed } from '@preact/signals';
3
+ import type { RefObject } from 'preact';
4
+ import { FaceLandmarker } from '@mediapipe/tasks-vision';
5
+ import throttle from 'lodash/throttle';
6
+ import {
7
+ calculateFaceSize,
8
+ isFaceInBounds,
9
+ calculateMouthOpening,
10
+ } from '../utils/faceDetection';
11
+ import {
12
+ createCroppedVideoFrame,
13
+ drawFaceMesh,
14
+ clearCanvas,
15
+ } from '../utils/canvas';
16
+ import { captureImageFromVideo } from '../utils/imageCapture';
17
+ import { ImageType } from '../constants';
18
+ import { MESSAGES, type MessageKey } from '../utils/alertMessages';
19
+ import { getMediapipeInstance } from '../utils/mediapipeManager';
20
+ import packageJson from '../../../../../../package.json';
21
+
22
+ const COMPONENTS_VERSION = packageJson.version;
23
+
24
+ interface UseFaceCaptureProps {
25
+ videoRef: RefObject<HTMLVideoElement>;
26
+ canvasRef: RefObject<HTMLCanvasElement>;
27
+ interval: number;
28
+ duration: number;
29
+ smileThreshold: number;
30
+ mouthOpenThreshold: number;
31
+ minFaceSize: number;
32
+ maxFaceSize: number;
33
+ smileCooldown: number;
34
+ getFacingMode: () => CameraFacingMode;
35
+ }
36
+
37
+ export const useFaceCapture = ({
38
+ videoRef,
39
+ canvasRef,
40
+ interval,
41
+ duration,
42
+ smileThreshold,
43
+ mouthOpenThreshold,
44
+ minFaceSize,
45
+ maxFaceSize,
46
+ smileCooldown,
47
+ getFacingMode,
48
+ }: UseFaceCaptureProps) => {
49
+ const faceLandmarkerRef = useRef<FaceLandmarker | null>(null);
50
+ const animationFrameRef = useRef<number | null>(null);
51
+ const captureTimerRef = useRef<NodeJS.Timeout | null>(null);
52
+ const resumeCaptureRef = useRef<(() => void) | null>(null);
53
+
54
+ const faceDetected = useSignal(false);
55
+ const faceInBounds = useSignal(false);
56
+ const faceProximity = useSignal<'too-close' | 'too-far' | 'good'>('good');
57
+ const multipleFaces = useSignal(false);
58
+ const videoAspectRatio = useSignal(16 / 9);
59
+ const faceLandmarks = useSignal<any[]>([]);
60
+ const currentSmileScore = useSignal(0);
61
+ const currentFaceSize = useSignal(0);
62
+ const currentMouthOpen = useSignal(0);
63
+ const lastSmileTime = useSignal(0);
64
+ const alertTitle = useSignal('');
65
+ const isInitializing = useSignal(true);
66
+
67
+ const isCapturing = useSignal(false);
68
+ const isPaused = useSignal(false);
69
+ const countdown = useSignal(0);
70
+ const capturedImages = useSignal<string[]>([]);
71
+ const referencePhoto = useSignal<string | null>(null);
72
+ const totalCaptures = useSignal(1);
73
+ const capturesTaken = useSignal(0);
74
+ const hasFinishedCapture = useSignal(false);
75
+
76
+ const smileCheckpoint = useComputed(() =>
77
+ Math.floor(totalCaptures.value * 0.4),
78
+ );
79
+ const neutralZone = useComputed(() => Math.floor(totalCaptures.value * 0.2));
80
+
81
+ const isReadyToCapture = useComputed(
82
+ () =>
83
+ faceDetected.value &&
84
+ faceInBounds.value &&
85
+ faceProximity.value === 'good' &&
86
+ !multipleFaces.value,
87
+ );
88
+
89
+ const updateAlertImmediate = (messageKey: MessageKey | null) => {
90
+ if (messageKey && MESSAGES[messageKey]) {
91
+ alertTitle.value = MESSAGES[messageKey];
92
+ } else {
93
+ alertTitle.value = '';
94
+ }
95
+ };
96
+
97
+ const updateAlert = useRef(
98
+ throttle((messageKey: MessageKey | null) => {
99
+ updateAlertImmediate(messageKey);
100
+ }, 600),
101
+ ).current;
102
+
103
+ const initializeFaceLandmarker = async () => {
104
+ try {
105
+ const isAlreadyLoaded =
106
+ window.__smileIdentityMediapipe?.loaded &&
107
+ window.__smileIdentityMediapipe?.instance;
108
+
109
+ if (!isAlreadyLoaded) {
110
+ isInitializing.value = true;
111
+ updateAlertImmediate('initializing');
112
+ }
113
+
114
+ faceLandmarkerRef.current = await getMediapipeInstance();
115
+ isInitializing.value = false;
116
+ } catch (error) {
117
+ console.error('Failed to initialize MediaPipe:', error);
118
+ isInitializing.value = false;
119
+ }
120
+ };
121
+
122
+ const setupCanvas = () => {
123
+ if (videoRef.current && canvasRef.current) {
124
+ const { videoWidth, videoHeight } = videoRef.current;
125
+
126
+ videoAspectRatio.value = videoWidth / videoHeight;
127
+
128
+ canvasRef.current.width = videoWidth;
129
+ canvasRef.current.height = videoHeight;
130
+
131
+ const container = videoRef.current.parentElement;
132
+ if (container) {
133
+ canvasRef.current.style.left = '50%';
134
+ canvasRef.current.style.top = '50%';
135
+ }
136
+ }
137
+ };
138
+
139
+ const updateCaptureAlerts = () => {
140
+ const isInNeutralZone = capturesTaken.value < neutralZone.value;
141
+ const isInSmileZone = capturesTaken.value >= smileCheckpoint.value;
142
+
143
+ if (isInNeutralZone) {
144
+ alertTitle.value = 'Capturing...';
145
+ } else if (isInSmileZone) {
146
+ const timeSinceSmile = Date.now() - lastSmileTime.value;
147
+ if (timeSinceSmile > smileCooldown) {
148
+ if (
149
+ currentSmileScore.value >= smileThreshold &&
150
+ currentMouthOpen.value < mouthOpenThreshold
151
+ ) {
152
+ updateAlert('open-mouth-smile');
153
+ } else {
154
+ updateAlert('smile-required');
155
+ }
156
+ } else {
157
+ alertTitle.value = 'Keep smiling!';
158
+ }
159
+ } else {
160
+ updateAlert(null);
161
+ }
162
+ };
163
+
164
+ const updateAlerts = () => {
165
+ if (isInitializing.value) {
166
+ updateAlertImmediate('initializing');
167
+ } else if (multipleFaces.value) {
168
+ updateAlert('multiple-faces');
169
+ } else if (!faceDetected.value) {
170
+ updateAlert('no-face');
171
+ } else if (faceProximity.value === 'too-close') {
172
+ updateAlert('too-close');
173
+ } else if (faceProximity.value === 'too-far') {
174
+ updateAlert('too-far');
175
+ } else if (!faceInBounds.value) {
176
+ updateAlert('out-of-bounds');
177
+ } else if (isCapturing.value) {
178
+ updateCaptureAlerts();
179
+ } else {
180
+ alertTitle.value = 'Ready to capture';
181
+ }
182
+ };
183
+
184
+ const stopDetectionLoop = () => {
185
+ if (animationFrameRef.current) {
186
+ cancelAnimationFrame(animationFrameRef.current);
187
+ animationFrameRef.current = null;
188
+ }
189
+ };
190
+
191
+ const detectFace = async () => {
192
+ if (!faceLandmarkerRef.current || !videoRef.current) {
193
+ stopDetectionLoop();
194
+ return;
195
+ }
196
+
197
+ // ensure video has valid dimensions before processing
198
+ if (
199
+ videoRef.current.videoWidth <= 0 ||
200
+ videoRef.current.videoHeight <= 0 ||
201
+ videoRef.current.readyState < 2
202
+ ) {
203
+ animationFrameRef.current = requestAnimationFrame(detectFace);
204
+ return;
205
+ }
206
+
207
+ try {
208
+ if (isInitializing.value) {
209
+ isInitializing.value = false;
210
+ }
211
+
212
+ const croppedCanvas = createCroppedVideoFrame(videoRef.current);
213
+ const detectionSource = croppedCanvas || videoRef.current;
214
+
215
+ const results = faceLandmarkerRef.current.detectForVideo(
216
+ detectionSource,
217
+ performance.now(),
218
+ );
219
+
220
+ faceLandmarks.value = results.faceLandmarks || [];
221
+
222
+ if (results.faceLandmarks && canvasRef.current && videoRef.current) {
223
+ // we run detection on a cropped video frame
224
+ // adjust landmark coordinates back to full video space
225
+ if (croppedCanvas) {
226
+ const sourceWidth = videoRef.current.videoWidth;
227
+ const sourceHeight = videoRef.current.videoHeight;
228
+ const squareSize = Math.min(sourceWidth, sourceHeight);
229
+ const offsetX = (sourceWidth - squareSize) / (2 * sourceWidth);
230
+ const offsetY = (sourceHeight - squareSize) / (2 * sourceHeight);
231
+ const scaleFactor = squareSize / sourceWidth;
232
+ const scaleFactorY = squareSize / sourceHeight;
233
+
234
+ const adjustedLandmarks = results.faceLandmarks.map((face) =>
235
+ face.map((landmark: any) => ({
236
+ x: landmark.x * scaleFactor + offsetX,
237
+ y: landmark.y * scaleFactorY + offsetY,
238
+ z: landmark.z,
239
+ })),
240
+ );
241
+
242
+ drawFaceMesh(
243
+ canvasRef.current,
244
+ adjustedLandmarks,
245
+ capturesTaken.value,
246
+ smileCheckpoint.value,
247
+ );
248
+ } else {
249
+ drawFaceMesh(
250
+ canvasRef.current,
251
+ results.faceLandmarks,
252
+ capturesTaken.value,
253
+ smileCheckpoint.value,
254
+ );
255
+ }
256
+ } else if (canvasRef.current) {
257
+ clearCanvas(canvasRef.current);
258
+ }
259
+
260
+ // Check number of faces
261
+ const numFaces = results.faceLandmarks ? results.faceLandmarks.length : 0;
262
+ multipleFaces.value = numFaces > 1;
263
+
264
+ // Check if face is detected
265
+ const hasFace =
266
+ results.faceBlendshapes &&
267
+ results.faceBlendshapes.length > 0 &&
268
+ numFaces === 1;
269
+ faceDetected.value = hasFace;
270
+
271
+ if (hasFace && results.faceLandmarks) {
272
+ // Calculate face size and position
273
+ const faceSize = calculateFaceSize(results.faceLandmarks);
274
+ currentFaceSize.value = faceSize;
275
+
276
+ // Check face proximity
277
+ if (faceSize > maxFaceSize) {
278
+ faceProximity.value = 'too-close';
279
+ } else if (faceSize < minFaceSize) {
280
+ faceProximity.value = 'too-far';
281
+ } else {
282
+ faceProximity.value = 'good';
283
+ }
284
+
285
+ // Check face position
286
+ faceInBounds.value = isFaceInBounds(
287
+ results.faceLandmarks,
288
+ videoAspectRatio.value,
289
+ );
290
+
291
+ // Get smile and mouth open data
292
+ const blendshapes = results.faceBlendshapes[0].categories;
293
+ const smileLeft =
294
+ blendshapes.find((b) => b.categoryName === 'mouthSmileLeft')?.score ||
295
+ 0;
296
+ const smileRight =
297
+ blendshapes.find((b) => b.categoryName === 'mouthSmileRight')
298
+ ?.score || 0;
299
+ const mouthOpen = calculateMouthOpening(results.faceLandmarks);
300
+ const smileScore = (smileLeft + smileRight) / 2;
301
+
302
+ currentSmileScore.value = smileScore;
303
+ currentMouthOpen.value = mouthOpen;
304
+
305
+ if (smileScore >= smileThreshold && mouthOpen >= mouthOpenThreshold) {
306
+ lastSmileTime.value = Date.now();
307
+
308
+ if (isPaused.value && isCapturing.value && resumeCaptureRef.current) {
309
+ // defer execution
310
+ setTimeout(() => {
311
+ const stillSmiling = Date.now() - lastSmileTime.value <= 100;
312
+ if (
313
+ stillSmiling &&
314
+ isPaused.value &&
315
+ isCapturing.value &&
316
+ resumeCaptureRef.current
317
+ ) {
318
+ resumeCaptureRef.current();
319
+ }
320
+ }, 0);
321
+ }
322
+ }
323
+ } else {
324
+ // No face detected or multiple faces - reset values
325
+ currentSmileScore.value = 0;
326
+ currentFaceSize.value = 0;
327
+ currentMouthOpen.value = 0;
328
+ faceInBounds.value = false;
329
+ faceProximity.value = 'good';
330
+ }
331
+
332
+ updateAlerts();
333
+ } catch (error) {
334
+ faceDetected.value = false;
335
+ faceInBounds.value = false;
336
+ multipleFaces.value = false;
337
+ faceProximity.value = 'good';
338
+ currentMouthOpen.value = 0;
339
+
340
+ if (isCapturing.value) {
341
+ updateAlert('no-face');
342
+ }
343
+ }
344
+
345
+ animationFrameRef.current = requestAnimationFrame(detectFace);
346
+ };
347
+
348
+ const startDetectionLoop = () => {
349
+ if (animationFrameRef.current) {
350
+ cancelAnimationFrame(animationFrameRef.current);
351
+ }
352
+ animationFrameRef.current = requestAnimationFrame(detectFace);
353
+ };
354
+
355
+ const captureImage = () => {
356
+ if (!videoRef.current) return;
357
+
358
+ const isReference = capturesTaken.value === totalCaptures.value - 1;
359
+ const imageData = captureImageFromVideo(videoRef.current, isReference);
360
+
361
+ if (!imageData) return;
362
+
363
+ if (isReference) {
364
+ referencePhoto.value = imageData;
365
+ } else {
366
+ capturedImages.value = [...capturedImages.value, imageData];
367
+ }
368
+
369
+ capturesTaken.value++;
370
+ countdown.value = totalCaptures.value - capturesTaken.value;
371
+ };
372
+
373
+ const stopCapture = () => {
374
+ if (captureTimerRef.current) {
375
+ clearInterval(captureTimerRef.current);
376
+ captureTimerRef.current = null;
377
+ }
378
+
379
+ isCapturing.value = false;
380
+ isPaused.value = false;
381
+
382
+ if (capturesTaken.value >= totalCaptures.value && referencePhoto.value) {
383
+ const livenessImages = capturedImages.value.map((img) => ({
384
+ image: img.split(',')[1],
385
+ image_type_id: ImageType.LIVENESS_IMAGE_BASE64,
386
+ }));
387
+
388
+ const referenceImage = {
389
+ image: referencePhoto.value.split(',')[1],
390
+ image_type_id: ImageType.SELFIE_IMAGE_BASE64,
391
+ };
392
+
393
+ const eventDetail = {
394
+ images: [...livenessImages, referenceImage],
395
+ referenceImage: referencePhoto.value,
396
+ previewImage: referencePhoto.value,
397
+ facingMode: getFacingMode(),
398
+ meta: { libraryVersion: COMPONENTS_VERSION },
399
+ };
400
+
401
+ window.dispatchEvent(
402
+ new CustomEvent('selfie-capture.publish', {
403
+ detail: eventDetail,
404
+ }),
405
+ );
406
+
407
+ hasFinishedCapture.value = true;
408
+ }
409
+ };
410
+
411
+ const pauseCapture = () => {
412
+ if (captureTimerRef.current) {
413
+ clearInterval(captureTimerRef.current);
414
+ captureTimerRef.current = null;
415
+ }
416
+ isPaused.value = true;
417
+
418
+ if (
419
+ !multipleFaces.value &&
420
+ faceDetected.value &&
421
+ faceInBounds.value &&
422
+ faceProximity.value === 'good'
423
+ ) {
424
+ updateAlert('smile-required');
425
+ }
426
+ };
427
+
428
+ const startCaptureInterval = () => {
429
+ if (captureTimerRef.current) {
430
+ clearInterval(captureTimerRef.current);
431
+ }
432
+
433
+ captureTimerRef.current = setInterval(() => {
434
+ if (capturesTaken.value >= totalCaptures.value) {
435
+ stopCapture();
436
+ return;
437
+ }
438
+
439
+ if (multipleFaces.value) {
440
+ pauseCapture();
441
+ return;
442
+ }
443
+
444
+ if (!faceDetected.value) {
445
+ return;
446
+ }
447
+
448
+ if (!faceInBounds.value) {
449
+ pauseCapture();
450
+ return;
451
+ }
452
+
453
+ if (faceProximity.value !== 'good') {
454
+ pauseCapture();
455
+ return;
456
+ }
457
+
458
+ const isInSmileZone = capturesTaken.value >= smileCheckpoint.value;
459
+
460
+ if (isInSmileZone) {
461
+ const timeSinceSmile = Date.now() - lastSmileTime.value;
462
+ if (timeSinceSmile > smileCooldown) {
463
+ pauseCapture();
464
+ return;
465
+ }
466
+ }
467
+
468
+ captureImage();
469
+ }, interval);
470
+ };
471
+
472
+ const resumeCapture = () => {
473
+ if (
474
+ faceDetected.value &&
475
+ faceProximity.value === 'good' &&
476
+ faceInBounds.value &&
477
+ !multipleFaces.value
478
+ ) {
479
+ const isInSmileZone = capturesTaken.value >= smileCheckpoint.value;
480
+ if (isInSmileZone) {
481
+ const timeSinceSmile = Date.now() - lastSmileTime.value;
482
+ if (timeSinceSmile > smileCooldown) {
483
+ return;
484
+ }
485
+ }
486
+
487
+ isPaused.value = false;
488
+ updateAlert(null);
489
+ startCaptureInterval();
490
+ }
491
+ };
492
+
493
+ resumeCaptureRef.current = resumeCapture;
494
+
495
+ const startCapture = async () => {
496
+ capturedImages.value = [];
497
+ isCapturing.value = true;
498
+ isPaused.value = false;
499
+ totalCaptures.value = Math.ceil(duration / interval);
500
+ capturesTaken.value = 0;
501
+ countdown.value = totalCaptures.value;
502
+
503
+ const smartCameraWeb = document.querySelector('smart-camera-web');
504
+ smartCameraWeb?.dispatchEvent(
505
+ new CustomEvent('metadata.selfie-capture-start'),
506
+ );
507
+ smartCameraWeb?.dispatchEvent(
508
+ new CustomEvent('metadata.selfie-origin', {
509
+ detail: {
510
+ imageOrigin: {
511
+ environment: 'back_camera',
512
+ user: 'front_camera',
513
+ }[getFacingMode()],
514
+ },
515
+ }),
516
+ );
517
+
518
+ startCaptureInterval();
519
+ };
520
+
521
+ const handleCancel = () => {
522
+ stopCapture();
523
+ window.dispatchEvent(
524
+ new CustomEvent('selfie-capture.cancelled', {
525
+ detail: { meta: { libraryVersion: COMPONENTS_VERSION } },
526
+ }),
527
+ );
528
+
529
+ // TODO: remove - for backwards compatibility
530
+ window.dispatchEvent(
531
+ new CustomEvent('selfie-capture-screens.cancelled', {
532
+ detail: { meta: { libraryVersion: COMPONENTS_VERSION } },
533
+ }),
534
+ );
535
+ };
536
+
537
+ const handleClose = () => {
538
+ stopCapture();
539
+
540
+ window.dispatchEvent(
541
+ new CustomEvent('selfie-capture.close', {
542
+ detail: { meta: { libraryVersion: COMPONENTS_VERSION } },
543
+ }),
544
+ );
545
+
546
+ // TODO: remove - backwards compatibility
547
+ window.dispatchEvent(
548
+ new CustomEvent('selfie-capture-screens.close', {
549
+ detail: { meta: { libraryVersion: COMPONENTS_VERSION } },
550
+ }),
551
+ );
552
+ };
553
+
554
+ const cleanup = () => {
555
+ if (captureTimerRef.current) {
556
+ clearInterval(captureTimerRef.current);
557
+ }
558
+ stopDetectionLoop();
559
+ updateAlert.cancel();
560
+ };
561
+
562
+ const resetFaceDetectionState = () => {
563
+ faceDetected.value = false;
564
+ faceInBounds.value = false;
565
+ faceProximity.value = 'good';
566
+ multipleFaces.value = false;
567
+ faceLandmarks.value = [];
568
+ currentSmileScore.value = 0;
569
+ currentFaceSize.value = 0;
570
+ currentMouthOpen.value = 0;
571
+ lastSmileTime.value = 0;
572
+
573
+ if (canvasRef.current) {
574
+ clearCanvas(canvasRef.current);
575
+ }
576
+ };
577
+
578
+ return {
579
+ faceDetected,
580
+ faceInBounds,
581
+ faceProximity,
582
+ multipleFaces,
583
+ videoAspectRatio,
584
+ faceLandmarks,
585
+ currentSmileScore,
586
+ currentFaceSize,
587
+ currentMouthOpen,
588
+ lastSmileTime,
589
+ alertTitle,
590
+ isInitializing,
591
+ isReadyToCapture,
592
+
593
+ isCapturing,
594
+ isPaused,
595
+ countdown,
596
+ capturedImages,
597
+ referencePhoto,
598
+ totalCaptures,
599
+ capturesTaken,
600
+ hasFinishedCapture,
601
+ smileCheckpoint,
602
+ neutralZone,
603
+
604
+ initializeFaceLandmarker,
605
+ setupCanvas,
606
+ startDetectionLoop,
607
+ stopDetectionLoop,
608
+ updateAlert,
609
+ startCapture,
610
+ stopCapture,
611
+ pauseCapture,
612
+ resumeCapture,
613
+ handleCancel,
614
+ handleClose,
615
+ cleanup,
616
+ resetFaceDetectionState,
617
+ };
618
+ };