@swan-admin/swan-web-component 1.0.121 → 1.0.123

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 (169) hide show
  1. package/dist/BodyScan-CCRXkFFL.mjs +3 -0
  2. package/dist/BodyScan-CCRXkFFL.mjs.map +1 -0
  3. package/dist/BodyScan-RBxSYdGc.js +3 -0
  4. package/dist/BodyScan-RBxSYdGc.js.map +1 -0
  5. package/dist/FaceScan-DQvhrp3K.mjs +3 -0
  6. package/dist/FaceScan-DQvhrp3K.mjs.map +1 -0
  7. package/dist/{FaceScan-BRdpV_Yn.js → FaceScan-Dva9De8x.js} +3 -2
  8. package/dist/{FaceScan-BRdpV_Yn.js.map → FaceScan-Dva9De8x.js.map} +1 -1
  9. package/dist/{Modal-BPtRtRVC.js → Modal-CZgyeNwW.mjs} +3 -2
  10. package/dist/Modal-CZgyeNwW.mjs.map +1 -0
  11. package/dist/{Modal-HTYYx7sM.js → Modal-CmbYIXgn.js} +3 -2
  12. package/dist/{Modal-YZScjwEm.js.map → Modal-CmbYIXgn.js.map} +1 -1
  13. package/dist/bodyScan.d.ts +2 -2
  14. package/dist/bodyScan.js +2 -1
  15. package/dist/bodyScan.mjs +2 -1
  16. package/dist/faceScan.js +2 -1
  17. package/dist/faceScan.mjs +2 -1
  18. package/dist/index.css +1 -1
  19. package/dist/index.js +2 -1
  20. package/dist/index.js.map +1 -1
  21. package/dist/index.mjs +2 -1
  22. package/dist/index.mjs.map +1 -1
  23. package/dist/{pose-detection.esm-Bc8T4UAD.js → pose-detection.esm-DFB9u8DH.js} +2 -1
  24. package/dist/{pose-detection.esm-Bc8T4UAD.js.map → pose-detection.esm-DFB9u8DH.js.map} +1 -1
  25. package/dist/{pose-detection.esm-DC0_P6R7.js → pose-detection.esm-EvS-BndH.mjs} +2 -1
  26. package/dist/pose-detection.esm-EvS-BndH.mjs.map +1 -0
  27. package/package.json +3 -2
  28. package/dist/BodyScan-3YoMZG7n.js +0 -2
  29. package/dist/BodyScan-8qgqyl5-.js +0 -2
  30. package/dist/BodyScan-B0qqqK3C.js +0 -2
  31. package/dist/BodyScan-B1VBoA6S.js +0 -2
  32. package/dist/BodyScan-B1afPG1Q.js +0 -2
  33. package/dist/BodyScan-B1afPG1Q.js.map +0 -1
  34. package/dist/BodyScan-B4-sO3R2.js +0 -2
  35. package/dist/BodyScan-B87W6dpH.js +0 -2
  36. package/dist/BodyScan-B8pglBAp.js +0 -2
  37. package/dist/BodyScan-BEFwluXG.js +0 -2
  38. package/dist/BodyScan-BHgnqB6A.js +0 -2
  39. package/dist/BodyScan-BLvWlYnA.js +0 -2
  40. package/dist/BodyScan-BMAkl5Iw.js +0 -2
  41. package/dist/BodyScan-BMTK6e-E.js +0 -2
  42. package/dist/BodyScan-BQri8pAO.js +0 -2
  43. package/dist/BodyScan-BVNPC7bJ.js +0 -2
  44. package/dist/BodyScan-BfLKF5PU.js +0 -2
  45. package/dist/BodyScan-BjYHCskz.js +0 -2
  46. package/dist/BodyScan-BoAbG01d.js +0 -2
  47. package/dist/BodyScan-Bq64fsmL.js +0 -2
  48. package/dist/BodyScan-Bre1BIHK.js +0 -2
  49. package/dist/BodyScan-BsDJmy0G.js +0 -2
  50. package/dist/BodyScan-ByMGumuH.js +0 -2
  51. package/dist/BodyScan-C0V-EDdB.js +0 -2
  52. package/dist/BodyScan-C1dWJ2qu.js +0 -2
  53. package/dist/BodyScan-C43x2o2T.js +0 -2
  54. package/dist/BodyScan-C57PuQgF.js +0 -2
  55. package/dist/BodyScan-C9hQU-dK.js +0 -2
  56. package/dist/BodyScan-CA4rNyqL.js +0 -2
  57. package/dist/BodyScan-CH-_x55M.js +0 -2
  58. package/dist/BodyScan-CKH_WyTt.js +0 -2
  59. package/dist/BodyScan-CKmPcrkx.js +0 -2
  60. package/dist/BodyScan-CLpL3Uwx.js +0 -2
  61. package/dist/BodyScan-CM12T_-T.js +0 -2
  62. package/dist/BodyScan-CNhb6UOX.js +0 -2
  63. package/dist/BodyScan-CWsaPB8W.js +0 -2
  64. package/dist/BodyScan-CXwtxfOd.js +0 -2
  65. package/dist/BodyScan-CYn7eLoz.js +0 -2
  66. package/dist/BodyScan-CYnHFqsR.js +0 -2
  67. package/dist/BodyScan-CZTiQzpy.js +0 -2
  68. package/dist/BodyScan-Cc68SnU1.js +0 -2
  69. package/dist/BodyScan-CfS4bPCN.js +0 -2
  70. package/dist/BodyScan-CiG19l_n.js +0 -2
  71. package/dist/BodyScan-CjvyMLT9.js +0 -2
  72. package/dist/BodyScan-CkmrPAq9.js +0 -2
  73. package/dist/BodyScan-CoObDhac.js +0 -2
  74. package/dist/BodyScan-Cyfo46EK.js +0 -2
  75. package/dist/BodyScan-Cz9ggKm6.js +0 -2
  76. package/dist/BodyScan-D6Y_W5e2.js +0 -2
  77. package/dist/BodyScan-DCEgmVbG.js +0 -2
  78. package/dist/BodyScan-DEDdENv7.js +0 -2
  79. package/dist/BodyScan-DEdrK-ld.js +0 -2
  80. package/dist/BodyScan-DHMf2V5R.js +0 -2
  81. package/dist/BodyScan-DK9UmNBr.js +0 -2
  82. package/dist/BodyScan-DPCd26i-.js +0 -2
  83. package/dist/BodyScan-DPCd26i-.js.map +0 -1
  84. package/dist/BodyScan-DPSQ1hKh.js +0 -2
  85. package/dist/BodyScan-DVKnmJuJ.js +0 -2
  86. package/dist/BodyScan-DX_KbG5U.js +0 -2
  87. package/dist/BodyScan-DbfP9-G3.js +0 -2
  88. package/dist/BodyScan-DeBJWo0L.js +0 -2
  89. package/dist/BodyScan-DgZpiChn.js +0 -2
  90. package/dist/BodyScan-DkPwUgVu.js +0 -2
  91. package/dist/BodyScan-DntA0MBx.js +0 -2
  92. package/dist/BodyScan-DxidLEhk.js +0 -2
  93. package/dist/BodyScan-DyDxGqfI.js +0 -2
  94. package/dist/BodyScan-Dysj7b77.js +0 -2
  95. package/dist/BodyScan-DzyamZmb.js +0 -2
  96. package/dist/BodyScan-Ehsr_cYc.js +0 -2
  97. package/dist/BodyScan-MSB66I12.js +0 -2
  98. package/dist/BodyScan-Ot6nAH1j.js +0 -2
  99. package/dist/BodyScan-Srq29PK8.js +0 -2
  100. package/dist/BodyScan-SzaquTgH.js +0 -2
  101. package/dist/BodyScan-TPpfyief.js +0 -2
  102. package/dist/BodyScan-XW2vsiE3.js +0 -2
  103. package/dist/BodyScan-eUuIC3jY.js +0 -2
  104. package/dist/BodyScan-enDyqSjO.js +0 -2
  105. package/dist/BodyScan-iOXndWaO.js +0 -2
  106. package/dist/BodyScan-qVHOWabf.js +0 -2
  107. package/dist/BodyScan-t9qdQAL-.js +0 -2
  108. package/dist/BodyScan-twE2YOwy.js +0 -2
  109. package/dist/BodyScan-z6h5fueJ.js +0 -2
  110. package/dist/FaceScan-3rVSqkKB.js +0 -2
  111. package/dist/FaceScan-6Aoz5uUy.js +0 -2
  112. package/dist/FaceScan-7fl5pLnb.js +0 -2
  113. package/dist/FaceScan-9kUfXRSv.js +0 -2
  114. package/dist/FaceScan-AHZ-ajep.js +0 -2
  115. package/dist/FaceScan-B0pFv4Us.js +0 -2
  116. package/dist/FaceScan-BE0PB0fZ.js +0 -2
  117. package/dist/FaceScan-BWSeJEqI.js +0 -2
  118. package/dist/FaceScan-BdjT7nMG.js +0 -2
  119. package/dist/FaceScan-Bji5lGcQ.js +0 -2
  120. package/dist/FaceScan-Bji5lGcQ.js.map +0 -1
  121. package/dist/FaceScan-BmDNM8tt.js +0 -2
  122. package/dist/FaceScan-CNoW9DIE.js +0 -2
  123. package/dist/FaceScan-CPf6-siO.js +0 -2
  124. package/dist/FaceScan-CQayY4q-.js +0 -2
  125. package/dist/FaceScan-CQkfSMC2.js +0 -2
  126. package/dist/FaceScan-CaxQ6fGF.js +0 -2
  127. package/dist/FaceScan-CxDcvM4f.js +0 -2
  128. package/dist/FaceScan-D2PL8KpZ.js +0 -2
  129. package/dist/FaceScan-D3T_l4nN.js +0 -2
  130. package/dist/FaceScan-DCm43Nrq.js +0 -2
  131. package/dist/FaceScan-DKP93c3l.js +0 -2
  132. package/dist/FaceScan-DW6Ix1a1.js +0 -2
  133. package/dist/FaceScan-DYJVZoZ4.js +0 -2
  134. package/dist/FaceScan-Da2XEApH.js +0 -2
  135. package/dist/FaceScan-DrW2yUSA.js +0 -2
  136. package/dist/FaceScan-DxnydFcx.js +0 -2
  137. package/dist/FaceScan-Gm4F4cO1.js +0 -2
  138. package/dist/FaceScan-Nhc7myLG.js +0 -2
  139. package/dist/FaceScan-VFLJ9h_T.js +0 -2
  140. package/dist/FaceScan-iUXyDuza.js +0 -2
  141. package/dist/LoadingScreen-BILrJVZm.js +0 -2
  142. package/dist/LoadingScreen-FKDLJRUj.js +0 -2
  143. package/dist/Modal-4T_aWWPQ.js +0 -2
  144. package/dist/Modal-BHfJVhRi.js +0 -2
  145. package/dist/Modal-BitizIvu.js +0 -2
  146. package/dist/Modal-BpgpPVxR.js +0 -2
  147. package/dist/Modal-BzH-_ch3.js +0 -2
  148. package/dist/Modal-CB_MHF7l.js +0 -2
  149. package/dist/Modal-CDiBoVXR.js +0 -2
  150. package/dist/Modal-CWoUZTh4.js +0 -2
  151. package/dist/Modal-CaPtqgjI.js +0 -2
  152. package/dist/Modal-CbZJwbLZ.js +0 -2
  153. package/dist/Modal-DRjJKUrw.js +0 -2
  154. package/dist/Modal-DU2Jymve.js +0 -2
  155. package/dist/Modal-D_XGokez.js +0 -2
  156. package/dist/Modal-DnweWp6L.js +0 -2
  157. package/dist/Modal-Do--CErH.js +0 -2
  158. package/dist/Modal-Do--CErH.js.map +0 -1
  159. package/dist/Modal-YZScjwEm.js +0 -2
  160. package/dist/fonts/Switzer-Regular.eot +0 -0
  161. package/dist/fonts/Switzer-Regular.svg +0 -0
  162. package/dist/fonts/Switzer-Regular.ttf +0 -0
  163. package/dist/fonts/Switzer-Regular.woff +0 -0
  164. package/dist/fonts/Switzer-Regular.woff2 +0 -0
  165. package/dist/interfaces-B5ysRXpa.d.ts +0 -209
  166. package/dist/interfaces-CaaERZjZ.d.ts +0 -209
  167. package/dist/pose-detection.esm-D08ZA0zl.js +0 -18
  168. package/dist/pose-detection.esm-DejsYGYM.js +0 -18
  169. package/dist/pose-detection.esm-DejsYGYM.js.map +0 -1
