@smileid/web-components 11.0.0 → 11.0.2

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 (141) 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-RECPb0wH.js → DocumentCaptureScreens-CRx5ymqY.js} +2 -2
  13. package/dist/esm/DocumentCaptureScreens-CRx5ymqY.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-CqBVGEJk.js → SelfieCaptureScreens-DuQjKt_K.js} +274 -257
  18. package/dist/esm/SelfieCaptureScreens-DuQjKt_K.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-BDJnoIAU.js → package-C_cKNrUu.js} +2 -2
  25. package/dist/esm/package-C_cKNrUu.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 +23 -23
  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 -410
  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 -420
  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 -1099
  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 +281 -256
  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 -265
  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 -78
  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 -618
  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 +118 -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-RECPb0wH.js.map +0 -1
  140. package/dist/esm/SelfieCaptureScreens-CqBVGEJk.js.map +0 -1
  141. package/dist/esm/package-BDJnoIAU.js.map +0 -1
@@ -1,618 +1,618 @@
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
- };
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
+ };