@@ -1,2 +0,0 @@
1
- import{jsx as e,jsxs as t,Fragment as n}from"react/jsx-runtime";import r,{useState as a,useCallback as s,useEffect as o,createContext as c,useLayoutEffect as i,useMemo as l,useContext as d,useRef as u}from"react";import{L as m,u as p,H as f,b as h,S as g,z as y,a as v,i as w,P as x,o as b,s as S,j as C,k as N,l as D,p as k,A as I,x as F,B as T,q as E,f as L,r as M,D as _,c as $,M as U,v as j,E as A,I as P,V as z,J as V,K as R,N as B,G as q,O as K,Q as O,R as W,h as H,n as J,w as G,T as Q,t as Y,C as X,y as Z}from"./Modal-CB_MHF7l.js";import ee from"clsx";import te from"react-webcam";import{X as ne}from"lucide-react";import{Dialog as re,Box as ae,Drawer as se}from"@mui/material";import oe from"video.js";const ce="DESKTOP",ie="TAB",le="MOBILE",de=c(void 0);function ue({children:t}){const[n,r]=a([window?.innerWidth,window?.innerHeight]),[s,c]=a(!1),d=()=>{r([window?.innerWidth,window?.innerHeight])};o(()=>{d()},[]),i(()=>(window.addEventListener("resize",d),()=>window.removeEventListener("resize",d)),[d]);let u=ce;n[0]>768&&n[0]<1024&&(u=ie),n[0]<768&&(u=le);const m=l(()=>({size:n,setSize:r,clearInputs:s,setClearInputs:c,media:u}),[n,s,u]);return e(de.Provider,{value:m,children:t})}var me=r.memo(function({size:n=16}){return t("svg",{width:n,height:n,viewBox:"0 0 25 25",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[e("path",{d:"M22.6968 14.6968C22.6968 16.8185 21.8539 18.8533 20.3536 20.3536C18.8533 21.8539 16.8185 22.6968 14.6968 22.6968",stroke:"white",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"}),e("path",{d:"M18.6968 11.6968V10.6968C18.6968 10.1663 18.4861 9.65764 18.111 9.28256C17.7359 8.90749 17.2272 8.69678 16.6968 8.69678C16.1663 8.69678 15.6576 8.90749 15.2826 9.28256C14.9075 9.65764 14.6968 10.1663 14.6968 10.6968",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"}),e("path",{d:"M14.6968 10.6968V9.69678C14.6968 9.16634 14.4861 8.65764 14.111 8.28256C13.7359 7.90749 13.2272 7.69678 12.6968 7.69678C12.1663 7.69678 11.6576 7.90749 11.2826 8.28256C10.9075 8.65764 10.6968 9.16634 10.6968 9.69678V10.6968",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"}),e("path",{d:"M10.6968 10.1968V4.69678C10.6968 4.16634 10.4861 3.65764 10.111 3.28256C9.73592 2.90749 9.22721 2.69678 8.69678 2.69678C8.16634 2.69678 7.65764 2.90749 7.28256 3.28256C6.90749 3.65764 6.69678 4.16634 6.69678 4.69678V14.6968",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"}),e("path",{d:"M18.6969 11.6968C18.6969 11.1663 18.9076 10.6576 19.2827 10.2826C19.6577 9.90749 20.1664 9.69678 20.6969 9.69678C21.2273 9.69678 21.736 9.90749 22.1111 10.2826C22.4862 10.6576 22.6969 11.1663 22.6969 11.6968V14.6968C22.6969 16.8185 21.854 18.8533 20.3537 20.3536C18.8534 21.8539 16.8186 22.6968 14.6969 22.6968H12.6969C9.89688 22.6968 8.19688 21.8368 6.70688 20.3568L3.10688 16.7568C2.76282 16.3757 2.57847 15.8769 2.592 15.3637C2.60554 14.8505 2.81593 14.3621 3.1796 13.9997C3.54327 13.6373 4.03238 13.4287 4.54565 13.417C5.05892 13.4053 5.55704 13.5914 5.93688 13.9368L7.69688 15.6968",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})]})});var pe=r.memo(function({angle:n,countdown:r,isScanning:a,isInTargetRange:o,stabilityScore:c,children:i}){const{translate:u}=d(m)||{},g=p(),y=s(()=>n<80?Math.max(0,Math.min(100,10*(n-60))):n>95?Math.max(0,Math.min(100,10*(105-n))):100,[n]),v=l(()=>{if(a)return g?.style?.angleDetector?.successAngleBackground||"#4f46e5";const e=y();if(0===e)return g?.style?.angleDetector?.successAngleLowBackground||"#ffffff";if(100===e)return g?.style?.angleDetector?.successAngleBackground||"#4f46e5";return`rgb(${Math.round(255-e/100*116)}, ${Math.round(255-e/100*163)}, ${Math.round(255-e/100*9)})`},[a,y]),w=s((e,t)=>t>70?e?`text-[${g?.style?.angleDetector?.successAngleTextLightColor}]/70`:`text-[${g?.style?.angleDetector?.successAngleTextLightColor}]`:e?`text-[${g?.style?.angleDetector?.successAngleTextLightColor}]/40`:`text-[${g?.style?.angleDetector?.successAngleTextDarkColor}]/70`,[]),x=s((e=!1)=>{const t=y();return a?`text-[${g?.style?.angleDetector?.successAngleTextLightColor}]`:w(e,t)},[a,y]),b=s((e,t)=>t>70||e?g?.style?.angleDetector?.successAngleTextLightColor:g?.style?.angleDetector?.successAngleTextDarkColor,[]),S=s((e=!1)=>{const t=y();return a?g?.style?.angleDetector?.successAngleTextLightColor:b(e,t)},[a,y]),C=r;function N(){document.documentElement.style.setProperty("--real-vh",window.innerHeight+"px")}return N(),window.addEventListener("resize",N),t("div",{className:"flex common-ui-main w-screen flex-col items-center h-[var(--real-vh)] overflow-hidden touch-none justify-center transition-all duration-300 max-w-[28rem] mx-auto",style:{backgroundColor:v},"data-testid":"level-screen","data-angle-state":a?"locked":o?"target":"adjusting",children:[e("div",{className:"flex justify-start fixed top-[.5rem] max-w-[28rem] mx-auto w-full px-[1rem]",children:e("div",{className:"flex justify-start ",children:e(f,{noTitle:!0})})}),null!==C?e("div",{className:"relative flex h-[6rem] w-[6rem] items-center justify-center rounded-[9999px] bg-[#fff]/20 transition-all duration-300",style:{border:`2px solid ${S()}`},children:e("div",{className:`text-[3rem] font-bold text-[${S()}]`,style:{fontFamily:g?.style?.base?.baseFontFamily||"Inter, sans-serif",color:S()},children:C})}):t("div",a?{className:"relative flex flex-col items-center justify-center",children:[e("div",{className:"relative flex h-16 w-16 items-center justify-center rounded-[9999px] border-2 bg-[#fff]/30 border-[#fff]",children:e("div",{className:"h-4 w-4 rounded-[9999px] animate-pulse bg-[#fff]/80"})}),i]}:{className:ee("relative flex h-[4rem] w-[4rem] items-center justify-center rounded-[9999px] ",o?"bg-[#fff]/20 border-[#fff]":"bg-[#fff]/10 border-[#fff]"),style:{transform:`translateY(${3*(90-n)}px)`,transition:"transform 0.2s ease-out",border:`2px solid ${S()}`},children:[e("div",{className:`h-[1rem] w-[1rem] rounded-[9999px] bg-[${S()}]/80`,style:{backgroundColor:`${S()}B3`}}),t("div",{className:ee("mt-[.5rem] text-center w-[180px] flex-col flex items-center absolute top-[60px]",x()),style:{color:S()},children:[e(me,{size:30}),t("p",{style:{fontFamily:g?.style?.base?.baseFontFamily||"Inter, sans-serif"},children:[" ",u?.(h.startLevelCheck),e("br",{})]})]})]}),null!==C&&e("div",{className:"absolute bottom-[8rem] text-center",children:e("div",{className:ee("text-sm font-medium px-4 py-1.5 bg-black/20 rounded-[9999px] mt-8",x()),style:{fontFamily:g?.style?.base?.baseFontFamily||"Inter, sans-serif",color:S()},children:u?.(h.leavePhone)})}),o&&null===C&&!a&&e("div",{className:"absolute bottom-[8rem] w-[12rem]",children:e("div",{className:`h-[.375rem] w-full bg-[${S()}]/20 rounded-[9999px] overflow-hidden`,style:{backgroundColor:`${S()}33`},children:e("div",{className:`h-full bg-[${S()}]/70 transition-all duration-300 rounded-[9999px]`,style:{width:`${n}%`,backgroundColor:`${S()}B3`}})})}),null===C&&!a&&e("div",{className:"absolute bottom-[5rem] text-center",children:t("div",{className:ee("text-[1.5rem] font-light",x()),style:{color:S()},children:[Math.round(n),"°"]})}),null===C&&!a&&e("div",{className:"absolute bottom-[2rem] text-center max-w-[20rem] mx-auto",children:e("div",{className:ee("text-[.75rem] opacity-50",x()),style:{fontFamily:g?.style?.base?.baseFontFamily||"Inter, sans-serif",color:S()},children:u?.(h.placePhoneUpright)})})]})});function fe({resetScan:n,loadingCam:r,onUserMedia:a,onPause:s,pause:o,onReScan:c,recordingStarted:i,startSendingVideoFrames:l,showPause:u,webcamRef:p,onUserMediaError:f,resetDetector:w,videoConstraints:x,webcamKey:b,faceDone:S,isScanning:C}){const{media:N}=d(de)||{},{translate:D}=d(m)||{};return t("div",{className:"App w-screen h-[100vh] relative common-ui-main",style:{background:"#000"},"data-testid":"camera-scan","data-scan-phase":S?"spinning":i?"pose-detecting":C?"starting":"ready",children:[e("span",{onClick:()=>{n(),w()},className:"fixed right-[20px] top-[20px] z-[999]",children:e(ne,{className:"text-[#fff]"})}),e("div",{className:"w-full h-full overflow-hidden ",children:N===le&&e(te,{audio:!1,ref:p,screenshotQuality:1,videoConstraints:x,mirrored:!0,screenshotFormat:"image/jpeg",onUserMedia:a,onUserMediaError:f,style:{position:"fixed",top:0,bottom:0,zIndex:0,width:"100%",height:"100%",objectFit:"cover"}},b)}),t("div",{className:"fixed bottom-[30px] w-full z-[999] flex flex-col gap-4 items-center justify-center",children:[u&&e(g,{className:"!w-[180px] !h-[40px] !py-[0] mx-auto ",prefix:y,buttonText:D?.(h.pause),buttonFunc:s,btnSecondary:!0}),o?e("div",{children:e(g,{className:"!w-[180px] !h-[40px] !py-[0] mx-auto",buttonText:D?.(h.restart),buttonFunc:c,btnSecondary:!0})}):i?null:e(g,{"data-testid":"start-scan-btn",className:"!w-[180px] !h-[40px] !py-[0] mx-auto !bg-[#ffffff] !text-[#000000] "+(r?"!opacity-50":""),buttonText:D?.(h.startScan),buttonFunc:l,disabled:r})]}),e("audio",{id:"audioElement",crossOrigin:"anonymous",preload:"auto",style:{position:"absolute",zIndex:-99999},src:`${v}scanAudioInstructions/silence.mp3`})]})}let he,ge=null,ye=null,ve=null;let we=null;var xe=r.memo(function({setIsScanLocked:t,resetDetector:n,scanID:r,setIsVideoUploaded:c,setScanFailsError:i,setScanStartTime:m,setScanUniqueKey:p,userDetails:f}){const{gender:h,heightInCm:g,email:y,shopDomain:_}=f,$=u(null),U=u(null),j=u(null),[A,P]=a([]),[z,V]=a(!0),[R,B]=a(!1),[q,K]=a(!1),[O,W]=a(!0),[H,J]=a(!1),G=u(null),[Q,Y]=a(""),[X,Z]=a([]),[ee,te]=a(""),[ne,re]=a(!1),[ae,se]=a(!1),[oe,ce]=a(!1),[ie,le]=a([]),[de,ue]=a(!1),me=u(!0),{poseDetector:pe}=function(){const[e,t]=a(0),[n,r]=a(0),[s,c]=a(!1),i=u(0),l=u(0),d=u(!0);async function m(){if("undefined"==typeof window||"undefined"==typeof navigator)return!1;try{console.log("Starting TensorFlow preload...");const[e,t,n]=await Promise.all([import("./pose-detection.esm-DejsYGYM.js"),import("@tensorflow/tfjs-core"),import("@tensorflow/tfjs-backend-webgl")]);ve=e,await t.setBackend("webgl"),await t.ready(),console.log("TensorFlow backend ready (WebGL)");const r={runtime:"mediapipe",modelType:"full",solutionPath:"https://cdn.jsdelivr.net/npm/@mediapipe/pose"};try{ye=await ve.createDetector(ve.SupportedModels.BlazePose,r),console.log("MediaPipe detector created successfully")}catch(e){console.warn("MediaPipe failed, falling back to TFJS runtime:",e),ye=await ve.createDetector(ve.SupportedModels.BlazePose,{runtime:"tfjs",modelType:"full"}),console.log("TFJS detector created successfully")}return!0}catch(e){return console.error("Failed to load TensorFlow dependencies:",e),ge=null,!1}}function p(e){return!(!e||0===e.length)&&22===e.filter(e=>e[2]>.7).length}return o(()=>{if(d.current=!0,!ye)return ge||(ge=m()),ge.then(e=>{e&&d.current&&c(!0)}),()=>{d.current=!1};c(!0)},[]),o(()=>{l.current=e,e>6&&i.current<2&&(r(e=>e+1),t(0))},[e]),o(()=>{i.current=n},[n]),{poseDetector:async(e,n)=>{if(!ye||!d.current||!n?.current?.video)return;const r=n.current.video;if(!(r.readyState<2))try{const n=await ye.estimatePoses(r,{flipHorizontal:!1});if(!n||!n.length)return;const a=n[0].keypoints.slice(11).map(e=>[e.x>0&&e.x<720?e.x:-1,e.y>0&&e.y<1280?e.y:-1,e.score??0]);0!==i.current||p(a)||t(e=>e+1),1===i.current&&p(a)&&t(e=>e+1),2===i.current&&e()}catch(e){console.error("Pose detection error:",e)}},isLoaded:s,spinPhase:n,resetDetector:()=>{i.current=0,l.current=0,t(0),r(0)},retryLoading:async()=>{ye||ge||(ge=m(),await ge&&d.current&&c(!0))}}}(),xe=u(!0),be=u(!1),Se=u(0),Ce=u(0),Ne=u(!1),De=u(!1),ke=u(!1),Ie=u(()=>{}),Fe=u(()=>{}),Te=u(null),[Ee,Le]=a([]),[Me,_e]=a(0),[$e,Ue]=a(w),{setStartGyro:je,uploadScanFile:Ae,setUploadLoading:Pe,swan:ze,onScanStart:Ve,onCaptureComplete:Re}=d(x),Be=()=>{be.current=!1,clearTimeout(he),G.current&&clearTimeout(G.current),p(L()),i(""),Pe?.(!1),P([]),j.current=null,V(!0),B(!1),K(!1),W(!0),J(!1),G.current=null,Y(""),Z([]),te(""),re(!ne),je(!1),S.stopAudio(),se(!1),ce(!1),Se.current=0,Ce.current=0,Ne.current=!1,ke.current=!1,null!==U.current&&U.current.stop(),ie.forEach(e=>{U.current&&U.current.removeEventListener("dataavailable",e)}),le([]),me.current=!0,ue(!1),c(!1),$.current?.stream&&V(!1)},qe=s(()=>{setTimeout(()=>{V(!1)},1e3)},[]),Ke=s(e=>{if(console.log("camera error",e),$e===w)return Ue(b),void _e(e=>e+1);V(!1)},[$e]),Oe=s(()=>{me.current=!1,ce(!0),ue(!1),G.current&&clearTimeout(G.current),U.current&&U.current.pause(),S.stopAudio(),ze.poseDetection.disconnect(),Se.current=0,Ce.current=0,Ne.current=!1,ke.current=!1,U.current&&U.current.stop(),ie.forEach(e=>{U.current&&U.current.removeEventListener("dataavailable",e)}),le([]),clearTimeout(he)},[U,ie,S,me]),We=l(()=>C(),[]),He=N(Ee),Je=D(He),Ge=s(async()=>{me.current=!0,await S.playAudio(`${v}SpotOn.mp3`),ce(!1),ue(!1),G.current&&clearTimeout(G.current),B(!1)},[G,S]),Qe=s(async()=>{if(!De.current&&!Te.current){De.current=!0;try{Te.current=await ze.poseDetection.connect(),k.capture(`${_}/pose_detection_connected`,{scanID:r,email:y,id:Te.current})}catch(e){console.log(e,"while connecting websocket")}finally{De.current=!1}}},[r,_,y]),Ye=s(async()=>{I({eventName:`${_}/rescan`,email:y,scanID:r,height:g,gender:h,status:!1}),me.current=!1,ze.poseDetection.disconnect(),Te.current=null,Be(),await Qe(),Fe.current()},[Qe,r,y]),Xe=s(({data:e})=>{e&&e.size>0&&me.current&&(P(t=>t.concat(e)),!be.current&&$.current&&(be.current=!0,pe(()=>{Ge(),F({eventName:`${_}/tensorFlow`,scanID:r,email:y,message:"recording stopped by tensorflow "})},$)))},[Ge,F,_,r,y,$]),Ze=s(async()=>{const e=X[X.length-1];e&&me.current&&(await S.playAudio(v+e),me.current&&(he=setTimeout(Ze,2e3)))},[X,me]),et=s(()=>{U&&U.current&&U.current.stop(),B(!0);try{if($&&$.current&&$.current.stream){const e=$.current.stream.getVideoTracks()[0];if(e){const t=e.getSettings();j.current=t.frameRate||null}const t={videoBitsPerSecond:15e5};Ee[0]&&(t.mimeType=Ee[0]),U.current=new MediaRecorder($.current.stream,t),U.current.addEventListener("dataavailable",Xe),U.current.addEventListener("stop",()=>{W(!0)}),le([...ie,Xe]),U.current.start(1e3),W(!1)}}catch(e){console.log("error while using media recorder",e)}},[$,Ee,Xe,ie]),tt=s(async()=>{G.current&&clearTimeout(G.current),et(),me.current&&(G.current=setTimeout(async()=>{me.current&&(await S.playAudio(`${v}SpotOn.mp3`),B(!1))},15e3)),K(!0),me.current&&await S.playAudio(`${v}Spin.mp3`)},[et,me,S]);o(()=>{Ie.current=tt},[tt]);const nt=s(({data:e})=>{const t=ze.poseDetection.connected();e.size>0&&t&&(Ne.current||(Ne.current=!0,ze.poseDetection.poseStatus(async e=>{if(e&&e.audio&&e.audio.length>0){const t=document.querySelector("#audioElement");k.capture(`${_}/pose_instruction_received`,{scanID:r,email:y,audio:e.audio,status:e.status,sid:e.sid,counter:Se.current,consecutiveFalse:Ce.current,type:"body_scan_instruction"}),!0===e.status&&e.sid===Te.current?(Ce.current=0,Se.current<2?(Se.current+=1,1!==Se.current||ke.current?2===Se.current&&t?.paused&&S.playAudio(v+e.audio):(ke.current=!0,S.stopAudio(),await S.playAudio(v+e.audio))):(te(e.audio),clearTimeout(he),ze.poseDetection.disconnect(),Ne.current=!1,setTimeout(()=>Ie.current(),1e3))):(Ce.current+=1,Ce.current>=3&&(Se.current=0,ke.current=!1),!t?.paused||we&&we?.audioName===e.audio?we?.audioName===e.audio&&t?.paused&&(we&&we.no_of_times_skipped>=we.skipCount?(we.no_of_times_skipped=0,S.playAudio(v+e.audio)):we&&(we.no_of_times_skipped+=1)):(we={skipCount:2,no_of_times_skipped:0,audioName:e.audio},S.playAudio(v+e.audio)))}})),$?.current&&null!==$.current.getScreenshot()&&ze.poseDetection.videoEmit({image:$.current.getScreenshot()||"",scanId:r}))},[$,r,ze,S,_,y]),rt=s(async()=>{J(!0),je(!0),Ve?.(),xe.current&&(xe.current=!1,F({eventName:"scan started",scanID:r,status:"success",email:y})),m(T()),V(!0),me.current&&await S.playAudio(`${v}StartScan.mp3`),me.current&&await S.playAudio(`${v}LiftArmsAndHoldAtHip.mp3`),me.current&&(J(!1),B(!0),se(!0),ue(!0),qe());try{if($&&$.current&&$.current.stream&&me.current){const e=$.current.stream.getVideoTracks()[0];if(e){const t=e.getSettings();j.current=t.frameRate||null}const t={videoBitsPerSecond:15e5};Ee[0]&&(t.mimeType=Ee[0]),me.current&&(U.current=new MediaRecorder($.current.stream,t)),me.current&&U.current&&U.current.addEventListener("dataavailable",nt),le([...ie,nt]),U.current&&U.current.start(1e3),W(!1),me.current&&(he=setTimeout(Ze,2e3))}}catch(e){console.log("error ----------",e)}},[$,Ee,nt,ie,Ze,me,Ve]);return o(()=>(_&&(t(!0),Qe()),()=>{const e=Te.current;Te.current=null,e&&(ze.poseDetection.disconnect(),k.capture(`${_}/pose_detection_disconnected`,{scanID:r,email:y,id:e})),ie.forEach(e=>{U?.current?.removeEventListener("dataavailable",e)})}),[_]),o(()=>{X.push(Q)},[Q]),o(()=>{Z([])},[ee]),o(()=>{const e=A.length&&A.length>0;O||!e||R||!me.current||oe||U&&U.current&&(R||U.current.stop())},[O,R,A,oe]),o(()=>{const e=A.length&&A.length>0;if(O&&e&&!R&&U&&U.current&&me.current&&!oe&&!R){const e=new File(A,`${r}.${Je}`,{type:He});Re?.(),Pe?.(!0),i(""),Ae?.(e,j.current)}},[O,R,A,oe,U,me]),o(()=>{Fe.current=rt},[rt]),o(()=>{const e=E(We,M);Le(e)},[We]),o(()=>{Be()},[]),e(fe,{resetDetector:n,resetScan:Be,loadingCam:z,onPause:Oe,showRestart:ae,pause:oe,onReScan:Ye,recordingStarted:R,isScanning:H,startSendingVideoFrames:rt,faceDone:q,stopRecording:Ge,showPause:de,webcamRef:$,onUserMedia:qe,onUserMediaError:Ke,videoConstraints:$e,webcamKey:Me})});function be({scanID:t,userDetails:n,setIsVideoUploaded:r,setScanFailsError:s,setScanStartTime:c,setScanUniqueKey:i}){const[l,d]=a(90),[m,p]=a(0),[f,h]=a(null),[g,y]=a(!1),[v,w]=a(0),x=u([]),[b,S]=a(!1),C=l-m,N=C>=80&&C<=95;o(()=>{if("undefined"!=typeof window&&window.DeviceOrientationEvent){const e=e=>{if(null!==e.beta){let t=Math.abs(e.beta);null!==e.gamma&&(t*=Math.cos(e.gamma*Math.PI/180)),t=Math.max(0,Math.min(180,t)),d(t)}},t=async()=>{const t=DeviceOrientationEvent;if(t&&"function"==typeof t.requestPermission)try{"granted"===await t.requestPermission()&&window.addEventListener("deviceorientation",e)}catch(e){console.error("Permission error",e)}else window.addEventListener("deviceorientation",e);return()=>{e&&window.removeEventListener("deviceorientation",e)}};document.addEventListener("click",t,{once:!0})}},[]),o(()=>{if(x.current=[...x.current.slice(-4),C],x.current.length>=5){const e=Math.max(...x.current)-Math.min(...x.current);w(N&&e<2?e=>Math.min(100,e+10):e=>Math.max(0,e-20))}N||null===f&&!g||k()},[C,N,f,g]),o(()=>{v>=100&&null===f&&!g&&D(),v<50&&null!==f&&k()},[v,f,g]);const D=()=>{h(3);const e=setInterval(()=>{h(t=>null===t||t<=1?(clearInterval(e),y(!0),null):t-1)},1e3)},k=()=>{h(null),b||y(!1)};return e(pe,{angle:C,countdown:f,isScanning:g,isInTargetRange:N,stabilityScore:v,children:g&&e(xe,{setIsScanLocked:S,resetDetector:()=>{d(90),p(0),h(null),y(!1),w(0),S(!1),x.current=[]},scanID:t,userDetails:n,setIsVideoUploaded:r,setScanFailsError:s,setScanStartTime:c,setScanUniqueKey:i})})}function Se({setShowDrawer:t,config:n,loader:r}){const[c,i]=a({disabled:!1,message:""}),[l,d]=a(!0),m=u(null),p=s(async()=>{const e=await _();i(e),d(!1)},[]);return o(()=>{p()},[]),l?e($,{url:r,loaderType:"black"}):c?.disabled?e(U,{config:n,message:c?.message}):e(te,{audio:!1,ref:m,screenshotQuality:1,videoConstraints:j,mirrored:!0,onUserMedia:()=>t?.(!0),screenshotFormat:"image/jpeg",style:{position:"relative",top:0,bottom:0,zIndex:0,width:"100%",height:"100%",objectFit:"cover"}})}function Ce({link:t,onReady:n,wrapperClassName:r="[&_video]:rounded-t-[20px] w-full h-full"}){const a=u(null),s=u(null);let c={autoplay:!0,controls:!1,responsive:!0,fluid:!0,muted:!0,navigationUI:"hide",preload:"metadata",poster:A};return o(()=>{if(!s.current&&t&&a?.current){const e=oe(a.current,{...c});e.ready(()=>{s.current=e;const r={...c,sources:[{src:t,type:"application/x-mpegURL"}]};e.autoplay(r.autoplay),e.src(r.sources),n?.(e)})}},[t,a]),o(()=>{const e=s.current;return()=>{e&&!e.isDisposed()&&(e.dispose(),s.current=null)}},[s]),e("div",{className:r,children:e("video",{ref:a,muted:!0,className:"video-js",playsInline:!0,onDrag:e=>e.preventDefault()})})}function Ne({scanFailsError:r,onNext:s,gender:o,setScanUniqueKey:c,setIsVideoUploaded:i}){const{translate:l}=d(m)||{},u=p(),[y,v]=a(!1),w=()=>{v(!y)};return t(n,{children:[t("div",{"data-testid":"scan-error-message",className:"flex common-ui-main flex-col h-full max-w-[28rem] mx-auto w-full rounded-t-[20px] overflow-y-auto",style:{background:u?.style?.base?.backgroundColor},children:[e("div",{className:"w-full max-w-[28rem] mx-auto pt-[1rem] px-[1rem]",children:e(f,{noTitle:!0})}),e("div",{className:"flex-1",children:r&&t("div",{className:"px-[1rem]",children:[e("h2",{className:"text-center",style:{fontFamily:u?.style?.heading?.headingFontFamily||"SeriouslyNostalgic Fn",fontSize:u?.style?.heading?.headingFontSize||"32px",color:u?.style?.heading?.headingColor||"#000",fontWeight:u?.style?.heading?.headingFontWeight||"normal"},children:l?.(h.issueWithScan)}),e("p",{style:{fontFamily:u?.style?.base?.baseFontFamily||"Inter, sans-serif",fontSize:u?.style?.base?.baseFontSize||"16px",color:u?.style?.base?.baseTextColor||"#1E1E1E"},children:l?.(h.reason)}),e("p",{style:{fontFamily:u?.style?.base?.baseFontFamily||"Inter, sans-serif",fontSize:u?.style?.base?.baseFontSize||"16px",color:u?.style?.base?.baseTextColor||"#1E1E1E"},children:P(r)}),e("img",{className:"my-[0.5rem] aspect-[2/1.4] w-full object-cover",onClick:w,src:z[o],alt:"icon"})]})}),r&&e("div",{className:"p-[1rem] flex gap-[0.5rem]",children:e(g,{"data-testid":"scan-again-btn",disabled:!1,buttonText:l?.(h.scanAgain),className:"!shadow-none",buttonFunc:()=>{s?s?.():c?.(L()),i?.(!1)}})})]}),y&&t(re,{className:"w-screen h-screen video-modal",onClose:w,open:y,children:[e("div",{className:"flex justifyEnd ",children:e("span",{className:"closeBtn",onClick:w,children:e(ne,{className:"absolute right-[8px] top-[8px] text-white z-[9]"})})}),e("div",{className:"aspect-video object-cover rounded-[20px] ",children:e(Ce,{link:o?V[o].PRE_LINK:V.male.PRE_LINK,wrapperClassName:"w-screen h-screen fixed top-[0] left-[0]"})})]})]})}function De({scanId:n,userDetails:r,config:c,isVideoUploadedCorrect:i,isMeasurementAvailable:l,onComplete:u,isSuccess:p,onCustomScanSuccess:y,swan:v}){const{gender:w,shopDomain:x,heightInCm:b,deviceFocalLength:S,userName:C,email:N,scanType:D}=r||{},I=[K,O,W].includes(D??""),[F,T]=a(!0),E=s(async()=>{try{I&&(await(v?.auth.addUser({scanId:n,email:N,name:C,gender:w,height:b})),y?.()),k.capture(x??"",{scanID:n,email:N,height:b,focalLength:S,clothesFit:"0",gender:w})}catch(e){console.log(e)}},[I]),{translate:L}=d(m)||{};o(()=>{(i||l)&&E()},[i,l]);const M=p||i||l;return e(ae,{className:"flex h-full w-full flex-col common-ui-main",children:t("div",{className:"h-full w-full flex-col items-center justify-center flex",children:[e(Se,{loader:c?.loader,setShowDrawer:T}),e(se,{open:F,onClose:(e,t)=>{},className:"camera-drawer",anchor:"bottom",children:e("div",{className:"max-w-[28rem] mx-auto w-full h-full flex text-center flex-col justify-between items-center bg-primary rounded-t-[30px] p-[1rem]",style:{background:c?.style?.base?.backgroundColor},children:t("div",{className:"w-full h-full flex flex-col",children:[e(f,{title:L?.(h.measurementsBeingTaken)}),e("div",{className:"flex items-center justify-center flex-1",children:e("video",{preload:"auto",className:"max-h-[calc(100vh-450px)] mx-auto w-full object-contain border-none",muted:!0,loop:!0,autoPlay:!0,playsInline:!0,children:e("source",{src:w===q.Male?R:B,type:"video/mp4"})})}),M&&e(g,{className:"!w-[180px] mx-auto",buttonText:L?.(h.next),buttonFunc:()=>{u?.()}})]})})})]})})}const ke=()=>{const{userDetails:n,onRetry:r,isError:a,isSuccess:s,gender:o,scanUniqueKey:c,scanFailsError:i,setScanUniqueKey:l,setIsVideoUploaded:u,isMeasurementAvailable:m,isVideoUploadedCorrect:f,loading:h,showDeniedModal:g,uploadLoading:y,setScanFailsError:v,setScanStartTime:w,resetScan:b,onCustomScanSuccess:S,swan:C,onComplete:N}=d(x),D=p();return a?t("div",{"data-scan-state":"error",children:[e(Se,{}),e(se,{anchor:"bottom",open:!0,className:"camera-drawer",onClose:(e,t)=>{},children:e(Ne,{scanFailsError:!0,onNext:r,gender:o})})]}):s?e("div",{"data-scan-state":"success",children:e(De,{isSuccess:!0,onComplete:N})}):h?e("div",{"data-scan-state":"loading",className:"flex top-0 !mt-0 left-0 z-[999] absolute justify-center items-center w-full h-full",style:{background:D?.style?.base?.backgroundColor},children:e($,{url:D?.loader,loaderType:"black"})}):g.disabled?e("div",{"data-scan-state":"camera-denied",children:e(U,{})}):y||i||m||f?(y||m||f)&&!i?e("div",{"data-scan-state":"processing",children:e(De,{scanId:c,isMeasurementAvailable:m,userDetails:n,isVideoUploadedCorrect:f,onCustomScanSuccess:S,swan:C,onComplete:N})}):t("div",{"data-scan-state":"error-retry",children:[e(Se,{}),e(se,{anchor:"bottom",open:!0,className:"camera-drawer",onClose:(e,t)=>{},children:e(Ne,{scanFailsError:i,onNext:()=>{r?.(),b()},setScanUniqueKey:l,gender:o,setIsVideoUploaded:u})})]}):e("div",{"data-scan-state":"scanning",children:e(be,{scanID:c,userDetails:n,setIsVideoUploaded:u,setScanFailsError:v,setScanStartTime:w,setScanUniqueKey:l})})},Ie=t=>{const{config:n,onRetry:r,onScanStart:c,onCaptureComplete:i,onUploadStart:d,onUploadEnd:u,onMeasurementSocketStart:m,onMeasurementSocketClose:p,onIntermediateScanSuccess:f,onScanError:h,onScanSuccess:g,onCustomScanSuccess:y,onComplete:v,isError:w,isSuccess:b}=t,S={email:"",shopDomain:"",gender:"male",heightInCm:0,scanType:"",deviceFocalLength:0,deviceModelName:"",sourceTag:"",callbackUrl:null,...t.userDetails??{}},C=t.token??"",{gender:N,scanType:D,shopDomain:k,heightInCm:I,email:E,deviceFocalLength:M,deviceModelName:$,callbackUrl:U,sourceTag:j}=S,A=l(()=>H(C),[C]),[z,V]=a(!1),[R,B]=a(!1),[q,K]=a(!1),[O,W]=a({disabled:!1,message:""}),[ee,te]=a(""),[ne,re]=a(!1),[ae,se]=a(!0),[oe,ce]=a(!1),[ie,le]=a(""),[de,me]=a(T()),{gyroData:pe}=function(e){const[t,n]=a([]),[r,c]=a(!1),i=s(e=>{try{const{alpha:t,beta:r,gamma:a}=e;n(e=>[...e,{alpha:t?.toString()||void 0,beta:r?.toString()||void 0,gamma:a?.toString()||void 0,timestamp:(new Date).toISOString()}])}catch(e){console.log(e)}},[]),l=s(async()=>{const e=DeviceOrientationEvent;if(void 0!==e&&"function"==typeof e.requestPermission)try{"granted"===await e.requestPermission()?c(!0):console.warn("Device orientation permission denied.")}catch(e){console.error("Error requesting device orientation permission:",e)}else c(!0)},[]);return o(()=>(e&&r?window.addEventListener("deviceorientation",i):n([]),()=>{window.removeEventListener("deviceorientation",i)}),[e,r,i]),o(()=>{e&&l()},[e,l]),{gyroData:t}}(oe);J();const fe=s(()=>{le(L()),te(""),V(!1),re(!1)},[]),he=()=>{me(null),le("")},ge=s(async e=>{if(e&&"success"===e?.scanStatus&&"intermediate"===e?.resultType&&200===e?.code)return F({eventName:`${k}/measurement_success/intermediate`,scanID:ie,status:"success",email:E}),B(!0),void f?.(e);g?.(e),B(!0),he();const t=ie;K(!0),F({eventName:`${k}/measurement_success/fit-view`,scanID:t,status:"success",email:E}),de&&F({eventName:`${k}/scan_completion_time`,scanID:t,status:"success",completionTime:T()-de,email:E})},[D,k,ie]),ye=e=>{K(!1),te(""),B(!1),A.measurement.handleMeasurementSocket({scanId:ie,onPreopen:()=>{Z({eventName:`${k}/webSocket`,scanID:ie,connection:"pre_open",type:"measurement_recommendation",email:E})},onOpen:()=>{m?.(),Z({eventName:`${k}/webSocket`,scanID:ie,connection:"open",type:"measurement_recommendation",email:E})},onClose:()=>{p?.(),Z({eventName:`${k}/webSocket`,scanID:ie,connection:"close",type:"measurement_recommendation",email:E})},onError:e=>{var t;t=e,h?.({...t,message:P(t)}),he(),K(!1),te(t),B(!1),F({eventName:`${k}/measurement_failed/fit-view`,scanID:ie,status:"failed",email:E,message:P(t)}),de&&F({eventName:`${k}/scan_completion_time`,scanID:ie,status:"failed",completionTime:T()-de,email:E}),Z({eventName:`${k}/webSocket`,scanID:ie,connection:"error",type:"measurement_recommendation",email:E})},onSuccess:e=>{Z({eventName:`${k}/webSocket`,scanID:ie,connection:"success",type:"measurement_recommendation",email:E}),ge(e)}})},ve=s(async(e,t)=>{const n=Number((e.size/1048576).toFixed(2)),r=null!=t?t:await G(e),a=Q({gender:N,focal_length:`${M}`,height:`${I}`,customer_store_url:k,clothes_fit:"0",scan_type:D,callback_url:U,source_tag:j});F({eventName:`${k}/body_scan_meta_data`,scanID:ie,email:E,data:JSON.stringify([...a,{fileSizeInMB:n,video_fps:r||0}])}),d?.();try{await A.fileUpload.uploadFileFrontend({file:e,arrayMetaData:a,scanId:ie,email:E}),await A.fileUpload.setDeviceInfo({model:$,detection:"manual",gyro:pe,scanId:ie}),console.log("video successfully uploaded"),re(!1),F({eventName:`${k}/scan_success`,scanID:ie,status:"success",email:E,data:JSON.stringify(a)}),F({eventName:"scan finished",scanID:ie,status:"success",email:E}),me(T()),setTimeout(()=>{re(!0)},3e3)}catch(e){F({eventName:"scan finished",scanID:ie,status:"failed",email:E,message:P(e)}),F({eventName:`${k}/scan_failed`,scanID:ie,status:"failed",email:E,message:P(e),data:JSON.stringify(a)}),te(P(e)),re(!1),h?.({...e,message:P(e)}),he()}finally{ce(!1),u?.()}},[ie,pe,d,u]),we=s(async()=>{if(+I<152.4||+I>213.36)return void h?.({message:"Height must be between 152.4cm (5ft) and 213.36cm (7ft)"});const e=await _();e.disabled?(F({eventName:`${k}/camera_activation`,scanID:ie,status:"failed",email:E}),se(!1)):(se(!1),F({eventName:`${k}/camera_activation`,scanID:ie,status:"success",email:E})),W(e),te(""),re(!1)},[E,ie,le,k]);return o(()=>{w||b||k&&we()},[k,I,w,b]),o(()=>{w||b||ne&&k&&ie&&ye()},[ne,k,ie,w,b]),e("div",{"data-testid":"body-scan-root",children:e(Y,{children:e(X,{config:n,children:e(ue,{children:e(x.Provider,{value:{userDetails:S,onRetry:r,onScanError:h,isError:w,isSuccess:b,onScanSuccess:g,gender:N,scanUniqueKey:ie,scanFailsError:ee,setScanUniqueKey:le,setIsVideoUploaded:re,isMeasurementAvailable:q,isVideoUploadedCorrect:R,loading:ae,showDeniedModal:O,uploadLoading:z,setStartGyro:ce,uploadScanFile:ve,setUploadLoading:V,resetScan:fe,setScanFailsError:te,setScanStartTime:me,onScanStart:c,onCaptureComplete:i,onCustomScanSuccess:y,onComplete:v,swan:A},children:e(ke,{})})})})})})};export{Ie as B};
2
- //# sourceMappingURL=BodyScan-z6h5fueJ.js.map
@@ -1,2 +0,0 @@
1
- "use strict";var e=require("react/jsx-runtime"),t=require("react"),a=require("./Modal-BpgpPVxR.js"),n=require("lucide-react"),r=require("@mui/material");let o=null,s=!1;const c=async()=>{if("undefined"==typeof window)return null;if(o)return o;if(s)for(;s;)if(await new Promise(e=>setTimeout(e,100)),o)return o;s=!0;try{const[e,t]=await Promise.all([import("@tensorflow/tfjs"),Promise.resolve().then(function(){return require("./pose-detection.esm-Bc8T4UAD.js")})]);await e.setBackend("webgl"),await e.ready();const n=await t.createDetector(t.SupportedModels.BlazePose,{runtime:"tfjs",modelType:"full"}),r=document.createElement("canvas");r.width="number"==typeof a.videoConstraints.width?a.videoConstraints.width:a.videoConstraints.width.ideal??a.videoConstraints.width.max??1280,r.height="number"==typeof a.videoConstraints.height?a.videoConstraints.height:a.videoConstraints.height.ideal??a.videoConstraints.height.max??720;const s=r.getContext("2d");if(s){s.fillStyle="black",s.fillRect(0,0,r.width,r.height);try{await n.estimatePoses(r)}catch(e){console.warn("Warmup frame failed (non-fatal):",e)}}return o=n,n}catch(e){return console.error("Failed to preload detector:",e),null}finally{s=!1}};function i({faceScanId:e,onValidPose:n,onScanComplete:r,onModelReady:o,onStartRecording:s,shopDomain:i,isError:l,isSuccess:d}){const u=t.useRef(null),[f,g]=t.useState(0),[h,m]=t.useState(0),[p,y]=t.useState(!1),[S,x]=t.useState(!1),v=t.useRef(!1),b=t.useRef(null),w=t.useRef(null),F=t.useRef(f),C=t.useRef(h),j=t.useRef([]),E=t.useRef(""),_=t.useRef(0),N=t.useRef(!1),T=t.useRef(0),k="undefined"!=typeof navigator&&(/iPad|iPhone|iPod/.test(navigator.userAgent)||"MacIntel"===navigator.platform&&navigator.maxTouchPoints>1),R=t.useMemo(()=>["Face front","Turn head fully left","Turn head fully right","Smile facing front"],[]),I=t.useMemo(()=>function(e,t){let a;return(...n)=>{a&&clearTimeout(a),a=setTimeout(()=>e(...n),t)}}(e=>{a.posthog.capture(`${i}/face_scan_pose_detection`,e)},4e3),[i]),D=t.useCallback((t,a,n,r,o,s)=>{const c=Date.now();if(!(c-T.current<4e3)){T.current=c;try{const c=t[0]||[0,0,0],i=t[2]||[0,0,0],l=t[5]||[0,0,0],d=t[9]||[0,0,0],u=t[10]||[0,0,0],f=t.map(e=>e[2]).filter(e=>e>0),g=f.length>0?f.reduce((e,t)=>e+t,0)/f.length:0,h=a.map(e=>e[2]).filter(e=>e>0),m=h.length>0?h.reduce((e,t)=>e+t,0)/h.length:0,p=Math.abs(i[0]-l[0]),y=c[0]-l[0],S=i[0]-c[0];let x="frontal";1===n?x="left":2===n?x="right":3===n&&(x="frontal_smile");const v={faceScanId:e,stage:n,timestamp:(new Date).toISOString(),data:JSON.stringify({headValid:r,bodyInvalid:o,consecutiveValid:s,avgFaceScore:parseFloat(g.toFixed(3)),avgBodyScore:parseFloat(m.toFixed(3)),faceKeypointsDetected:f.length,bodyKeypointsDetected:h.length,eyeDistance:parseFloat(p.toFixed(2)),noseToRightRatio:parseFloat((y/p).toFixed(3)),noseToLeftRatio:parseFloat((S/p).toFixed(3)),noseScore:parseFloat(c[2].toFixed(3)),leftEyeScore:parseFloat(i[2].toFixed(3)),rightEyeScore:parseFloat(l[2].toFixed(3)),leftMouthScore:parseFloat(d[2].toFixed(3)),rightMouthScore:parseFloat(u[2].toFixed(3)),expectedPosition:x})};I(v)}catch(e){console.warn("Failed to track pose detection:",e)}}},[e,I]),M=()=>{a.posthog.capture(`${i}/face_scan_detection_started`,{faceScanId:e,stage:F.current,timestamp:(new Date).toISOString(),stageName:R[F.current]}),setTimeout(()=>{x(!0)},1500)};return t.useEffect(()=>{if(!l&&!d)return(async()=>{if("undefined"!=typeof window)try{console.log("Initializing Face Scan...");const e=await c();e&&(u.current=e,console.log("Face scan model loaded successfully"),y(!0),o?.())}catch(e){console.error("Error initializing face scan:",e)}})(),()=>{(async()=>{try{y(!1)}catch(e){console.error("Error disposing resources:",e)}finally{g(0),m(0),F.current=0,C.current=0,j.current=[]}})()}},[l,d]),t.useEffect(()=>{F.current=f},[f]),t.useEffect(()=>{C.current=h},[h]),{faceScanDetector:async(t,o)=>{if(u.current&&t.current&&p&&S&&!(t.current.readyState<2||v.current)){v.current=!0;try{const c=t.current.videoWidth||720,l=t.current.videoHeight||1280;b.current||(b.current=document.createElement("canvas"),b.current.width=c,b.current.height=l);const d=b.current.getContext("2d");d&&d.drawImage(t.current,0,0,c,l);const f=await u.current.estimatePoses(d?b.current:t.current);if(f.length>0){const t=[],c=[];if(f[0].keypoints.forEach((e,a)=>{const n=e.score??0,r=[e.x??-1,e.y??-1,n];a<=10?t.push(r):c.push(r)}),o?.current){const e=o.current.getContext("2d"),{width:t,height:a}=o.current;if(e){e.clearRect(0,0,t,a);const n=Math.min(C.current/2,1),r=.35*a;e.beginPath(),e.strokeStyle="#00ff00",e.lineWidth=6,e.arc(t/2,a/2,r+10,-Math.PI/2,-Math.PI/2+2*n*Math.PI),e.stroke()}}const l=((e,t)=>{if(!t[0]||!t[2]||!t[5]||t[0][2]<.2||t[2][2]<.2||t[5][2]<.2)return!1;const a=.5*(t[10][1]+t[9][1])-.5*(t[5][1]+t[2][1]),n=(.5*(t[10][1]+t[9][1])-t[0][1])/a,r=n>.7||n<.3,o=Math.abs(t[2][1]-t[5][1])<.5*a&&Math.abs(t[9][1]-t[10][1])<.5*a,s=t[2][0]-t[5][0],c=t[0][0]-t[5][0],i=c>.4*s&&c<.6*s,l=c>.85*s,d=t[2][0]-t[0][0]>.85*s;switch(e){case 0:case 3:return!r&&o&&i;case 1:return!r&&o&&l;case 2:return!r&&o&&d;default:return!1}})(F.current,t),d=c.slice(2).filter(e=>e[2]>.7).length<=2;j.current.push(l&&d),j.current.length>10&&j.current.shift();if(j.current.filter(Boolean).length>=2){const e=C.current+1;m(e)}else m(Math.max(0,C.current-1));if(C.current>=2){n?.();const t=F.current+1;m(0),j.current=[],g(t),x(!1),(async()=>{if(await a.speechService.playAudio(`${a.voiceOverAssetsPath}face-scan-vos/Sound-effect.mp3`),a.posthog.capture(`${i}/face_scan_detection_stage_completed`,{faceScanId:e,completedStage:F.current,nextStage:t,timestamp:(new Date).toISOString(),totalStages:4,stageName:R[F.current]}),1===t&&s&&s(),t>=4)r?.();else{let e=null;switch(t){case 1:e="Left.mp3";break;case 2:e="Right.mp3";break;case 3:e="Smile.mp3"}e&&await a.speechService.playAudio(`${a.voiceOverAssetsPath}face-scan-vos/${e}`),M()}})()}D(t,c,F.current,l,d,C.current)}}catch(e){console.error("Pose detection error:",e)}finally{v.current=!1}}},scanStage:f,setScanStage:g,consecutiveValid:h,isModelLoaded:p,resetScan:()=>{a.posthog.capture(`${i}/face_scan_reset`,{faceScanId:e,stage:F.current,timestamp:(new Date).toISOString(),stageName:R[F.current],consecutiveValid:C.current}),g(0),m(0),x(!1),F.current=0,C.current=0,j.current=[],E.current="",_.current=0,N.current=!1,w.current&&(speechSynthesis.cancel(),w.current=null)},enableVoiceCommands:()=>{if(N.current=!0,"undefined"!=typeof window&&k&&"speechSynthesis"in window){const e=new SpeechSynthesisUtterance("");e.volume=0,speechSynthesis.speak(e)}},startScanSequence:M,isScanningActive:S}}function l({onRetry:r,loading:o}){const{translate:s}=t.useContext(a.LanguageContext)||{},c=a.useConfig();return e.jsx("div",{"data-testid":"face-scan-error-screen",className:"fixed common-ui-main top-[0] left-[0] z-[999] flex justify-center items-center w-full h-full",style:{background:c?.style?.base?.backgroundColor},children:e.jsxs("div",{className:"flex flex-col w-full items-center p-[1rem] rounded-lg ",children:[e.jsx(a.Header,{noTitle:!0}),e.jsxs("div",{className:"flex flex-col items-center w-full",children:[e.jsx("h2",{className:"text-xl font-semibold text-gray-800 ",style:{fontFamily:c?.style?.heading?.headingFontFamily||"SeriouslyNostalgic Fn",fontSize:c?.style?.heading?.headingFontSize||"32px",color:c?.style?.heading?.headingColor||"#000",fontWeight:c?.style?.heading?.headingFontWeight||"normal"},children:s?.(a.LanguageKeys.scanFailed)}),e.jsx("p",{className:"mb-[1.5rem]",style:{fontFamily:c?.style?.subheading?.subheadingFontFamily||"'Inter', sans-serif",fontSize:c?.style?.subheading?.subheadingFontSize||"14px",color:c?.style?.subheading?.subheadingColor||"#4b5563",fontWeight:c?.style?.subheading?.subheadingFontWeight||"normal"},children:s?.(a.LanguageKeys.clickToResetScan)}),e.jsx(a.SpecificButton,{"data-testid":"face-scan-retry-btn",disabled:o,className:"w-full h-[45px] shadow-[0px_1px_2px_0px_#00000040] text-[16px]",buttonText:s?.(a.LanguageKeys.resetScan),postfixIcon:e.jsx(n.ArrowRight,{}),buttonFunc:()=>r?.()})]})]})})}function d({stage:n,videoLoading:r,setVideoLoading:o,videoError:s,setVideoError:c,gender:i,btnConfig:l}){const{translate:d}=t.useContext(a.LanguageContext)||{},u=a.useConfig();return-1===n?e.jsxs("div",{"data-testid":"face-scan-guide",className:"text-center common-ui-main p-[16px] w-full h-full",style:{background:u?.style?.base?.backgroundColor},children:[e.jsxs("div",{className:"w-full",children:[e.jsx(a.Header,{noTitle:!0}),e.jsx("h2",{style:{fontFamily:u?.style?.heading?.headingFontFamily||"SeriouslyNostalgic Fn",fontSize:u?.style?.heading?.headingFontSize||"32px",color:u?.style?.heading?.headingColor||"#000",fontWeight:u?.style?.heading?.headingFontWeight||"normal"},children:d?.(a.LanguageKeys.faceVisible)}),r&&e.jsx("div",{className:"mb-4 flex items-center justify-center",style:{fontFamily:u?.style?.subheading?.subheadingFontFamily||"'Inter', sans-serif",fontSize:u?.style?.subheading?.subheadingFontSize||"14px",color:u?.style?.subheading?.subheadingColor||"#4b5563",fontWeight:u?.style?.subheading?.subheadingFontWeight||"normal"},children:d?.(a.LanguageKeys.loadingVideo)}),s&&e.jsx("div",{className:"mb-4 text-red-600",style:{fontFamily:u?.style?.subheading?.subheadingFontFamily||"'Inter', sans-serif",fontSize:u?.style?.subheading?.subheadingFontSize||"14px",color:"#ff0000",fontWeight:u?.style?.subheading?.subheadingFontWeight||"normal"},children:d?.(a.LanguageKeys.videoLoadFailed)}),!s&&e.jsx("div",{className:" w-[100px] mx-auto",children:e.jsx("video",{src:i===a.GenderType.Male?a.maleGlassesOffVideo:a.glassesOffVideo,autoPlay:!0,loop:!0,controls:!1,muted:!0,playsInline:!0,className:"h-full w-full object-contain border-none",onCanPlay:()=>o(!1),onLoadStart:()=>o(!0),onError:()=>c(!0),"aria-label":"Instructional video: Please remove your glasses before starting the scan."})})]}),e.jsx("div",{className:"flex justify-center w-full p-[1rem]",children:e.jsx(a.SpecificButton,{"data-testid":"face-scan-start-btn",disabled:l.isDisabled,className:"!w-[60px] !h-[35px] !py-0 !px-0",buttonText:d?.(l.label),postfixIcon:l?.icon,buttonFunc:l.onClick})})]}):e.jsx("div",{className:"text-center common-ui-main p-[16px] w-full h-full",style:{background:u?.style?.base?.backgroundColor},children:e.jsxs("div",{className:"w-full",children:[e.jsx(a.Header,{noTitle:!0}),e.jsx("h3",{className:"mb-[0.5rem]",style:{fontFamily:u?.style?.heading?.headingFontFamily||"SeriouslyNostalgic Fn",fontSize:u?.style?.heading?.headingFontSize||"32px",color:u?.style?.heading?.headingColor||"#000",fontWeight:u?.style?.heading?.headingFontWeight||"normal"},children:d?.(a.directionMessages[n])}),e.jsxs("div",{className:"max-w-[400px] justify-center gap-1 mx-auto flex items-center",children:[e.jsx("div",{className:` w-[120px] overflow-hidden ${0===n?"opacity-100":"opacity-0 hidden"} `,children:e.jsx("video",{className:"h-full w-full object-contain border-none",muted:!0,loop:!0,autoPlay:!0,playsInline:!0,children:e.jsx("source",{src:i===a.GenderType.Male?a.FACE_SCAN_HEADSHOT.male.forward:a.FACE_SCAN_HEADSHOT.female.forward,type:"video/mp4"})})}),e.jsx("div",{className:` w-[120px] overflow-hidden ${1===n?"opacity-100":"opacity-0 hidden"} `,children:e.jsx("video",{className:"h-full w-full object-contain border-none",muted:!0,loop:!0,autoPlay:!0,playsInline:!0,children:e.jsx("source",{src:i===a.GenderType.Male?a.FACE_SCAN_HEADSHOT.male.left:a.FACE_SCAN_HEADSHOT.female.left,type:"video/mp4"})})}),e.jsx("div",{className:` w-[120px] overflow-hidden ${2===n?"opacity-100":"opacity-0 hidden"} `,children:e.jsx("video",{className:"h-full w-full object-contain border-none",muted:!0,loop:!0,autoPlay:!0,playsInline:!0,children:e.jsx("source",{src:i===a.GenderType.Male?a.FACE_SCAN_HEADSHOT.male.right:a.FACE_SCAN_HEADSHOT.female.right,type:"video/mp4"})})}),e.jsx("div",{className:` w-[120px] overflow-hidden ${3===n?"opacity-100":"opacity-0 hidden"} `,children:e.jsx("video",{className:"h-full w-full object-contain border-none",muted:!0,loop:!0,autoPlay:!0,playsInline:!0,children:e.jsx("source",{src:i===a.GenderType.Male?a.FACE_SCAN_HEADSHOT.male.smile:a.FACE_SCAN_HEADSHOT.female.smile,type:"video/mp4"})})})]})]})})}const u=({webcamRef:o,canvasRef:s})=>{const{isError:c,isSuccess:i,showLoader:u,hasError:f,errorType:g,resetScanState:h,showGuideCard:m,scanStage:p,videoLoading:y,setVideoLoading:S,videoError:x,setVideoError:v,gender:b,getButtonText:w,isScanning:F,startScan:C,isModelLoaded:j,onRetry:E}=t.useContext(a.ParamsContext),_=a.useConfig();return c?e.jsx(l,{onRetry:E}):i?e.jsx("div",{className:"fixed z-[9] common-ui-main w-full h-full",style:{background:_?.style?.base?.backgroundColor},children:e.jsx(a.LoadingScreen,{url:_?.loader,loaderType:"black"})}):e.jsxs(e.Fragment,{children:[e.jsx("audio",{id:"audioElement",crossOrigin:"anonymous",preload:"auto",style:{position:"absolute",zIndex:-99999},src:void 0}),u&&!f&&e.jsx("div",{className:"fixed z-[9] common-ui-main w-full h-full",style:{background:_?.style?.base?.backgroundColor},children:e.jsx(a.LoadingScreen,{url:_?.loader,loaderType:"black"})}),e.jsx("div",{className:"h-full flex-col common-ui-main relative w-full flex justify-center items-center text-center rounded-t-[20px]",style:{background:_?.style?.base?.backgroundColor},children:e.jsx("div",{className:"flex-1 w-full max-w-md overflow-hidden",children:e.jsxs("div",{className:"w-full h-full",children:[e.jsx("video",{ref:o,autoPlay:!0,playsInline:!0,muted:!0,width:a.videoConstraints.width.ideal,height:a.videoConstraints.height.ideal,className:"w-full h-full object-cover fixed left-0 top-0 z-0",style:{transform:"scaleX(-1)"}}),e.jsx("canvas",{ref:s,width:a.videoConstraints.width.ideal,height:a.videoConstraints.height.ideal,style:{transform:"scaleX(-1)",opacity:"0"}})]})})}),!u&&f&&g===a.FaceScanErrorType.Camera&&e.jsx(a.Modal,{testId:"face-scan-camera-error-screen",config:_}),!u&&f&&g!==a.FaceScanErrorType.Camera&&e.jsx(l,{loading:u,onRetry:h}),m&&!f&&!u&&e.jsx(r.Drawer,{open:!0,className:"face-scan-small camera-draw",anchor:"bottom",onClose:(e,t)=>{},hideBackdrop:!0,children:e.jsx(d,{stage:p,videoLoading:y,setVideoLoading:S,videoError:x,setVideoError:v,gender:b,btnConfig:{label:w(),onClick:F?h:C,isDisabled:u||!j,icon:F?e.jsx(n.ArrowRight,{}):e.jsx(e.Fragment,{})}})})]})};exports.FaceScan=n=>{const{onScanSuccess:r,onScanError:o,onRetry:s,onScanStart:c,onCaptureComplete:l,onUploadStart:d,onUploadEnd:f,onMeasurementSocketStart:g,onMeasurementSocketClose:h,config:m,isError:p,isSuccess:y}=n,S=n.userDetails??{email:"",gender:"male",deviceFocalLength:0,shopDomain:"",bodyScanId:"",callbackUrl:null},x=n.token??"",v=t.useRef(null),b=t.useRef(null),w=t.useRef(null),F=t.useRef([]),C=t.useRef(null),j=t.useRef(null),E=t.useRef(0),_=t.useRef(null),[N,T]=t.useState(!1),[k,R]=t.useState(!1),[I,D]=t.useState(!1),[M,P]=t.useState(!0),[A,L]=t.useState(!1),[O,z]=t.useState(!1),[$,H]=t.useState(!1),[V,W]=t.useState(null),[K,U]=t.useState(a.generateUuid()),q=t.useMemo(()=>a.getSwanService(x),[x]),{email:B,gender:G,deviceFocalLength:J,shopDomain:X,callbackUrl:Q,bodyScanId:Y}=S,[Z,ee]=t.useState([]),[te,ae]=t.useState(a.videoConstraintsExact),ne=t.useMemo(()=>a.getPreferredMediaRecorderTypes(),[]),re=a.getRecordingMimeType(Z),oe=a.getRecordingExtension(re);a.usePosthogPageview();const se=t.useCallback(()=>{console.log("Stopping recording..."),cancelAnimationFrame(E.current),_.current&&(_.current.pause(),_.current.srcObject=null,_.current=null),w.current&&"recording"===w.current.state&&w.current.stop(),w.current=null},[]),ce=async()=>{if(l?.(),F.current){if(0===F.current.length)return console.error("No video data recorded"),W(a.FaceScanErrorType.Scan),H(!0),void T(!1);d?.(),T(!0);const e=new File(F.current,`${K}.${oe}`,{type:re}),t=j.current??await a.getVideoFPS(e),n=e.size,r=(n/1048576).toFixed(2),o=Math.round(n/1e4),s={video_size_mb:parseFloat(r),video_size_bytes:n,video_fps:t||0,blob_count:F.current.length,estimated_duration_seconds:o},c=[{gender:G},{face_scan_id:K},{focal_length:`${J}`},{customer_store_url:X},{scan_type:"face_scan"},{body_scan_id:Y}];Q&&c.push({callback_url:Q}),a.handleScanTimeCapture({eventName:`${X}/face_scan_meta_data`,faceScanId:K,email:B,data:JSON.stringify({metaData:c,videoData:s})});const i=Date.now();a.handleScanTimeCapture({eventName:`${X}/face_scan_upload_start`,faceScanId:K,email:B,startTime:i});try{const t=await q.fileUpload.faceScanFileUploader({file:e,arrayMetaData:c,objectKey:K,email:B,contentType:e.type}),n=Date.now(),r=n-i;a.handleScanTimeCapture({eventName:`${X}/face_scan_upload_complete`,faceScanId:K,email:B,completionTime:n,uploadDuration:r}),f?.(),console.log("✅ Upload successful",t),q.measurement.handlFaceScaneSocket({onPreopen:()=>{g?.(),a.handleWebSocketCapture({eventName:`${X}/webSocket`,faceScanID:K,connection:"pre_open",type:"faceScan_recommendation",email:B})},faceScanId:K,onOpen:()=>{a.handleWebSocketCapture({eventName:`${X}/webSocket`,faceScanID:K,connection:"open",type:"faceScan_recommendation",email:B}),console.log("websocket connect open")},onError:e=>{a.handleWebSocketCapture({eventName:`${X}/webSocket`,faceScanID:K,connection:"error",type:"faceScan_recommendation",email:B}),ye(e)},onSuccess:e=>{a.handleWebSocketCapture({eventName:`${X}/webSocket`,faceScanID:K,connection:"success",type:"faceScan_recommendation",email:B}),Se(e)},onClose:()=>{h?.(),console.log("websocket connect close"),a.handleWebSocketCapture({eventName:`${X}/webSocket`,faceScanID:K,connection:"close",type:"faceScan_recommendation",email:B})}})}catch(e){f?.(),ye(e)}}},ie=t.useCallback(()=>{const e=v.current?.srcObject;if(!e)return;const t=e.getVideoTracks()[0].getSettings(),{width:n=1280,height:r=720}=t,o=document.createElement("canvas"),s=o.getContext("2d");n>r?(o.width=r,o.height=n):(o.width=n,o.height=r);const c=document.createElement("video");c.srcObject=e,c.muted=!0,c.playsInline=!0,c.play(),_.current=c;const i=()=>{n>r?(s?.save(),s?.translate(o.width,0),s?.rotate(Math.PI/2),s?.drawImage(c,0,0,r,n),s?.restore()):s?.drawImage(c,0,0,n,r),E.current=requestAnimationFrame(i)};E.current=requestAnimationFrame(i);const l=t.frameRate??10;j.current=l;const d=o.captureStream(l),u={videoBitsPerSecond:15e5};let f;Z.length>0&&(u.mimeType=Z[0]);try{f=new MediaRecorder(d,u)}catch(e){return console.error("MediaRecorder init failed:",e),W(a.FaceScanErrorType.Scan),H(!0),void T(!1)}F.current=[],f.ondataavailable=e=>{e?.data&&e.data.size>0&&F.current&&F.current.push(e.data)},f.onstop=()=>{console.log("Recording stopped, total blobs:",F?.current?.length),ce()},f.start(100),w.current=f,console.log("Recording started successfully (portrait normalized)")},[Z,ce]),{faceScanDetector:le,scanStage:de,setScanStage:ue,resetScan:fe,isModelLoaded:ge,startScanSequence:he}=i({faceScanId:K,shopDomain:X,isError:p,isSuccess:y,onScanComplete:()=>{se()},onModelReady:()=>{R(!0)},onStartRecording:()=>{console.log("Stage 0 completed - starting recording for stages 1-3"),ie()}}),me=t.useCallback(()=>{ge&&(c?.(),ue(0),a.speechService.playAudio(`${a.voiceOverAssetsPath}face-scan-vos/Face-forward.mp3`),setTimeout(()=>{D(!0),setTimeout(()=>{he()},200)},200))},[ue,D,he,ge,c]),pe=t.useCallback(()=>{D(!1),P(!0),se(),fe(),s?.(),F.current=[],j.current=null,w.current&&(w.current=null),H(!1),W(null),ue(-1),U(a.generateUuid()),v.current&&C.current&&(v.current.srcObject=C.current,console.log("Camera stream restored after reset"))},[ue,D,P,se,fe,U]),ye=e=>{console.log(e,"ws error"),o?.(e),W(a.FaceScanErrorType.Scan),H(!0),T(!1),P(!1),a.handleScanTimeCapture({eventName:`${X}/faceScan`,faceScanId:K,status:"failed",email:B,data:JSON.stringify(e)})},Se=e=>{console.log(e,"ws success"),e&&"intermediate"===e?.resultType&&a.handleScanTimeCapture({eventName:`${X}/faceScan_success/intermediate`,faceScanId:K,status:"success",email:B,data:JSON.stringify(e)}),r?.(e)};t.useEffect(()=>{if(!p&&!y)return navigator.mediaDevices.getUserMedia&&navigator.mediaDevices.getUserMedia({video:te}).then(e=>{C.current=e,v.current&&(v.current.srcObject=e)}).catch(e=>{if(console.error("Error accessing webcam:",e),te===a.videoConstraintsExact)return void ae(a.videoConstraintsFallback);const t=["NotAllowedError","PermissionDeniedError","NotFoundError","DevicesNotFoundError","NotReadableError","TrackStartError"].includes(e?.name);W(t?a.FaceScanErrorType.Camera:a.FaceScanErrorType.Scan),H(!0)}),()=>{C.current&&C.current.getTracks().forEach(e=>e.stop())}},[p,y,te]),t.useEffect(()=>{if(!k||!I)return;const e=setInterval(()=>{le(v,b)},500);return()=>clearInterval(e)},[le,k,I]);return console.log("Model ready:",k,"Has error:",$,"Is scanning:",I,"showLoader",N),t.useEffect(()=>{const e=a.getSupportedMediaRecorderTypes(ne,a.videoTypes);ee(e)},[ne]),t.useEffect(()=>{ue(-1)},[]),e.jsx("div",{"data-face-scan-stage":de,children:e.jsx(a.LanguageContextProvider,{children:e.jsx(a.ConfigProvider,{config:m,children:e.jsx(a.ParamsContext.Provider,{value:{isError:p,isSuccess:y,showLoader:N,hasError:$,errorType:V,resetScanState:pe,showGuideCard:M,scanStage:de,videoLoading:A,setVideoLoading:L,videoError:O,setVideoError:z,gender:G,getButtonText:()=>I?a.LanguageKeys.reset:ge?a.LanguageKeys.start:a.LanguageKeys.loading,isScanning:I,startScan:me,isModelLoaded:ge,onRetry:s},children:e.jsx(u,{webcamRef:v,canvasRef:b})})})})})},exports.preloadDetector=c;
2
- //# sourceMappingURL=FaceScan-3rVSqkKB.js.map
@@ -1,2 +0,0 @@
1
- "use strict";var e=require("react/jsx-runtime"),t=require("react"),a=require("./Modal-HTYYx7sM.js"),n=require("lucide-react"),o=require("@mui/material");let r=null,s=!1;function c({faceScanId:e,onValidPose:n,onScanComplete:o,onModelReady:c,onStartRecording:i,shopDomain:l,isError:d,isSuccess:u}){const f=t.useRef(null),[g,h]=t.useState(0),[m,p]=t.useState(0),[y,S]=t.useState(!1),[x,v]=t.useState(!1),b=t.useRef(null),w=t.useRef(g),F=t.useRef(m),C=t.useRef([]),j=t.useRef(""),E=t.useRef(0),_=t.useRef(!1),N=t.useRef(0),T="undefined"!=typeof navigator&&(/iPad|iPhone|iPod/.test(navigator.userAgent)||"MacIntel"===navigator.platform&&navigator.maxTouchPoints>1),k=t.useMemo(()=>["Face front","Turn head fully left","Turn head fully right","Smile facing front"],[]),I=t.useMemo(()=>function(e,t){let a;return(...n)=>{a&&clearTimeout(a),a=setTimeout(()=>e(...n),t)}}(e=>{a.posthog.capture(`${l}/face_scan_pose_detection`,e)},4e3),[l]),R=t.useCallback((t,a,n,o,r,s)=>{const c=Date.now();if(!(c-N.current<4e3)){N.current=c;try{const c=t[0]||[0,0,0],i=t[2]||[0,0,0],l=t[5]||[0,0,0],d=t[9]||[0,0,0],u=t[10]||[0,0,0],f=t.map(e=>e[2]).filter(e=>e>0),g=f.length>0?f.reduce((e,t)=>e+t,0)/f.length:0,h=a.map(e=>e[2]).filter(e=>e>0),m=h.length>0?h.reduce((e,t)=>e+t,0)/h.length:0,p=Math.abs(i[0]-l[0]),y=c[0]-l[0],S=i[0]-c[0];let x="frontal";1===n?x="left":2===n?x="right":3===n&&(x="frontal_smile");const v={faceScanId:e,stage:n,timestamp:(new Date).toISOString(),data:JSON.stringify({headValid:o,bodyInvalid:r,consecutiveValid:s,avgFaceScore:parseFloat(g.toFixed(3)),avgBodyScore:parseFloat(m.toFixed(3)),faceKeypointsDetected:f.length,bodyKeypointsDetected:h.length,eyeDistance:parseFloat(p.toFixed(2)),noseToRightRatio:parseFloat((y/p).toFixed(3)),noseToLeftRatio:parseFloat((S/p).toFixed(3)),noseScore:parseFloat(c[2].toFixed(3)),leftEyeScore:parseFloat(i[2].toFixed(3)),rightEyeScore:parseFloat(l[2].toFixed(3)),leftMouthScore:parseFloat(d[2].toFixed(3)),rightMouthScore:parseFloat(u[2].toFixed(3)),expectedPosition:x})};I(v)}catch(e){console.warn("Failed to track pose detection:",e)}}},[e,I]),M=()=>{a.posthog.capture(`${l}/face_scan_detection_started`,{faceScanId:e,stage:w.current,timestamp:(new Date).toISOString(),stageName:k[w.current]}),setTimeout(()=>{v(!0)},1500)},D=async()=>{if("undefined"!=typeof window)try{console.log("Initializing Face Scan...");const e=await(async()=>{if("undefined"==typeof window)return null;if(r)return r;if(s)for(;s;)if(await new Promise(e=>setTimeout(e,100)),r)return r;s=!0;try{const[e,t]=await Promise.all([import("@tensorflow/tfjs"),Promise.resolve().then(function(){return require("./pose-detection.esm-Bc8T4UAD.js")})]);await e.setBackend("webgl"),await e.ready();const n=await t.createDetector(t.SupportedModels.BlazePose,{runtime:"tfjs",modelType:"full"}),o=document.createElement("canvas");o.width="number"==typeof a.videoConstraints.width?a.videoConstraints.width:a.videoConstraints.width.ideal??a.videoConstraints.width.max??1280,o.height="number"==typeof a.videoConstraints.height?a.videoConstraints.height:a.videoConstraints.height.ideal??a.videoConstraints.height.max??720;const s=o.getContext("2d");if(s){s.fillStyle="black",s.fillRect(0,0,o.width,o.height);try{await n.estimatePoses(o)}catch(e){console.warn("Warmup frame failed (non-fatal):",e)}}return r=n,n}catch(e){return console.error("Failed to preload detector:",e),null}finally{s=!1}})();e&&(f.current=e,console.log("Face scan model loaded successfully"),S(!0),c?.())}catch(e){console.error("Error initializing face scan:",e)}};return t.useEffect(()=>{if(!d&&!u)return D(),()=>{(async()=>{try{S(!1)}catch(e){console.error("Error disposing resources:",e)}finally{h(0),p(0),w.current=0,F.current=0,C.current=[]}})()}},[d,u]),t.useEffect(()=>{w.current=g},[g]),t.useEffect(()=>{F.current=m},[m]),{faceScanDetector:async(t,r)=>{if(f.current&&t.current&&y&&x&&!(t.current.readyState<2))try{const s=await f.current.estimatePoses(t.current);if(s.length>0){const t=[],c=[];if(s[0].keypoints.forEach((e,a)=>{const n=e.score??0,o=[e.x??-1,e.y??-1,n];a<=10?t.push(o):c.push(o)}),r?.current){const e=r.current.getContext("2d"),{width:t,height:a}=r.current;if(e){e.clearRect(0,0,t,a);const n=Math.min(F.current/2,1),o=.35*a;e.beginPath(),e.strokeStyle="#00ff00",e.lineWidth=6,e.arc(t/2,a/2,o+10,-Math.PI/2,-Math.PI/2+2*n*Math.PI),e.stroke()}}const d=((e,t)=>{if(!t[0]||!t[2]||!t[5]||t[0][2]<.2||t[2][2]<.2||t[5][2]<.2)return!1;const a=.5*(t[10][1]+t[9][1])-.5*(t[5][1]+t[2][1]),n=(.5*(t[10][1]+t[9][1])-t[0][1])/a,o=n>.7||n<.3,r=Math.abs(t[2][1]-t[5][1])<.5*a&&Math.abs(t[9][1]-t[10][1])<.5*a,s=t[2][0]-t[5][0],c=t[0][0]-t[5][0],i=c>.4*s&&c<.6*s,l=c>.85*s,d=t[2][0]-t[0][0]>.85*s;switch(e){case 0:case 3:return!o&&r&&i;case 1:return!o&&r&&l;case 2:return!o&&r&&d;default:return!1}})(w.current,t),u=c.slice(2).filter(e=>e[2]>.7).length<=2;C.current.push(d&&u),C.current.length>10&&C.current.shift();if(C.current.filter(Boolean).length>=2){const e=F.current+1;p(e)}else p(Math.max(0,F.current-1));if(F.current>=2){n?.();const t=w.current+1;p(0),C.current=[],h(t),v(!1),(async()=>{if(await a.speechService.playAudio(`${a.voiceOverAssetsPath}face-scan-vos/Sound-effect.mp3`),a.posthog.capture(`${l}/face_scan_detection_stage_completed`,{faceScanId:e,completedStage:w.current,nextStage:t,timestamp:(new Date).toISOString(),totalStages:4,stageName:k[w.current]}),1===t&&i&&i(),t>=4)o?.();else{let e=null;switch(t){case 1:e="Left.mp3";break;case 2:e="Right.mp3";break;case 3:e="Smile.mp3"}e&&await a.speechService.playAudio(`${a.voiceOverAssetsPath}face-scan-vos/${e}`),M()}})()}R(t,c,w.current,d,u,F.current)}}catch(e){console.error("Pose detection error:",e)}},scanStage:g,setScanStage:h,consecutiveValid:m,isModelLoaded:y,resetScan:()=>{a.posthog.capture(`${l}/face_scan_reset`,{faceScanId:e,stage:w.current,timestamp:(new Date).toISOString(),stageName:k[w.current],consecutiveValid:F.current}),h(0),p(0),v(!1),w.current=0,F.current=0,C.current=[],j.current="",E.current=0,_.current=!1,b.current&&(speechSynthesis.cancel(),b.current=null)},enableVoiceCommands:()=>{if(_.current=!0,"undefined"!=typeof window&&T&&"speechSynthesis"in window){const e=new SpeechSynthesisUtterance("");e.volume=0,speechSynthesis.speak(e)}},startScanSequence:M,isScanningActive:x}}function i({onRetry:o,loading:r}){const{translate:s}=t.useContext(a.LanguageContext)||{},c=a.useConfig();return e.jsx("div",{"data-testid":"face-scan-error-screen",className:"fixed common-ui-main top-[0] left-[0] z-[999] flex justify-center items-center w-full h-full",style:{background:c?.style?.base?.backgroundColor},children:e.jsxs("div",{className:"flex flex-col w-full items-center p-[1rem] rounded-lg ",children:[e.jsx(a.Header,{noTitle:!0}),e.jsxs("div",{className:"flex flex-col items-center w-full",children:[e.jsx("h2",{className:"text-xl font-semibold text-gray-800 ",style:{fontFamily:c?.style?.heading?.headingFontFamily||"SeriouslyNostalgic Fn",fontSize:c?.style?.heading?.headingFontSize||"32px",color:c?.style?.heading?.headingColor||"#000",fontWeight:c?.style?.heading?.headingFontWeight||"normal"},children:s?.(a.LanguageKeys.scanFailed)}),e.jsx("p",{className:"mb-[1.5rem]",style:{fontFamily:c?.style?.subheading?.subheadingFontFamily||"'Inter', sans-serif",fontSize:c?.style?.subheading?.subheadingFontSize||"14px",color:c?.style?.subheading?.subheadingColor||"#4b5563",fontWeight:c?.style?.subheading?.subheadingFontWeight||"normal"},children:s?.(a.LanguageKeys.clickToResetScan)}),e.jsx(a.SpecificButton,{"data-testid":"face-scan-retry-btn",disabled:r,className:"w-full h-[45px] shadow-[0px_1px_2px_0px_#00000040] text-[16px]",buttonText:s?.(a.LanguageKeys.resetScan),postfixIcon:e.jsx(n.ArrowRight,{}),buttonFunc:()=>o?.()})]})]})})}function l({stage:n,videoLoading:o,setVideoLoading:r,videoError:s,setVideoError:c,gender:i,btnConfig:l}){const{translate:d}=t.useContext(a.LanguageContext)||{},u=a.useConfig();return-1===n?e.jsxs("div",{"data-testid":"face-scan-guide",className:"text-center common-ui-main p-[16px] w-full h-full",style:{background:u?.style?.base?.backgroundColor},children:[e.jsxs("div",{className:"w-full",children:[e.jsx(a.Header,{noTitle:!0}),e.jsx("h2",{style:{fontFamily:u?.style?.heading?.headingFontFamily||"SeriouslyNostalgic Fn",fontSize:u?.style?.heading?.headingFontSize||"32px",color:u?.style?.heading?.headingColor||"#000",fontWeight:u?.style?.heading?.headingFontWeight||"normal"},children:d?.(a.LanguageKeys.faceVisible)}),o&&e.jsx("div",{className:"mb-4 flex items-center justify-center",style:{fontFamily:u?.style?.subheading?.subheadingFontFamily||"'Inter', sans-serif",fontSize:u?.style?.subheading?.subheadingFontSize||"14px",color:u?.style?.subheading?.subheadingColor||"#4b5563",fontWeight:u?.style?.subheading?.subheadingFontWeight||"normal"},children:d?.(a.LanguageKeys.loadingVideo)}),s&&e.jsx("div",{className:"mb-4 text-red-600",style:{fontFamily:u?.style?.subheading?.subheadingFontFamily||"'Inter', sans-serif",fontSize:u?.style?.subheading?.subheadingFontSize||"14px",color:"#ff0000",fontWeight:u?.style?.subheading?.subheadingFontWeight||"normal"},children:d?.(a.LanguageKeys.videoLoadFailed)}),!s&&e.jsx("div",{className:" w-[100px] mx-auto",children:e.jsx("video",{src:i===a.GenderType.Male?a.maleGlassesOffVideo:a.glassesOffVideo,autoPlay:!0,loop:!0,controls:!1,muted:!0,playsInline:!0,className:"h-full w-full object-contain border-none",onCanPlay:()=>r(!1),onLoadStart:()=>r(!0),onError:()=>c(!0),"aria-label":"Instructional video: Please remove your glasses before starting the scan."})})]}),e.jsx("div",{className:"flex justify-center w-full p-[1rem]",children:e.jsx(a.SpecificButton,{"data-testid":"face-scan-start-btn",disabled:l.isDisabled,className:"!w-[60px] !h-[35px] !py-0 !px-0",buttonText:d?.(l.label),postfixIcon:l?.icon,buttonFunc:l.onClick})})]}):e.jsx("div",{className:"text-center common-ui-main p-[16px] w-full h-full",style:{background:u?.style?.base?.backgroundColor},children:e.jsxs("div",{className:"w-full",children:[e.jsx(a.Header,{noTitle:!0}),e.jsx("h3",{className:"mb-[0.5rem]",style:{fontFamily:u?.style?.heading?.headingFontFamily||"SeriouslyNostalgic Fn",fontSize:u?.style?.heading?.headingFontSize||"32px",color:u?.style?.heading?.headingColor||"#000",fontWeight:u?.style?.heading?.headingFontWeight||"normal"},children:d?.(a.directionMessages[n])}),e.jsxs("div",{className:"max-w-[400px] justify-center gap-1 mx-auto flex items-center",children:[e.jsx("div",{className:` w-[120px] overflow-hidden ${0===n?"opacity-100":"opacity-0 hidden"} `,children:e.jsx("video",{className:"h-full w-full object-contain border-none",muted:!0,loop:!0,autoPlay:!0,playsInline:!0,children:e.jsx("source",{src:i===a.GenderType.Male?a.FACE_SCAN_HEADSHOT.male.forward:a.FACE_SCAN_HEADSHOT.female.forward,type:"video/mp4"})})}),e.jsx("div",{className:` w-[120px] overflow-hidden ${1===n?"opacity-100":"opacity-0 hidden"} `,children:e.jsx("video",{className:"h-full w-full object-contain border-none",muted:!0,loop:!0,autoPlay:!0,playsInline:!0,children:e.jsx("source",{src:i===a.GenderType.Male?a.FACE_SCAN_HEADSHOT.male.left:a.FACE_SCAN_HEADSHOT.female.left,type:"video/mp4"})})}),e.jsx("div",{className:` w-[120px] overflow-hidden ${2===n?"opacity-100":"opacity-0 hidden"} `,children:e.jsx("video",{className:"h-full w-full object-contain border-none",muted:!0,loop:!0,autoPlay:!0,playsInline:!0,children:e.jsx("source",{src:i===a.GenderType.Male?a.FACE_SCAN_HEADSHOT.male.right:a.FACE_SCAN_HEADSHOT.female.right,type:"video/mp4"})})}),e.jsx("div",{className:` w-[120px] overflow-hidden ${3===n?"opacity-100":"opacity-0 hidden"} `,children:e.jsx("video",{className:"h-full w-full object-contain border-none",muted:!0,loop:!0,autoPlay:!0,playsInline:!0,children:e.jsx("source",{src:i===a.GenderType.Male?a.FACE_SCAN_HEADSHOT.male.smile:a.FACE_SCAN_HEADSHOT.female.smile,type:"video/mp4"})})})]})]})})}const d=({webcamRef:r,canvasRef:s})=>{const{isError:c,isSuccess:d,showLoader:u,hasError:f,errorType:g,resetScanState:h,showGuideCard:m,scanStage:p,videoLoading:y,setVideoLoading:S,videoError:x,setVideoError:v,gender:b,getButtonText:w,isScanning:F,startScan:C,isModelLoaded:j,onRetry:E}=t.useContext(a.ParamsContext),_=a.useConfig();return c?e.jsx(i,{onRetry:E}):d?e.jsx("div",{className:"fixed z-[9] common-ui-main w-full h-full",style:{background:_?.style?.base?.backgroundColor},children:e.jsx(a.LoadingScreen,{url:_?.loader,loaderType:"black"})}):e.jsxs(e.Fragment,{children:[e.jsx("audio",{id:"audioElement",crossOrigin:"anonymous",preload:"auto",style:{position:"absolute",zIndex:-99999},src:void 0}),u&&!f&&e.jsx("div",{className:"fixed z-[9] common-ui-main w-full h-full",style:{background:_?.style?.base?.backgroundColor},children:e.jsx(a.LoadingScreen,{url:_?.loader,loaderType:"black"})}),e.jsx("div",{className:"h-full flex-col common-ui-main relative w-full flex justify-center items-center text-center rounded-t-[20px]",style:{background:_?.style?.base?.backgroundColor},children:e.jsx("div",{className:"flex-1 w-full max-w-md overflow-hidden",children:e.jsxs("div",{className:"w-full h-full",children:[e.jsx("video",{ref:r,autoPlay:!0,playsInline:!0,muted:!0,width:a.videoConstraints.width.ideal,height:a.videoConstraints.height.ideal,className:"w-full h-full object-cover fixed left-0 top-0 z-0",style:{transform:"scaleX(-1)"}}),e.jsx("canvas",{ref:s,width:a.videoConstraints.width.ideal,height:a.videoConstraints.height.ideal,style:{transform:"scaleX(-1)",opacity:"0"}})]})})}),!u&&f&&g===a.FaceScanErrorType.Camera&&e.jsx(a.Modal,{testId:"face-scan-camera-error-screen",config:_}),!u&&f&&g!==a.FaceScanErrorType.Camera&&e.jsx(i,{loading:u,onRetry:h}),m&&!f&&!u&&e.jsx(o.Drawer,{open:!0,className:"face-scan-small camera-draw",anchor:"bottom",onClose:(e,t)=>{},hideBackdrop:!0,children:e.jsx(l,{stage:p,videoLoading:y,setVideoLoading:S,videoError:x,setVideoError:v,gender:b,btnConfig:{label:w(),onClick:F?h:C,isDisabled:u||!j,icon:F?e.jsx(n.ArrowRight,{}):e.jsx(e.Fragment,{})}})})]})};exports.FaceScan=n=>{const{onScanSuccess:o,onScanError:r,onRetry:s,onScanStart:i,onCaptureComplete:l,onUploadStart:u,onUploadEnd:f,onMeasurementSocketStart:g,onMeasurementSocketClose:h,config:m,isError:p,isSuccess:y}=n,S=n.userDetails??{email:"",gender:"male",deviceFocalLength:0,shopDomain:"",bodyScanId:""},x=n.token??"",v=t.useRef(null),b=t.useRef(null),w=t.useRef(null),F=t.useRef([]),C=t.useRef(null),j=t.useRef(null),[E,_]=t.useState(!1),[N,T]=t.useState(!1),[k,I]=t.useState(!1),[R,M]=t.useState(!0),[D,P]=t.useState(!1),[A,L]=t.useState(!1),[O,z]=t.useState(!1),[$,H]=t.useState(null),[V,W]=t.useState(a.generateUuid()),K=t.useMemo(()=>a.getSwanService(x),[x]),{email:U,gender:B,deviceFocalLength:q,shopDomain:G,callbackUrl:J,bodyScanId:X}=S,[Q,Y]=t.useState([]),[Z,ee]=t.useState(a.videoConstraintsExact),te=t.useMemo(()=>a.getPreferredMediaRecorderTypes(),[]),ae=a.getRecordingMimeType(Q),ne=a.getRecordingExtension(ae);a.usePosthogPageview();const oe=t.useCallback(()=>{console.log("Stopping recording..."),w.current&&"recording"===w.current.state&&w.current.stop(),w.current=null},[]),re=async()=>{if(l?.(),F.current){if(0===F.current.length)return console.error("No video data recorded"),H(a.FaceScanErrorType.Scan),z(!0),void _(!1);u?.(),_(!0);const e=new File(F.current,`${V}.${ne}`,{type:ae}),t=j.current??await a.getVideoFPS(e),n=e.size,o=(n/1048576).toFixed(2),r=Math.round(n/1e4),s={video_size_mb:parseFloat(o),video_size_bytes:n,video_fps:t||0,blob_count:F.current.length,estimated_duration_seconds:r},c=[{gender:B},{face_scan_id:V},{focal_length:`${q}`},{customer_store_url:G},{scan_type:"face_scan"},{body_scan_id:X}];J&&c.push({callback_url:J}),a.handleScanTimeCapture({eventName:`${G}/face_scan_meta_data`,faceScanId:V,email:U,data:JSON.stringify({metaData:c,videoData:s})});const i=Date.now();a.handleScanTimeCapture({eventName:`${G}/face_scan_upload_start`,faceScanId:V,email:U,startTime:i});try{const t=await K.fileUpload.faceScanFileUploader({file:e,arrayMetaData:c,objectKey:V,email:U,contentType:e.type}),n=Date.now(),o=n-i;a.handleScanTimeCapture({eventName:`${G}/face_scan_upload_complete`,faceScanId:V,email:U,completionTime:n,uploadDuration:o}),f?.(),console.log("✅ Upload successful",t),K.measurement.handlFaceScaneSocket({onPreopen:()=>{g?.(),a.handleWebSocketCapture({eventName:`${G}/webSocket`,faceScanID:V,connection:"pre_open",type:"faceScan_recommendation",email:U})},faceScanId:V,onOpen:()=>{a.handleWebSocketCapture({eventName:`${G}/webSocket`,faceScanID:V,connection:"open",type:"faceScan_recommendation",email:U}),console.log("websocket connect open")},onError:e=>{a.handleWebSocketCapture({eventName:`${G}/webSocket`,faceScanID:V,connection:"error",type:"faceScan_recommendation",email:U}),me(e)},onSuccess:e=>{a.handleWebSocketCapture({eventName:`${G}/webSocket`,faceScanID:V,connection:"success",type:"faceScan_recommendation",email:U}),pe(e)},onClose:()=>{h?.(),console.log("websocket connect close"),a.handleWebSocketCapture({eventName:`${G}/webSocket`,faceScanID:V,connection:"close",type:"faceScan_recommendation",email:U})}})}catch(e){f?.(),me(e)}}},se=t.useCallback(()=>{const e=v.current?.srcObject;if(!e)return;const t=e.getVideoTracks()[0].getSettings(),{width:n=1280,height:o=720}=t,r=document.createElement("canvas"),s=r.getContext("2d");n>o?(r.width=o,r.height=n):(r.width=n,r.height=o);const c=document.createElement("video");c.srcObject=e,c.muted=!0,c.playsInline=!0,c.play();const i=()=>{n>o?(s?.save(),s?.translate(r.width,0),s?.rotate(Math.PI/2),s?.drawImage(c,0,0,o,n),s?.restore()):s?.drawImage(c,0,0,n,o),requestAnimationFrame(i)};i();const l=t.frameRate??10;j.current=l;const d=r.captureStream(l),u={videoBitsPerSecond:15e5};let f;Q.length>0&&(u.mimeType=Q[0]);try{f=new MediaRecorder(d,u)}catch(e){return console.error("MediaRecorder init failed:",e),H(a.FaceScanErrorType.Scan),z(!0),void _(!1)}F.current=[],f.ondataavailable=e=>{e?.data&&e.data.size>0&&F.current&&F.current.push(e.data)},f.onstop=()=>{console.log("Recording stopped, total blobs:",F?.current?.length),re()},f.start(100),w.current=f,console.log("Recording started successfully (portrait normalized)")},[Q,re]),{faceScanDetector:ce,scanStage:ie,setScanStage:le,resetScan:de,isModelLoaded:ue,startScanSequence:fe}=c({faceScanId:V,shopDomain:G,isError:p,isSuccess:y,onScanComplete:()=>{oe()},onModelReady:()=>{T(!0)},onStartRecording:()=>{console.log("Stage 0 completed - starting recording for stages 1-3"),se()}}),ge=t.useCallback(()=>{ue&&(i?.(),le(0),a.speechService.playAudio(`${a.voiceOverAssetsPath}face-scan-vos/Face-forward.mp3`),setTimeout(()=>{I(!0),setTimeout(()=>{fe()},200)},200))},[le,I,fe,ue,i]),he=t.useCallback(()=>{I(!1),M(!0),oe(),de(),s?.(),F.current=[],j.current=null,w.current&&(w.current=null),z(!1),H(null),le(-1),W(a.generateUuid()),v.current&&C.current&&(v.current.srcObject=C.current,console.log("Camera stream restored after reset"))},[le,I,M,oe,de,W]),me=e=>{console.log(e,"ws error"),r?.(e),H(a.FaceScanErrorType.Scan),z(!0),_(!1),M(!1),a.handleScanTimeCapture({eventName:`${G}/faceScan`,faceScanId:V,status:"failed",email:U,data:JSON.stringify(e)})},pe=e=>{console.log(e,"ws success"),e&&"intermediate"===e?.resultType&&a.handleScanTimeCapture({eventName:`${G}/faceScan_success/intermediate`,faceScanId:V,status:"success",email:U,data:JSON.stringify(e)}),o?.(e)};t.useEffect(()=>{if(!p&&!y)return navigator.mediaDevices.getUserMedia&&navigator.mediaDevices.getUserMedia({video:Z}).then(e=>{C.current=e,v.current&&(v.current.srcObject=e)}).catch(e=>{if(console.error("Error accessing webcam:",e),Z===a.videoConstraintsExact)return void ee(a.videoConstraintsFallback);const t=["NotAllowedError","PermissionDeniedError","NotFoundError","DevicesNotFoundError","NotReadableError","TrackStartError"].includes(e?.name);H(t?a.FaceScanErrorType.Camera:a.FaceScanErrorType.Scan),z(!0)}),()=>{C.current&&C.current.getTracks().forEach(e=>e.stop())}},[p,y,Z]),t.useEffect(()=>{if(!N||!k)return;const e=setInterval(()=>{ce(v,b)},500);return()=>clearInterval(e)},[ce,N,k]);return console.log("Model ready:",N,"Has error:",O,"Is scanning:",k,"showLoader",E),t.useEffect(()=>{const e=a.getSupportedMediaRecorderTypes(te,a.videoTypes);Y(e)},[te]),t.useEffect(()=>{le(-1)},[]),e.jsx("div",{"data-face-scan-stage":ie,children:e.jsx(a.LanguageContextProvider,{children:e.jsx(a.ConfigProvider,{config:m,children:e.jsx(a.ParamsContext.Provider,{value:{isError:p,isSuccess:y,showLoader:E,hasError:O,errorType:$,resetScanState:he,showGuideCard:R,scanStage:ie,videoLoading:D,setVideoLoading:P,videoError:A,setVideoError:L,gender:B,getButtonText:()=>k?a.LanguageKeys.reset:ue?a.LanguageKeys.start:a.LanguageKeys.loading,isScanning:k,startScan:ge,isModelLoaded:ue,onRetry:s},children:e.jsx(d,{webcamRef:v,canvasRef:b})})})})})};
2
- //# sourceMappingURL=FaceScan-6Aoz5uUy.js.map
@@ -1,2 +0,0 @@
1
- "use strict";var e=require("react/jsx-runtime"),t=require("react"),a=require("./Modal-HTYYx7sM.js"),n=require("lucide-react"),r=require("@mui/material");let o=null,s=!1;function c({faceScanId:e,onValidPose:n,onScanComplete:r,onModelReady:c,onStartRecording:i,shopDomain:l,isError:d,isSuccess:u}){const f=t.useRef(null),[g,h]=t.useState(0),[m,p]=t.useState(0),[y,S]=t.useState(!1),[x,v]=t.useState(!1),b=t.useRef(!1),w=t.useRef(null),F=t.useRef(null),C=t.useRef(g),j=t.useRef(m),E=t.useRef([]),_=t.useRef(""),N=t.useRef(0),T=t.useRef(!1),k=t.useRef(0),R="undefined"!=typeof navigator&&(/iPad|iPhone|iPod/.test(navigator.userAgent)||"MacIntel"===navigator.platform&&navigator.maxTouchPoints>1),I=t.useMemo(()=>["Face front","Turn head fully left","Turn head fully right","Smile facing front"],[]),M=t.useMemo(()=>function(e,t){let a;return(...n)=>{a&&clearTimeout(a),a=setTimeout(()=>e(...n),t)}}(e=>{a.posthog.capture(`${l}/face_scan_pose_detection`,e)},4e3),[l]),D=t.useCallback((t,a,n,r,o,s)=>{const c=Date.now();if(!(c-k.current<4e3)){k.current=c;try{const c=t[0]||[0,0,0],i=t[2]||[0,0,0],l=t[5]||[0,0,0],d=t[9]||[0,0,0],u=t[10]||[0,0,0],f=t.map(e=>e[2]).filter(e=>e>0),g=f.length>0?f.reduce((e,t)=>e+t,0)/f.length:0,h=a.map(e=>e[2]).filter(e=>e>0),m=h.length>0?h.reduce((e,t)=>e+t,0)/h.length:0,p=Math.abs(i[0]-l[0]),y=c[0]-l[0],S=i[0]-c[0];let x="frontal";1===n?x="left":2===n?x="right":3===n&&(x="frontal_smile");const v={faceScanId:e,stage:n,timestamp:(new Date).toISOString(),data:JSON.stringify({headValid:r,bodyInvalid:o,consecutiveValid:s,avgFaceScore:parseFloat(g.toFixed(3)),avgBodyScore:parseFloat(m.toFixed(3)),faceKeypointsDetected:f.length,bodyKeypointsDetected:h.length,eyeDistance:parseFloat(p.toFixed(2)),noseToRightRatio:parseFloat((y/p).toFixed(3)),noseToLeftRatio:parseFloat((S/p).toFixed(3)),noseScore:parseFloat(c[2].toFixed(3)),leftEyeScore:parseFloat(i[2].toFixed(3)),rightEyeScore:parseFloat(l[2].toFixed(3)),leftMouthScore:parseFloat(d[2].toFixed(3)),rightMouthScore:parseFloat(u[2].toFixed(3)),expectedPosition:x})};M(v)}catch(e){console.warn("Failed to track pose detection:",e)}}},[e,M]),P=()=>{a.posthog.capture(`${l}/face_scan_detection_started`,{faceScanId:e,stage:C.current,timestamp:(new Date).toISOString(),stageName:I[C.current]}),setTimeout(()=>{v(!0)},1500)},A=async()=>{if("undefined"!=typeof window)try{console.log("Initializing Face Scan...");const e=await(async()=>{if("undefined"==typeof window)return null;if(o)return o;if(s)for(;s;)if(await new Promise(e=>setTimeout(e,100)),o)return o;s=!0;try{const[e,t]=await Promise.all([import("@tensorflow/tfjs"),Promise.resolve().then(function(){return require("./pose-detection.esm-Bc8T4UAD.js")})]);await e.setBackend("webgl"),await e.ready();const n=await t.createDetector(t.SupportedModels.BlazePose,{runtime:"tfjs",modelType:"full"}),r=document.createElement("canvas");r.width="number"==typeof a.videoConstraints.width?a.videoConstraints.width:a.videoConstraints.width.ideal??a.videoConstraints.width.max??1280,r.height="number"==typeof a.videoConstraints.height?a.videoConstraints.height:a.videoConstraints.height.ideal??a.videoConstraints.height.max??720;const s=r.getContext("2d");if(s){s.fillStyle="black",s.fillRect(0,0,r.width,r.height);try{await n.estimatePoses(r)}catch(e){console.warn("Warmup frame failed (non-fatal):",e)}}return o=n,n}catch(e){return console.error("Failed to preload detector:",e),null}finally{s=!1}})();e&&(f.current=e,console.log("Face scan model loaded successfully"),S(!0),c?.())}catch(e){console.error("Error initializing face scan:",e)}};return t.useEffect(()=>{if(!d&&!u)return A(),()=>{(async()=>{try{S(!1)}catch(e){console.error("Error disposing resources:",e)}finally{h(0),p(0),C.current=0,j.current=0,E.current=[]}})()}},[d,u]),t.useEffect(()=>{C.current=g},[g]),t.useEffect(()=>{j.current=m},[m]),{faceScanDetector:async(t,o)=>{if(f.current&&t.current&&y&&x&&!(t.current.readyState<2||b.current)){b.current=!0;try{const s=t.current.videoWidth||720,c=t.current.videoHeight||1280;w.current||(w.current=document.createElement("canvas"),w.current.width=s,w.current.height=c);const d=w.current.getContext("2d");d&&d.drawImage(t.current,0,0,s,c);const u=await f.current.estimatePoses(d?w.current:t.current);if(u.length>0){const t=[],s=[];if(u[0].keypoints.forEach((e,a)=>{const n=e.score??0,r=[e.x??-1,e.y??-1,n];a<=10?t.push(r):s.push(r)}),o?.current){const e=o.current.getContext("2d"),{width:t,height:a}=o.current;if(e){e.clearRect(0,0,t,a);const n=Math.min(j.current/2,1),r=.35*a;e.beginPath(),e.strokeStyle="#00ff00",e.lineWidth=6,e.arc(t/2,a/2,r+10,-Math.PI/2,-Math.PI/2+2*n*Math.PI),e.stroke()}}const c=((e,t)=>{if(!t[0]||!t[2]||!t[5]||t[0][2]<.2||t[2][2]<.2||t[5][2]<.2)return!1;const a=.5*(t[10][1]+t[9][1])-.5*(t[5][1]+t[2][1]),n=(.5*(t[10][1]+t[9][1])-t[0][1])/a,r=n>.7||n<.3,o=Math.abs(t[2][1]-t[5][1])<.5*a&&Math.abs(t[9][1]-t[10][1])<.5*a,s=t[2][0]-t[5][0],c=t[0][0]-t[5][0],i=c>.4*s&&c<.6*s,l=c>.85*s,d=t[2][0]-t[0][0]>.85*s;switch(e){case 0:case 3:return!r&&o&&i;case 1:return!r&&o&&l;case 2:return!r&&o&&d;default:return!1}})(C.current,t),d=s.slice(2).filter(e=>e[2]>.7).length<=2;E.current.push(c&&d),E.current.length>10&&E.current.shift();if(E.current.filter(Boolean).length>=2){const e=j.current+1;p(e)}else p(Math.max(0,j.current-1));if(j.current>=2){n?.();const t=C.current+1;p(0),E.current=[],h(t),v(!1),(async()=>{if(await a.speechService.playAudio(`${a.voiceOverAssetsPath}face-scan-vos/Sound-effect.mp3`),a.posthog.capture(`${l}/face_scan_detection_stage_completed`,{faceScanId:e,completedStage:C.current,nextStage:t,timestamp:(new Date).toISOString(),totalStages:4,stageName:I[C.current]}),1===t&&i&&i(),t>=4)r?.();else{let e=null;switch(t){case 1:e="Left.mp3";break;case 2:e="Right.mp3";break;case 3:e="Smile.mp3"}e&&await a.speechService.playAudio(`${a.voiceOverAssetsPath}face-scan-vos/${e}`),P()}})()}D(t,s,C.current,c,d,j.current)}}catch(e){console.error("Pose detection error:",e)}finally{b.current=!1}}},scanStage:g,setScanStage:h,consecutiveValid:m,isModelLoaded:y,resetScan:()=>{a.posthog.capture(`${l}/face_scan_reset`,{faceScanId:e,stage:C.current,timestamp:(new Date).toISOString(),stageName:I[C.current],consecutiveValid:j.current}),h(0),p(0),v(!1),C.current=0,j.current=0,E.current=[],_.current="",N.current=0,T.current=!1,F.current&&(speechSynthesis.cancel(),F.current=null)},enableVoiceCommands:()=>{if(T.current=!0,"undefined"!=typeof window&&R&&"speechSynthesis"in window){const e=new SpeechSynthesisUtterance("");e.volume=0,speechSynthesis.speak(e)}},startScanSequence:P,isScanningActive:x}}function i({onRetry:r,loading:o}){const{translate:s}=t.useContext(a.LanguageContext)||{},c=a.useConfig();return e.jsx("div",{"data-testid":"face-scan-error-screen",className:"fixed common-ui-main top-[0] left-[0] z-[999] flex justify-center items-center w-full h-full",style:{background:c?.style?.base?.backgroundColor},children:e.jsxs("div",{className:"flex flex-col w-full items-center p-[1rem] rounded-lg ",children:[e.jsx(a.Header,{noTitle:!0}),e.jsxs("div",{className:"flex flex-col items-center w-full",children:[e.jsx("h2",{className:"text-xl font-semibold text-gray-800 ",style:{fontFamily:c?.style?.heading?.headingFontFamily||"SeriouslyNostalgic Fn",fontSize:c?.style?.heading?.headingFontSize||"32px",color:c?.style?.heading?.headingColor||"#000",fontWeight:c?.style?.heading?.headingFontWeight||"normal"},children:s?.(a.LanguageKeys.scanFailed)}),e.jsx("p",{className:"mb-[1.5rem]",style:{fontFamily:c?.style?.subheading?.subheadingFontFamily||"'Inter', sans-serif",fontSize:c?.style?.subheading?.subheadingFontSize||"14px",color:c?.style?.subheading?.subheadingColor||"#4b5563",fontWeight:c?.style?.subheading?.subheadingFontWeight||"normal"},children:s?.(a.LanguageKeys.clickToResetScan)}),e.jsx(a.SpecificButton,{"data-testid":"face-scan-retry-btn",disabled:o,className:"w-full h-[45px] shadow-[0px_1px_2px_0px_#00000040] text-[16px]",buttonText:s?.(a.LanguageKeys.resetScan),postfixIcon:e.jsx(n.ArrowRight,{}),buttonFunc:()=>r?.()})]})]})})}function l({stage:n,videoLoading:r,setVideoLoading:o,videoError:s,setVideoError:c,gender:i,btnConfig:l}){const{translate:d}=t.useContext(a.LanguageContext)||{},u=a.useConfig();return-1===n?e.jsxs("div",{"data-testid":"face-scan-guide",className:"text-center common-ui-main p-[16px] w-full h-full",style:{background:u?.style?.base?.backgroundColor},children:[e.jsxs("div",{className:"w-full",children:[e.jsx(a.Header,{noTitle:!0}),e.jsx("h2",{style:{fontFamily:u?.style?.heading?.headingFontFamily||"SeriouslyNostalgic Fn",fontSize:u?.style?.heading?.headingFontSize||"32px",color:u?.style?.heading?.headingColor||"#000",fontWeight:u?.style?.heading?.headingFontWeight||"normal"},children:d?.(a.LanguageKeys.faceVisible)}),r&&e.jsx("div",{className:"mb-4 flex items-center justify-center",style:{fontFamily:u?.style?.subheading?.subheadingFontFamily||"'Inter', sans-serif",fontSize:u?.style?.subheading?.subheadingFontSize||"14px",color:u?.style?.subheading?.subheadingColor||"#4b5563",fontWeight:u?.style?.subheading?.subheadingFontWeight||"normal"},children:d?.(a.LanguageKeys.loadingVideo)}),s&&e.jsx("div",{className:"mb-4 text-red-600",style:{fontFamily:u?.style?.subheading?.subheadingFontFamily||"'Inter', sans-serif",fontSize:u?.style?.subheading?.subheadingFontSize||"14px",color:"#ff0000",fontWeight:u?.style?.subheading?.subheadingFontWeight||"normal"},children:d?.(a.LanguageKeys.videoLoadFailed)}),!s&&e.jsx("div",{className:" w-[100px] mx-auto",children:e.jsx("video",{src:i===a.GenderType.Male?a.maleGlassesOffVideo:a.glassesOffVideo,autoPlay:!0,loop:!0,controls:!1,muted:!0,playsInline:!0,className:"h-full w-full object-contain border-none",onCanPlay:()=>o(!1),onLoadStart:()=>o(!0),onError:()=>c(!0),"aria-label":"Instructional video: Please remove your glasses before starting the scan."})})]}),e.jsx("div",{className:"flex justify-center w-full p-[1rem]",children:e.jsx(a.SpecificButton,{"data-testid":"face-scan-start-btn",disabled:l.isDisabled,className:"!w-[60px] !h-[35px] !py-0 !px-0",buttonText:d?.(l.label),postfixIcon:l?.icon,buttonFunc:l.onClick})})]}):e.jsx("div",{className:"text-center common-ui-main p-[16px] w-full h-full",style:{background:u?.style?.base?.backgroundColor},children:e.jsxs("div",{className:"w-full",children:[e.jsx(a.Header,{noTitle:!0}),e.jsx("h3",{className:"mb-[0.5rem]",style:{fontFamily:u?.style?.heading?.headingFontFamily||"SeriouslyNostalgic Fn",fontSize:u?.style?.heading?.headingFontSize||"32px",color:u?.style?.heading?.headingColor||"#000",fontWeight:u?.style?.heading?.headingFontWeight||"normal"},children:d?.(a.directionMessages[n])}),e.jsxs("div",{className:"max-w-[400px] justify-center gap-1 mx-auto flex items-center",children:[e.jsx("div",{className:` w-[120px] overflow-hidden ${0===n?"opacity-100":"opacity-0 hidden"} `,children:e.jsx("video",{className:"h-full w-full object-contain border-none",muted:!0,loop:!0,autoPlay:!0,playsInline:!0,children:e.jsx("source",{src:i===a.GenderType.Male?a.FACE_SCAN_HEADSHOT.male.forward:a.FACE_SCAN_HEADSHOT.female.forward,type:"video/mp4"})})}),e.jsx("div",{className:` w-[120px] overflow-hidden ${1===n?"opacity-100":"opacity-0 hidden"} `,children:e.jsx("video",{className:"h-full w-full object-contain border-none",muted:!0,loop:!0,autoPlay:!0,playsInline:!0,children:e.jsx("source",{src:i===a.GenderType.Male?a.FACE_SCAN_HEADSHOT.male.left:a.FACE_SCAN_HEADSHOT.female.left,type:"video/mp4"})})}),e.jsx("div",{className:` w-[120px] overflow-hidden ${2===n?"opacity-100":"opacity-0 hidden"} `,children:e.jsx("video",{className:"h-full w-full object-contain border-none",muted:!0,loop:!0,autoPlay:!0,playsInline:!0,children:e.jsx("source",{src:i===a.GenderType.Male?a.FACE_SCAN_HEADSHOT.male.right:a.FACE_SCAN_HEADSHOT.female.right,type:"video/mp4"})})}),e.jsx("div",{className:` w-[120px] overflow-hidden ${3===n?"opacity-100":"opacity-0 hidden"} `,children:e.jsx("video",{className:"h-full w-full object-contain border-none",muted:!0,loop:!0,autoPlay:!0,playsInline:!0,children:e.jsx("source",{src:i===a.GenderType.Male?a.FACE_SCAN_HEADSHOT.male.smile:a.FACE_SCAN_HEADSHOT.female.smile,type:"video/mp4"})})})]})]})})}const d=({webcamRef:o,canvasRef:s})=>{const{isError:c,isSuccess:d,showLoader:u,hasError:f,errorType:g,resetScanState:h,showGuideCard:m,scanStage:p,videoLoading:y,setVideoLoading:S,videoError:x,setVideoError:v,gender:b,getButtonText:w,isScanning:F,startScan:C,isModelLoaded:j,onRetry:E}=t.useContext(a.ParamsContext),_=a.useConfig();return c?e.jsx(i,{onRetry:E}):d?e.jsx("div",{className:"fixed z-[9] common-ui-main w-full h-full",style:{background:_?.style?.base?.backgroundColor},children:e.jsx(a.LoadingScreen,{url:_?.loader,loaderType:"black"})}):e.jsxs(e.Fragment,{children:[e.jsx("audio",{id:"audioElement",crossOrigin:"anonymous",preload:"auto",style:{position:"absolute",zIndex:-99999},src:void 0}),u&&!f&&e.jsx("div",{className:"fixed z-[9] common-ui-main w-full h-full",style:{background:_?.style?.base?.backgroundColor},children:e.jsx(a.LoadingScreen,{url:_?.loader,loaderType:"black"})}),e.jsx("div",{className:"h-full flex-col common-ui-main relative w-full flex justify-center items-center text-center rounded-t-[20px]",style:{background:_?.style?.base?.backgroundColor},children:e.jsx("div",{className:"flex-1 w-full max-w-md overflow-hidden",children:e.jsxs("div",{className:"w-full h-full",children:[e.jsx("video",{ref:o,autoPlay:!0,playsInline:!0,muted:!0,width:a.videoConstraints.width.ideal,height:a.videoConstraints.height.ideal,className:"w-full h-full object-cover fixed left-0 top-0 z-0",style:{transform:"scaleX(-1)"}}),e.jsx("canvas",{ref:s,width:a.videoConstraints.width.ideal,height:a.videoConstraints.height.ideal,style:{transform:"scaleX(-1)",opacity:"0"}})]})})}),!u&&f&&g===a.FaceScanErrorType.Camera&&e.jsx(a.Modal,{testId:"face-scan-camera-error-screen",config:_}),!u&&f&&g!==a.FaceScanErrorType.Camera&&e.jsx(i,{loading:u,onRetry:h}),m&&!f&&!u&&e.jsx(r.Drawer,{open:!0,className:"face-scan-small camera-draw",anchor:"bottom",onClose:(e,t)=>{},hideBackdrop:!0,children:e.jsx(l,{stage:p,videoLoading:y,setVideoLoading:S,videoError:x,setVideoError:v,gender:b,btnConfig:{label:w(),onClick:F?h:C,isDisabled:u||!j,icon:F?e.jsx(n.ArrowRight,{}):e.jsx(e.Fragment,{})}})})]})};exports.FaceScan=n=>{const{onScanSuccess:r,onScanError:o,onRetry:s,onScanStart:i,onCaptureComplete:l,onUploadStart:u,onUploadEnd:f,onMeasurementSocketStart:g,onMeasurementSocketClose:h,config:m,isError:p,isSuccess:y}=n,S=n.userDetails??{email:"",gender:"male",deviceFocalLength:0,shopDomain:"",bodyScanId:"",callbackUrl:null},x=n.token??"",v=t.useRef(null),b=t.useRef(null),w=t.useRef(null),F=t.useRef([]),C=t.useRef(null),j=t.useRef(null),E=t.useRef(0),_=t.useRef(null),[N,T]=t.useState(!1),[k,R]=t.useState(!1),[I,M]=t.useState(!1),[D,P]=t.useState(!0),[A,L]=t.useState(!1),[O,z]=t.useState(!1),[$,H]=t.useState(!1),[V,W]=t.useState(null),[K,U]=t.useState(a.generateUuid()),q=t.useMemo(()=>a.getSwanService(x),[x]),{email:B,gender:G,deviceFocalLength:J,shopDomain:X,callbackUrl:Q,bodyScanId:Y}=S,[Z,ee]=t.useState([]),[te,ae]=t.useState(a.videoConstraintsExact),ne=t.useMemo(()=>a.getPreferredMediaRecorderTypes(),[]),re=a.getRecordingMimeType(Z),oe=a.getRecordingExtension(re);a.usePosthogPageview();const se=t.useCallback(()=>{console.log("Stopping recording..."),cancelAnimationFrame(E.current),_.current&&(_.current.pause(),_.current.srcObject=null,_.current=null),w.current&&"recording"===w.current.state&&w.current.stop(),w.current=null},[]),ce=async()=>{if(l?.(),F.current){if(0===F.current.length)return console.error("No video data recorded"),W(a.FaceScanErrorType.Scan),H(!0),void T(!1);u?.(),T(!0);const e=new File(F.current,`${K}.${oe}`,{type:re}),t=j.current??await a.getVideoFPS(e),n=e.size,r=(n/1048576).toFixed(2),o=Math.round(n/1e4),s={video_size_mb:parseFloat(r),video_size_bytes:n,video_fps:t||0,blob_count:F.current.length,estimated_duration_seconds:o},c=[{gender:G},{face_scan_id:K},{focal_length:`${J}`},{customer_store_url:X},{scan_type:"face_scan"},{body_scan_id:Y}];Q&&c.push({callback_url:Q}),a.handleScanTimeCapture({eventName:`${X}/face_scan_meta_data`,faceScanId:K,email:B,data:JSON.stringify({metaData:c,videoData:s})});const i=Date.now();a.handleScanTimeCapture({eventName:`${X}/face_scan_upload_start`,faceScanId:K,email:B,startTime:i});try{const t=await q.fileUpload.faceScanFileUploader({file:e,arrayMetaData:c,objectKey:K,email:B,contentType:e.type}),n=Date.now(),r=n-i;a.handleScanTimeCapture({eventName:`${X}/face_scan_upload_complete`,faceScanId:K,email:B,completionTime:n,uploadDuration:r}),f?.(),console.log("✅ Upload successful",t),q.measurement.handlFaceScaneSocket({onPreopen:()=>{g?.(),a.handleWebSocketCapture({eventName:`${X}/webSocket`,faceScanID:K,connection:"pre_open",type:"faceScan_recommendation",email:B})},faceScanId:K,onOpen:()=>{a.handleWebSocketCapture({eventName:`${X}/webSocket`,faceScanID:K,connection:"open",type:"faceScan_recommendation",email:B}),console.log("websocket connect open")},onError:e=>{a.handleWebSocketCapture({eventName:`${X}/webSocket`,faceScanID:K,connection:"error",type:"faceScan_recommendation",email:B}),ye(e)},onSuccess:e=>{a.handleWebSocketCapture({eventName:`${X}/webSocket`,faceScanID:K,connection:"success",type:"faceScan_recommendation",email:B}),Se(e)},onClose:()=>{h?.(),console.log("websocket connect close"),a.handleWebSocketCapture({eventName:`${X}/webSocket`,faceScanID:K,connection:"close",type:"faceScan_recommendation",email:B})}})}catch(e){f?.(),ye(e)}}},ie=t.useCallback(()=>{const e=v.current?.srcObject;if(!e)return;const t=e.getVideoTracks()[0].getSettings(),{width:n=1280,height:r=720}=t,o=document.createElement("canvas"),s=o.getContext("2d");n>r?(o.width=r,o.height=n):(o.width=n,o.height=r);const c=document.createElement("video");c.srcObject=e,c.muted=!0,c.playsInline=!0,c.play(),_.current=c;const i=()=>{n>r?(s?.save(),s?.translate(o.width,0),s?.rotate(Math.PI/2),s?.drawImage(c,0,0,r,n),s?.restore()):s?.drawImage(c,0,0,n,r),E.current=requestAnimationFrame(i)};E.current=requestAnimationFrame(i);const l=t.frameRate??10;j.current=l;const d=o.captureStream(l),u={videoBitsPerSecond:15e5};let f;Z.length>0&&(u.mimeType=Z[0]);try{f=new MediaRecorder(d,u)}catch(e){return console.error("MediaRecorder init failed:",e),W(a.FaceScanErrorType.Scan),H(!0),void T(!1)}F.current=[],f.ondataavailable=e=>{e?.data&&e.data.size>0&&F.current&&F.current.push(e.data)},f.onstop=()=>{console.log("Recording stopped, total blobs:",F?.current?.length),ce()},f.start(100),w.current=f,console.log("Recording started successfully (portrait normalized)")},[Z,ce]),{faceScanDetector:le,scanStage:de,setScanStage:ue,resetScan:fe,isModelLoaded:ge,startScanSequence:he}=c({faceScanId:K,shopDomain:X,isError:p,isSuccess:y,onScanComplete:()=>{se()},onModelReady:()=>{R(!0)},onStartRecording:()=>{console.log("Stage 0 completed - starting recording for stages 1-3"),ie()}}),me=t.useCallback(()=>{ge&&(i?.(),ue(0),a.speechService.playAudio(`${a.voiceOverAssetsPath}face-scan-vos/Face-forward.mp3`),setTimeout(()=>{M(!0),setTimeout(()=>{he()},200)},200))},[ue,M,he,ge,i]),pe=t.useCallback(()=>{M(!1),P(!0),se(),fe(),s?.(),F.current=[],j.current=null,w.current&&(w.current=null),H(!1),W(null),ue(-1),U(a.generateUuid()),v.current&&C.current&&(v.current.srcObject=C.current,console.log("Camera stream restored after reset"))},[ue,M,P,se,fe,U]),ye=e=>{console.log(e,"ws error"),o?.(e),W(a.FaceScanErrorType.Scan),H(!0),T(!1),P(!1),a.handleScanTimeCapture({eventName:`${X}/faceScan`,faceScanId:K,status:"failed",email:B,data:JSON.stringify(e)})},Se=e=>{console.log(e,"ws success"),e&&"intermediate"===e?.resultType&&a.handleScanTimeCapture({eventName:`${X}/faceScan_success/intermediate`,faceScanId:K,status:"success",email:B,data:JSON.stringify(e)}),r?.(e)};t.useEffect(()=>{if(!p&&!y)return navigator.mediaDevices.getUserMedia&&navigator.mediaDevices.getUserMedia({video:te}).then(e=>{C.current=e,v.current&&(v.current.srcObject=e)}).catch(e=>{if(console.error("Error accessing webcam:",e),te===a.videoConstraintsExact)return void ae(a.videoConstraintsFallback);const t=["NotAllowedError","PermissionDeniedError","NotFoundError","DevicesNotFoundError","NotReadableError","TrackStartError"].includes(e?.name);W(t?a.FaceScanErrorType.Camera:a.FaceScanErrorType.Scan),H(!0)}),()=>{C.current&&C.current.getTracks().forEach(e=>e.stop())}},[p,y,te]),t.useEffect(()=>{if(!k||!I)return;const e=setInterval(()=>{le(v,b)},500);return()=>clearInterval(e)},[le,k,I]);return console.log("Model ready:",k,"Has error:",$,"Is scanning:",I,"showLoader",N),t.useEffect(()=>{const e=a.getSupportedMediaRecorderTypes(ne,a.videoTypes);ee(e)},[ne]),t.useEffect(()=>{ue(-1)},[]),e.jsx("div",{"data-face-scan-stage":de,children:e.jsx(a.LanguageContextProvider,{children:e.jsx(a.ConfigProvider,{config:m,children:e.jsx(a.ParamsContext.Provider,{value:{isError:p,isSuccess:y,showLoader:N,hasError:$,errorType:V,resetScanState:pe,showGuideCard:D,scanStage:de,videoLoading:A,setVideoLoading:L,videoError:O,setVideoError:z,gender:G,getButtonText:()=>I?a.LanguageKeys.reset:ge?a.LanguageKeys.start:a.LanguageKeys.loading,isScanning:I,startScan:me,isModelLoaded:ge,onRetry:s},children:e.jsx(d,{webcamRef:v,canvasRef:b})})})})})};
2
- //# sourceMappingURL=FaceScan-7fl5pLnb.js.map
@@ -1,2 +0,0 @@
1
- "use strict";var e=require("react/jsx-runtime"),t=require("react"),a=require("./LoadingScreen-BILrJVZm.js"),n=require("lucide-react"),o=require("@mui/material");let s=null,r=!1;function c({faceScanId:e,onValidPose:n,onScanComplete:o,onModelReady:c,onStartRecording:i,shopDomain:l,isError:d,isSuccess:u}){const f=t.useRef(null),[g,h]=t.useState(0),[m,p]=t.useState(0),[y,S]=t.useState(!1),[x,v]=t.useState(!1),b=t.useRef(null),w=t.useRef(g),C=t.useRef(m),F=t.useRef([]),j=t.useRef(""),_=t.useRef(0),N=t.useRef(!1),E=t.useRef(0),k="undefined"!=typeof navigator&&(/iPad|iPhone|iPod/.test(navigator.userAgent)||"MacIntel"===navigator.platform&&navigator.maxTouchPoints>1),T=t.useMemo(()=>["Face front","Turn head fully left","Turn head fully right","Smile facing front"],[]),I=t.useMemo(()=>function(e,t){let a;return(...n)=>{a&&clearTimeout(a),a=setTimeout(()=>e(...n),t)}}(e=>{a.posthog.capture(`${l}/face_scan_pose_detection`,e)},4e3),[l]),R=t.useCallback((t,a,n,o,s,r)=>{const c=Date.now();if(!(c-E.current<4e3)){E.current=c;try{const c=t[0]||[0,0,0],i=t[2]||[0,0,0],l=t[5]||[0,0,0],d=t[9]||[0,0,0],u=t[10]||[0,0,0],f=t.map(e=>e[2]).filter(e=>e>0),g=f.length>0?f.reduce((e,t)=>e+t,0)/f.length:0,h=a.map(e=>e[2]).filter(e=>e>0),m=h.length>0?h.reduce((e,t)=>e+t,0)/h.length:0,p=Math.abs(i[0]-l[0]),y=c[0]-l[0],S=i[0]-c[0];let x="frontal";1===n?x="left":2===n?x="right":3===n&&(x="frontal_smile");const v={faceScanId:e,stage:n,timestamp:(new Date).toISOString(),data:JSON.stringify({headValid:o,bodyInvalid:s,consecutiveValid:r,avgFaceScore:parseFloat(g.toFixed(3)),avgBodyScore:parseFloat(m.toFixed(3)),faceKeypointsDetected:f.length,bodyKeypointsDetected:h.length,eyeDistance:parseFloat(p.toFixed(2)),noseToRightRatio:parseFloat((y/p).toFixed(3)),noseToLeftRatio:parseFloat((S/p).toFixed(3)),noseScore:parseFloat(c[2].toFixed(3)),leftEyeScore:parseFloat(i[2].toFixed(3)),rightEyeScore:parseFloat(l[2].toFixed(3)),leftMouthScore:parseFloat(d[2].toFixed(3)),rightMouthScore:parseFloat(u[2].toFixed(3)),expectedPosition:x})};I(v)}catch(e){console.warn("Failed to track pose detection:",e)}}},[e,I]),M=()=>{a.posthog.capture(`${l}/face_scan_detection_started`,{faceScanId:e,stage:w.current,timestamp:(new Date).toISOString(),stageName:T[w.current]}),setTimeout(()=>{v(!0)},1500)},D=async()=>{if("undefined"!=typeof window)try{console.log("Initializing Face Scan...");const e=await(async()=>{if("undefined"==typeof window)return null;if(s)return s;if(r)for(;r;)if(await new Promise(e=>setTimeout(e,100)),s)return s;r=!0;try{const[e,t]=await Promise.all([import("@tensorflow/tfjs"),Promise.resolve().then(function(){return require("./pose-detection.esm-Bc8T4UAD.js")})]);await e.setBackend("webgl"),await e.ready();const n=await t.createDetector(t.SupportedModels.BlazePose,{runtime:"tfjs",modelType:"full"}),o=document.createElement("canvas");o.width="number"==typeof a.videoConstraints.width?a.videoConstraints.width:a.videoConstraints.width.ideal??a.videoConstraints.width.max??1280,o.height="number"==typeof a.videoConstraints.height?a.videoConstraints.height:a.videoConstraints.height.ideal??a.videoConstraints.height.max??720;const r=o.getContext("2d");if(r){r.fillStyle="black",r.fillRect(0,0,o.width,o.height);try{await n.estimatePoses(o)}catch(e){console.warn("Warmup frame failed (non-fatal):",e)}}return s=n,n}catch(e){return console.error("Failed to preload detector:",e),null}finally{r=!1}})();e&&(f.current=e,console.log("Face scan model loaded successfully"),S(!0),c?.())}catch(e){console.error("Error initializing face scan:",e)}};return t.useEffect(()=>{if(!d&&!u)return D(),()=>{(async()=>{try{S(!1)}catch(e){console.error("Error disposing resources:",e)}finally{h(0),p(0),w.current=0,C.current=0,F.current=[]}})()}},[d,u]),t.useEffect(()=>{w.current=g},[g]),t.useEffect(()=>{C.current=m},[m]),{faceScanDetector:async(t,s)=>{if(f.current&&t.current&&y&&x&&!(t.current.readyState<2))try{const r=await f.current.estimatePoses(t.current);if(r.length>0){const t=[],c=[];if(r[0].keypoints.forEach((e,a)=>{const n=e.score??0,o=[e.x??-1,e.y??-1,n];a<=10?t.push(o):c.push(o)}),s?.current){const e=s.current.getContext("2d"),{width:t,height:a}=s.current;if(e){e.clearRect(0,0,t,a);const n=Math.min(C.current/2,1),o=.35*a;e.beginPath(),e.strokeStyle="#00ff00",e.lineWidth=6,e.arc(t/2,a/2,o+10,-Math.PI/2,-Math.PI/2+2*n*Math.PI),e.stroke()}}const d=((e,t)=>{if(!t[0]||!t[2]||!t[5]||t[0][2]<.2||t[2][2]<.2||t[5][2]<.2)return!1;const a=.5*(t[10][1]+t[9][1])-.5*(t[5][1]+t[2][1]),n=(.5*(t[10][1]+t[9][1])-t[0][1])/a,o=n>.7||n<.3,s=Math.abs(t[2][1]-t[5][1])<.5*a&&Math.abs(t[9][1]-t[10][1])<.5*a,r=t[2][0]-t[5][0],c=t[0][0]-t[5][0],i=c>.4*r&&c<.6*r,l=c>.85*r,d=t[2][0]-t[0][0]>.85*r;switch(e){case 0:case 3:return!o&&s&&i;case 1:return!o&&s&&l;case 2:return!o&&s&&d;default:return!1}})(w.current,t),u=c.slice(2).filter(e=>e[2]>.7).length<=2;F.current.push(d&&u),F.current.length>10&&F.current.shift();if(F.current.filter(Boolean).length>=2){const e=C.current+1;p(e)}else p(Math.max(0,C.current-1));if(C.current>=2){n?.();const t=w.current+1;p(0),F.current=[],h(t),v(!1),(async()=>{if(await a.speechService.playAudio(`${a.voiceOverAssetsPath}face-scan-vos/Sound-effect.mp3`),a.posthog.capture(`${l}/face_scan_detection_stage_completed`,{faceScanId:e,completedStage:w.current,nextStage:t,timestamp:(new Date).toISOString(),totalStages:4,stageName:T[w.current]}),1===t&&i&&i(),t>=4)o?.();else{let e=null;switch(t){case 1:e="Left.mp3";break;case 2:e="Right.mp3";break;case 3:e="Smile.mp3"}e&&await a.speechService.playAudio(`${a.voiceOverAssetsPath}face-scan-vos/${e}`),M()}})()}R(t,c,w.current,d,u,C.current)}}catch(e){console.error("Pose detection error:",e)}},scanStage:g,setScanStage:h,consecutiveValid:m,isModelLoaded:y,resetScan:()=>{a.posthog.capture(`${l}/face_scan_reset`,{faceScanId:e,stage:w.current,timestamp:(new Date).toISOString(),stageName:T[w.current],consecutiveValid:C.current}),h(0),p(0),v(!1),w.current=0,C.current=0,F.current=[],j.current="",_.current=0,N.current=!1,b.current&&(speechSynthesis.cancel(),b.current=null)},enableVoiceCommands:()=>{if(N.current=!0,"undefined"!=typeof window&&k&&"speechSynthesis"in window){const e=new SpeechSynthesisUtterance("");e.volume=0,speechSynthesis.speak(e)}},startScanSequence:M,isScanningActive:x}}function i({onRetry:o,loading:s}){const{translate:r}=t.useContext(a.LanguageContext)||{},c=a.useConfig();return e.jsx("div",{"data-testid":"face-scan-error-screen",className:"fixed common-ui-main top-[0] left-[0] z-[999] flex justify-center items-center w-full h-full",style:{background:c?.style?.base?.backgroundColor},children:e.jsxs("div",{className:"flex flex-col w-full items-center p-[1rem] rounded-lg ",children:[e.jsx(a.Header,{noTitle:!0}),e.jsxs("div",{className:"flex flex-col items-center w-full",children:[e.jsx("h2",{className:"text-xl font-semibold text-gray-800 ",style:{fontFamily:c?.style?.heading?.headingFontFamily||"SeriouslyNostalgic Fn",fontSize:c?.style?.heading?.headingFontSize||"32px",color:c?.style?.heading?.headingColor||"#000",fontWeight:c?.style?.heading?.headingFontWeight||"normal"},children:r?.(a.LanguageKeys.scanFailed)}),e.jsx("p",{className:"mb-[1.5rem]",style:{fontFamily:c?.style?.subheading?.subheadingFontFamily||"'Inter', sans-serif",fontSize:c?.style?.subheading?.subheadingFontSize||"14px",color:c?.style?.subheading?.subheadingColor||"#4b5563",fontWeight:c?.style?.subheading?.subheadingFontWeight||"normal"},children:r?.(a.LanguageKeys.clickToResetScan)}),e.jsx(a.SpecificButton,{"data-testid":"face-scan-retry-btn",disabled:s,className:"w-full h-[45px] shadow-[0px_1px_2px_0px_#00000040] text-[16px]",buttonText:r?.(a.LanguageKeys.resetScan),postfixIcon:e.jsx(n.ArrowRight,{}),buttonFunc:()=>o?.()})]})]})})}function l({stage:n,videoLoading:o,setVideoLoading:s,videoError:r,setVideoError:c,gender:i,btnConfig:l}){const{translate:d}=t.useContext(a.LanguageContext)||{},u=a.useConfig();return-1===n?e.jsxs("div",{"data-testid":"face-scan-guide",className:"text-center common-ui-main p-[16px] w-full h-full",style:{background:u?.style?.base?.backgroundColor},children:[e.jsxs("div",{className:"w-full",children:[e.jsx(a.Header,{noTitle:!0}),e.jsx("h2",{style:{fontFamily:u?.style?.heading?.headingFontFamily||"SeriouslyNostalgic Fn",fontSize:u?.style?.heading?.headingFontSize||"32px",color:u?.style?.heading?.headingColor||"#000",fontWeight:u?.style?.heading?.headingFontWeight||"normal"},children:d?.(a.LanguageKeys.faceVisible)}),o&&e.jsx("div",{className:"mb-4 flex items-center justify-center",style:{fontFamily:u?.style?.subheading?.subheadingFontFamily||"'Inter', sans-serif",fontSize:u?.style?.subheading?.subheadingFontSize||"14px",color:u?.style?.subheading?.subheadingColor||"#4b5563",fontWeight:u?.style?.subheading?.subheadingFontWeight||"normal"},children:d?.(a.LanguageKeys.loadingVideo)}),r&&e.jsx("div",{className:"mb-4 text-red-600",style:{fontFamily:u?.style?.subheading?.subheadingFontFamily||"'Inter', sans-serif",fontSize:u?.style?.subheading?.subheadingFontSize||"14px",color:"#ff0000",fontWeight:u?.style?.subheading?.subheadingFontWeight||"normal"},children:d?.(a.LanguageKeys.videoLoadFailed)}),!r&&e.jsx("div",{className:" w-[100px] mx-auto",children:e.jsx("video",{src:i===a.GenderType.Male?a.maleGlassesOffVideo:a.glassesOffVideo,autoPlay:!0,loop:!0,controls:!1,muted:!0,playsInline:!0,className:"h-full w-full object-contain border-none",onCanPlay:()=>s(!1),onLoadStart:()=>s(!0),onError:()=>c(!0),"aria-label":"Instructional video: Please remove your glasses before starting the scan."})})]}),e.jsx("div",{className:"flex justify-center w-full p-[1rem]",children:e.jsx(a.SpecificButton,{"data-testid":"face-scan-start-btn",disabled:l.isDisabled,className:"!w-[60px] !h-[35px] !py-0 !px-0",buttonText:d?.(l.label),postfixIcon:l?.icon,buttonFunc:l.onClick})})]}):e.jsx("div",{className:"text-center common-ui-main p-[16px] w-full h-full",style:{background:u?.style?.base?.backgroundColor},children:e.jsxs("div",{className:"w-full",children:[e.jsx(a.Header,{noTitle:!0}),e.jsx("h3",{className:"mb-[0.5rem]",style:{fontFamily:u?.style?.heading?.headingFontFamily||"SeriouslyNostalgic Fn",fontSize:u?.style?.heading?.headingFontSize||"32px",color:u?.style?.heading?.headingColor||"#000",fontWeight:u?.style?.heading?.headingFontWeight||"normal"},children:d?.(a.directionMessages[n])}),e.jsxs("div",{className:"max-w-[400px] justify-center gap-1 mx-auto flex items-center",children:[e.jsx("div",{className:` w-[120px] overflow-hidden ${0===n?"opacity-100":"opacity-0 hidden"} `,children:e.jsx("video",{className:"h-full w-full object-contain border-none",muted:!0,loop:!0,autoPlay:!0,playsInline:!0,children:e.jsx("source",{src:i===a.GenderType.Male?a.FACE_SCAN_HEADSHOT.male.forward:a.FACE_SCAN_HEADSHOT.female.forward,type:"video/mp4"})})}),e.jsx("div",{className:` w-[120px] overflow-hidden ${1===n?"opacity-100":"opacity-0 hidden"} `,children:e.jsx("video",{className:"h-full w-full object-contain border-none",muted:!0,loop:!0,autoPlay:!0,playsInline:!0,children:e.jsx("source",{src:i===a.GenderType.Male?a.FACE_SCAN_HEADSHOT.male.left:a.FACE_SCAN_HEADSHOT.female.left,type:"video/mp4"})})}),e.jsx("div",{className:` w-[120px] overflow-hidden ${2===n?"opacity-100":"opacity-0 hidden"} `,children:e.jsx("video",{className:"h-full w-full object-contain border-none",muted:!0,loop:!0,autoPlay:!0,playsInline:!0,children:e.jsx("source",{src:i===a.GenderType.Male?a.FACE_SCAN_HEADSHOT.male.right:a.FACE_SCAN_HEADSHOT.female.right,type:"video/mp4"})})}),e.jsx("div",{className:` w-[120px] overflow-hidden ${3===n?"opacity-100":"opacity-0 hidden"} `,children:e.jsx("video",{className:"h-full w-full object-contain border-none",muted:!0,loop:!0,autoPlay:!0,playsInline:!0,children:e.jsx("source",{src:i===a.GenderType.Male?a.FACE_SCAN_HEADSHOT.male.smile:a.FACE_SCAN_HEADSHOT.female.smile,type:"video/mp4"})})})]})]})})}const d=({webcamRef:s,canvasRef:r})=>{const{isError:c,isSuccess:d,showLoader:u,hasError:f,resetScanState:g,showGuideCard:h,scanStage:m,videoLoading:p,setVideoLoading:y,videoError:S,setVideoError:x,gender:v,getButtonText:b,isScanning:w,startScan:C,isModelLoaded:F,onRetry:j}=t.useContext(a.ParamsContext),_=a.useConfig();return c?e.jsx(i,{onRetry:j}):d?e.jsx("div",{className:"fixed z-[9] common-ui-main w-full h-full",style:{background:_?.style?.base?.backgroundColor},children:e.jsx(a.LoadingScreen,{url:_?.loader,loaderType:"black"})}):e.jsxs(e.Fragment,{children:[e.jsx("audio",{id:"audioElement",crossOrigin:"anonymous",preload:"auto",style:{position:"absolute",zIndex:-99999},src:void 0}),u&&!f&&e.jsx("div",{className:"fixed z-[9] common-ui-main w-full h-full",style:{background:_?.style?.base?.backgroundColor},children:e.jsx(a.LoadingScreen,{url:_?.loader,loaderType:"black"})}),e.jsx("div",{className:"h-full flex-col common-ui-main relative w-full flex justify-center items-center text-center rounded-t-[20px]",style:{background:_?.style?.base?.backgroundColor},children:e.jsx("div",{className:"flex-1 w-full max-w-md overflow-hidden",children:e.jsxs("div",{className:"w-full h-full",children:[e.jsx("video",{ref:s,autoPlay:!0,playsInline:!0,muted:!0,width:a.videoConstraints.width.ideal,height:a.videoConstraints.height.ideal,className:"w-full h-full object-cover fixed left-0 top-0 z-0",style:{transform:"scaleX(-1)"}}),e.jsx("canvas",{ref:r,width:a.videoConstraints.width.ideal,height:a.videoConstraints.height.ideal,style:{transform:"scaleX(-1)",opacity:"0"}})]})})}),!u&&f&&e.jsx(i,{loading:u,onRetry:g}),h&&!f&&!u&&e.jsx(o.Drawer,{open:!0,className:"face-scan-small camera-draw",anchor:"bottom",onClose:(e,t)=>{},hideBackdrop:!0,children:e.jsx(l,{stage:m,videoLoading:p,setVideoLoading:y,videoError:S,setVideoError:x,gender:v,btnConfig:{label:b(),onClick:w?g:C,isDisabled:u||!F,icon:w?e.jsx(n.ArrowRight,{}):e.jsx(e.Fragment,{})}})})]})};exports.FaceScan=n=>{const{onScanSuccess:o,onScanError:s,onRetry:r,onScanStart:i,onCaptureComplete:l,onUploadStart:u,onUploadEnd:f,onMeasurementSocketStart:g,onMeasurementSocketClose:h,config:m,isError:p,isSuccess:y}=n,S=n.userDetails??{email:"",gender:"male",deviceFocalLength:0,shopDomain:"",bodyScanId:""},x=n.token??"",v=t.useRef(null),b=t.useRef(null),w=t.useRef(null),C=t.useRef([]),F=t.useRef(null),j=t.useRef(null),[_,N]=t.useState(!1),[E,k]=t.useState(!1),[T,I]=t.useState(!1),[R,M]=t.useState(!0),[D,P]=t.useState(!1),[L,A]=t.useState(!1),[O,z]=t.useState(!1),[$,H]=t.useState(a.generateUuid()),V=t.useMemo(()=>a.getSwanService(x),[x]),{email:W,gender:K,deviceFocalLength:U,shopDomain:B,callbackUrl:q,bodyScanId:G}=S,[J,X]=t.useState([]),[Q,Y]=t.useState(a.videoConstraintsExact),Z=t.useMemo(()=>a.getPreferredMediaRecorderTypes(),[]),ee=a.getRecordingMimeType(J),te=a.getRecordingExtension(ee);a.usePosthogPageview();const ae=t.useCallback(()=>{console.log("Stopping recording..."),w.current&&"recording"===w.current.state&&w.current.stop(),w.current=null},[]),ne=async()=>{if(l?.(),C.current){if(0===C.current.length)return console.error("No video data recorded"),z(!0),void N(!1);u?.(),N(!0);const e=new File(C.current,`${$}.${te}`,{type:ee}),t=j.current??await a.getVideoFPS(e),n=e.size,o=(n/1048576).toFixed(2),s=Math.round(n/1e4),r={video_size_mb:parseFloat(o),video_size_bytes:n,video_fps:t||0,blob_count:C.current.length,estimated_duration_seconds:s},c=[{gender:K},{face_scan_id:$},{focal_length:`${U}`},{customer_store_url:B},{scan_type:"face_scan"},{body_scan_id:G}];q&&c.push({callback_url:q}),a.handleScanTimeCapture({eventName:`${B}/face_scan_meta_data`,faceScanId:$,email:W,data:JSON.stringify({metaData:c,videoData:r})});const i=Date.now();a.handleScanTimeCapture({eventName:`${B}/face_scan_upload_start`,faceScanId:$,email:W,startTime:i});try{const t=await V.fileUpload.faceScanFileUploader({file:e,arrayMetaData:c,objectKey:$,email:W,contentType:e.type}),n=Date.now(),o=n-i;a.handleScanTimeCapture({eventName:`${B}/face_scan_upload_complete`,faceScanId:$,email:W,completionTime:n,uploadDuration:o}),f?.(),console.log("✅ Upload successful",t),V.measurement.handlFaceScaneSocket({onPreopen:()=>{g?.(),a.handleWebSocketCapture({eventName:`${B}/webSocket`,faceScanID:$,connection:"pre_open",type:"faceScan_recommendation",email:W})},faceScanId:$,onOpen:()=>{a.handleWebSocketCapture({eventName:`${B}/webSocket`,faceScanID:$,connection:"open",type:"faceScan_recommendation",email:W}),console.log("websocket connect open")},onError:e=>{a.handleWebSocketCapture({eventName:`${B}/webSocket`,faceScanID:$,connection:"error",type:"faceScan_recommendation",email:W}),ge(e)},onSuccess:e=>{a.handleWebSocketCapture({eventName:`${B}/webSocket`,faceScanID:$,connection:"success",type:"faceScan_recommendation",email:W}),he(e)},onClose:()=>{h?.(),console.log("websocket connect close"),a.handleWebSocketCapture({eventName:`${B}/webSocket`,faceScanID:$,connection:"close",type:"faceScan_recommendation",email:W})}})}catch(e){f?.(),ge(e)}}},oe=t.useCallback(()=>{const e=v.current?.srcObject;if(!e)return;const t=e.getVideoTracks()[0].getSettings(),{width:a=1280,height:n=720}=t,o=document.createElement("canvas"),s=o.getContext("2d");a>n?(o.width=n,o.height=a):(o.width=a,o.height=n);const r=document.createElement("video");r.srcObject=e,r.muted=!0,r.playsInline=!0,r.play();const c=()=>{a>n?(s?.save(),s?.translate(o.width,0),s?.rotate(Math.PI/2),s?.drawImage(r,0,0,n,a),s?.restore()):s?.drawImage(r,0,0,a,n),requestAnimationFrame(c)};c();const i=t.frameRate??10;j.current=i;const l=o.captureStream(i),d={videoBitsPerSecond:15e5};let u;J.length>0&&(d.mimeType=J[0]);try{u=new MediaRecorder(l,d)}catch(e){return console.error("MediaRecorder init failed:",e),z(!0),void N(!1)}C.current=[],u.ondataavailable=e=>{e?.data&&e.data.size>0&&C.current&&C.current.push(e.data)},u.onstop=()=>{console.log("Recording stopped, total blobs:",C?.current?.length),ne()},u.start(100),w.current=u,console.log("Recording started successfully (portrait normalized)")},[J,ne]),{faceScanDetector:se,scanStage:re,setScanStage:ce,resetScan:ie,isModelLoaded:le,startScanSequence:de}=c({faceScanId:$,shopDomain:B,isError:p,isSuccess:y,onScanComplete:()=>{ae()},onModelReady:()=>{k(!0)},onStartRecording:()=>{console.log("Stage 0 completed - starting recording for stages 1-3"),oe()}}),ue=t.useCallback(()=>{le&&(i?.(),ce(0),a.speechService.playAudio(`${a.voiceOverAssetsPath}face-scan-vos/Face-forward.mp3`),setTimeout(()=>{I(!0),setTimeout(()=>{de()},200)},200))},[ce,I,de,le,i]),fe=t.useCallback(()=>{I(!1),M(!0),ae(),ie(),r?.(),C.current=[],j.current=null,w.current&&(w.current=null),z(!1),ce(-1),H(a.generateUuid()),v.current&&F.current&&(v.current.srcObject=F.current,console.log("Camera stream restored after reset"))},[ce,I,M,ae,ie,H]),ge=e=>{console.log(e,"ws error"),s?.(e),z(!0),N(!1),M(!1),a.handleScanTimeCapture({eventName:`${B}/faceScan`,faceScanId:$,status:"failed",email:W,data:JSON.stringify(e)})},he=e=>{console.log(e,"ws success"),e&&"intermediate"===e?.resultType&&a.handleScanTimeCapture({eventName:`${B}/faceScan_success/intermediate`,faceScanId:$,status:"success",email:W,data:JSON.stringify(e)}),o?.(e)};t.useEffect(()=>{if(!p&&!y)return navigator.mediaDevices.getUserMedia&&navigator.mediaDevices.getUserMedia({video:Q}).then(e=>{F.current=e,v.current&&(v.current.srcObject=e)}).catch(e=>{console.error("Error accessing webcam:",e),Q!==a.videoConstraintsExact?z(!0):Y(a.videoConstraintsFallback)}),()=>{F.current&&F.current.getTracks().forEach(e=>e.stop())}},[p,y,Q]),t.useEffect(()=>{if(!E||!T)return;const e=setInterval(()=>{se(v,b)},500);return()=>clearInterval(e)},[se,E,T]);return console.log("Model ready:",E,"Has error:",O,"Is scanning:",T,"showLoader",_),t.useEffect(()=>{const e=a.getSupportedMediaRecorderTypes(Z,a.videoTypes);X(e)},[Z]),t.useEffect(()=>{ce(-1)},[]),e.jsx("div",{"data-face-scan-stage":re,children:e.jsx(a.LanguageContextProvider,{children:e.jsx(a.ConfigProvider,{config:m,children:e.jsx(a.ParamsContext.Provider,{value:{isError:p,isSuccess:y,showLoader:_,hasError:O,resetScanState:fe,showGuideCard:R,scanStage:re,videoLoading:D,setVideoLoading:P,videoError:L,setVideoError:A,gender:K,getButtonText:()=>T?a.LanguageKeys.reset:le?a.LanguageKeys.start:a.LanguageKeys.loading,isScanning:T,startScan:ue,isModelLoaded:le,onRetry:r},children:e.jsx(d,{webcamRef:v,canvasRef:b})})})})})};
2
- //# sourceMappingURL=FaceScan-9kUfXRSv.js.map
@@ -1,2 +0,0 @@
1
- import{jsx as e,jsxs as t,Fragment as a}from"react/jsx-runtime";import{useRef as n,useState as r,useMemo as o,useCallback as c,useEffect as i,useContext as s}from"react";import{v as l,p as d,s as u,a as m,L as f,u as h,H as g,b as p,S as y,m as S,g as b,G as v,d as w,F as x,P as F,c as N,M as I,e as _,f as k,h as E,i as C,j as M,k as D,l as T,n as P,o as z,q as R,r as L,t as $,w as j,C as V,x as O,y as W,z as A,A as U}from"./Modal-BzH-_ch3.js";import{ArrowRight as B}from"lucide-react";import{Drawer as q}from"@mui/material";let J=null,G=!1;const H=async()=>{if("undefined"==typeof window)return null;if(J)return J;if(G)for(;G;)if(await new Promise(e=>setTimeout(e,100)),J)return J;G=!0;try{const[e,t]=await Promise.all([import("@tensorflow/tfjs"),import("./pose-detection.esm-DC0_P6R7.js")]);await e.setBackend("webgl"),await e.ready();const a=await t.createDetector(t.SupportedModels.BlazePose,{runtime:"tfjs",modelType:"full"}),n=document.createElement("canvas");n.width="number"==typeof l.width?l.width:l.width.ideal??l.width.max??1280,n.height="number"==typeof l.height?l.height:l.height.ideal??l.height.max??720;const r=n.getContext("2d");if(r){r.fillStyle="black",r.fillRect(0,0,n.width,n.height);try{await a.estimatePoses(n)}catch(e){console.warn("Warmup frame failed (non-fatal):",e)}}return J=a,a}catch(e){return console.error("Failed to preload detector:",e),null}finally{G=!1}};function K({faceScanId:e,onValidPose:t,onScanComplete:a,onModelReady:s,onStartRecording:l,shopDomain:f,isError:h,isSuccess:g}){const p=n(null),[y,S]=r(0),[b,v]=r(0),[w,x]=r(!1),[F,N]=r(!1),I=n(!1),_=n(null),k=n(null),E=n(y),C=n(b),M=n([]),D=n(""),T=n(0),P=n(!1),z=n(0),R="undefined"!=typeof navigator&&(/iPad|iPhone|iPod/.test(navigator.userAgent)||"MacIntel"===navigator.platform&&navigator.maxTouchPoints>1),L=o(()=>["Face front","Turn head fully left","Turn head fully right","Smile facing front"],[]),$=o(()=>function(e,t){let a;return(...n)=>{a&&clearTimeout(a),a=setTimeout(()=>e(...n),t)}}(e=>{d.capture(`${f}/face_scan_pose_detection`,e)},4e3),[f]),j=c((t,a,n,r,o,c)=>{const i=Date.now();if(!(i-z.current<4e3)){z.current=i;try{const i=t[0]||[0,0,0],s=t[2]||[0,0,0],l=t[5]||[0,0,0],d=t[9]||[0,0,0],u=t[10]||[0,0,0],m=t.map(e=>e[2]).filter(e=>e>0),f=m.length>0?m.reduce((e,t)=>e+t,0)/m.length:0,h=a.map(e=>e[2]).filter(e=>e>0),g=h.length>0?h.reduce((e,t)=>e+t,0)/h.length:0,p=Math.abs(s[0]-l[0]),y=i[0]-l[0],S=s[0]-i[0];let b="frontal";1===n?b="left":2===n?b="right":3===n&&(b="frontal_smile");const v={faceScanId:e,stage:n,timestamp:(new Date).toISOString(),data:JSON.stringify({headValid:r,bodyInvalid:o,consecutiveValid:c,avgFaceScore:parseFloat(f.toFixed(3)),avgBodyScore:parseFloat(g.toFixed(3)),faceKeypointsDetected:m.length,bodyKeypointsDetected:h.length,eyeDistance:parseFloat(p.toFixed(2)),noseToRightRatio:parseFloat((y/p).toFixed(3)),noseToLeftRatio:parseFloat((S/p).toFixed(3)),noseScore:parseFloat(i[2].toFixed(3)),leftEyeScore:parseFloat(s[2].toFixed(3)),rightEyeScore:parseFloat(l[2].toFixed(3)),leftMouthScore:parseFloat(d[2].toFixed(3)),rightMouthScore:parseFloat(u[2].toFixed(3)),expectedPosition:b})};$(v)}catch(e){console.warn("Failed to track pose detection:",e)}}},[e,$]),V=()=>{d.capture(`${f}/face_scan_detection_started`,{faceScanId:e,stage:E.current,timestamp:(new Date).toISOString(),stageName:L[E.current]}),setTimeout(()=>{N(!0)},1500)};return i(()=>{if(!h&&!g)return(async()=>{if("undefined"!=typeof window)try{console.log("Initializing Face Scan...");const e=await H();e&&(p.current=e,console.log("Face scan model loaded successfully"),x(!0),s?.())}catch(e){console.error("Error initializing face scan:",e)}})(),()=>{(async()=>{try{x(!1)}catch(e){console.error("Error disposing resources:",e)}finally{S(0),v(0),E.current=0,C.current=0,M.current=[]}})()}},[h,g]),i(()=>{E.current=y},[y]),i(()=>{C.current=b},[b]),{faceScanDetector:async(n,r)=>{if(p.current&&n.current&&w&&F&&!(n.current.readyState<2||I.current)){I.current=!0;try{const o=n.current.videoWidth||720,c=n.current.videoHeight||1280;_.current||(_.current=document.createElement("canvas"),_.current.width=o,_.current.height=c);const i=_.current.getContext("2d");i&&i.drawImage(n.current,0,0,o,c);const s=await p.current.estimatePoses(i?_.current:n.current);if(s.length>0){const n=[],o=[];if(s[0].keypoints.forEach((e,t)=>{const a=e.score??0,r=[e.x??-1,e.y??-1,a];t<=10?n.push(r):o.push(r)}),r?.current){const e=r.current.getContext("2d"),{width:t,height:a}=r.current;if(e){e.clearRect(0,0,t,a);const n=Math.min(C.current/2,1),r=.35*a;e.beginPath(),e.strokeStyle="#00ff00",e.lineWidth=6,e.arc(t/2,a/2,r+10,-Math.PI/2,-Math.PI/2+2*n*Math.PI),e.stroke()}}const c=((e,t)=>{if(!t[0]||!t[2]||!t[5]||t[0][2]<.2||t[2][2]<.2||t[5][2]<.2)return!1;const a=.5*(t[10][1]+t[9][1])-.5*(t[5][1]+t[2][1]),n=(.5*(t[10][1]+t[9][1])-t[0][1])/a,r=n>.7||n<.3,o=Math.abs(t[2][1]-t[5][1])<.5*a&&Math.abs(t[9][1]-t[10][1])<.5*a,c=t[2][0]-t[5][0],i=t[0][0]-t[5][0],s=i>.4*c&&i<.6*c,l=i>.85*c,d=t[2][0]-t[0][0]>.85*c;switch(e){case 0:case 3:return!r&&o&&s;case 1:return!r&&o&&l;case 2:return!r&&o&&d;default:return!1}})(E.current,n),i=o.slice(2).filter(e=>e[2]>.7).length<=2;M.current.push(c&&i),M.current.length>10&&M.current.shift();if(M.current.filter(Boolean).length>=2){const e=C.current+1;v(e)}else v(Math.max(0,C.current-1));if(C.current>=2){t?.();const n=E.current+1;v(0),M.current=[],S(n),N(!1),(async()=>{if(await u.playAudio(`${m}face-scan-vos/Sound-effect.mp3`),d.capture(`${f}/face_scan_detection_stage_completed`,{faceScanId:e,completedStage:E.current,nextStage:n,timestamp:(new Date).toISOString(),totalStages:4,stageName:L[E.current]}),1===n&&l&&l(),n>=4)a?.();else{let e=null;switch(n){case 1:e="Left.mp3";break;case 2:e="Right.mp3";break;case 3:e="Smile.mp3"}e&&await u.playAudio(`${m}face-scan-vos/${e}`),V()}})()}j(n,o,E.current,c,i,C.current)}}catch(e){console.error("Pose detection error:",e)}finally{I.current=!1}}},scanStage:y,setScanStage:S,consecutiveValid:b,isModelLoaded:w,resetScan:()=>{d.capture(`${f}/face_scan_reset`,{faceScanId:e,stage:E.current,timestamp:(new Date).toISOString(),stageName:L[E.current],consecutiveValid:C.current}),S(0),v(0),N(!1),E.current=0,C.current=0,M.current=[],D.current="",T.current=0,P.current=!1,k.current&&(speechSynthesis.cancel(),k.current=null)},enableVoiceCommands:()=>{if(P.current=!0,"undefined"!=typeof window&&R&&"speechSynthesis"in window){const e=new SpeechSynthesisUtterance("");e.volume=0,speechSynthesis.speak(e)}},startScanSequence:V,isScanningActive:F}}function X({onRetry:a,loading:n}){const{translate:r}=s(f)||{},o=h();return e("div",{"data-testid":"face-scan-error-screen",className:"fixed common-ui-main top-[0] left-[0] z-[999] flex justify-center items-center w-full h-full",style:{background:o?.style?.base?.backgroundColor},children:t("div",{className:"flex flex-col w-full items-center p-[1rem] rounded-lg ",children:[e(g,{noTitle:!0}),t("div",{className:"flex flex-col items-center w-full",children:[e("h2",{className:"text-xl my-[0] font-semibold text-gray-800 ",style:{fontFamily:o?.style?.heading?.headingFontFamily||"SeriouslyNostalgic Fn",fontSize:o?.style?.heading?.headingFontSize||"32px",color:o?.style?.heading?.headingColor||"#000",fontWeight:o?.style?.heading?.headingFontWeight||"normal"},children:r?.(p.scanFailed)}),e("p",{className:"mb-[1.5rem]",style:{fontFamily:o?.style?.subheading?.subheadingFontFamily||"'Inter', sans-serif",fontSize:o?.style?.subheading?.subheadingFontSize||"14px",color:o?.style?.subheading?.subheadingColor||"#4b5563",fontWeight:o?.style?.subheading?.subheadingFontWeight||"normal"},children:r?.(p.clickToResetScan)}),e(y,{"data-testid":"face-scan-retry-btn",disabled:n,className:"w-full h-[45px] shadow-[0px_1px_2px_0px_#00000040] text-[16px]",buttonText:r?.(p.resetScan),postfixIcon:e(B,{}),buttonFunc:()=>a?.()})]})]})})}function Q({stage:a,videoLoading:n,setVideoLoading:r,videoError:o,setVideoError:c,gender:i,btnConfig:l}){const{translate:d}=s(f)||{},u=h();return-1===a?t("div",{"data-testid":"face-scan-guide",className:"text-center common-ui-main p-[16px] w-full h-full",style:{background:u?.style?.base?.backgroundColor},children:[t("div",{className:"w-full",children:[e(g,{noTitle:!0}),e("h2",{className:"my-[0]",style:{fontFamily:u?.style?.heading?.headingFontFamily||"SeriouslyNostalgic Fn",fontSize:u?.style?.heading?.headingFontSize||"32px",color:u?.style?.heading?.headingColor||"#000",fontWeight:u?.style?.heading?.headingFontWeight||"normal"},children:d?.(p.faceVisible)}),n&&e("div",{className:"mb-4 flex items-center justify-center",style:{fontFamily:u?.style?.subheading?.subheadingFontFamily||"'Inter', sans-serif",fontSize:u?.style?.subheading?.subheadingFontSize||"14px",color:u?.style?.subheading?.subheadingColor||"#4b5563",fontWeight:u?.style?.subheading?.subheadingFontWeight||"normal"},children:d?.(p.loadingVideo)}),o&&e("div",{className:"mb-4 text-red-600",style:{fontFamily:u?.style?.subheading?.subheadingFontFamily||"'Inter', sans-serif",fontSize:u?.style?.subheading?.subheadingFontSize||"14px",color:"#ff0000",fontWeight:u?.style?.subheading?.subheadingFontWeight||"normal"},children:d?.(p.videoLoadFailed)}),!o&&e("div",{className:" w-[100px] mx-auto",children:e("video",{src:i===v.Male?S:b,autoPlay:!0,loop:!0,controls:!1,muted:!0,playsInline:!0,className:"h-full w-full object-contain border-none",onCanPlay:()=>r(!1),onLoadStart:()=>r(!0),onError:()=>c(!0),"aria-label":"Instructional video: Please remove your glasses before starting the scan."})})]}),e("div",{className:"flex justify-center w-full p-[1rem]",children:e(y,{"data-testid":"face-scan-start-btn",disabled:l.isDisabled,className:"!w-[60px] !h-[35px] !py-0 !px-0",buttonText:d?.(l.label),postfixIcon:l?.icon,buttonFunc:l.onClick})})]}):e("div",{className:"text-center common-ui-main p-[16px] w-full h-full",style:{background:u?.style?.base?.backgroundColor},children:t("div",{className:"w-full",children:[e(g,{noTitle:!0}),e("h3",{className:"mb-[0.5rem] mt-[0]",style:{fontFamily:u?.style?.heading?.headingFontFamily||"SeriouslyNostalgic Fn",fontSize:u?.style?.heading?.headingFontSize||"32px",color:u?.style?.heading?.headingColor||"#000",fontWeight:u?.style?.heading?.headingFontWeight||"normal"},children:d?.(w[a])}),t("div",{className:"max-w-[400px] justify-center gap-1 mx-auto flex items-center",children:[e("div",{className:` w-[120px] overflow-hidden ${0===a?"opacity-100":"opacity-0 hidden"} `,children:e("video",{className:"h-full w-full object-contain border-none",muted:!0,loop:!0,autoPlay:!0,playsInline:!0,children:e("source",{src:i===v.Male?x.male.forward:x.female.forward,type:"video/mp4"})})}),e("div",{className:` w-[120px] overflow-hidden ${1===a?"opacity-100":"opacity-0 hidden"} `,children:e("video",{className:"h-full w-full object-contain border-none",muted:!0,loop:!0,autoPlay:!0,playsInline:!0,children:e("source",{src:i===v.Male?x.male.left:x.female.left,type:"video/mp4"})})}),e("div",{className:` w-[120px] overflow-hidden ${2===a?"opacity-100":"opacity-0 hidden"} `,children:e("video",{className:"h-full w-full object-contain border-none",muted:!0,loop:!0,autoPlay:!0,playsInline:!0,children:e("source",{src:i===v.Male?x.male.right:x.female.right,type:"video/mp4"})})}),e("div",{className:` w-[120px] overflow-hidden ${3===a?"opacity-100":"opacity-0 hidden"} `,children:e("video",{className:"h-full w-full object-contain border-none",muted:!0,loop:!0,autoPlay:!0,playsInline:!0,children:e("source",{src:i===v.Male?x.male.smile:x.female.smile,type:"video/mp4"})})})]})]})})}const Y=({webcamRef:n,canvasRef:r})=>{const{isError:o,isSuccess:c,showLoader:i,hasError:d,errorType:u,resetScanState:m,showGuideCard:f,scanStage:g,videoLoading:p,setVideoLoading:y,videoError:S,setVideoError:b,gender:v,getButtonText:w,isScanning:x,startScan:k,isModelLoaded:E,isLandscape:C,onRetry:M}=s(F),D=h();return o?e(X,{onRetry:M}):c?e("div",{className:"fixed z-[9] common-ui-main w-full h-full",style:{background:D?.style?.base?.backgroundColor},children:e(N,{url:D?.loader,loaderType:"black"})}):t(a,{children:[e("audio",{id:"audioElement",crossOrigin:"anonymous",preload:"auto",style:{position:"absolute",zIndex:-99999},src:void 0}),C&&!i&&!d&&e("div",{className:"fixed inset-0 z-[9999] common-ui-main",style:{background:"#fff"},children:e(I,{variant:"portrait",config:D})}),i&&!d&&e("div",{className:"fixed z-[9] common-ui-main w-full h-full",style:{background:D?.style?.base?.backgroundColor},children:e(N,{url:D?.loader,loaderType:"black"})}),e("div",{className:"h-full flex-col common-ui-main relative w-full flex justify-center items-center text-center rounded-t-[20px]",style:{background:D?.style?.base?.backgroundColor},children:e("div",{className:"flex-1 w-full max-w-md overflow-hidden",children:t("div",{className:"w-full h-full",children:[e("video",{ref:n,autoPlay:!0,playsInline:!0,muted:!0,width:l.width.ideal,height:l.height.ideal,className:"w-full h-full object-cover fixed left-0 top-0 z-0",style:{transform:"scaleX(-1)",visibility:C?"hidden":"visible"}}),e("canvas",{ref:r,width:l.width.ideal,height:l.height.ideal,style:{transform:"scaleX(-1)",opacity:"0"}})]})})}),!i&&d&&u===_.Camera&&e(I,{testId:"face-scan-camera-error-screen",config:D}),!i&&d&&u!==_.Camera&&e(X,{loading:i,onRetry:m}),f&&!d&&!i&&!C&&e(q,{open:!0,className:"face-scan-small camera-draw",anchor:"bottom",onClose:(e,t)=>{},disablePortal:!0,hideBackdrop:!0,children:e(Q,{stage:g,videoLoading:p,setVideoLoading:y,videoError:S,setVideoError:b,gender:v,btnConfig:{label:w(),onClick:x?m:k,isDisabled:i||!E,icon:e(x?B:a,{})}})})]})},Z=t=>{const{onScanSuccess:a,onScanError:s,onRetry:l,onScanStart:d,onCaptureComplete:f,onUploadStart:h,onUploadEnd:g,onMeasurementSocketStart:y,onMeasurementSocketClose:S,config:b,isError:v,isSuccess:w}=t,x=t.userDetails??{email:"",gender:"male",deviceFocalLength:0,shopDomain:"",bodyScanId:"",callbackUrl:null},N=t.token??"",I=n(null),B=n(null),q=n(null),J=n([]),G=n(null),H=n(null),X=n(0),Q=n(null),[Z,ee]=r(!1),[te,ae]=r(!1),[ne,re]=r(!1),[oe,ce]=r(!0),[ie,se]=r(!1),[le,de]=r(!1),[ue,me]=r(!1),[fe,he]=r(null),[ge,pe]=r(k()),ye=o(()=>E(N),[N]),{isLandscape:Se}=C(),{email:be,gender:ve,deviceFocalLength:we,shopDomain:xe,callbackUrl:Fe,bodyScanId:Ne}=x,[Ie,_e]=r([]),[ke,Ee]=r(M),Ce=o(()=>D(),[]),Me=T(Ie),De=P(Me);z();const Te=c(()=>{console.log("Stopping recording..."),cancelAnimationFrame(X.current),Q.current&&(Q.current.pause(),Q.current.srcObject=null,Q.current=null),q.current&&"recording"===q.current.state&&q.current.stop(),q.current=null},[]),Pe=async()=>{if(f?.(),J.current){if(0===J.current.length)return console.error("No video data recorded"),he(_.Scan),me(!0),void ee(!1);h?.(),ee(!0);const e=new File(J.current,`${ge}.${De}`,{type:Me}),t=H.current??await W(e),a=e.size,n=(a/1048576).toFixed(2),r=Math.round(a/1e4),o={video_size_mb:parseFloat(n),video_size_bytes:a,video_fps:t||0,blob_count:J.current.length,estimated_duration_seconds:r},c=[{gender:ve},{face_scan_id:ge},{focal_length:`${we}`},{customer_store_url:xe},{scan_type:"face_scan"},{body_scan_id:Ne}];Fe&&c.push({callback_url:Fe}),A({eventName:`${xe}/face_scan_meta_data`,faceScanId:ge,email:be,data:JSON.stringify({metaData:c,videoData:o})});const i=Date.now();A({eventName:`${xe}/face_scan_upload_start`,faceScanId:ge,email:be,startTime:i});try{const t=await ye.fileUpload.faceScanFileUploader({file:e,arrayMetaData:c,objectKey:ge,email:be,contentType:e.type}),a=Date.now();A({eventName:`${xe}/face_scan_upload_complete`,faceScanId:ge,email:be,completionTime:a,uploadDuration:a-i}),g?.(),console.log("✅ Upload successful",t),ye.measurement.handlFaceScaneSocket({onPreopen:()=>{y?.(),U({eventName:`${xe}/webSocket`,faceScanID:ge,connection:"pre_open",type:"faceScan_recommendation",email:be})},faceScanId:ge,onOpen:()=>{U({eventName:`${xe}/webSocket`,faceScanID:ge,connection:"open",type:"faceScan_recommendation",email:be}),console.log("websocket connect open")},onError:e=>{U({eventName:`${xe}/webSocket`,faceScanID:ge,connection:"error",type:"faceScan_recommendation",email:be}),Be(e)},onSuccess:e=>{U({eventName:`${xe}/webSocket`,faceScanID:ge,connection:"success",type:"faceScan_recommendation",email:be}),qe(e)},onClose:()=>{S?.(),console.log("websocket connect close"),U({eventName:`${xe}/webSocket`,faceScanID:ge,connection:"close",type:"faceScan_recommendation",email:be})}})}catch(e){g?.(),Be(e)}}},ze=c(()=>{const e=I.current?.srcObject;if(!e)return;const t=e.getVideoTracks()[0].getSettings(),{width:a=1280,height:n=720}=t,r=document.createElement("canvas"),o=r.getContext("2d");a>n?(r.width=n,r.height=a):(r.width=a,r.height=n);const c=document.createElement("video");c.srcObject=e,c.muted=!0,c.playsInline=!0,c.play(),Q.current=c;const i=()=>{a>n?(o?.save(),o?.translate(r.width,0),o?.rotate(Math.PI/2),o?.drawImage(c,0,0,n,a),o?.restore()):o?.drawImage(c,0,0,a,n),X.current=requestAnimationFrame(i)};X.current=requestAnimationFrame(i);const s=t.frameRate??10;H.current=s;const l=r.captureStream(s),d={videoBitsPerSecond:15e5};let u;Ie.length>0&&(d.mimeType=Ie[0]);try{u=new MediaRecorder(l,d)}catch(e){return console.error("MediaRecorder init failed:",e),he(_.Scan),me(!0),void ee(!1)}J.current=[],u.ondataavailable=e=>{e?.data&&e.data.size>0&&J.current&&J.current.push(e.data)},u.onstop=()=>{console.log("Recording stopped, total blobs:",J?.current?.length),Pe()},u.start(100),q.current=u,console.log("Recording started successfully (portrait normalized)")},[Ie,Pe]),{faceScanDetector:Re,scanStage:Le,setScanStage:$e,resetScan:je,isModelLoaded:Ve,startScanSequence:Oe}=K({faceScanId:ge,shopDomain:xe,isError:v,isSuccess:w,onScanComplete:()=>{Te()},onModelReady:()=>{ae(!0)},onStartRecording:()=>{console.log("Stage 0 completed - starting recording for stages 1-3"),ze()}}),We=c(()=>{Ve&&(d?.(),$e(0),u.playAudio(`${m}face-scan-vos/Face-forward.mp3`),setTimeout(()=>{re(!0),setTimeout(()=>{Oe()},200)},200))},[$e,re,Oe,Ve,d]),Ae=c(()=>{re(!1),ce(!0),Te(),je(),l?.(),J.current=[],H.current=null,q.current&&(q.current=null),me(!1),he(null),$e(-1),pe(k()),I.current&&G.current&&(I.current.srcObject=G.current,console.log("Camera stream restored after reset"))},[$e,re,ce,Te,je,pe]),Ue=n(!1);i(()=>{!Se||Ue.current||Z||v||w||ue||(u.stopAudio(),q.current&&(q.current.onstop=null,"recording"===q.current.state&&q.current.stop(),q.current=null),J.current=[],H.current=null,Ae()),Ue.current=Se},[Se,Z,v,w,ue,Ae]);const Be=e=>{console.log(e,"ws error"),s?.(e),he(_.Scan),me(!0),ee(!1),ce(!1),A({eventName:`${xe}/faceScan`,faceScanId:ge,status:"failed",email:be,data:JSON.stringify(e)})},qe=e=>{console.log(e,"ws success"),e&&"intermediate"===e?.resultType&&A({eventName:`${xe}/faceScan_success/intermediate`,faceScanId:ge,status:"success",email:be,data:JSON.stringify(e)}),a?.(e)};i(()=>{if(!v&&!w)return navigator.mediaDevices.getUserMedia&&navigator.mediaDevices.getUserMedia({video:ke}).then(e=>{G.current=e,I.current&&(I.current.srcObject=e)}).catch(e=>{if(console.error("Error accessing webcam:",e),ke===M)return void Ee(R);const t=["NotAllowedError","PermissionDeniedError","NotFoundError","DevicesNotFoundError","NotReadableError","TrackStartError"].includes(e?.name);he(t?_.Camera:_.Scan),me(!0)}),()=>{G.current&&G.current.getTracks().forEach(e=>e.stop())}},[v,w,ke]),i(()=>{if(!te||!ne)return;const e=setInterval(()=>{Re(I,B)},500);return()=>clearInterval(e)},[Re,te,ne]);return console.log("Model ready:",te,"Has error:",ue,"Is scanning:",ne,"showLoader",Z),i(()=>{const e=L(Ce,$);_e(e)},[Ce]),i(()=>{$e(-1)},[]),e("div",{"data-face-scan-stage":Le,children:e(j,{children:e(V,{config:b,children:e(F.Provider,{value:{isError:v,isSuccess:w,showLoader:Z,hasError:ue,errorType:fe,resetScanState:Ae,showGuideCard:oe,scanStage:Le,videoLoading:ie,setVideoLoading:se,videoError:le,setVideoError:de,gender:ve,getButtonText:()=>ne?p.reset:Ve?p.start:p.loading,isScanning:ne,startScan:We,isModelLoaded:Ve,isLandscape:Se,onRetry:l},children:e(O,{children:e(Y,{webcamRef:I,canvasRef:B})})})})})})};export{Z as F,H as p};
2
- //# sourceMappingURL=FaceScan-AHZ-ajep.js.map
@@ -1,2 +0,0 @@
1
- import{jsx as e,jsxs as t,Fragment as a}from"react/jsx-runtime";import{useRef as n,useState as r,useMemo as o,useCallback as c,useEffect as i,useContext as s}from"react";import{v as l,p as d,s as u,a as m,L as h,u as f,H as g,b as p,S as y,m as S,g as b,G as w,d as v,F as x,P as F,c as N,e as I,M as _,f as k,h as E,i as C,j as M,k as D,l as T,n as P,o as R,q as z,r as $,t as j,C as L,w as V,x as O,y as W}from"./Modal-CB_MHF7l.js";import{ArrowRight as U}from"lucide-react";import{Drawer as A}from"@mui/material";let B=null,q=!1;const J=async()=>{if("undefined"==typeof window)return null;if(B)return B;if(q)for(;q;)if(await new Promise(e=>setTimeout(e,100)),B)return B;q=!0;try{const[e,t]=await Promise.all([import("@tensorflow/tfjs"),import("./pose-detection.esm-DejsYGYM.js")]);await e.setBackend("webgl"),await e.ready();const a=await t.createDetector(t.SupportedModels.BlazePose,{runtime:"tfjs",modelType:"full"}),n=document.createElement("canvas");n.width="number"==typeof l.width?l.width:l.width.ideal??l.width.max??1280,n.height="number"==typeof l.height?l.height:l.height.ideal??l.height.max??720;const r=n.getContext("2d");if(r){r.fillStyle="black",r.fillRect(0,0,n.width,n.height);try{await a.estimatePoses(n)}catch(e){console.warn("Warmup frame failed (non-fatal):",e)}}return B=a,a}catch(e){return console.error("Failed to preload detector:",e),null}finally{q=!1}};function G({faceScanId:e,onValidPose:t,onScanComplete:a,onModelReady:s,onStartRecording:l,shopDomain:h,isError:f,isSuccess:g}){const p=n(null),[y,S]=r(0),[b,w]=r(0),[v,x]=r(!1),[F,N]=r(!1),I=n(!1),_=n(null),k=n(null),E=n(y),C=n(b),M=n([]),D=n(""),T=n(0),P=n(!1),R=n(0),z="undefined"!=typeof navigator&&(/iPad|iPhone|iPod/.test(navigator.userAgent)||"MacIntel"===navigator.platform&&navigator.maxTouchPoints>1),$=o(()=>["Face front","Turn head fully left","Turn head fully right","Smile facing front"],[]),j=o(()=>function(e,t){let a;return(...n)=>{a&&clearTimeout(a),a=setTimeout(()=>e(...n),t)}}(e=>{d.capture(`${h}/face_scan_pose_detection`,e)},4e3),[h]),L=c((t,a,n,r,o,c)=>{const i=Date.now();if(!(i-R.current<4e3)){R.current=i;try{const i=t[0]||[0,0,0],s=t[2]||[0,0,0],l=t[5]||[0,0,0],d=t[9]||[0,0,0],u=t[10]||[0,0,0],m=t.map(e=>e[2]).filter(e=>e>0),h=m.length>0?m.reduce((e,t)=>e+t,0)/m.length:0,f=a.map(e=>e[2]).filter(e=>e>0),g=f.length>0?f.reduce((e,t)=>e+t,0)/f.length:0,p=Math.abs(s[0]-l[0]),y=i[0]-l[0],S=s[0]-i[0];let b="frontal";1===n?b="left":2===n?b="right":3===n&&(b="frontal_smile");const w={faceScanId:e,stage:n,timestamp:(new Date).toISOString(),data:JSON.stringify({headValid:r,bodyInvalid:o,consecutiveValid:c,avgFaceScore:parseFloat(h.toFixed(3)),avgBodyScore:parseFloat(g.toFixed(3)),faceKeypointsDetected:m.length,bodyKeypointsDetected:f.length,eyeDistance:parseFloat(p.toFixed(2)),noseToRightRatio:parseFloat((y/p).toFixed(3)),noseToLeftRatio:parseFloat((S/p).toFixed(3)),noseScore:parseFloat(i[2].toFixed(3)),leftEyeScore:parseFloat(s[2].toFixed(3)),rightEyeScore:parseFloat(l[2].toFixed(3)),leftMouthScore:parseFloat(d[2].toFixed(3)),rightMouthScore:parseFloat(u[2].toFixed(3)),expectedPosition:b})};j(w)}catch(e){console.warn("Failed to track pose detection:",e)}}},[e,j]),V=()=>{d.capture(`${h}/face_scan_detection_started`,{faceScanId:e,stage:E.current,timestamp:(new Date).toISOString(),stageName:$[E.current]}),setTimeout(()=>{N(!0)},1500)};return i(()=>{if(!f&&!g)return(async()=>{if("undefined"!=typeof window)try{console.log("Initializing Face Scan...");const e=await J();e&&(p.current=e,console.log("Face scan model loaded successfully"),x(!0),s?.())}catch(e){console.error("Error initializing face scan:",e)}})(),()=>{(async()=>{try{x(!1)}catch(e){console.error("Error disposing resources:",e)}finally{S(0),w(0),E.current=0,C.current=0,M.current=[]}})()}},[f,g]),i(()=>{E.current=y},[y]),i(()=>{C.current=b},[b]),{faceScanDetector:async(n,r)=>{if(p.current&&n.current&&v&&F&&!(n.current.readyState<2||I.current)){I.current=!0;try{const o=n.current.videoWidth||720,c=n.current.videoHeight||1280;_.current||(_.current=document.createElement("canvas"),_.current.width=o,_.current.height=c);const i=_.current.getContext("2d");i&&i.drawImage(n.current,0,0,o,c);const s=await p.current.estimatePoses(i?_.current:n.current);if(s.length>0){const n=[],o=[];if(s[0].keypoints.forEach((e,t)=>{const a=e.score??0,r=[e.x??-1,e.y??-1,a];t<=10?n.push(r):o.push(r)}),r?.current){const e=r.current.getContext("2d"),{width:t,height:a}=r.current;if(e){e.clearRect(0,0,t,a);const n=Math.min(C.current/2,1),r=.35*a;e.beginPath(),e.strokeStyle="#00ff00",e.lineWidth=6,e.arc(t/2,a/2,r+10,-Math.PI/2,-Math.PI/2+2*n*Math.PI),e.stroke()}}const c=((e,t)=>{if(!t[0]||!t[2]||!t[5]||t[0][2]<.2||t[2][2]<.2||t[5][2]<.2)return!1;const a=.5*(t[10][1]+t[9][1])-.5*(t[5][1]+t[2][1]),n=(.5*(t[10][1]+t[9][1])-t[0][1])/a,r=n>.7||n<.3,o=Math.abs(t[2][1]-t[5][1])<.5*a&&Math.abs(t[9][1]-t[10][1])<.5*a,c=t[2][0]-t[5][0],i=t[0][0]-t[5][0],s=i>.4*c&&i<.6*c,l=i>.85*c,d=t[2][0]-t[0][0]>.85*c;switch(e){case 0:case 3:return!r&&o&&s;case 1:return!r&&o&&l;case 2:return!r&&o&&d;default:return!1}})(E.current,n),i=o.slice(2).filter(e=>e[2]>.7).length<=2;M.current.push(c&&i),M.current.length>10&&M.current.shift();if(M.current.filter(Boolean).length>=2){const e=C.current+1;w(e)}else w(Math.max(0,C.current-1));if(C.current>=2){t?.();const n=E.current+1;w(0),M.current=[],S(n),N(!1),(async()=>{if(await u.playAudio(`${m}face-scan-vos/Sound-effect.mp3`),d.capture(`${h}/face_scan_detection_stage_completed`,{faceScanId:e,completedStage:E.current,nextStage:n,timestamp:(new Date).toISOString(),totalStages:4,stageName:$[E.current]}),1===n&&l&&l(),n>=4)a?.();else{let e=null;switch(n){case 1:e="Left.mp3";break;case 2:e="Right.mp3";break;case 3:e="Smile.mp3"}e&&await u.playAudio(`${m}face-scan-vos/${e}`),V()}})()}L(n,o,E.current,c,i,C.current)}}catch(e){console.error("Pose detection error:",e)}finally{I.current=!1}}},scanStage:y,setScanStage:S,consecutiveValid:b,isModelLoaded:v,resetScan:()=>{d.capture(`${h}/face_scan_reset`,{faceScanId:e,stage:E.current,timestamp:(new Date).toISOString(),stageName:$[E.current],consecutiveValid:C.current}),S(0),w(0),N(!1),E.current=0,C.current=0,M.current=[],D.current="",T.current=0,P.current=!1,k.current&&(speechSynthesis.cancel(),k.current=null)},enableVoiceCommands:()=>{if(P.current=!0,"undefined"!=typeof window&&z&&"speechSynthesis"in window){const e=new SpeechSynthesisUtterance("");e.volume=0,speechSynthesis.speak(e)}},startScanSequence:V,isScanningActive:F}}function H({onRetry:a,loading:n}){const{translate:r}=s(h)||{},o=f();return e("div",{"data-testid":"face-scan-error-screen",className:"fixed common-ui-main top-[0] left-[0] z-[999] flex justify-center items-center w-full h-full",style:{background:o?.style?.base?.backgroundColor},children:t("div",{className:"flex flex-col w-full items-center p-[1rem] rounded-lg ",children:[e(g,{noTitle:!0}),t("div",{className:"flex flex-col items-center w-full",children:[e("h2",{className:"text-xl font-semibold text-gray-800 ",style:{fontFamily:o?.style?.heading?.headingFontFamily||"SeriouslyNostalgic Fn",fontSize:o?.style?.heading?.headingFontSize||"32px",color:o?.style?.heading?.headingColor||"#000",fontWeight:o?.style?.heading?.headingFontWeight||"normal"},children:r?.(p.scanFailed)}),e("p",{className:"mb-[1.5rem]",style:{fontFamily:o?.style?.subheading?.subheadingFontFamily||"'Inter', sans-serif",fontSize:o?.style?.subheading?.subheadingFontSize||"14px",color:o?.style?.subheading?.subheadingColor||"#4b5563",fontWeight:o?.style?.subheading?.subheadingFontWeight||"normal"},children:r?.(p.clickToResetScan)}),e(y,{"data-testid":"face-scan-retry-btn",disabled:n,className:"w-full h-[45px] shadow-[0px_1px_2px_0px_#00000040] text-[16px]",buttonText:r?.(p.resetScan),postfixIcon:e(U,{}),buttonFunc:()=>a?.()})]})]})})}function K({stage:a,videoLoading:n,setVideoLoading:r,videoError:o,setVideoError:c,gender:i,btnConfig:l}){const{translate:d}=s(h)||{},u=f();return-1===a?t("div",{"data-testid":"face-scan-guide",className:"text-center common-ui-main p-[16px] w-full h-full",style:{background:u?.style?.base?.backgroundColor},children:[t("div",{className:"w-full",children:[e(g,{noTitle:!0}),e("h2",{style:{fontFamily:u?.style?.heading?.headingFontFamily||"SeriouslyNostalgic Fn",fontSize:u?.style?.heading?.headingFontSize||"32px",color:u?.style?.heading?.headingColor||"#000",fontWeight:u?.style?.heading?.headingFontWeight||"normal"},children:d?.(p.faceVisible)}),n&&e("div",{className:"mb-4 flex items-center justify-center",style:{fontFamily:u?.style?.subheading?.subheadingFontFamily||"'Inter', sans-serif",fontSize:u?.style?.subheading?.subheadingFontSize||"14px",color:u?.style?.subheading?.subheadingColor||"#4b5563",fontWeight:u?.style?.subheading?.subheadingFontWeight||"normal"},children:d?.(p.loadingVideo)}),o&&e("div",{className:"mb-4 text-red-600",style:{fontFamily:u?.style?.subheading?.subheadingFontFamily||"'Inter', sans-serif",fontSize:u?.style?.subheading?.subheadingFontSize||"14px",color:"#ff0000",fontWeight:u?.style?.subheading?.subheadingFontWeight||"normal"},children:d?.(p.videoLoadFailed)}),!o&&e("div",{className:" w-[100px] mx-auto",children:e("video",{src:i===w.Male?S:b,autoPlay:!0,loop:!0,controls:!1,muted:!0,playsInline:!0,className:"h-full w-full object-contain border-none",onCanPlay:()=>r(!1),onLoadStart:()=>r(!0),onError:()=>c(!0),"aria-label":"Instructional video: Please remove your glasses before starting the scan."})})]}),e("div",{className:"flex justify-center w-full p-[1rem]",children:e(y,{"data-testid":"face-scan-start-btn",disabled:l.isDisabled,className:"!w-[60px] !h-[35px] !py-0 !px-0",buttonText:d?.(l.label),postfixIcon:l?.icon,buttonFunc:l.onClick})})]}):e("div",{className:"text-center common-ui-main p-[16px] w-full h-full",style:{background:u?.style?.base?.backgroundColor},children:t("div",{className:"w-full",children:[e(g,{noTitle:!0}),e("h3",{className:"mb-[0.5rem]",style:{fontFamily:u?.style?.heading?.headingFontFamily||"SeriouslyNostalgic Fn",fontSize:u?.style?.heading?.headingFontSize||"32px",color:u?.style?.heading?.headingColor||"#000",fontWeight:u?.style?.heading?.headingFontWeight||"normal"},children:d?.(v[a])}),t("div",{className:"max-w-[400px] justify-center gap-1 mx-auto flex items-center",children:[e("div",{className:` w-[120px] overflow-hidden ${0===a?"opacity-100":"opacity-0 hidden"} `,children:e("video",{className:"h-full w-full object-contain border-none",muted:!0,loop:!0,autoPlay:!0,playsInline:!0,children:e("source",{src:i===w.Male?x.male.forward:x.female.forward,type:"video/mp4"})})}),e("div",{className:` w-[120px] overflow-hidden ${1===a?"opacity-100":"opacity-0 hidden"} `,children:e("video",{className:"h-full w-full object-contain border-none",muted:!0,loop:!0,autoPlay:!0,playsInline:!0,children:e("source",{src:i===w.Male?x.male.left:x.female.left,type:"video/mp4"})})}),e("div",{className:` w-[120px] overflow-hidden ${2===a?"opacity-100":"opacity-0 hidden"} `,children:e("video",{className:"h-full w-full object-contain border-none",muted:!0,loop:!0,autoPlay:!0,playsInline:!0,children:e("source",{src:i===w.Male?x.male.right:x.female.right,type:"video/mp4"})})}),e("div",{className:` w-[120px] overflow-hidden ${3===a?"opacity-100":"opacity-0 hidden"} `,children:e("video",{className:"h-full w-full object-contain border-none",muted:!0,loop:!0,autoPlay:!0,playsInline:!0,children:e("source",{src:i===w.Male?x.male.smile:x.female.smile,type:"video/mp4"})})})]})]})})}const X=({webcamRef:n,canvasRef:r})=>{const{isError:o,isSuccess:c,showLoader:i,hasError:d,errorType:u,resetScanState:m,showGuideCard:h,scanStage:g,videoLoading:p,setVideoLoading:y,videoError:S,setVideoError:b,gender:w,getButtonText:v,isScanning:x,startScan:k,isModelLoaded:E,onRetry:C}=s(F),M=f();return o?e(H,{onRetry:C}):c?e("div",{className:"fixed z-[9] common-ui-main w-full h-full",style:{background:M?.style?.base?.backgroundColor},children:e(N,{url:M?.loader,loaderType:"black"})}):t(a,{children:[e("audio",{id:"audioElement",crossOrigin:"anonymous",preload:"auto",style:{position:"absolute",zIndex:-99999},src:void 0}),i&&!d&&e("div",{className:"fixed z-[9] common-ui-main w-full h-full",style:{background:M?.style?.base?.backgroundColor},children:e(N,{url:M?.loader,loaderType:"black"})}),e("div",{className:"h-full flex-col common-ui-main relative w-full flex justify-center items-center text-center rounded-t-[20px]",style:{background:M?.style?.base?.backgroundColor},children:e("div",{className:"flex-1 w-full max-w-md overflow-hidden",children:t("div",{className:"w-full h-full",children:[e("video",{ref:n,autoPlay:!0,playsInline:!0,muted:!0,width:l.width.ideal,height:l.height.ideal,className:"w-full h-full object-cover fixed left-0 top-0 z-0",style:{transform:"scaleX(-1)"}}),e("canvas",{ref:r,width:l.width.ideal,height:l.height.ideal,style:{transform:"scaleX(-1)",opacity:"0"}})]})})}),!i&&d&&u===I.Camera&&e(_,{testId:"face-scan-camera-error-screen",config:M}),!i&&d&&u!==I.Camera&&e(H,{loading:i,onRetry:m}),h&&!d&&!i&&e(A,{open:!0,className:"face-scan-small camera-draw",anchor:"bottom",onClose:(e,t)=>{},hideBackdrop:!0,children:e(K,{stage:g,videoLoading:p,setVideoLoading:y,videoError:S,setVideoError:b,gender:w,btnConfig:{label:v(),onClick:x?m:k,isDisabled:i||!E,icon:e(x?U:a,{})}})})]})},Q=t=>{const{onScanSuccess:a,onScanError:s,onRetry:l,onScanStart:d,onCaptureComplete:h,onUploadStart:f,onUploadEnd:g,onMeasurementSocketStart:y,onMeasurementSocketClose:S,config:b,isError:w,isSuccess:v}=t,x=t.userDetails??{email:"",gender:"male",deviceFocalLength:0,shopDomain:"",bodyScanId:"",callbackUrl:null},N=t.token??"",_=n(null),U=n(null),A=n(null),B=n([]),q=n(null),J=n(null),H=n(0),K=n(null),[Q,Y]=r(!1),[Z,ee]=r(!1),[te,ae]=r(!1),[ne,re]=r(!0),[oe,ce]=r(!1),[ie,se]=r(!1),[le,de]=r(!1),[ue,me]=r(null),[he,fe]=r(k()),ge=o(()=>E(N),[N]),{email:pe,gender:ye,deviceFocalLength:Se,shopDomain:be,callbackUrl:we,bodyScanId:ve}=x,[xe,Fe]=r([]),[Ne,Ie]=r(C),_e=o(()=>M(),[]),ke=D(xe),Ee=T(ke);P();const Ce=c(()=>{console.log("Stopping recording..."),cancelAnimationFrame(H.current),K.current&&(K.current.pause(),K.current.srcObject=null,K.current=null),A.current&&"recording"===A.current.state&&A.current.stop(),A.current=null},[]),Me=async()=>{if(h?.(),B.current){if(0===B.current.length)return console.error("No video data recorded"),me(I.Scan),de(!0),void Y(!1);f?.(),Y(!0);const e=new File(B.current,`${he}.${Ee}`,{type:ke}),t=J.current??await V(e),a=e.size,n=(a/1048576).toFixed(2),r=Math.round(a/1e4),o={video_size_mb:parseFloat(n),video_size_bytes:a,video_fps:t||0,blob_count:B.current.length,estimated_duration_seconds:r},c=[{gender:ye},{face_scan_id:he},{focal_length:`${Se}`},{customer_store_url:be},{scan_type:"face_scan"},{body_scan_id:ve}];we&&c.push({callback_url:we}),O({eventName:`${be}/face_scan_meta_data`,faceScanId:he,email:pe,data:JSON.stringify({metaData:c,videoData:o})});const i=Date.now();O({eventName:`${be}/face_scan_upload_start`,faceScanId:he,email:pe,startTime:i});try{const t=await ge.fileUpload.faceScanFileUploader({file:e,arrayMetaData:c,objectKey:he,email:pe,contentType:e.type}),a=Date.now();O({eventName:`${be}/face_scan_upload_complete`,faceScanId:he,email:pe,completionTime:a,uploadDuration:a-i}),g?.(),console.log("✅ Upload successful",t),ge.measurement.handlFaceScaneSocket({onPreopen:()=>{y?.(),W({eventName:`${be}/webSocket`,faceScanID:he,connection:"pre_open",type:"faceScan_recommendation",email:pe})},faceScanId:he,onOpen:()=>{W({eventName:`${be}/webSocket`,faceScanID:he,connection:"open",type:"faceScan_recommendation",email:pe}),console.log("websocket connect open")},onError:e=>{W({eventName:`${be}/webSocket`,faceScanID:he,connection:"error",type:"faceScan_recommendation",email:pe}),Oe(e)},onSuccess:e=>{W({eventName:`${be}/webSocket`,faceScanID:he,connection:"success",type:"faceScan_recommendation",email:pe}),We(e)},onClose:()=>{S?.(),console.log("websocket connect close"),W({eventName:`${be}/webSocket`,faceScanID:he,connection:"close",type:"faceScan_recommendation",email:pe})}})}catch(e){g?.(),Oe(e)}}},De=c(()=>{const e=_.current?.srcObject;if(!e)return;const t=e.getVideoTracks()[0].getSettings(),{width:a=1280,height:n=720}=t,r=document.createElement("canvas"),o=r.getContext("2d");a>n?(r.width=n,r.height=a):(r.width=a,r.height=n);const c=document.createElement("video");c.srcObject=e,c.muted=!0,c.playsInline=!0,c.play(),K.current=c;const i=()=>{a>n?(o?.save(),o?.translate(r.width,0),o?.rotate(Math.PI/2),o?.drawImage(c,0,0,n,a),o?.restore()):o?.drawImage(c,0,0,a,n),H.current=requestAnimationFrame(i)};H.current=requestAnimationFrame(i);const s=t.frameRate??10;J.current=s;const l=r.captureStream(s),d={videoBitsPerSecond:15e5};let u;xe.length>0&&(d.mimeType=xe[0]);try{u=new MediaRecorder(l,d)}catch(e){return console.error("MediaRecorder init failed:",e),me(I.Scan),de(!0),void Y(!1)}B.current=[],u.ondataavailable=e=>{e?.data&&e.data.size>0&&B.current&&B.current.push(e.data)},u.onstop=()=>{console.log("Recording stopped, total blobs:",B?.current?.length),Me()},u.start(100),A.current=u,console.log("Recording started successfully (portrait normalized)")},[xe,Me]),{faceScanDetector:Te,scanStage:Pe,setScanStage:Re,resetScan:ze,isModelLoaded:$e,startScanSequence:je}=G({faceScanId:he,shopDomain:be,isError:w,isSuccess:v,onScanComplete:()=>{Ce()},onModelReady:()=>{ee(!0)},onStartRecording:()=>{console.log("Stage 0 completed - starting recording for stages 1-3"),De()}}),Le=c(()=>{$e&&(d?.(),Re(0),u.playAudio(`${m}face-scan-vos/Face-forward.mp3`),setTimeout(()=>{ae(!0),setTimeout(()=>{je()},200)},200))},[Re,ae,je,$e,d]),Ve=c(()=>{ae(!1),re(!0),Ce(),ze(),l?.(),B.current=[],J.current=null,A.current&&(A.current=null),de(!1),me(null),Re(-1),fe(k()),_.current&&q.current&&(_.current.srcObject=q.current,console.log("Camera stream restored after reset"))},[Re,ae,re,Ce,ze,fe]),Oe=e=>{console.log(e,"ws error"),s?.(e),me(I.Scan),de(!0),Y(!1),re(!1),O({eventName:`${be}/faceScan`,faceScanId:he,status:"failed",email:pe,data:JSON.stringify(e)})},We=e=>{console.log(e,"ws success"),e&&"intermediate"===e?.resultType&&O({eventName:`${be}/faceScan_success/intermediate`,faceScanId:he,status:"success",email:pe,data:JSON.stringify(e)}),a?.(e)};i(()=>{if(!w&&!v)return navigator.mediaDevices.getUserMedia&&navigator.mediaDevices.getUserMedia({video:Ne}).then(e=>{q.current=e,_.current&&(_.current.srcObject=e)}).catch(e=>{if(console.error("Error accessing webcam:",e),Ne===C)return void Ie(R);const t=["NotAllowedError","PermissionDeniedError","NotFoundError","DevicesNotFoundError","NotReadableError","TrackStartError"].includes(e?.name);me(t?I.Camera:I.Scan),de(!0)}),()=>{q.current&&q.current.getTracks().forEach(e=>e.stop())}},[w,v,Ne]),i(()=>{if(!Z||!te)return;const e=setInterval(()=>{Te(_,U)},500);return()=>clearInterval(e)},[Te,Z,te]);return console.log("Model ready:",Z,"Has error:",le,"Is scanning:",te,"showLoader",Q),i(()=>{const e=z(_e,$);Fe(e)},[_e]),i(()=>{Re(-1)},[]),e("div",{"data-face-scan-stage":Pe,children:e(j,{children:e(L,{config:b,children:e(F.Provider,{value:{isError:w,isSuccess:v,showLoader:Q,hasError:le,errorType:ue,resetScanState:Ve,showGuideCard:ne,scanStage:Pe,videoLoading:oe,setVideoLoading:ce,videoError:ie,setVideoError:se,gender:ye,getButtonText:()=>te?p.reset:$e?p.start:p.loading,isScanning:te,startScan:Le,isModelLoaded:$e,onRetry:l},children:e(X,{webcamRef:_,canvasRef:U})})})})})};export{Q as F,J as p};
2
- //# sourceMappingURL=FaceScan-B0pFv4Us.js.map
@@ -1,2 +0,0 @@
1
- "use strict";var e=require("react/jsx-runtime"),t=require("react"),a=require("./LoadingScreen-BILrJVZm.js"),n=require("lucide-react"),o=require("@mui/material");let r=null,s=!1;function c({faceScanId:e,onValidPose:n,onScanComplete:o,onModelReady:c,onStartRecording:i,shopDomain:l,isError:d,isSuccess:u}){const f=t.useRef(null),[g,h]=t.useState(0),[m,p]=t.useState(0),[y,S]=t.useState(!1),[x,v]=t.useState(!1),b=t.useRef(null),w=t.useRef(g),C=t.useRef(m),F=t.useRef([]),j=t.useRef(""),_=t.useRef(0),N=t.useRef(!1),E=t.useRef(0),k="undefined"!=typeof navigator&&(/iPad|iPhone|iPod/.test(navigator.userAgent)||"MacIntel"===navigator.platform&&navigator.maxTouchPoints>1),T=t.useMemo(()=>["Face front","Turn head fully left","Turn head fully right","Smile facing front"],[]),I=t.useMemo(()=>function(e,t){let a;return(...n)=>{a&&clearTimeout(a),a=setTimeout(()=>e(...n),t)}}(e=>{a.posthog.capture(`${l}/face_scan_pose_detection`,e)},4e3),[l]),R=t.useCallback((t,a,n,o,r,s)=>{const c=Date.now();if(!(c-E.current<4e3)){E.current=c;try{const c=t[0]||[0,0,0],i=t[2]||[0,0,0],l=t[5]||[0,0,0],d=t[9]||[0,0,0],u=t[10]||[0,0,0],f=t.map(e=>e[2]).filter(e=>e>0),g=f.length>0?f.reduce((e,t)=>e+t,0)/f.length:0,h=a.map(e=>e[2]).filter(e=>e>0),m=h.length>0?h.reduce((e,t)=>e+t,0)/h.length:0,p=Math.abs(i[0]-l[0]),y=c[0]-l[0],S=i[0]-c[0];let x="frontal";1===n?x="left":2===n?x="right":3===n&&(x="frontal_smile");const v={faceScanId:e,stage:n,timestamp:(new Date).toISOString(),data:JSON.stringify({headValid:o,bodyInvalid:r,consecutiveValid:s,avgFaceScore:parseFloat(g.toFixed(3)),avgBodyScore:parseFloat(m.toFixed(3)),faceKeypointsDetected:f.length,bodyKeypointsDetected:h.length,eyeDistance:parseFloat(p.toFixed(2)),noseToRightRatio:parseFloat((y/p).toFixed(3)),noseToLeftRatio:parseFloat((S/p).toFixed(3)),noseScore:parseFloat(c[2].toFixed(3)),leftEyeScore:parseFloat(i[2].toFixed(3)),rightEyeScore:parseFloat(l[2].toFixed(3)),leftMouthScore:parseFloat(d[2].toFixed(3)),rightMouthScore:parseFloat(u[2].toFixed(3)),expectedPosition:x})};I(v)}catch(e){console.warn("Failed to track pose detection:",e)}}},[e,I]),M=()=>{a.posthog.capture(`${l}/face_scan_detection_started`,{faceScanId:e,stage:w.current,timestamp:(new Date).toISOString(),stageName:T[w.current]}),setTimeout(()=>{v(!0)},1500)},D=async()=>{if("undefined"!=typeof window)try{console.log("Initializing Face Scan...");const e=await(async()=>{if("undefined"==typeof window)return null;if(r)return r;if(s)for(;s;)if(await new Promise(e=>setTimeout(e,100)),r)return r;s=!0;try{const[e,t]=await Promise.all([import("@tensorflow/tfjs"),Promise.resolve().then(function(){return require("./pose-detection.esm-Bc8T4UAD.js")})]);await e.setBackend("webgl"),await e.ready();const n=await t.createDetector(t.SupportedModels.BlazePose,{runtime:"tfjs",modelType:"full"}),o=document.createElement("canvas");o.width="number"==typeof a.videoConstraints.width?a.videoConstraints.width:a.videoConstraints.width.ideal??a.videoConstraints.width.max??1280,o.height="number"==typeof a.videoConstraints.height?a.videoConstraints.height:a.videoConstraints.height.ideal??a.videoConstraints.height.max??720;const s=o.getContext("2d");if(s){s.fillStyle="black",s.fillRect(0,0,o.width,o.height);try{await n.estimatePoses(o)}catch(e){console.warn("Warmup frame failed (non-fatal):",e)}}return r=n,n}catch(e){return console.error("Failed to preload detector:",e),null}finally{s=!1}})();e&&(f.current=e,console.log("Face scan model loaded successfully"),S(!0),c?.())}catch(e){console.error("Error initializing face scan:",e)}};return t.useEffect(()=>{if(!d&&!u)return D(),()=>{(async()=>{try{S(!1)}catch(e){console.error("Error disposing resources:",e)}finally{h(0),p(0),w.current=0,C.current=0,F.current=[]}})()}},[d,u]),t.useEffect(()=>{w.current=g},[g]),t.useEffect(()=>{C.current=m},[m]),{faceScanDetector:async(t,r)=>{if(f.current&&t.current&&y&&x&&!(t.current.readyState<2))try{const s=await f.current.estimatePoses(t.current);if(s.length>0){const t=[],c=[];if(s[0].keypoints.forEach((e,a)=>{const n=e.score??0,o=[e.x??-1,e.y??-1,n];a<=10?t.push(o):c.push(o)}),r?.current){const e=r.current.getContext("2d"),{width:t,height:a}=r.current;if(e){e.clearRect(0,0,t,a);const n=Math.min(C.current/2,1),o=.35*a;e.beginPath(),e.strokeStyle="#00ff00",e.lineWidth=6,e.arc(t/2,a/2,o+10,-Math.PI/2,-Math.PI/2+2*n*Math.PI),e.stroke()}}const d=((e,t)=>{if(!t[0]||!t[2]||!t[5]||t[0][2]<.2||t[2][2]<.2||t[5][2]<.2)return!1;const a=.5*(t[10][1]+t[9][1])-.5*(t[5][1]+t[2][1]),n=(.5*(t[10][1]+t[9][1])-t[0][1])/a,o=n>.7||n<.3,r=Math.abs(t[2][1]-t[5][1])<.5*a&&Math.abs(t[9][1]-t[10][1])<.5*a,s=t[2][0]-t[5][0],c=t[0][0]-t[5][0],i=c>.4*s&&c<.6*s,l=c>.85*s,d=t[2][0]-t[0][0]>.85*s;switch(e){case 0:case 3:return!o&&r&&i;case 1:return!o&&r&&l;case 2:return!o&&r&&d;default:return!1}})(w.current,t),u=c.slice(2).filter(e=>e[2]>.7).length<=2;F.current.push(d&&u),F.current.length>10&&F.current.shift();if(F.current.filter(Boolean).length>=2){const e=C.current+1;p(e)}else p(Math.max(0,C.current-1));if(C.current>=2){n?.();const t=w.current+1;p(0),F.current=[],h(t),v(!1),(async()=>{if(await a.speechService.playAudio(`${a.voiceOverAssetsPath}face-scan-vos/Sound-effect.mp3`),a.posthog.capture(`${l}/face_scan_detection_stage_completed`,{faceScanId:e,completedStage:w.current,nextStage:t,timestamp:(new Date).toISOString(),totalStages:4,stageName:T[w.current]}),1===t&&i&&i(),t>=4)o?.();else{let e=null;switch(t){case 1:e="Left.mp3";break;case 2:e="Right.mp3";break;case 3:e="Smile.mp3"}e&&await a.speechService.playAudio(`${a.voiceOverAssetsPath}face-scan-vos/${e}`),M()}})()}R(t,c,w.current,d,u,C.current)}}catch(e){console.error("Pose detection error:",e)}},scanStage:g,setScanStage:h,consecutiveValid:m,isModelLoaded:y,resetScan:()=>{a.posthog.capture(`${l}/face_scan_reset`,{faceScanId:e,stage:w.current,timestamp:(new Date).toISOString(),stageName:T[w.current],consecutiveValid:C.current}),h(0),p(0),v(!1),w.current=0,C.current=0,F.current=[],j.current="",_.current=0,N.current=!1,b.current&&(speechSynthesis.cancel(),b.current=null)},enableVoiceCommands:()=>{if(N.current=!0,"undefined"!=typeof window&&k&&"speechSynthesis"in window){const e=new SpeechSynthesisUtterance("");e.volume=0,speechSynthesis.speak(e)}},startScanSequence:M,isScanningActive:x}}function i({onRetry:o,loading:r}){const{translate:s}=t.useContext(a.LanguageContext)||{},c=a.useConfig();return e.jsx("div",{className:"fixed common-ui-main top-[0] left-[0] z-[999] flex justify-center items-center w-full h-full",style:{background:c?.style?.base?.backgroundColor},children:e.jsxs("div",{className:"flex flex-col w-full items-center p-[1rem] rounded-lg ",children:[e.jsx(a.Header,{noTitle:!0}),e.jsxs("div",{className:"flex flex-col items-center w-full",children:[e.jsx("h2",{className:"text-xl font-semibold text-gray-800 ",style:{fontFamily:c?.style?.heading?.headingFontFamily||"SeriouslyNostalgic Fn",fontSize:c?.style?.heading?.headingFontSize||"32px",color:c?.style?.heading?.headingColor||"#000",fontWeight:c?.style?.heading?.headingFontWeight||"normal"},children:s?.(a.LanguageKeys.scanFailed)}),e.jsx("p",{className:"mb-[1.5rem]",style:{fontFamily:c?.style?.subheading?.subheadingFontFamily||"'Inter', sans-serif",fontSize:c?.style?.subheading?.subheadingFontSize||"14px",color:c?.style?.subheading?.subheadingColor||"#4b5563",fontWeight:c?.style?.subheading?.subheadingFontWeight||"normal"},children:s?.(a.LanguageKeys.clickToResetScan)}),e.jsx(a.SpecificButton,{disabled:r,className:"w-full h-[45px] shadow-[0px_1px_2px_0px_#00000040] text-[16px]",buttonText:s?.(a.LanguageKeys.resetScan),postfixIcon:e.jsx(n.ArrowRight,{}),buttonFunc:()=>o?.()})]})]})})}function l({stage:n,videoLoading:o,setVideoLoading:r,videoError:s,setVideoError:c,gender:i,btnConfig:l}){const{translate:d}=t.useContext(a.LanguageContext)||{},u=a.useConfig();return-1===n?e.jsxs("div",{className:"text-center common-ui-main p-[16px] w-full h-full",style:{background:u?.style?.base?.backgroundColor},children:[e.jsxs("div",{className:"w-full",children:[e.jsx(a.Header,{noTitle:!0}),e.jsx("h2",{style:{fontFamily:u?.style?.heading?.headingFontFamily||"SeriouslyNostalgic Fn",fontSize:u?.style?.heading?.headingFontSize||"32px",color:u?.style?.heading?.headingColor||"#000",fontWeight:u?.style?.heading?.headingFontWeight||"normal"},children:d?.(a.LanguageKeys.faceVisible)}),o&&e.jsx("div",{className:"mb-4 flex items-center justify-center",style:{fontFamily:u?.style?.subheading?.subheadingFontFamily||"'Inter', sans-serif",fontSize:u?.style?.subheading?.subheadingFontSize||"14px",color:u?.style?.subheading?.subheadingColor||"#4b5563",fontWeight:u?.style?.subheading?.subheadingFontWeight||"normal"},children:d?.(a.LanguageKeys.loadingVideo)}),s&&e.jsx("div",{className:"mb-4 text-red-600",style:{fontFamily:u?.style?.subheading?.subheadingFontFamily||"'Inter', sans-serif",fontSize:u?.style?.subheading?.subheadingFontSize||"14px",color:"#ff0000",fontWeight:u?.style?.subheading?.subheadingFontWeight||"normal"},children:d?.(a.LanguageKeys.videoLoadFailed)}),!s&&e.jsx("div",{className:" w-[100px] mx-auto",children:e.jsx("video",{src:i===a.GenderType.Male?a.maleGlassesOffVideo:a.glassesOffVideo,autoPlay:!0,loop:!0,controls:!1,muted:!0,playsInline:!0,className:"h-full w-full object-contain border-none",onCanPlay:()=>r(!1),onLoadStart:()=>r(!0),onError:()=>c(!0),"aria-label":"Instructional video: Please remove your glasses before starting the scan."})})]}),e.jsx("div",{className:"flex justify-center w-full p-[1rem]",children:e.jsx(a.SpecificButton,{disabled:l.isDisabled,className:"!w-[60px] !h-[35px] !py-0 !px-0",buttonText:d?.(l.label),postfixIcon:l?.icon,buttonFunc:l.onClick})})]}):e.jsx("div",{className:"text-center common-ui-main p-[16px] w-full h-full",style:{background:u?.style?.base?.backgroundColor},children:e.jsxs("div",{className:"w-full",children:[e.jsx(a.Header,{noTitle:!0}),e.jsx("h3",{className:"mb-[0.5rem]",style:{fontFamily:u?.style?.heading?.headingFontFamily||"SeriouslyNostalgic Fn",fontSize:u?.style?.heading?.headingFontSize||"32px",color:u?.style?.heading?.headingColor||"#000",fontWeight:u?.style?.heading?.headingFontWeight||"normal"},children:d?.(a.directionMessages[n])}),e.jsxs("div",{className:"max-w-[400px] justify-center gap-1 mx-auto flex items-center",children:[e.jsx("div",{className:` w-[120px] overflow-hidden ${0===n?"opacity-100":"opacity-0 hidden"} `,children:e.jsx("video",{className:"h-full w-full object-contain border-none",muted:!0,loop:!0,autoPlay:!0,playsInline:!0,children:e.jsx("source",{src:i===a.GenderType.Male?a.FACE_SCAN_HEADSHOT.male.forward:a.FACE_SCAN_HEADSHOT.female.forward,type:"video/mp4"})})}),e.jsx("div",{className:` w-[120px] overflow-hidden ${1===n?"opacity-100":"opacity-0 hidden"} `,children:e.jsx("video",{className:"h-full w-full object-contain border-none",muted:!0,loop:!0,autoPlay:!0,playsInline:!0,children:e.jsx("source",{src:i===a.GenderType.Male?a.FACE_SCAN_HEADSHOT.male.left:a.FACE_SCAN_HEADSHOT.female.left,type:"video/mp4"})})}),e.jsx("div",{className:` w-[120px] overflow-hidden ${2===n?"opacity-100":"opacity-0 hidden"} `,children:e.jsx("video",{className:"h-full w-full object-contain border-none",muted:!0,loop:!0,autoPlay:!0,playsInline:!0,children:e.jsx("source",{src:i===a.GenderType.Male?a.FACE_SCAN_HEADSHOT.male.right:a.FACE_SCAN_HEADSHOT.female.right,type:"video/mp4"})})}),e.jsx("div",{className:` w-[120px] overflow-hidden ${3===n?"opacity-100":"opacity-0 hidden"} `,children:e.jsx("video",{className:"h-full w-full object-contain border-none",muted:!0,loop:!0,autoPlay:!0,playsInline:!0,children:e.jsx("source",{src:i===a.GenderType.Male?a.FACE_SCAN_HEADSHOT.male.smile:a.FACE_SCAN_HEADSHOT.female.smile,type:"video/mp4"})})})]})]})})}const d=({webcamRef:r,canvasRef:s})=>{const{isError:c,isSuccess:d,showLoader:u,hasError:f,resetScanState:g,showGuideCard:h,scanStage:m,videoLoading:p,setVideoLoading:y,videoError:S,setVideoError:x,gender:v,getButtonText:b,isScanning:w,startScan:C,isModelLoaded:F,onRetry:j}=t.useContext(a.ParamsContext),_=a.useConfig();return c?e.jsx(i,{onRetry:j}):d?e.jsx("div",{className:"fixed z-[9] common-ui-main w-full h-full",style:{background:_?.style?.base?.backgroundColor},children:e.jsx(a.LoadingScreen,{url:_?.loader,loaderType:"black"})}):e.jsxs(e.Fragment,{children:[e.jsx("audio",{id:"audioElement",crossOrigin:"anonymous",preload:"auto",style:{position:"absolute",zIndex:-99999},src:void 0}),u&&!f&&e.jsx("div",{className:"fixed z-[9] common-ui-main w-full h-full",style:{background:_?.style?.base?.backgroundColor},children:e.jsx(a.LoadingScreen,{url:_?.loader,loaderType:"black"})}),e.jsx("div",{className:"h-full flex-col common-ui-main relative w-full flex justify-center items-center text-center rounded-t-[20px]",style:{background:_?.style?.base?.backgroundColor},children:e.jsx("div",{className:"flex-1 w-full max-w-md overflow-hidden",children:e.jsxs("div",{className:"w-full h-full",children:[e.jsx("video",{ref:r,autoPlay:!0,playsInline:!0,muted:!0,width:a.videoConstraints.width.ideal,height:a.videoConstraints.height.ideal,className:"w-full h-full object-cover fixed left-0 top-0 z-0",style:{transform:"scaleX(-1)"}}),e.jsx("canvas",{ref:s,width:a.videoConstraints.width.ideal,height:a.videoConstraints.height.ideal,style:{transform:"scaleX(-1)",opacity:"0"}})]})})}),!u&&f&&e.jsx(i,{loading:u,onRetry:g}),h&&!f&&!u&&e.jsx(o.Drawer,{open:!0,className:"face-scan-small camera-draw",anchor:"bottom",onClose:(e,t)=>{},hideBackdrop:!0,children:e.jsx(l,{stage:m,videoLoading:p,setVideoLoading:y,videoError:S,setVideoError:x,gender:v,btnConfig:{label:b(),onClick:w?g:C,isDisabled:u||!F,icon:w?e.jsx(n.ArrowRight,{}):e.jsx(e.Fragment,{})}})})]})};exports.FaceScan=n=>{const{onScanSuccess:o,onScanError:r,onRetry:s,onScanStart:i,onCaptureComplete:l,onUploadStart:u,onUploadEnd:f,onMeasurementSocketStart:g,onMeasurementSocketClose:h,config:m,isError:p,isSuccess:y}=n,S=n.userDetails??{email:"",gender:"male",deviceFocalLength:0,shopDomain:"",bodyScanId:""},x=n.token??"",v=t.useRef(null),b=t.useRef(null),w=t.useRef(null),C=t.useRef([]),F=t.useRef(null),j=t.useRef(null),[_,N]=t.useState(!1),[E,k]=t.useState(!1),[T,I]=t.useState(!1),[R,M]=t.useState(!0),[D,P]=t.useState(!1),[L,A]=t.useState(!1),[O,z]=t.useState(!1),[$,H]=t.useState(a.generateUuid()),V=t.useMemo(()=>a.getSwanService(x),[x]),{email:W,gender:K,deviceFocalLength:U,shopDomain:B,callbackUrl:q,bodyScanId:G}=S,[J,X]=t.useState([]),[Q,Y]=t.useState(a.videoConstraintsExact),Z=t.useMemo(()=>a.getPreferredMediaRecorderTypes(),[]),ee=a.getRecordingMimeType(J),te=a.getRecordingExtension(ee);a.usePosthogPageview();const ae=t.useCallback(()=>{console.log("Stopping recording..."),w.current&&"recording"===w.current.state&&w.current.stop(),w.current=null},[]),ne=async()=>{if(l?.(),C.current){if(0===C.current.length)return console.error("No video data recorded"),z(!0),void N(!1);u?.(),N(!0);const e=new File(C.current,`${$}.${te}`,{type:ee}),t=j.current??await a.getVideoFPS(e),n=e.size,o=(n/1048576).toFixed(2),r=Math.round(n/1e4),s={video_size_mb:parseFloat(o),video_size_bytes:n,video_fps:t||0,blob_count:C.current.length,estimated_duration_seconds:r},c=[{gender:K},{face_scan_id:$},{focal_length:`${U}`},{customer_store_url:B},{scan_type:"face_scan"},{body_scan_id:G}];q&&c.push({callback_url:q}),a.handleScanTimeCapture({eventName:`${B}/face_scan_meta_data`,faceScanId:$,email:W,data:JSON.stringify({metaData:c,videoData:s})});const i=Date.now();a.handleScanTimeCapture({eventName:`${B}/face_scan_upload_start`,faceScanId:$,email:W,startTime:i});try{const t=await V.fileUpload.faceScanFileUploader({file:e,arrayMetaData:c,objectKey:$,email:W,contentType:e.type}),n=Date.now(),o=n-i;a.handleScanTimeCapture({eventName:`${B}/face_scan_upload_complete`,faceScanId:$,email:W,completionTime:n,uploadDuration:o}),f?.(),console.log("✅ Upload successful",t),V.measurement.handlFaceScaneSocket({onPreopen:()=>{g?.(),a.handleWebSocketCapture({eventName:`${B}/webSocket`,faceScanID:$,connection:"pre_open",type:"faceScan_recommendation",email:W})},faceScanId:$,onOpen:()=>{a.handleWebSocketCapture({eventName:`${B}/webSocket`,faceScanID:$,connection:"open",type:"faceScan_recommendation",email:W}),console.log("websocket connect open")},onError:e=>{a.handleWebSocketCapture({eventName:`${B}/webSocket`,faceScanID:$,connection:"error",type:"faceScan_recommendation",email:W}),ge(e)},onSuccess:e=>{a.handleWebSocketCapture({eventName:`${B}/webSocket`,faceScanID:$,connection:"success",type:"faceScan_recommendation",email:W}),he(e)},onClose:()=>{h?.(),console.log("websocket connect close"),a.handleWebSocketCapture({eventName:`${B}/webSocket`,faceScanID:$,connection:"close",type:"faceScan_recommendation",email:W})}})}catch(e){f?.(),ge(e)}}},oe=t.useCallback(()=>{const e=v.current?.srcObject;if(!e)return;const t=e.getVideoTracks()[0].getSettings(),{width:a=1280,height:n=720}=t,o=document.createElement("canvas"),r=o.getContext("2d");a>n?(o.width=n,o.height=a):(o.width=a,o.height=n);const s=document.createElement("video");s.srcObject=e,s.muted=!0,s.playsInline=!0,s.play();const c=()=>{a>n?(r?.save(),r?.translate(o.width,0),r?.rotate(Math.PI/2),r?.drawImage(s,0,0,n,a),r?.restore()):r?.drawImage(s,0,0,a,n),requestAnimationFrame(c)};c();const i=t.frameRate??10;j.current=i;const l=o.captureStream(i),d={videoBitsPerSecond:15e5};let u;J.length>0&&(d.mimeType=J[0]);try{u=new MediaRecorder(l,d)}catch(e){return console.error("MediaRecorder init failed:",e),z(!0),void N(!1)}C.current=[],u.ondataavailable=e=>{e?.data&&e.data.size>0&&C.current&&C.current.push(e.data)},u.onstop=()=>{console.log("Recording stopped, total blobs:",C?.current?.length),ne()},u.start(100),w.current=u,console.log("Recording started successfully (portrait normalized)")},[J,ne]),{faceScanDetector:re,scanStage:se,setScanStage:ce,resetScan:ie,isModelLoaded:le,startScanSequence:de}=c({faceScanId:$,shopDomain:B,isError:p,isSuccess:y,onScanComplete:()=>{ae()},onModelReady:()=>{k(!0)},onStartRecording:()=>{console.log("Stage 0 completed - starting recording for stages 1-3"),oe()}}),ue=t.useCallback(()=>{le&&(i?.(),ce(0),a.speechService.playAudio(`${a.voiceOverAssetsPath}face-scan-vos/Face-forward.mp3`),setTimeout(()=>{I(!0),setTimeout(()=>{de()},200)},200))},[ce,I,de,le,i]),fe=t.useCallback(()=>{I(!1),M(!0),ae(),ie(),s?.(),C.current=[],j.current=null,w.current&&(w.current=null),z(!1),ce(-1),H(a.generateUuid()),v.current&&F.current&&(v.current.srcObject=F.current,console.log("Camera stream restored after reset"))},[ce,I,M,ae,ie,H]),ge=e=>{console.log(e,"ws error"),r?.(e),z(!0),N(!1),M(!1),a.handleScanTimeCapture({eventName:`${B}/faceScan`,faceScanId:$,status:"failed",email:W,data:JSON.stringify(e)})},he=e=>{console.log(e,"ws success"),e&&"intermediate"===e?.resultType&&a.handleScanTimeCapture({eventName:`${B}/faceScan_success/intermediate`,faceScanId:$,status:"success",email:W,data:JSON.stringify(e)}),o?.(e)};t.useEffect(()=>{if(!p&&!y)return navigator.mediaDevices.getUserMedia&&navigator.mediaDevices.getUserMedia({video:Q}).then(e=>{F.current=e,v.current&&(v.current.srcObject=e)}).catch(e=>{console.error("Error accessing webcam:",e),Q!==a.videoConstraintsExact?z(!0):Y(a.videoConstraintsFallback)}),()=>{F.current&&F.current.getTracks().forEach(e=>e.stop())}},[p,y,Q]),t.useEffect(()=>{if(!E||!T)return;const e=setInterval(()=>{re(v,b)},500);return()=>clearInterval(e)},[re,E,T]);return console.log("Model ready:",E,"Has error:",O,"Is scanning:",T,"showLoader",_),t.useEffect(()=>{const e=a.getSupportedMediaRecorderTypes(Z,a.videoTypes);X(e)},[Z]),t.useEffect(()=>{ce(-1)},[]),e.jsx(a.LanguageContextProvider,{children:e.jsx(a.ConfigProvider,{config:m,children:e.jsx(a.ParamsContext.Provider,{value:{isError:p,isSuccess:y,showLoader:_,hasError:O,resetScanState:fe,showGuideCard:R,scanStage:se,videoLoading:D,setVideoLoading:P,videoError:L,setVideoError:A,gender:K,getButtonText:()=>T?a.LanguageKeys.reset:le?a.LanguageKeys.start:a.LanguageKeys.loading,isScanning:T,startScan:ue,isModelLoaded:le,onRetry:s},children:e.jsx(d,{webcamRef:v,canvasRef:b})})})})};
2
- //# sourceMappingURL=FaceScan-BE0PB0fZ.js.map
@@ -1,2 +0,0 @@
1
- import{jsx as e,jsxs as t,Fragment as a}from"react/jsx-runtime";import{useRef as n,useState as o,useMemo as r,useCallback as c,useEffect as i,useContext as s}from"react";import{p as l,s as d,v as u,a as m,L as f,u as h,H as g,b as p,S as y,m as S,g as b,G as w,d as v,F as x,P as F,c as N,e as _,f as I,h as k,i as M,j as C,k as D,l as E,n as P,o as T,q as R,r as z,C as $,t as L,w as j,x as V}from"./LoadingScreen-FKDLJRUj.js";import{ArrowRight as O}from"lucide-react";import{Drawer as W}from"@mui/material";let U=null,B=!1;function A({faceScanId:e,onValidPose:t,onScanComplete:a,onModelReady:s,onStartRecording:f,shopDomain:h,isError:g,isSuccess:p}){const y=n(null),[S,b]=o(0),[w,v]=o(0),[x,F]=o(!1),[N,_]=o(!1),I=n(null),k=n(S),M=n(w),C=n([]),D=n(""),E=n(0),P=n(!1),T=n(0),R="undefined"!=typeof navigator&&(/iPad|iPhone|iPod/.test(navigator.userAgent)||"MacIntel"===navigator.platform&&navigator.maxTouchPoints>1),z=r(()=>["Face front","Turn head fully left","Turn head fully right","Smile facing front"],[]),$=r(()=>function(e,t){let a;return(...n)=>{a&&clearTimeout(a),a=setTimeout(()=>e(...n),t)}}(e=>{l.capture(`${h}/face_scan_pose_detection`,e)},4e3),[h]),L=c((t,a,n,o,r,c)=>{const i=Date.now();if(!(i-T.current<4e3)){T.current=i;try{const i=t[0]||[0,0,0],s=t[2]||[0,0,0],l=t[5]||[0,0,0],d=t[9]||[0,0,0],u=t[10]||[0,0,0],m=t.map(e=>e[2]).filter(e=>e>0),f=m.length>0?m.reduce((e,t)=>e+t,0)/m.length:0,h=a.map(e=>e[2]).filter(e=>e>0),g=h.length>0?h.reduce((e,t)=>e+t,0)/h.length:0,p=Math.abs(s[0]-l[0]),y=i[0]-l[0],S=s[0]-i[0];let b="frontal";1===n?b="left":2===n?b="right":3===n&&(b="frontal_smile");const w={faceScanId:e,stage:n,timestamp:(new Date).toISOString(),data:JSON.stringify({headValid:o,bodyInvalid:r,consecutiveValid:c,avgFaceScore:parseFloat(f.toFixed(3)),avgBodyScore:parseFloat(g.toFixed(3)),faceKeypointsDetected:m.length,bodyKeypointsDetected:h.length,eyeDistance:parseFloat(p.toFixed(2)),noseToRightRatio:parseFloat((y/p).toFixed(3)),noseToLeftRatio:parseFloat((S/p).toFixed(3)),noseScore:parseFloat(i[2].toFixed(3)),leftEyeScore:parseFloat(s[2].toFixed(3)),rightEyeScore:parseFloat(l[2].toFixed(3)),leftMouthScore:parseFloat(d[2].toFixed(3)),rightMouthScore:parseFloat(u[2].toFixed(3)),expectedPosition:b})};$(w)}catch(e){console.warn("Failed to track pose detection:",e)}}},[e,$]),j=()=>{l.capture(`${h}/face_scan_detection_started`,{faceScanId:e,stage:k.current,timestamp:(new Date).toISOString(),stageName:z[k.current]}),setTimeout(()=>{_(!0)},1500)},V=async()=>{if("undefined"!=typeof window)try{console.log("Initializing Face Scan...");const e=await(async()=>{if("undefined"==typeof window)return null;if(U)return U;if(B)for(;B;)if(await new Promise(e=>setTimeout(e,100)),U)return U;B=!0;try{const[e,t]=await Promise.all([import("@tensorflow/tfjs"),import("./pose-detection.esm-DejsYGYM.js")]);await e.setBackend("webgl"),await e.ready();const a=await t.createDetector(t.SupportedModels.BlazePose,{runtime:"tfjs",modelType:"full"}),n=document.createElement("canvas");n.width="number"==typeof m.width?m.width:m.width.ideal??m.width.max??1280,n.height="number"==typeof m.height?m.height:m.height.ideal??m.height.max??720;const o=n.getContext("2d");if(o){o.fillStyle="black",o.fillRect(0,0,n.width,n.height);try{await a.estimatePoses(n)}catch(e){console.warn("Warmup frame failed (non-fatal):",e)}}return U=a,a}catch(e){return console.error("Failed to preload detector:",e),null}finally{B=!1}})();e&&(y.current=e,console.log("Face scan model loaded successfully"),F(!0),s?.())}catch(e){console.error("Error initializing face scan:",e)}};return i(()=>{if(!g&&!p)return V(),()=>{(async()=>{try{F(!1)}catch(e){console.error("Error disposing resources:",e)}finally{b(0),v(0),k.current=0,M.current=0,C.current=[]}})()}},[g,p]),i(()=>{k.current=S},[S]),i(()=>{M.current=w},[w]),{faceScanDetector:async(n,o)=>{if(y.current&&n.current&&x&&N&&!(n.current.readyState<2))try{const r=await y.current.estimatePoses(n.current);if(r.length>0){const n=[],c=[];if(r[0].keypoints.forEach((e,t)=>{const a=e.score??0,o=[e.x??-1,e.y??-1,a];t<=10?n.push(o):c.push(o)}),o?.current){const e=o.current.getContext("2d"),{width:t,height:a}=o.current;if(e){e.clearRect(0,0,t,a);const n=Math.min(M.current/2,1),o=.35*a;e.beginPath(),e.strokeStyle="#00ff00",e.lineWidth=6,e.arc(t/2,a/2,o+10,-Math.PI/2,-Math.PI/2+2*n*Math.PI),e.stroke()}}const i=((e,t)=>{if(!t[0]||!t[2]||!t[5]||t[0][2]<.2||t[2][2]<.2||t[5][2]<.2)return!1;const a=.5*(t[10][1]+t[9][1])-.5*(t[5][1]+t[2][1]),n=(.5*(t[10][1]+t[9][1])-t[0][1])/a,o=n>.7||n<.3,r=Math.abs(t[2][1]-t[5][1])<.5*a&&Math.abs(t[9][1]-t[10][1])<.5*a,c=t[2][0]-t[5][0],i=t[0][0]-t[5][0],s=i>.4*c&&i<.6*c,l=i>.85*c,d=t[2][0]-t[0][0]>.85*c;switch(e){case 0:case 3:return!o&&r&&s;case 1:return!o&&r&&l;case 2:return!o&&r&&d;default:return!1}})(k.current,n),s=c.slice(2).filter(e=>e[2]>.7).length<=2;C.current.push(i&&s),C.current.length>10&&C.current.shift();if(C.current.filter(Boolean).length>=2){const e=M.current+1;v(e)}else v(Math.max(0,M.current-1));if(M.current>=2){t?.();const n=k.current+1;v(0),C.current=[],b(n),_(!1),(async()=>{if(await d.playAudio(`${u}face-scan-vos/Sound-effect.mp3`),l.capture(`${h}/face_scan_detection_stage_completed`,{faceScanId:e,completedStage:k.current,nextStage:n,timestamp:(new Date).toISOString(),totalStages:4,stageName:z[k.current]}),1===n&&f&&f(),n>=4)a?.();else{let e=null;switch(n){case 1:e="Left.mp3";break;case 2:e="Right.mp3";break;case 3:e="Smile.mp3"}e&&await d.playAudio(`${u}face-scan-vos/${e}`),j()}})()}L(n,c,k.current,i,s,M.current)}}catch(e){console.error("Pose detection error:",e)}},scanStage:S,setScanStage:b,consecutiveValid:w,isModelLoaded:x,resetScan:()=>{l.capture(`${h}/face_scan_reset`,{faceScanId:e,stage:k.current,timestamp:(new Date).toISOString(),stageName:z[k.current],consecutiveValid:M.current}),b(0),v(0),_(!1),k.current=0,M.current=0,C.current=[],D.current="",E.current=0,P.current=!1,I.current&&(speechSynthesis.cancel(),I.current=null)},enableVoiceCommands:()=>{if(P.current=!0,"undefined"!=typeof window&&R&&"speechSynthesis"in window){const e=new SpeechSynthesisUtterance("");e.volume=0,speechSynthesis.speak(e)}},startScanSequence:j,isScanningActive:N}}function q({onRetry:a,loading:n}){const{translate:o}=s(f)||{},r=h();return e("div",{"data-testid":"face-scan-error-screen",className:"fixed common-ui-main top-[0] left-[0] z-[999] flex justify-center items-center w-full h-full",style:{background:r?.style?.base?.backgroundColor},children:t("div",{className:"flex flex-col w-full items-center p-[1rem] rounded-lg ",children:[e(g,{noTitle:!0}),t("div",{className:"flex flex-col items-center w-full",children:[e("h2",{className:"text-xl font-semibold text-gray-800 ",style:{fontFamily:r?.style?.heading?.headingFontFamily||"SeriouslyNostalgic Fn",fontSize:r?.style?.heading?.headingFontSize||"32px",color:r?.style?.heading?.headingColor||"#000",fontWeight:r?.style?.heading?.headingFontWeight||"normal"},children:o?.(p.scanFailed)}),e("p",{className:"mb-[1.5rem]",style:{fontFamily:r?.style?.subheading?.subheadingFontFamily||"'Inter', sans-serif",fontSize:r?.style?.subheading?.subheadingFontSize||"14px",color:r?.style?.subheading?.subheadingColor||"#4b5563",fontWeight:r?.style?.subheading?.subheadingFontWeight||"normal"},children:o?.(p.clickToResetScan)}),e(y,{"data-testid":"face-scan-retry-btn",disabled:n,className:"w-full h-[45px] shadow-[0px_1px_2px_0px_#00000040] text-[16px]",buttonText:o?.(p.resetScan),postfixIcon:e(O,{}),buttonFunc:()=>a?.()})]})]})})}function J({stage:a,videoLoading:n,setVideoLoading:o,videoError:r,setVideoError:c,gender:i,btnConfig:l}){const{translate:d}=s(f)||{},u=h();return-1===a?t("div",{"data-testid":"face-scan-guide",className:"text-center common-ui-main p-[16px] w-full h-full",style:{background:u?.style?.base?.backgroundColor},children:[t("div",{className:"w-full",children:[e(g,{noTitle:!0}),e("h2",{style:{fontFamily:u?.style?.heading?.headingFontFamily||"SeriouslyNostalgic Fn",fontSize:u?.style?.heading?.headingFontSize||"32px",color:u?.style?.heading?.headingColor||"#000",fontWeight:u?.style?.heading?.headingFontWeight||"normal"},children:d?.(p.faceVisible)}),n&&e("div",{className:"mb-4 flex items-center justify-center",style:{fontFamily:u?.style?.subheading?.subheadingFontFamily||"'Inter', sans-serif",fontSize:u?.style?.subheading?.subheadingFontSize||"14px",color:u?.style?.subheading?.subheadingColor||"#4b5563",fontWeight:u?.style?.subheading?.subheadingFontWeight||"normal"},children:d?.(p.loadingVideo)}),r&&e("div",{className:"mb-4 text-red-600",style:{fontFamily:u?.style?.subheading?.subheadingFontFamily||"'Inter', sans-serif",fontSize:u?.style?.subheading?.subheadingFontSize||"14px",color:"#ff0000",fontWeight:u?.style?.subheading?.subheadingFontWeight||"normal"},children:d?.(p.videoLoadFailed)}),!r&&e("div",{className:" w-[100px] mx-auto",children:e("video",{src:i===w.Male?S:b,autoPlay:!0,loop:!0,controls:!1,muted:!0,playsInline:!0,className:"h-full w-full object-contain border-none",onCanPlay:()=>o(!1),onLoadStart:()=>o(!0),onError:()=>c(!0),"aria-label":"Instructional video: Please remove your glasses before starting the scan."})})]}),e("div",{className:"flex justify-center w-full p-[1rem]",children:e(y,{"data-testid":"face-scan-start-btn",disabled:l.isDisabled,className:"!w-[60px] !h-[35px] !py-0 !px-0",buttonText:d?.(l.label),postfixIcon:l?.icon,buttonFunc:l.onClick})})]}):e("div",{className:"text-center common-ui-main p-[16px] w-full h-full",style:{background:u?.style?.base?.backgroundColor},children:t("div",{className:"w-full",children:[e(g,{noTitle:!0}),e("h3",{className:"mb-[0.5rem]",style:{fontFamily:u?.style?.heading?.headingFontFamily||"SeriouslyNostalgic Fn",fontSize:u?.style?.heading?.headingFontSize||"32px",color:u?.style?.heading?.headingColor||"#000",fontWeight:u?.style?.heading?.headingFontWeight||"normal"},children:d?.(v[a])}),t("div",{className:"max-w-[400px] justify-center gap-1 mx-auto flex items-center",children:[e("div",{className:` w-[120px] overflow-hidden ${0===a?"opacity-100":"opacity-0 hidden"} `,children:e("video",{className:"h-full w-full object-contain border-none",muted:!0,loop:!0,autoPlay:!0,playsInline:!0,children:e("source",{src:i===w.Male?x.male.forward:x.female.forward,type:"video/mp4"})})}),e("div",{className:` w-[120px] overflow-hidden ${1===a?"opacity-100":"opacity-0 hidden"} `,children:e("video",{className:"h-full w-full object-contain border-none",muted:!0,loop:!0,autoPlay:!0,playsInline:!0,children:e("source",{src:i===w.Male?x.male.left:x.female.left,type:"video/mp4"})})}),e("div",{className:` w-[120px] overflow-hidden ${2===a?"opacity-100":"opacity-0 hidden"} `,children:e("video",{className:"h-full w-full object-contain border-none",muted:!0,loop:!0,autoPlay:!0,playsInline:!0,children:e("source",{src:i===w.Male?x.male.right:x.female.right,type:"video/mp4"})})}),e("div",{className:` w-[120px] overflow-hidden ${3===a?"opacity-100":"opacity-0 hidden"} `,children:e("video",{className:"h-full w-full object-contain border-none",muted:!0,loop:!0,autoPlay:!0,playsInline:!0,children:e("source",{src:i===w.Male?x.male.smile:x.female.smile,type:"video/mp4"})})})]})]})})}const G=({webcamRef:n,canvasRef:o})=>{const{isError:r,isSuccess:c,showLoader:i,hasError:l,resetScanState:d,showGuideCard:u,scanStage:f,videoLoading:g,setVideoLoading:p,videoError:y,setVideoError:S,gender:b,getButtonText:w,isScanning:v,startScan:x,isModelLoaded:_,onRetry:I}=s(F),k=h();return r?e(q,{onRetry:I}):c?e("div",{className:"fixed z-[9] common-ui-main w-full h-full",style:{background:k?.style?.base?.backgroundColor},children:e(N,{url:k?.loader,loaderType:"black"})}):t(a,{children:[e("audio",{id:"audioElement",crossOrigin:"anonymous",preload:"auto",style:{position:"absolute",zIndex:-99999},src:void 0}),i&&!l&&e("div",{className:"fixed z-[9] common-ui-main w-full h-full",style:{background:k?.style?.base?.backgroundColor},children:e(N,{url:k?.loader,loaderType:"black"})}),e("div",{className:"h-full flex-col common-ui-main relative w-full flex justify-center items-center text-center rounded-t-[20px]",style:{background:k?.style?.base?.backgroundColor},children:e("div",{className:"flex-1 w-full max-w-md overflow-hidden",children:t("div",{className:"w-full h-full",children:[e("video",{ref:n,autoPlay:!0,playsInline:!0,muted:!0,width:m.width.ideal,height:m.height.ideal,className:"w-full h-full object-cover fixed left-0 top-0 z-0",style:{transform:"scaleX(-1)"}}),e("canvas",{ref:o,width:m.width.ideal,height:m.height.ideal,style:{transform:"scaleX(-1)",opacity:"0"}})]})})}),!i&&l&&e(q,{loading:i,onRetry:d}),u&&!l&&!i&&e(W,{open:!0,className:"face-scan-small camera-draw",anchor:"bottom",onClose:(e,t)=>{},hideBackdrop:!0,children:e(J,{stage:f,videoLoading:g,setVideoLoading:p,videoError:y,setVideoError:S,gender:b,btnConfig:{label:w(),onClick:v?d:x,isDisabled:i||!_,icon:e(v?O:a,{})}})})]})},K=t=>{const{onScanSuccess:a,onScanError:s,onRetry:l,onScanStart:m,onCaptureComplete:f,onUploadStart:h,onUploadEnd:g,onMeasurementSocketStart:y,onMeasurementSocketClose:S,config:b,isError:w,isSuccess:v}=t,x=t.userDetails??{email:"",gender:"male",deviceFocalLength:0,shopDomain:"",bodyScanId:""},N=t.token??"",O=n(null),W=n(null),U=n(null),B=n([]),q=n(null),J=n(null),[K,H]=o(!1),[X,Q]=o(!1),[Y,Z]=o(!1),[ee,te]=o(!0),[ae,ne]=o(!1),[oe,re]=o(!1),[ce,ie]=o(!1),[se,le]=o(_()),de=r(()=>I(N),[N]),{email:ue,gender:me,deviceFocalLength:fe,shopDomain:he,callbackUrl:ge,bodyScanId:pe}=x,[ye,Se]=o([]),[be,we]=o(k),ve=r(()=>M(),[]),xe=C(ye),Fe=D(xe);E();const Ne=c(()=>{console.log("Stopping recording..."),U.current&&"recording"===U.current.state&&U.current.stop(),U.current=null},[]),_e=async()=>{if(f?.(),B.current){if(0===B.current.length)return console.error("No video data recorded"),ie(!0),void H(!1);h?.(),H(!0);const e=new File(B.current,`${se}.${Fe}`,{type:xe}),t=J.current??await L(e),a=e.size,n=(a/1048576).toFixed(2),o=Math.round(a/1e4),r={video_size_mb:parseFloat(n),video_size_bytes:a,video_fps:t||0,blob_count:B.current.length,estimated_duration_seconds:o},c=[{gender:me},{face_scan_id:se},{focal_length:`${fe}`},{customer_store_url:he},{scan_type:"face_scan"},{body_scan_id:pe}];ge&&c.push({callback_url:ge}),j({eventName:`${he}/face_scan_meta_data`,faceScanId:se,email:ue,data:JSON.stringify({metaData:c,videoData:r})});const i=Date.now();j({eventName:`${he}/face_scan_upload_start`,faceScanId:se,email:ue,startTime:i});try{const t=await de.fileUpload.faceScanFileUploader({file:e,arrayMetaData:c,objectKey:se,email:ue,contentType:e.type}),a=Date.now();j({eventName:`${he}/face_scan_upload_complete`,faceScanId:se,email:ue,completionTime:a,uploadDuration:a-i}),g?.(),console.log("✅ Upload successful",t),de.measurement.handlFaceScaneSocket({onPreopen:()=>{y?.(),V({eventName:`${he}/webSocket`,faceScanID:se,connection:"pre_open",type:"faceScan_recommendation",email:ue})},faceScanId:se,onOpen:()=>{V({eventName:`${he}/webSocket`,faceScanID:se,connection:"open",type:"faceScan_recommendation",email:ue}),console.log("websocket connect open")},onError:e=>{V({eventName:`${he}/webSocket`,faceScanID:se,connection:"error",type:"faceScan_recommendation",email:ue}),ze(e)},onSuccess:e=>{V({eventName:`${he}/webSocket`,faceScanID:se,connection:"success",type:"faceScan_recommendation",email:ue}),$e(e)},onClose:()=>{S?.(),console.log("websocket connect close"),V({eventName:`${he}/webSocket`,faceScanID:se,connection:"close",type:"faceScan_recommendation",email:ue})}})}catch(e){g?.(),ze(e)}}},Ie=c(()=>{const e=O.current?.srcObject;if(!e)return;const t=e.getVideoTracks()[0].getSettings(),{width:a=1280,height:n=720}=t,o=document.createElement("canvas"),r=o.getContext("2d");a>n?(o.width=n,o.height=a):(o.width=a,o.height=n);const c=document.createElement("video");c.srcObject=e,c.muted=!0,c.playsInline=!0,c.play();const i=()=>{a>n?(r?.save(),r?.translate(o.width,0),r?.rotate(Math.PI/2),r?.drawImage(c,0,0,n,a),r?.restore()):r?.drawImage(c,0,0,a,n),requestAnimationFrame(i)};i();const s=t.frameRate??10;J.current=s;const l=o.captureStream(s),d={videoBitsPerSecond:15e5};let u;ye.length>0&&(d.mimeType=ye[0]);try{u=new MediaRecorder(l,d)}catch(e){return console.error("MediaRecorder init failed:",e),ie(!0),void H(!1)}B.current=[],u.ondataavailable=e=>{e?.data&&e.data.size>0&&B.current&&B.current.push(e.data)},u.onstop=()=>{console.log("Recording stopped, total blobs:",B?.current?.length),_e()},u.start(100),U.current=u,console.log("Recording started successfully (portrait normalized)")},[ye,_e]),{faceScanDetector:ke,scanStage:Me,setScanStage:Ce,resetScan:De,isModelLoaded:Ee,startScanSequence:Pe}=A({faceScanId:se,shopDomain:he,isError:w,isSuccess:v,onScanComplete:()=>{Ne()},onModelReady:()=>{Q(!0)},onStartRecording:()=>{console.log("Stage 0 completed - starting recording for stages 1-3"),Ie()}}),Te=c(()=>{Ee&&(m?.(),Ce(0),d.playAudio(`${u}face-scan-vos/Face-forward.mp3`),setTimeout(()=>{Z(!0),setTimeout(()=>{Pe()},200)},200))},[Ce,Z,Pe,Ee,m]),Re=c(()=>{Z(!1),te(!0),Ne(),De(),l?.(),B.current=[],J.current=null,U.current&&(U.current=null),ie(!1),Ce(-1),le(_()),O.current&&q.current&&(O.current.srcObject=q.current,console.log("Camera stream restored after reset"))},[Ce,Z,te,Ne,De,le]),ze=e=>{console.log(e,"ws error"),s?.(e),ie(!0),H(!1),te(!1),j({eventName:`${he}/faceScan`,faceScanId:se,status:"failed",email:ue,data:JSON.stringify(e)})},$e=e=>{console.log(e,"ws success"),e&&"intermediate"===e?.resultType&&j({eventName:`${he}/faceScan_success/intermediate`,faceScanId:se,status:"success",email:ue,data:JSON.stringify(e)}),a?.(e)};i(()=>{if(!w&&!v)return navigator.mediaDevices.getUserMedia&&navigator.mediaDevices.getUserMedia({video:be}).then(e=>{q.current=e,O.current&&(O.current.srcObject=e)}).catch(e=>{console.error("Error accessing webcam:",e),be!==k?ie(!0):we(P)}),()=>{q.current&&q.current.getTracks().forEach(e=>e.stop())}},[w,v,be]),i(()=>{if(!X||!Y)return;const e=setInterval(()=>{ke(O,W)},500);return()=>clearInterval(e)},[ke,X,Y]);return console.log("Model ready:",X,"Has error:",ce,"Is scanning:",Y,"showLoader",K),i(()=>{const e=T(ve,R);Se(e)},[ve]),i(()=>{Ce(-1)},[]),e("div",{"data-face-scan-stage":Me,children:e(z,{children:e($,{config:b,children:e(F.Provider,{value:{isError:w,isSuccess:v,showLoader:K,hasError:ce,resetScanState:Re,showGuideCard:ee,scanStage:Me,videoLoading:ae,setVideoLoading:ne,videoError:oe,setVideoError:re,gender:me,getButtonText:()=>Y?p.reset:Ee?p.start:p.loading,isScanning:Y,startScan:Te,isModelLoaded:Ee,onRetry:l},children:e(G,{webcamRef:O,canvasRef:W})})})})})};export{K as F};
2
- //# sourceMappingURL=FaceScan-BWSeJEqI.js.map