@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.
- package/dist/BodyScan-CCRXkFFL.mjs +3 -0
- package/dist/BodyScan-CCRXkFFL.mjs.map +1 -0
- package/dist/BodyScan-RBxSYdGc.js +3 -0
- package/dist/BodyScan-RBxSYdGc.js.map +1 -0
- package/dist/FaceScan-DQvhrp3K.mjs +3 -0
- package/dist/FaceScan-DQvhrp3K.mjs.map +1 -0
- package/dist/{FaceScan-BRdpV_Yn.js → FaceScan-Dva9De8x.js} +3 -2
- package/dist/{FaceScan-BRdpV_Yn.js.map → FaceScan-Dva9De8x.js.map} +1 -1
- package/dist/{Modal-BPtRtRVC.js → Modal-CZgyeNwW.mjs} +3 -2
- package/dist/Modal-CZgyeNwW.mjs.map +1 -0
- package/dist/{Modal-HTYYx7sM.js → Modal-CmbYIXgn.js} +3 -2
- package/dist/{Modal-YZScjwEm.js.map → Modal-CmbYIXgn.js.map} +1 -1
- package/dist/bodyScan.d.ts +2 -2
- package/dist/bodyScan.js +2 -1
- package/dist/bodyScan.mjs +2 -1
- package/dist/faceScan.js +2 -1
- package/dist/faceScan.mjs +2 -1
- package/dist/index.css +1 -1
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +2 -1
- package/dist/index.mjs.map +1 -1
- package/dist/{pose-detection.esm-Bc8T4UAD.js → pose-detection.esm-DFB9u8DH.js} +2 -1
- package/dist/{pose-detection.esm-Bc8T4UAD.js.map → pose-detection.esm-DFB9u8DH.js.map} +1 -1
- package/dist/{pose-detection.esm-DC0_P6R7.js → pose-detection.esm-EvS-BndH.mjs} +2 -1
- package/dist/pose-detection.esm-EvS-BndH.mjs.map +1 -0
- package/package.json +3 -2
- package/dist/BodyScan-3YoMZG7n.js +0 -2
- package/dist/BodyScan-8qgqyl5-.js +0 -2
- package/dist/BodyScan-B0qqqK3C.js +0 -2
- package/dist/BodyScan-B1VBoA6S.js +0 -2
- package/dist/BodyScan-B1afPG1Q.js +0 -2
- package/dist/BodyScan-B1afPG1Q.js.map +0 -1
- package/dist/BodyScan-B4-sO3R2.js +0 -2
- package/dist/BodyScan-B87W6dpH.js +0 -2
- package/dist/BodyScan-B8pglBAp.js +0 -2
- package/dist/BodyScan-BEFwluXG.js +0 -2
- package/dist/BodyScan-BHgnqB6A.js +0 -2
- package/dist/BodyScan-BLvWlYnA.js +0 -2
- package/dist/BodyScan-BMAkl5Iw.js +0 -2
- package/dist/BodyScan-BMTK6e-E.js +0 -2
- package/dist/BodyScan-BQri8pAO.js +0 -2
- package/dist/BodyScan-BVNPC7bJ.js +0 -2
- package/dist/BodyScan-BfLKF5PU.js +0 -2
- package/dist/BodyScan-BjYHCskz.js +0 -2
- package/dist/BodyScan-BoAbG01d.js +0 -2
- package/dist/BodyScan-Bq64fsmL.js +0 -2
- package/dist/BodyScan-Bre1BIHK.js +0 -2
- package/dist/BodyScan-BsDJmy0G.js +0 -2
- package/dist/BodyScan-ByMGumuH.js +0 -2
- package/dist/BodyScan-C0V-EDdB.js +0 -2
- package/dist/BodyScan-C1dWJ2qu.js +0 -2
- package/dist/BodyScan-C43x2o2T.js +0 -2
- package/dist/BodyScan-C57PuQgF.js +0 -2
- package/dist/BodyScan-C9hQU-dK.js +0 -2
- package/dist/BodyScan-CA4rNyqL.js +0 -2
- package/dist/BodyScan-CH-_x55M.js +0 -2
- package/dist/BodyScan-CKH_WyTt.js +0 -2
- package/dist/BodyScan-CKmPcrkx.js +0 -2
- package/dist/BodyScan-CLpL3Uwx.js +0 -2
- package/dist/BodyScan-CM12T_-T.js +0 -2
- package/dist/BodyScan-CNhb6UOX.js +0 -2
- package/dist/BodyScan-CWsaPB8W.js +0 -2
- package/dist/BodyScan-CXwtxfOd.js +0 -2
- package/dist/BodyScan-CYn7eLoz.js +0 -2
- package/dist/BodyScan-CYnHFqsR.js +0 -2
- package/dist/BodyScan-CZTiQzpy.js +0 -2
- package/dist/BodyScan-Cc68SnU1.js +0 -2
- package/dist/BodyScan-CfS4bPCN.js +0 -2
- package/dist/BodyScan-CiG19l_n.js +0 -2
- package/dist/BodyScan-CjvyMLT9.js +0 -2
- package/dist/BodyScan-CkmrPAq9.js +0 -2
- package/dist/BodyScan-CoObDhac.js +0 -2
- package/dist/BodyScan-Cyfo46EK.js +0 -2
- package/dist/BodyScan-Cz9ggKm6.js +0 -2
- package/dist/BodyScan-D6Y_W5e2.js +0 -2
- package/dist/BodyScan-DCEgmVbG.js +0 -2
- package/dist/BodyScan-DEDdENv7.js +0 -2
- package/dist/BodyScan-DEdrK-ld.js +0 -2
- package/dist/BodyScan-DHMf2V5R.js +0 -2
- package/dist/BodyScan-DK9UmNBr.js +0 -2
- package/dist/BodyScan-DPCd26i-.js +0 -2
- package/dist/BodyScan-DPCd26i-.js.map +0 -1
- package/dist/BodyScan-DPSQ1hKh.js +0 -2
- package/dist/BodyScan-DVKnmJuJ.js +0 -2
- package/dist/BodyScan-DX_KbG5U.js +0 -2
- package/dist/BodyScan-DbfP9-G3.js +0 -2
- package/dist/BodyScan-DeBJWo0L.js +0 -2
- package/dist/BodyScan-DgZpiChn.js +0 -2
- package/dist/BodyScan-DkPwUgVu.js +0 -2
- package/dist/BodyScan-DntA0MBx.js +0 -2
- package/dist/BodyScan-DxidLEhk.js +0 -2
- package/dist/BodyScan-DyDxGqfI.js +0 -2
- package/dist/BodyScan-Dysj7b77.js +0 -2
- package/dist/BodyScan-DzyamZmb.js +0 -2
- package/dist/BodyScan-Ehsr_cYc.js +0 -2
- package/dist/BodyScan-MSB66I12.js +0 -2
- package/dist/BodyScan-Ot6nAH1j.js +0 -2
- package/dist/BodyScan-Srq29PK8.js +0 -2
- package/dist/BodyScan-SzaquTgH.js +0 -2
- package/dist/BodyScan-TPpfyief.js +0 -2
- package/dist/BodyScan-XW2vsiE3.js +0 -2
- package/dist/BodyScan-eUuIC3jY.js +0 -2
- package/dist/BodyScan-enDyqSjO.js +0 -2
- package/dist/BodyScan-iOXndWaO.js +0 -2
- package/dist/BodyScan-qVHOWabf.js +0 -2
- package/dist/BodyScan-t9qdQAL-.js +0 -2
- package/dist/BodyScan-twE2YOwy.js +0 -2
- package/dist/BodyScan-z6h5fueJ.js +0 -2
- package/dist/FaceScan-3rVSqkKB.js +0 -2
- package/dist/FaceScan-6Aoz5uUy.js +0 -2
- package/dist/FaceScan-7fl5pLnb.js +0 -2
- package/dist/FaceScan-9kUfXRSv.js +0 -2
- package/dist/FaceScan-AHZ-ajep.js +0 -2
- package/dist/FaceScan-B0pFv4Us.js +0 -2
- package/dist/FaceScan-BE0PB0fZ.js +0 -2
- package/dist/FaceScan-BWSeJEqI.js +0 -2
- package/dist/FaceScan-BdjT7nMG.js +0 -2
- package/dist/FaceScan-Bji5lGcQ.js +0 -2
- package/dist/FaceScan-Bji5lGcQ.js.map +0 -1
- package/dist/FaceScan-BmDNM8tt.js +0 -2
- package/dist/FaceScan-CNoW9DIE.js +0 -2
- package/dist/FaceScan-CPf6-siO.js +0 -2
- package/dist/FaceScan-CQayY4q-.js +0 -2
- package/dist/FaceScan-CQkfSMC2.js +0 -2
- package/dist/FaceScan-CaxQ6fGF.js +0 -2
- package/dist/FaceScan-CxDcvM4f.js +0 -2
- package/dist/FaceScan-D2PL8KpZ.js +0 -2
- package/dist/FaceScan-D3T_l4nN.js +0 -2
- package/dist/FaceScan-DCm43Nrq.js +0 -2
- package/dist/FaceScan-DKP93c3l.js +0 -2
- package/dist/FaceScan-DW6Ix1a1.js +0 -2
- package/dist/FaceScan-DYJVZoZ4.js +0 -2
- package/dist/FaceScan-Da2XEApH.js +0 -2
- package/dist/FaceScan-DrW2yUSA.js +0 -2
- package/dist/FaceScan-DxnydFcx.js +0 -2
- package/dist/FaceScan-Gm4F4cO1.js +0 -2
- package/dist/FaceScan-Nhc7myLG.js +0 -2
- package/dist/FaceScan-VFLJ9h_T.js +0 -2
- package/dist/FaceScan-iUXyDuza.js +0 -2
- package/dist/LoadingScreen-BILrJVZm.js +0 -2
- package/dist/LoadingScreen-FKDLJRUj.js +0 -2
- package/dist/Modal-4T_aWWPQ.js +0 -2
- package/dist/Modal-BHfJVhRi.js +0 -2
- package/dist/Modal-BitizIvu.js +0 -2
- package/dist/Modal-BpgpPVxR.js +0 -2
- package/dist/Modal-BzH-_ch3.js +0 -2
- package/dist/Modal-CB_MHF7l.js +0 -2
- package/dist/Modal-CDiBoVXR.js +0 -2
- package/dist/Modal-CWoUZTh4.js +0 -2
- package/dist/Modal-CaPtqgjI.js +0 -2
- package/dist/Modal-CbZJwbLZ.js +0 -2
- package/dist/Modal-DRjJKUrw.js +0 -2
- package/dist/Modal-DU2Jymve.js +0 -2
- package/dist/Modal-D_XGokez.js +0 -2
- package/dist/Modal-DnweWp6L.js +0 -2
- package/dist/Modal-Do--CErH.js +0 -2
- package/dist/Modal-Do--CErH.js.map +0 -1
- package/dist/Modal-YZScjwEm.js +0 -2
- package/dist/fonts/Switzer-Regular.eot +0 -0
- package/dist/fonts/Switzer-Regular.svg +0 -0
- package/dist/fonts/Switzer-Regular.ttf +0 -0
- package/dist/fonts/Switzer-Regular.woff +0 -0
- package/dist/fonts/Switzer-Regular.woff2 +0 -0
- package/dist/interfaces-B5ysRXpa.d.ts +0 -209
- package/dist/interfaces-CaaERZjZ.d.ts +0 -209
- package/dist/pose-detection.esm-D08ZA0zl.js +0 -18
- package/dist/pose-detection.esm-DejsYGYM.js +0 -18
- package/dist/pose-detection.esm-DejsYGYM.js.map +0 -1
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";var e=require("react/jsx-runtime"),t=require("react"),a=require("./Modal-DnweWp6L.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-BdjT7nMG.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-Do--CErH.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-Bji5lGcQ.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"FaceScan-Bji5lGcQ.js","sources":["../src/customHooks/useFaceScan.ts","../src/components/faceScan/FaceScanErrorScreen.tsx","../src/components/faceScan/FaceScanGuide.tsx","../src/components/faceScan/FaceScanStep.tsx","../src/components/faceScan/FaceScan.tsx"],"sourcesContent":["import {\n useState,\n useRef,\n useEffect,\n useCallback,\n useMemo,\n RefObject,\n} from \"react\";\n// 1. Use TYPE-ONLY imports. These are erased at build time and won't crash SSR.\nimport type { PoseDetector } from \"@tensorflow-models/pose-detection\";\nimport posthog from \"../utils/posthog\";\nimport speechService from \"../utils/service/speechService\";\nimport { videoConstraints, voiceOverAssetsPath } from \"../utils/constants\";\n\n/**\n * useFaceScan Hook with PostHog Analytics\n * Refactored for Zero-Config SSR/CSR Compatibility\n */\n\n// Debounce utility\nfunction debounce(fn: (...args: any) => void, delay: number) {\n let timer: ReturnType<typeof setTimeout>;\n return (...args: any) => {\n if (timer) clearTimeout(timer);\n timer = setTimeout(() => fn(...args), delay);\n };\n}\n\n// Global Singleton Cache (Preserves state across re-renders)\nlet preloadedDetector: PoseDetector | null = null;\nlet isPreloading = false;\n\n// 2. Async Preloader with Dynamic Imports\nexport const preloadDetector = async (): Promise<PoseDetector | null> => {\n // Guard: Never run on server\n if (typeof window === \"undefined\") return null;\n if (preloadedDetector) return preloadedDetector;\n if (isPreloading) {\n // Simple wait mechanism if already loading\n while (isPreloading) {\n await new Promise(r => setTimeout(r, 100));\n if (preloadedDetector) return preloadedDetector;\n }\n }\n\n isPreloading = true;\n\n try {\n // DYNAMIC IMPORTS: Only fetch these heavy bundles in the browser\n const [tf, poseDetection] = await Promise.all([\n import(\"@tensorflow/tfjs\"),\n import(\"@tensorflow-models/pose-detection\")\n ]);\n\n // Initialize Backend\n await tf.setBackend(\"webgl\");\n await tf.ready();\n\n const detector = await poseDetection.createDetector(\n poseDetection.SupportedModels.BlazePose,\n {\n runtime: \"tfjs\",\n modelType: \"full\",\n }\n );\n\n // Dummy video warmup (Performance Optimization)\n // This runs the model once on a blank canvas to \"wake up\" the GPU\n // so the first user frame detects instantly.\n const dummyCanvas = document.createElement(\"canvas\");\n dummyCanvas.width = typeof videoConstraints.width === \"number\" ? videoConstraints.width : videoConstraints.width.ideal ?? videoConstraints.width.max ?? 1280;\n dummyCanvas.height = typeof videoConstraints.height === \"number\" ? videoConstraints.height : videoConstraints.height.ideal ?? videoConstraints.height.max ?? 720;\n const ctx = dummyCanvas.getContext(\"2d\");\n if (ctx) {\n ctx.fillStyle = \"black\";\n ctx.fillRect(0, 0, dummyCanvas.width, dummyCanvas.height);\n try {\n await detector.estimatePoses(dummyCanvas);\n } catch (e) {\n console.warn(\"Warmup frame failed (non-fatal):\", e);\n }\n }\n\n preloadedDetector = detector;\n return detector;\n } catch (err) {\n console.error(\"Failed to preload detector:\", err);\n return null;\n } finally {\n isPreloading = false;\n }\n};\n\ntype Point = [number, number, number];\n\nfunction useFaceScan({\n faceScanId,\n onValidPose,\n onScanComplete,\n onModelReady,\n onStartRecording,\n shopDomain,\n isError,\n isSuccess,\n}: {\n faceScanId: string;\n onValidPose?: () => void;\n onScanComplete?: () => void;\n onModelReady?: () => void;\n onStartRecording: () => void;\n shopDomain: string;\n isError?: boolean;\n isSuccess?: boolean;\n}) {\n const detectorRef = useRef<PoseDetector | null>(null);\n const [scanStage, setScanStage] = useState(0);\n const [consecutiveValid, setConsecutiveValid] = useState(0);\n const [isModelLoaded, setIsModelLoaded] = useState(false);\n const [isScanningActive, setIsScanningActive] = useState(false);\n const isInferencingRef = useRef(false);\n // Persistent offscreen canvas for inference input.\n // tf.browser.fromPixels(videoElement) calls gl.texImage2D with the video,\n // which returns black frames on SwiftShader (headless CI) because video decoded\n // frames aren't in SW-composited memory. Drawing to a canvas first makes the\n // pixels CPU-accessible so SwiftShader can read them correctly.\n const inferenceCanvasRef = useRef<HTMLCanvasElement | null>(null);\n \n const utteranceRef = useRef<SpeechSynthesisUtterance | null>(null);\n const scanStageRef = useRef(scanStage);\n const consecutiveValidRef = useRef(consecutiveValid);\n const validityBufferRef = useRef<boolean[]>([]);\n const lastSpokenMessageRef = useRef(\"\");\n const lastSpokenTimeRef = useRef(0);\n const voiceEnabledRef = useRef(false);\n \n const VALIDITY_BUFFER_LENGTH = 10;\n const CONSECUTIVE_VALID_LENGTH = 2;\n const TOTAL_STAGES = 4;\n const POSE_TRACKING_INTERVAL = 4000;\n const lastPoseTrackingTimeRef = useRef(0);\n\n // Safe iOS detection (SSR safe)\n const isIOS = typeof navigator !== 'undefined' && (\n /iPad|iPhone|iPod/.test(navigator.userAgent) ||\n (navigator.platform === \"MacIntel\" && navigator.maxTouchPoints > 1)\n );\n\n const directionMessages = useMemo(\n () => [\n \"Face front\",\n \"Turn head fully left\",\n \"Turn head fully right\",\n \"Smile facing front\",\n ],\n []\n );\n\n const debouncedTrackPoseDetection = useMemo(\n () =>\n debounce((payload) => {\n posthog.capture(`${shopDomain}/face_scan_pose_detection`, payload);\n }, 4000),\n [shopDomain]\n );\n\n const trackPoseDetection = useCallback(\n (\n faceKeypoints: Point[],\n bodyKeypoints: Point[],\n stage: number,\n headValid: boolean,\n bodyInvalid: boolean,\n consecutiveValidCount: number\n ) => {\n const now = Date.now();\n if (now - lastPoseTrackingTimeRef.current < POSE_TRACKING_INTERVAL) {\n return;\n }\n\n lastPoseTrackingTimeRef.current = now;\n\n try {\n const nose = faceKeypoints[0] || [0, 0, 0];\n const leftEye = faceKeypoints[2] || [0, 0, 0];\n const rightEye = faceKeypoints[5] || [0, 0, 0];\n const leftMouth = faceKeypoints[9] || [0, 0, 0];\n const rightMouth = faceKeypoints[10] || [0, 0, 0];\n\n const faceKeypointScores = faceKeypoints\n .map((kp: Point) => kp[2])\n .filter((score: number) => score > 0);\n const avgFaceScore =\n faceKeypointScores.length > 0\n ? faceKeypointScores.reduce((a, b) => a + b, 0) /\n faceKeypointScores.length\n : 0;\n\n const bodyKeypointScores = bodyKeypoints\n .map((kp: Point) => kp[2])\n .filter((score: number) => score > 0);\n const avgBodyScore =\n bodyKeypointScores.length > 0\n ? bodyKeypointScores.reduce((a: number, b: number) => a + b, 0) /\n bodyKeypointScores.length\n : 0;\n\n const eyeDistance = Math.abs(leftEye[0] - rightEye[0]);\n const noseToRight = nose[0] - rightEye[0];\n const noseToLeft = leftEye[0] - nose[0];\n\n let expectedPosition = \"frontal\";\n if (stage === 1) expectedPosition = \"left\";\n else if (stage === 2) expectedPosition = \"right\";\n else if (stage === 3) expectedPosition = \"frontal_smile\";\n\n const payload = {\n faceScanId,\n stage,\n timestamp: new Date().toISOString(),\n data: JSON.stringify({\n headValid,\n bodyInvalid,\n consecutiveValid: consecutiveValidCount,\n avgFaceScore: parseFloat(avgFaceScore.toFixed(3)),\n avgBodyScore: parseFloat(avgBodyScore.toFixed(3)),\n faceKeypointsDetected: faceKeypointScores.length,\n bodyKeypointsDetected: bodyKeypointScores.length,\n eyeDistance: parseFloat(eyeDistance.toFixed(2)),\n noseToRightRatio: parseFloat((noseToRight / eyeDistance).toFixed(3)),\n noseToLeftRatio: parseFloat((noseToLeft / eyeDistance).toFixed(3)),\n noseScore: parseFloat(nose[2].toFixed(3)),\n leftEyeScore: parseFloat(leftEye[2].toFixed(3)),\n rightEyeScore: parseFloat(rightEye[2].toFixed(3)),\n leftMouthScore: parseFloat(leftMouth[2].toFixed(3)),\n rightMouthScore: parseFloat(rightMouth[2].toFixed(3)),\n expectedPosition,\n }),\n };\n debouncedTrackPoseDetection(payload);\n } catch (error) {\n console.warn(\"Failed to track pose detection:\", error);\n }\n },\n [faceScanId, debouncedTrackPoseDetection]\n );\n\n const enableVoiceCommands = () => {\n voiceEnabledRef.current = true;\n if (typeof window !== 'undefined' && isIOS && \"speechSynthesis\" in window) {\n const silentUtterance = new SpeechSynthesisUtterance(\"\");\n silentUtterance.volume = 0;\n speechSynthesis.speak(silentUtterance);\n }\n };\n\n const startScanSequence = () => {\n posthog.capture(`${shopDomain}/face_scan_detection_started`, {\n faceScanId,\n stage: scanStageRef.current,\n timestamp: new Date().toISOString(),\n stageName: directionMessages[scanStageRef.current],\n });\n\n setTimeout(() => {\n setIsScanningActive(true);\n }, 1500);\n };\n\n const isHeadInPosition = (stage: number, keypoints: Point[]) => {\n // ... logic unchanged ...\n const nose = 0;\n const leftEye = 2;\n const rightEye = 5;\n const leftMouth = 9;\n const rightMouth = 10;\n\n const minScore = 0.2;\n if (\n !keypoints[nose] || !keypoints[leftEye] || !keypoints[rightEye] ||\n keypoints[nose][2] < minScore ||\n keypoints[leftEye][2] < minScore ||\n keypoints[rightEye][2] < minScore\n ) {\n return false;\n }\n\n const eyesToMouthVerticalDistance =\n 0.5 * (keypoints[rightMouth][1] + keypoints[leftMouth][1]) -\n 0.5 * (keypoints[rightEye][1] + keypoints[leftEye][1]);\n\n const faceTiltedness =\n (0.5 * (keypoints[rightMouth][1] + keypoints[leftMouth][1]) -\n keypoints[nose][1]) /\n eyesToMouthVerticalDistance;\n\n const faceIsTilted = faceTiltedness > 0.7 || faceTiltedness < 0.3;\n\n const faceIsVertical =\n Math.abs(keypoints[leftEye][1] - keypoints[rightEye][1]) <\n 0.5 * eyesToMouthVerticalDistance &&\n Math.abs(keypoints[leftMouth][1] - keypoints[rightMouth][1]) <\n 0.5 * eyesToMouthVerticalDistance;\n\n const eyeDistance = keypoints[leftEye][0] - keypoints[rightEye][0];\n const noseToRight = keypoints[nose][0] - keypoints[rightEye][0];\n const noseToLeft = keypoints[leftEye][0] - keypoints[nose][0];\n\n const frontalFace =\n noseToRight > 0.4 * eyeDistance && noseToRight < 0.6 * eyeDistance;\n const fullLeft = noseToRight > 0.85 * eyeDistance;\n const fullRight = noseToLeft > 0.85 * eyeDistance;\n\n switch (stage) {\n case 0:\n return !faceIsTilted && faceIsVertical && frontalFace;\n case 1:\n return !faceIsTilted && faceIsVertical && fullLeft;\n case 2:\n return !faceIsTilted && faceIsVertical && fullRight;\n case 3:\n return !faceIsTilted && faceIsVertical && frontalFace;\n default:\n return false;\n }\n };\n\n const faceScanDetector = async (\n webcamRef: RefObject<HTMLVideoElement | null>,\n canvasRef: RefObject<HTMLCanvasElement | null>\n ) => {\n if (\n !detectorRef.current ||\n !webcamRef.current ||\n !isModelLoaded ||\n !isScanningActive\n )\n return;\n\n // Safety: ensure video is actually playing with data\n if (webcamRef.current.readyState < 2) return;\n\n // Prevent concurrent inference calls — important on slow GPUs (SwiftShader/CI)\n // where a single estimatePoses() can take longer than the 500ms interval.\n if (isInferencingRef.current) return;\n isInferencingRef.current = true;\n\n try {\n const vw = webcamRef.current.videoWidth || 720;\n const vh = webcamRef.current.videoHeight || 1280;\n if (!inferenceCanvasRef.current) {\n inferenceCanvasRef.current = document.createElement(\"canvas\");\n inferenceCanvasRef.current.width = vw;\n inferenceCanvasRef.current.height = vh;\n }\n const ictx = inferenceCanvasRef.current.getContext(\"2d\");\n if (ictx) ictx.drawImage(webcamRef.current, 0, 0, vw, vh);\n const poses = await detectorRef.current.estimatePoses(\n ictx ? inferenceCanvasRef.current : webcamRef.current\n );\n if (poses.length > 0) {\n const faceKeypoints: Point[] = [];\n const bodyKeypoints: Point[] = [];\n poses[0].keypoints.forEach((landmark, idx) => {\n const score = landmark.score ?? 0;\n const point: Point = [landmark.x ?? -1, landmark.y ?? -1, score];\n if (idx <= 10) faceKeypoints.push(point);\n else bodyKeypoints.push(point);\n });\n\n // Optional drawing\n if (canvasRef?.current) {\n const ctx = canvasRef.current.getContext(\"2d\");\n const { width, height } = canvasRef.current;\n if (ctx) {\n ctx.clearRect(0, 0, width, height);\n\n const progress = Math.min(\n consecutiveValidRef.current / CONSECUTIVE_VALID_LENGTH,\n 1\n );\n const radius = height * 0.35;\n ctx.beginPath();\n ctx.strokeStyle = \"#00ff00\";\n ctx.lineWidth = 6;\n ctx.arc(\n width / 2,\n height / 2,\n radius + 10,\n -Math.PI / 2,\n -Math.PI / 2 + progress * 2 * Math.PI\n );\n ctx.stroke();\n }\n }\n\n const headValid = isHeadInPosition(scanStageRef.current, faceKeypoints);\n const bodyInvalid =\n bodyKeypoints.slice(2).filter((p) => p[2] > 0.7).length <= 2;\n\n validityBufferRef.current.push(headValid && bodyInvalid);\n if (validityBufferRef.current.length > VALIDITY_BUFFER_LENGTH) {\n validityBufferRef.current.shift();\n }\n\n const validCount = validityBufferRef.current.filter(Boolean).length;\n if (validCount >= 2) {\n const nextValid = consecutiveValidRef.current + 1;\n setConsecutiveValid(nextValid);\n } else {\n setConsecutiveValid(Math.max(0, consecutiveValidRef.current - 1));\n }\n\n if (consecutiveValidRef.current >= CONSECUTIVE_VALID_LENGTH) {\n onValidPose?.();\n\n const nextStage = scanStageRef.current + 1;\n setConsecutiveValid(0);\n validityBufferRef.current = [];\n setScanStage(nextStage);\n setIsScanningActive(false);\n\n (async () => {\n await speechService.playAudio(\n `${voiceOverAssetsPath}face-scan-vos/Sound-effect.mp3`\n );\n posthog.capture(\n `${shopDomain}/face_scan_detection_stage_completed`,\n {\n faceScanId,\n completedStage: scanStageRef.current,\n nextStage,\n timestamp: new Date().toISOString(),\n totalStages: TOTAL_STAGES,\n stageName: directionMessages[scanStageRef.current],\n }\n );\n \n if (nextStage === 1 && onStartRecording) {\n onStartRecording();\n }\n if (nextStage >= TOTAL_STAGES) {\n onScanComplete?.();\n } else {\n let nextSound = null;\n switch (nextStage) {\n case 1: nextSound = \"Left.mp3\"; break;\n case 2: nextSound = \"Right.mp3\"; break;\n case 3: nextSound = \"Smile.mp3\"; break;\n }\n if (nextSound) {\n await speechService.playAudio(\n `${voiceOverAssetsPath}face-scan-vos/${nextSound}`\n );\n }\n startScanSequence();\n }\n })();\n }\n\n trackPoseDetection(\n faceKeypoints,\n bodyKeypoints,\n scanStageRef.current,\n headValid,\n bodyInvalid,\n consecutiveValidRef.current\n );\n }\n } catch (err) {\n console.error(\"Pose detection error:\", err);\n } finally {\n isInferencingRef.current = false;\n }\n };\n\n const initializeModels = async () => {\n // 3. Browser Guard\n if (typeof window === 'undefined') return;\n\n try {\n console.log(\"Initializing Face Scan...\");\n // Calls our safe, dynamic preloader\n const detector = await preloadDetector();\n \n if (detector) {\n detectorRef.current = detector;\n console.log(\"Face scan model loaded successfully\");\n setIsModelLoaded(true);\n onModelReady?.();\n }\n } catch (err) {\n console.error(\"Error initializing face scan:\", err);\n }\n };\n\n const disposeModelAndTf = async () => {\n // Optional: We might NOT want to dispose if we want to keep the cache \n // for re-mounting. But if you must dispose:\n try {\n setIsModelLoaded(false);\n // NOTE: We generally don't dispose the detector if we want to reuse it \n // via the 'preloadedDetector' global variable.\n // If you dispose here, make sure to set 'preloadedDetector = null' too.\n /* if (detectorRef.current) {\n await detectorRef.current.dispose();\n detectorRef.current = null;\n preloadedDetector = null; // Clear global cache if disposing\n }\n */\n } catch (err) {\n console.error(\"Error disposing resources:\", err);\n } finally {\n // Reset state\n setScanStage(0);\n setConsecutiveValid(0);\n scanStageRef.current = 0;\n consecutiveValidRef.current = 0;\n validityBufferRef.current = [];\n }\n };\n\n const resetScan = () => {\n posthog.capture(`${shopDomain}/face_scan_reset`, {\n faceScanId,\n stage: scanStageRef.current,\n timestamp: new Date().toISOString(),\n stageName: directionMessages[scanStageRef.current],\n consecutiveValid: consecutiveValidRef.current,\n });\n\n setScanStage(0);\n setConsecutiveValid(0);\n setIsScanningActive(false);\n scanStageRef.current = 0;\n consecutiveValidRef.current = 0;\n validityBufferRef.current = [];\n lastSpokenMessageRef.current = \"\";\n lastSpokenTimeRef.current = 0;\n voiceEnabledRef.current = false;\n if (utteranceRef.current) {\n speechSynthesis.cancel();\n utteranceRef.current = null;\n }\n };\n\n useEffect(() => {\n if (isError || isSuccess) return;\n initializeModels();\n return () => {\n disposeModelAndTf();\n };\n }, [isError, isSuccess]);\n\n useEffect(() => {\n scanStageRef.current = scanStage;\n }, [scanStage]);\n\n useEffect(() => {\n consecutiveValidRef.current = consecutiveValid;\n }, [consecutiveValid]);\n\n return {\n faceScanDetector,\n scanStage,\n setScanStage,\n consecutiveValid,\n isModelLoaded,\n resetScan,\n enableVoiceCommands,\n startScanSequence,\n isScanningActive,\n };\n}\n\nexport default useFaceScan;","import { ArrowRight } from \"lucide-react\";\nimport Header from \"../Header\";\nimport SpecificButton from \"../../atoms/specificButton/SpecificButton\";\nimport { useContext } from \"react\";\nimport { LanguageKeys } from \"../../utils/languageKeys\";\nimport { LanguageContext } from \"../../utils/context/languageContext\";\nimport { useConfig } from \"../../utils/context/configContext\";\n\nfunction FaceScanErrorScreen({ onRetry, loading }: { onRetry?: () => void; loading?: boolean }) {\n\tconst { translate } = useContext(LanguageContext) || {};\n\tconst config = useConfig();\n\n\treturn (\n\t\t<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: config?.style?.base?.backgroundColor }}>\n\t\t\t<div className=\"flex flex-col w-full items-center p-[1rem] rounded-lg \">\n\t\t\t\t<Header noTitle />\n\t\t\t\t<div className=\"flex flex-col items-center w-full\">\n\t\t\t\t\t<h2\n\t\t\t\t\t\tclassName=\"text-xl font-semibold text-gray-800 \"\n\t\t\t\t\t\tstyle={{\n\t\t\t\t\t\t\tfontFamily: config?.style?.heading?.headingFontFamily || \"SeriouslyNostalgic Fn\",\n\t\t\t\t\t\t\tfontSize: config?.style?.heading?.headingFontSize || \"32px\",\n\t\t\t\t\t\t\tcolor: config?.style?.heading?.headingColor || \"#000\",\n\t\t\t\t\t\t\tfontWeight: config?.style?.heading?.headingFontWeight || \"normal\",\n\t\t\t\t\t\t}}\n\t\t\t\t\t>\n\t\t\t\t\t\t{translate?.(LanguageKeys.scanFailed)}\n\t\t\t\t\t</h2>\n\t\t\t\t\t<p\n\t\t\t\t\t\tclassName=\"mb-[1.5rem]\"\n\t\t\t\t\t\tstyle={{\n\t\t\t\t\t\t\tfontFamily: config?.style?.subheading?.subheadingFontFamily || \"'Inter', sans-serif\",\n\t\t\t\t\t\t\tfontSize: config?.style?.subheading?.subheadingFontSize || \"14px\",\n\t\t\t\t\t\t\tcolor: config?.style?.subheading?.subheadingColor || \"#4b5563\",\n\t\t\t\t\t\t\tfontWeight: config?.style?.subheading?.subheadingFontWeight || \"normal\",\n\t\t\t\t\t\t}}\n\t\t\t\t\t>\n\t\t\t\t\t\t{translate?.(LanguageKeys.clickToResetScan)}\n\t\t\t\t\t</p>\n\t\t\t\t\t<SpecificButton\n\t\t\t\t\t\tdata-testid=\"face-scan-retry-btn\"\n\t\t\t\t\t\tdisabled={loading}\n\t\t\t\t\t\tclassName=\"w-full h-[45px] shadow-[0px_1px_2px_0px_#00000040] text-[16px]\"\n\t\t\t\t\t\tbuttonText={translate?.(LanguageKeys.resetScan)}\n\t\t\t\t\t\tpostfixIcon={<ArrowRight />}\n\t\t\t\t\t\tbuttonFunc={() => onRetry?.()}\n\t\t\t\t\t/>\n\t\t\t\t</div>\n\t\t\t</div>\n\t\t</div>\n\t);\n}\n\nexport default FaceScanErrorScreen;\n","import Header from \"../Header\";\nimport { GenderType } from \"../../utils/enums\";\nimport { directionMessages, FACE_SCAN_HEADSHOT, glassesOffVideo, maleGlassesOffVideo } from \"../../utils/constants\";\nimport { LanguageContext } from \"../../utils/context/languageContext\";\nimport { useContext } from \"react\";\nimport SpecificButton from \"../../atoms/specificButton/SpecificButton\";\nimport { LanguageKeys } from \"../../utils/languageKeys\";\nimport { useConfig } from \"../../utils/context/configContext\";\nimport { Dispatch, ReactNode, SetStateAction } from \"react\";\nimport { Gender } from \"../../types/interfaces\";\n\ninterface IButtonConfig {\n\tisDisabled: boolean;\n\ticon?: ReactNode;\n\tonClick: () => void;\n\tlabel: string;\n}\n\ninterface FaceScanGuideProps {\n\tstage: number;\n\tvideoLoading: boolean;\n\tsetVideoLoading: Dispatch<SetStateAction<boolean>>;\n\tvideoError: boolean;\n\tsetVideoError: Dispatch<SetStateAction<boolean>>;\n\tgender: Gender;\n\tbtnConfig: IButtonConfig;\n}\n\nfunction FaceScanGuide({ stage, videoLoading, setVideoLoading, videoError, setVideoError, gender, btnConfig }: FaceScanGuideProps) {\n\tconst { translate } = useContext(LanguageContext) || {};\n\tconst config = useConfig();\n\n\tif (stage === -1) {\n\t\treturn (\n\t\t\t<div data-testid=\"face-scan-guide\" className=\"text-center common-ui-main p-[16px] w-full h-full\" style={{ background: config?.style?.base?.backgroundColor }}>\n\t\t\t\t<div className=\"w-full\">\n\t\t\t\t\t<Header noTitle />\n\t\t\t\t\t<h2\n\t\t\t\t\t\tstyle={{\n\t\t\t\t\t\t\tfontFamily: config?.style?.heading?.headingFontFamily || \"SeriouslyNostalgic Fn\",\n\t\t\t\t\t\t\tfontSize: config?.style?.heading?.headingFontSize || \"32px\",\n\t\t\t\t\t\t\tcolor: config?.style?.heading?.headingColor || \"#000\",\n\t\t\t\t\t\t\tfontWeight: config?.style?.heading?.headingFontWeight || \"normal\",\n\t\t\t\t\t\t}}\n\t\t\t\t\t>\n\t\t\t\t\t\t{translate?.(LanguageKeys.faceVisible)}\n\t\t\t\t\t</h2>\n\t\t\t\t\t{videoLoading && (\n\t\t\t\t\t\t<div\n\t\t\t\t\t\t\tclassName=\"mb-4 flex items-center justify-center\"\n\t\t\t\t\t\t\tstyle={{\n\t\t\t\t\t\t\t\tfontFamily: config?.style?.subheading?.subheadingFontFamily || \"'Inter', sans-serif\",\n\t\t\t\t\t\t\t\tfontSize: config?.style?.subheading?.subheadingFontSize || \"14px\",\n\t\t\t\t\t\t\t\tcolor: config?.style?.subheading?.subheadingColor || \"#4b5563\",\n\t\t\t\t\t\t\t\tfontWeight: config?.style?.subheading?.subheadingFontWeight || \"normal\",\n\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t{translate?.(LanguageKeys.loadingVideo)}\n\t\t\t\t\t\t</div>\n\t\t\t\t\t)}\n\t\t\t\t\t{videoError && (\n\t\t\t\t\t\t<div\n\t\t\t\t\t\t\tclassName=\"mb-4 text-red-600\"\n\t\t\t\t\t\t\tstyle={{\n\t\t\t\t\t\t\t\tfontFamily: config?.style?.subheading?.subheadingFontFamily || \"'Inter', sans-serif\",\n\t\t\t\t\t\t\t\tfontSize: config?.style?.subheading?.subheadingFontSize || \"14px\",\n\t\t\t\t\t\t\t\tcolor: \"#ff0000\",\n\t\t\t\t\t\t\t\tfontWeight: config?.style?.subheading?.subheadingFontWeight || \"normal\",\n\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t{translate?.(LanguageKeys.videoLoadFailed)}\n\t\t\t\t\t\t</div>\n\t\t\t\t\t)}\n\t\t\t\t\t{!videoError && (\n\t\t\t\t\t\t<div className={` w-[100px] mx-auto`}>\n\t\t\t\t\t\t\t<video\n\t\t\t\t\t\t\t\tsrc={gender === GenderType.Male ? maleGlassesOffVideo : glassesOffVideo}\n\t\t\t\t\t\t\t\tautoPlay\n\t\t\t\t\t\t\t\tloop\n\t\t\t\t\t\t\t\tcontrols={false}\n\t\t\t\t\t\t\t\tmuted\n\t\t\t\t\t\t\t\tplaysInline\n\t\t\t\t\t\t\t\tclassName=\"h-full w-full object-contain border-none\"\n\t\t\t\t\t\t\t\tonCanPlay={() => setVideoLoading(false)}\n\t\t\t\t\t\t\t\tonLoadStart={() => setVideoLoading(true)}\n\t\t\t\t\t\t\t\tonError={() => setVideoError(true)}\n\t\t\t\t\t\t\t\taria-label=\"Instructional video: Please remove your glasses before starting the scan.\"\n\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t)}\n\t\t\t\t</div>\n\t\t\t\t<div className=\"flex justify-center w-full p-[1rem]\">\n\t\t\t\t\t<SpecificButton\n\t\t\t\t\t\tdata-testid=\"face-scan-start-btn\"\n\t\t\t\t\t\tdisabled={btnConfig.isDisabled}\n\t\t\t\t\t\tclassName=\"!w-[60px] !h-[35px] !py-0 !px-0\"\n\t\t\t\t\t\tbuttonText={translate?.(btnConfig.label)}\n\t\t\t\t\t\tpostfixIcon={btnConfig?.icon}\n\t\t\t\t\t\tbuttonFunc={btnConfig.onClick}\n\t\t\t\t\t/>\n\t\t\t\t</div>\n\t\t\t</div>\n\t\t);\n\t}\n\n\treturn (\n\t\t<div className=\"text-center common-ui-main p-[16px] w-full h-full\" style={{ background: config?.style?.base?.backgroundColor }}>\n\t\t\t<div className=\"w-full\">\n\t\t\t\t<Header noTitle />\n\t\t\t\t<h3\n\t\t\t\t\tclassName=\"mb-[0.5rem]\"\n\t\t\t\t\tstyle={{\n\t\t\t\t\t\tfontFamily: config?.style?.heading?.headingFontFamily || \"SeriouslyNostalgic Fn\",\n\t\t\t\t\t\tfontSize: config?.style?.heading?.headingFontSize || \"32px\",\n\t\t\t\t\t\tcolor: config?.style?.heading?.headingColor || \"#000\",\n\t\t\t\t\t\tfontWeight: config?.style?.heading?.headingFontWeight || \"normal\",\n\t\t\t\t\t}}\n\t\t\t\t>\n\t\t\t\t\t{translate?.(directionMessages[stage])}\n\t\t\t\t</h3>\n\t\t\t\t<div className=\"max-w-[400px] justify-center gap-1 mx-auto flex items-center\">\n\t\t\t\t\t<div className={` w-[120px] overflow-hidden ${stage === 0 ? \"opacity-100\" : \"opacity-0 hidden\"} `}>\n\t\t\t\t\t\t<video className=\"h-full w-full object-contain border-none\" muted loop autoPlay playsInline>\n\t\t\t\t\t\t\t<source src={gender === GenderType.Male ? FACE_SCAN_HEADSHOT.male.forward : FACE_SCAN_HEADSHOT.female.forward} type=\"video/mp4\" />\n\t\t\t\t\t\t</video>\n\t\t\t\t\t</div>\n\t\t\t\t\t<div className={` w-[120px] overflow-hidden ${stage === 1 ? \"opacity-100\" : \"opacity-0 hidden\"} `}>\n\t\t\t\t\t\t<video className=\"h-full w-full object-contain border-none\" muted loop autoPlay playsInline>\n\t\t\t\t\t\t\t<source src={gender === GenderType.Male ? FACE_SCAN_HEADSHOT.male.left : FACE_SCAN_HEADSHOT.female.left} type=\"video/mp4\" />\n\t\t\t\t\t\t</video>\n\t\t\t\t\t</div>\n\t\t\t\t\t<div className={` w-[120px] overflow-hidden ${stage === 2 ? \"opacity-100\" : \"opacity-0 hidden\"} `}>\n\t\t\t\t\t\t<video className=\"h-full w-full object-contain border-none\" muted loop autoPlay playsInline>\n\t\t\t\t\t\t\t<source src={gender === GenderType.Male ? FACE_SCAN_HEADSHOT.male.right : FACE_SCAN_HEADSHOT.female.right} type=\"video/mp4\" />\n\t\t\t\t\t\t</video>\n\t\t\t\t\t</div>\n\t\t\t\t\t<div className={` w-[120px] overflow-hidden ${stage === 3 ? \"opacity-100\" : \"opacity-0 hidden\"} `}>\n\t\t\t\t\t\t<video className=\"h-full w-full object-contain border-none\" muted loop autoPlay playsInline>\n\t\t\t\t\t\t\t<source src={gender === GenderType.Male ? FACE_SCAN_HEADSHOT.male.smile : FACE_SCAN_HEADSHOT.female.smile} type=\"video/mp4\" />\n\t\t\t\t\t\t</video>\n\t\t\t\t\t</div>\n\t\t\t\t</div>\n\t\t\t</div>\n\t\t</div>\n\t);\n}\n\nexport default FaceScanGuide;\n","import React, { useContext } from \"react\";\nimport ParamsContext from \"../../utils/context/paramsContext\";\nimport FaceScanErrorScreen from \"./FaceScanErrorScreen\";\nimport LoadingScreen from \"../LoadingScreen\";\nimport { videoConstraints } from \"../../utils/constants\";\nimport { Drawer } from \"@mui/material\";\nimport FaceScanGuide from \"./FaceScanGuide\";\nimport Modal from \"../Modal\";\nimport { FaceScanErrorType } from \"../../utils/enums\";\nimport { ArrowRight } from \"lucide-react\";\nimport { useConfig } from \"../../utils/context/configContext\";\ninterface FaceScanStepProps {\n\twebcamRef: React.RefObject<HTMLVideoElement | null>;\n\tcanvasRef: React.RefObject<HTMLCanvasElement | null>;\n}\n\nconst FaceScanStep: React.FC<FaceScanStepProps> = ({ webcamRef, canvasRef }) => {\n\tconst {\n\t\tisError,\n\t\tisSuccess,\n\t\tshowLoader,\n\t\thasError,\n\t\terrorType,\n\t\tresetScanState,\n\t\tshowGuideCard,\n\t\tscanStage,\n\t\tvideoLoading,\n\t\tsetVideoLoading,\n\t\tvideoError,\n\t\tsetVideoError,\n\t\tgender,\n\t\tgetButtonText,\n\t\tisScanning,\n\t\tstartScan,\n\t\tisModelLoaded,\n\t\tonRetry,\n\t} = useContext(ParamsContext);\n\tconst resolvedConfig = useConfig();\n\tif (isError) {\n\t\treturn <FaceScanErrorScreen onRetry={onRetry} />;\n\t}\n\tif (isSuccess) {\n\t\treturn (\n\t\t\t<div className=\"fixed z-[9] common-ui-main w-full h-full\" style={{ background: resolvedConfig?.style?.base?.backgroundColor }}>\n\t\t\t\t<LoadingScreen url={resolvedConfig?.loader} loaderType=\"black\" />\n\t\t\t</div>\n\t\t);\n\t}\n\n\treturn (\n\t\t<>\n\t\t\t<audio id=\"audioElement\" crossOrigin=\"anonymous\" preload=\"auto\" style={{ position: \"absolute\", zIndex: -99999 }} src={undefined} />\n\n\t\t\t{/* Error overlay */}\n\t\t\t{showLoader && !hasError && (\n\t\t\t\t<div className=\"fixed z-[9] common-ui-main w-full h-full\" style={{ background: resolvedConfig?.style?.base?.backgroundColor }}>\n\t\t\t\t\t{/* <Asset genderType={gender} /> */}\n\t\t\t\t\t<LoadingScreen url={resolvedConfig?.loader} loaderType=\"black\" />\n\t\t\t\t</div>\n\t\t\t)}\n\n\t\t\t{/* Always show camera view */}\n\t\t\t<div className=\"h-full flex-col common-ui-main relative w-full flex justify-center items-center text-center rounded-t-[20px]\" style={{ background: resolvedConfig?.style?.base?.backgroundColor }}>\n\t\t\t\t<div className=\"flex-1 w-full max-w-md overflow-hidden\">\n\t\t\t\t\t<div className=\"w-full h-full\">\n\t\t\t\t\t\t<video\n\t\t\t\t\t\t\tref={webcamRef}\n\t\t\t\t\t\t\tautoPlay\n\t\t\t\t\t\t\tplaysInline\n\t\t\t\t\t\t\tmuted\n\t\t\t\t\t\t\twidth={videoConstraints.width.ideal}\n\t\t\t\t\t\t\theight={videoConstraints.height.ideal}\n\t\t\t\t\t\t\tclassName=\"w-full h-full object-cover fixed left-0 top-0 z-0\"\n\t\t\t\t\t\t\tstyle={{ transform: \"scaleX(-1)\" }}\n\t\t\t\t\t\t/>\n\t\t\t\t\t\t<canvas ref={canvasRef} width={videoConstraints.width.ideal} height={videoConstraints.height.ideal} style={{ transform: \"scaleX(-1)\", opacity: \"0\" }} />\n\t\t\t\t\t</div>\n\t\t\t\t</div>\n\t\t\t</div>\n\n\t\t\t{/* Error overlay */}\n\t\t\t{!showLoader && hasError && errorType === FaceScanErrorType.Camera && (\n\t\t\t\t<Modal testId=\"face-scan-camera-error-screen\" config={resolvedConfig} />\n\t\t\t)}\n\t\t\t{!showLoader && hasError && errorType !== FaceScanErrorType.Camera && (\n\t\t\t\t<FaceScanErrorScreen loading={showLoader} onRetry={resetScanState} />\n\t\t\t)}\n\n\t\t\t{/* Scan guide drawer - only show when scanning */}\n\t\t\t{showGuideCard && !hasError && !showLoader && (\n\t\t\t\t<Drawer\n\t\t\t\t\topen\n\t\t\t\t\tclassName=\"face-scan-small camera-draw\"\n\t\t\t\t\tanchor=\"bottom\"\n\t\t\t\t\tonClose={(event, reason) => {\n\t\t\t\t\t\tif (reason === \"backdropClick\") {\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t}}\n\t\t\t\t\thideBackdrop\n\t\t\t\t>\n\t\t\t\t\t<FaceScanGuide\n\t\t\t\t\t\tstage={scanStage}\n\t\t\t\t\t\tvideoLoading={videoLoading}\n\t\t\t\t\t\tsetVideoLoading={setVideoLoading}\n\t\t\t\t\t\tvideoError={videoError}\n\t\t\t\t\t\tsetVideoError={setVideoError}\n\t\t\t\t\t\tgender={gender}\n\t\t\t\t\t\tbtnConfig={{\n\t\t\t\t\t\t\tlabel: getButtonText(),\n\t\t\t\t\t\t\tonClick: isScanning ? resetScanState : startScan,\n\t\t\t\t\t\t\tisDisabled: showLoader || !isModelLoaded,\n\t\t\t\t\t\t\ticon: isScanning ? <ArrowRight /> : <></>,\n\t\t\t\t\t\t}}\n\t\t\t\t\t/>\n\t\t\t\t</Drawer>\n\t\t\t)}\n\t\t</>\n\t);\n};\n\nexport default FaceScanStep;\n","\"use client\";\nimport { useEffect, useRef, useState, useCallback, useMemo } from \"react\";\nimport { FaceScanMetaData, FaceScanProps } from \"../../types/interfaces\";\nimport {\n\tgenerateUuid,\n\tgetPreferredMediaRecorderTypes,\n\tgetRecordingExtension,\n\tgetRecordingMimeType,\n\tgetSupportedMediaRecorderTypes,\n\tgetVideoFPS,\n\thandleScanTimeCapture,\n\thandleWebSocketCapture,\n} from \"../../utils/utils\";\nimport { videoConstraintsExact, videoConstraintsFallback, videoTypes, voiceOverAssetsPath } from \"../../utils/constants\";\nimport { getSwanService } from \"../../utils/service/swanService\";\nimport speechService from \"../../utils/service/speechService\";\nimport useFaceScan from \"../../customHooks/useFaceScan\";\nimport usePosthogPageview from \"../../customHooks/usePosthogPageview\";\nimport { LanguageKeys } from \"../../utils/languageKeys\";\nimport { FaceScanErrorType } from \"../../utils/enums\";\nimport LanguageContextProvider from \"../../utils/context/languageContext\";\nimport { ConfigProvider } from \"../../utils/context/configContext\";\nimport FaceScanStep from \"./FaceScanStep\";\nimport ParamsContext from \"../../utils/context/paramsContext\";\n\nexport const FaceScan: React.FC<FaceScanProps> = (props) => {\n\tconst { onScanSuccess, onScanError, onRetry, onScanStart, onCaptureComplete, onUploadStart, onUploadEnd, onMeasurementSocketStart, onMeasurementSocketClose, config, isError, isSuccess } = props;\n\tconst userDetails: FaceScanMetaData = props.userDetails ?? {\n\t\temail: \"\",\n\t\tgender: \"male\",\n\t\tdeviceFocalLength: 0,\n\t\tshopDomain: \"\",\n\t\tbodyScanId: \"\",\n\t\tcallbackUrl: null,\n\t};\n\tconst token = props.token ?? \"\";\n\tconst webcamRef = useRef<HTMLVideoElement | null>(null);\n\tconst canvasRef = useRef<HTMLCanvasElement | null>(null);\n\tconst mediaRecorderRef = useRef<MediaRecorder | null>(null);\n\tconst recordedBlobsRef = useRef<Blob[] | null>([]);\n\tconst streamRef = useRef<MediaStream | null>(null);\n\tconst recordedFpsRef = useRef<number | null>(null);\n\tconst drawFrameRafRef = useRef<number>(0);\n\tconst recordingVideoElRef = useRef<HTMLVideoElement | null>(null);\n\tconst [showLoader, setShowLoader] = useState(false);\n\tconst [modelReady, setModelReady] = useState(false);\n\tconst [isScanning, setIsScanning] = useState(false);\n\tconst [showGuideCard, setShowGuideCard] = useState(true);\n\tconst [videoLoading, setVideoLoading] = useState(false);\n\tconst [videoError, setVideoError] = useState(false);\n\tconst [hasError, setHasError] = useState(false);\n\tconst [errorType, setErrorType] = useState<FaceScanErrorType | null>(null);\n\tconst [faceScanId, setFaceScanId] = useState(generateUuid());\n\tconst swan = useMemo(() => getSwanService(token), [token]);\n\tconst { email, gender, deviceFocalLength, shopDomain, callbackUrl, bodyScanId } = userDetails;\n\tconst [supportedTypes, setSupportedTypes] = useState<string[]>([]);\n\tconst [currentVideoConstraints, setCurrentVideoConstraints] = useState<MediaTrackConstraints>(videoConstraintsExact);\n\tconst preferredVideoTypes = useMemo(() => getPreferredMediaRecorderTypes(), []);\n\tconst recordingMimeType = getRecordingMimeType(supportedTypes);\n\tconst recordingExtension = getRecordingExtension(recordingMimeType);\n\tusePosthogPageview();\n\n\tconst stopRecording = useCallback(() => {\n\t\tconsole.log(\"Stopping recording...\");\n\t\tcancelAnimationFrame(drawFrameRafRef.current);\n\t\tif (recordingVideoElRef.current) {\n\t\t\trecordingVideoElRef.current.pause();\n\t\t\trecordingVideoElRef.current.srcObject = null;\n\t\t\trecordingVideoElRef.current = null;\n\t\t}\n\t\tif (mediaRecorderRef.current && mediaRecorderRef.current.state === \"recording\") {\n\t\t\tmediaRecorderRef.current.stop();\n\t\t}\n\t\tmediaRecorderRef.current = null;\n\t}, []);\n\n\tconst uploadFinalVideo = async () => {\n\t\tonCaptureComplete?.();\n\t\tif (recordedBlobsRef.current) {\n\t\t\tif (recordedBlobsRef.current.length === 0) {\n\t\t\t\tconsole.error(\"No video data recorded\");\n\t\t\t\tsetErrorType(FaceScanErrorType.Scan);\n\t\t\t\tsetHasError(true);\n\t\t\t\tsetShowLoader(false);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tonUploadStart?.();\n\t\t\tsetShowLoader(true);\n\t\t\tconst videoFile = new File(recordedBlobsRef.current, `${faceScanId}.${recordingExtension}`, {\n\t\t\t\ttype: recordingMimeType,\n\t\t\t});\n\t\t\t// Use FPS captured at recording time, fallback to calculation if not available\n\t\t\tconst videoFps = recordedFpsRef.current ?? (await getVideoFPS(videoFile));\n\n\t\t\tconst fileSize = videoFile.size;\n\t\t\tconst fileSizeMB = (fileSize / (1024 * 1024)).toFixed(2);\n\t\t\tconst estimatedDuration = Math.round(fileSize / 10000);\n\t\t\tconst videoData = {\n\t\t\t\tvideo_size_mb: parseFloat(fileSizeMB),\n\t\t\t\tvideo_size_bytes: fileSize,\n\t\t\t\tvideo_fps: videoFps || 0,\n\t\t\t\tblob_count: recordedBlobsRef.current.length,\n\t\t\t\testimated_duration_seconds: estimatedDuration,\n\t\t\t};\n\n\t\t\tconst metaData: any[] = [\n\t\t\t\t{ gender: gender },\n\t\t\t\t{ face_scan_id: faceScanId },\n\t\t\t\t{focal_length: `${deviceFocalLength}`},\n\t\t\t\t{ customer_store_url: shopDomain },\n\t\t\t\t{ scan_type: \"face_scan\" },\n\t\t\t\t{ body_scan_id: bodyScanId }\n\t\t\t];\n\t\t\tif (callbackUrl) {\n\t\t\t\tmetaData.push({ callback_url: callbackUrl });\n\t\t\t}\n\n\t\t\thandleScanTimeCapture({\n\t\t\t\teventName: `${shopDomain}/face_scan_meta_data`,\n\t\t\t\tfaceScanId,\n\t\t\t\temail,\n\t\t\t\tdata: JSON.stringify({ metaData, videoData }),\n\t\t\t});\n\n\t\t\tconst uploadStartTime = Date.now();\n\t\t\thandleScanTimeCapture({\n\t\t\t\teventName: `${shopDomain}/face_scan_upload_start`,\n\t\t\t\tfaceScanId,\n\t\t\t\temail,\n\t\t\t\tstartTime: uploadStartTime,\n\t\t\t});\n\n\t\t\ttry {\n\t\t\t\tconst res = await swan.fileUpload.faceScanFileUploader({\n\t\t\t\t\tfile: videoFile,\n\t\t\t\t\tarrayMetaData: metaData,\n\t\t\t\t\tobjectKey: faceScanId,\n\t\t\t\t\temail,\n\t\t\t\t\tcontentType: videoFile.type,\n\t\t\t\t});\n\n\t\t\t\tconst uploadEndTime = Date.now();\n\t\t\t\tconst uploadDuration = uploadEndTime - uploadStartTime;\n\n\t\t\t\thandleScanTimeCapture({\n\t\t\t\t\teventName: `${shopDomain}/face_scan_upload_complete`,\n\t\t\t\t\tfaceScanId,\n\t\t\t\t\temail,\n\t\t\t\t\tcompletionTime: uploadEndTime,\n\t\t\t\t\tuploadDuration,\n\t\t\t\t});\n\t\t\t\tonUploadEnd?.();\n\t\t\t\tconsole.log(\"✅ Upload successful\", res);\n\t\t\t\tswan.measurement.handlFaceScaneSocket({\n\t\t\t\t\tonPreopen: () => {\n\t\t\t\t\t\tonMeasurementSocketStart?.();\n\t\t\t\t\t\thandleWebSocketCapture({\n\t\t\t\t\t\t\teventName: `${shopDomain}/webSocket`,\n\t\t\t\t\t\t\tfaceScanID: faceScanId,\n\t\t\t\t\t\t\tconnection: \"pre_open\",\n\t\t\t\t\t\t\ttype: \"faceScan_recommendation\",\n\t\t\t\t\t\t\temail,\n\t\t\t\t\t\t});\n\t\t\t\t\t},\n\t\t\t\t\tfaceScanId,\n\t\t\t\t\tonOpen: () => {\n\t\t\t\t\t\thandleWebSocketCapture({\n\t\t\t\t\t\t\teventName: `${shopDomain}/webSocket`,\n\t\t\t\t\t\t\tfaceScanID: faceScanId,\n\t\t\t\t\t\t\tconnection: \"open\",\n\t\t\t\t\t\t\ttype: \"faceScan_recommendation\",\n\t\t\t\t\t\t\temail,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tconsole.log(\"websocket connect open\");\n\t\t\t\t\t},\n\t\t\t\t\tonError: (err) => {\n\t\t\t\t\t\thandleWebSocketCapture({\n\t\t\t\t\t\t\teventName: `${shopDomain}/webSocket`,\n\t\t\t\t\t\t\tfaceScanID: faceScanId,\n\t\t\t\t\t\t\tconnection: \"error\",\n\t\t\t\t\t\t\ttype: \"faceScan_recommendation\",\n\t\t\t\t\t\t\temail,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tonError(err);\n\t\t\t\t\t},\n\t\t\t\t\tonSuccess: (data) => {\n\t\t\t\t\t\thandleWebSocketCapture({\n\t\t\t\t\t\t\teventName: `${shopDomain}/webSocket`,\n\t\t\t\t\t\t\tfaceScanID: faceScanId,\n\t\t\t\t\t\t\tconnection: \"success\",\n\t\t\t\t\t\t\ttype: \"faceScan_recommendation\",\n\t\t\t\t\t\t\temail,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tonSuccess(data);\n\t\t\t\t\t},\n\t\t\t\t\tonClose: () => {\n\t\t\t\t\t\tonMeasurementSocketClose?.();\n\t\t\t\t\t\tconsole.log(\"websocket connect close\");\n\t\t\t\t\t\thandleWebSocketCapture({\n\t\t\t\t\t\t\teventName: `${shopDomain}/webSocket`,\n\t\t\t\t\t\t\tfaceScanID: faceScanId,\n\t\t\t\t\t\t\tconnection: \"close\",\n\t\t\t\t\t\t\ttype: \"faceScan_recommendation\",\n\t\t\t\t\t\t\temail,\n\t\t\t\t\t\t});\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tonUploadEnd?.();\n\t\t\t\tonError(error);\n\t\t\t}\n\t\t}\n\t};\n\n\tconst startRecording = useCallback(() => {\n\t\tconst stream = webcamRef.current?.srcObject as MediaStream | null;\n\t\tif (!stream) return;\n\n\t\t// Create a canvas to normalize orientation\n\t\tconst videoTrack = stream.getVideoTracks()[0];\n\t\tconst settings = videoTrack.getSettings();\n\t\t// Fallback to landscape defaults (1280×720); portrait swap below handles orientation\n\t\tconst { width = 1280, height = 720 } = settings;\n\n\t\tconst canvas = document.createElement(\"canvas\");\n\t\tconst ctx = canvas.getContext(\"2d\");\n\n\t\t// Always force portrait (swap width/height if landscape)\n\t\tif (width > height) {\n\t\t\tcanvas.width = height;\n\t\t\tcanvas.height = width;\n\t\t} else {\n\t\t\tcanvas.width = width;\n\t\t\tcanvas.height = height;\n\t\t}\n\n\t\tconst videoEl = document.createElement(\"video\");\n\t\tvideoEl.srcObject = stream;\n\t\tvideoEl.muted = true;\n\t\tvideoEl.playsInline = true;\n\t\tvideoEl.play();\n\t\trecordingVideoElRef.current = videoEl;\n\n\t\t// Draw video frames onto canvas\n\t\tconst drawFrame = () => {\n\t\t\t// Rotate if camera gives landscape frames\n\t\t\tif (width > height) {\n\t\t\t\tctx?.save();\n\t\t\t\tctx?.translate(canvas.width, 0);\n\t\t\t\tctx?.rotate(Math.PI / 2);\n\t\t\t\tctx?.drawImage(videoEl, 0, 0, height, width);\n\t\t\t\tctx?.restore();\n\t\t\t} else {\n\t\t\t\tctx?.drawImage(videoEl, 0, 0, width, height);\n\t\t\t}\n\t\t\tdrawFrameRafRef.current = requestAnimationFrame(drawFrame);\n\t\t};\n\t\tdrawFrameRafRef.current = requestAnimationFrame(drawFrame);\n\n\t\t// Match recording FPS to actual camera FPS to avoid duplicate frames in the encoded video\n\t\tconst recordingFps = settings.frameRate ?? 10;\n\t\trecordedFpsRef.current = recordingFps; // Store FPS at recording time\n\t\tconst canvasStream = canvas.captureStream(recordingFps);\n\t\tconst mediaRecorderOptions: MediaRecorderOptions = {\n\t\t\tvideoBitsPerSecond: 1_500_000,\n\t\t};\n\t\tif (supportedTypes.length > 0) {\n\t\t\tmediaRecorderOptions.mimeType = supportedTypes[0];\n\t\t}\n\t\tlet mediaRecorder;\n\n\t\ttry {\n\t\t\tmediaRecorder = new MediaRecorder(canvasStream, mediaRecorderOptions);\n\t\t} catch (e) {\n\t\t\tconsole.error(\"MediaRecorder init failed:\", e);\n\t\t\tsetErrorType(FaceScanErrorType.Scan);\n\t\t\tsetHasError(true);\n\t\t\tsetShowLoader(false);\n\t\t\treturn;\n\t\t}\n\n\t\trecordedBlobsRef.current = [];\n\t\tmediaRecorder.ondataavailable = (event) => {\n\t\t\tif (event?.data && event.data.size > 0 && recordedBlobsRef.current) {\n\t\t\t\trecordedBlobsRef.current.push(event.data);\n\t\t\t}\n\t\t};\n\t\tmediaRecorder.onstop = () => {\n\t\t\tconsole.log(\"Recording stopped, total blobs:\", recordedBlobsRef?.current?.length);\n\t\t\tuploadFinalVideo();\n\t\t};\n\n\t\tmediaRecorder.start(100); // 100ms chunks\n\t\tmediaRecorderRef.current = mediaRecorder;\n\t\tconsole.log(\"Recording started successfully (portrait normalized)\");\n\t}, [supportedTypes, uploadFinalVideo]);\n\n\tconst { faceScanDetector, scanStage, setScanStage, resetScan, isModelLoaded, startScanSequence } = useFaceScan({\n\t\tfaceScanId,\n\t\tshopDomain,\n\t\tisError,\n\t\tisSuccess,\n\t\tonScanComplete: () => {\n\t\t\tstopRecording();\n\t\t},\n\t\tonModelReady: () => {\n\t\t\tsetModelReady(true);\n\t\t},\n\t\tonStartRecording: () => {\n\t\t\tconsole.log(\"Stage 0 completed - starting recording for stages 1-3\");\n\t\t\tstartRecording();\n\t\t},\n\t});\n\n\tconst startScan = useCallback(() => {\n\t\tif (!isModelLoaded) return;\n\t\tonScanStart?.();\n\t\tsetScanStage(0);\n\t\tspeechService.playAudio(`${voiceOverAssetsPath}face-scan-vos/Face-forward.mp3`);\n\t\tsetTimeout(() => {\n\t\t\tsetIsScanning(true);\n\t\t\tsetTimeout(() => {\n\t\t\t\tstartScanSequence();\n\t\t\t}, 200);\n\t\t}, 200);\n\t}, [setScanStage, setIsScanning, startScanSequence, isModelLoaded, onScanStart]);\n\n\tconst resetScanState = useCallback(() => {\n\t\tsetIsScanning(false);\n\t\tsetShowGuideCard(true);\n\t\tstopRecording();\n\t\tresetScan();\n\t\tonRetry?.();\n\t\trecordedBlobsRef.current = [];\n\t\trecordedFpsRef.current = null;\n\t\tif (mediaRecorderRef.current) {\n\t\t\tmediaRecorderRef.current = null;\n\t\t}\n\t\tsetHasError(false);\n\t\tsetErrorType(null);\n\t\tsetScanStage(-1);\n\t\tsetFaceScanId(generateUuid());\n\t\tif (webcamRef.current && streamRef.current) {\n\t\t\twebcamRef.current.srcObject = streamRef.current;\n\t\t\tconsole.log(\"Camera stream restored after reset\");\n\t\t}\n\t}, [setScanStage, setIsScanning, setShowGuideCard, stopRecording, resetScan, setFaceScanId]);\n\n\tconst onError = (data: any) => {\n\t\tconsole.log(data, \"ws error\");\n\t\tonScanError?.(data);\n\t\tsetErrorType(FaceScanErrorType.Scan);\n\t\tsetHasError(true);\n\t\tsetShowLoader(false);\n\t\tsetShowGuideCard(false);\n\t\thandleScanTimeCapture({\n\t\t\teventName: `${shopDomain}/faceScan`,\n\t\t\tfaceScanId,\n\t\t\tstatus: \"failed\",\n\t\t\temail,\n\t\t\tdata: JSON.stringify(data),\n\t\t});\n\t};\n\n\tconst onSuccess = (data: any) => {\n\t\tconsole.log(data, \"ws success\");\n\t\tif (data && data?.resultType === \"intermediate\") {\n\t\t\thandleScanTimeCapture({\n\t\t\t\teventName: `${shopDomain}/faceScan_success/intermediate`,\n\t\t\t\tfaceScanId,\n\t\t\t\tstatus: \"success\",\n\t\t\t\temail,\n\t\t\t\tdata: JSON.stringify(data),\n\t\t\t});\n\t\t}\n\t\tonScanSuccess?.(data);\n\t};\n\n\tuseEffect(() => {\n\t\tif (isError || isSuccess) return;\n\t\tif (navigator.mediaDevices.getUserMedia) {\n\t\t\tnavigator.mediaDevices\n\t\t\t\t.getUserMedia({ video: currentVideoConstraints })\n\t\t\t\t.then((stream) => {\n\t\t\t\t\tstreamRef.current = stream;\n\t\t\t\t\tif (webcamRef.current) {\n\t\t\t\t\t\twebcamRef.current.srcObject = stream;\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t\t.catch((err) => {\n\t\t\t\t\tconsole.error(\"Error accessing webcam:\", err);\n\t\t\t\t\tif (currentVideoConstraints === videoConstraintsExact) {\n\t\t\t\t\t\tsetCurrentVideoConstraints(videoConstraintsFallback);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tconst isCameraAccessError = [\"NotAllowedError\", \"PermissionDeniedError\", \"NotFoundError\", \"DevicesNotFoundError\", \"NotReadableError\", \"TrackStartError\"].includes(err?.name);\n\t\t\t\t\tsetErrorType(isCameraAccessError ? FaceScanErrorType.Camera : FaceScanErrorType.Scan);\n\t\t\t\t\tsetHasError(true);\n\t\t\t\t});\n\t\t}\n\t\treturn () => {\n\t\t\tif (streamRef.current) {\n\t\t\t\tstreamRef.current.getTracks().forEach((track) => track.stop());\n\t\t\t}\n\t\t};\n\t}, [isError, isSuccess, currentVideoConstraints]);\n\n\t// Face detection interval - only run when scanning is active\n\tuseEffect(() => {\n\t\tif (!modelReady || !isScanning) return;\n\t\tconst intervalId = setInterval(() => {\n\t\t\tfaceScanDetector(webcamRef, canvasRef);\n\t\t}, 500);\n\n\t\t// eslint-disable-next-line consistent-return\n\t\treturn () => clearInterval(intervalId);\n\t}, [faceScanDetector, modelReady, isScanning]);\n\n\tconst getButtonText = () => {\n\t\tif (isScanning) return LanguageKeys.reset;\n\t\tif (!isModelLoaded) return LanguageKeys.loading;\n\t\treturn LanguageKeys.start;\n\t};\n\n\tconsole.log(\"Model ready:\", modelReady, \"Has error:\", hasError, \"Is scanning:\", isScanning, \"showLoader\", showLoader);\n\tuseEffect(() => {\n\t\tconst supported = getSupportedMediaRecorderTypes(preferredVideoTypes, videoTypes);\n\t\tsetSupportedTypes(supported);\n\t}, [preferredVideoTypes]);\n\tuseEffect(() => {\n\t\tsetScanStage(-1);\n\t}, []);\n\n\treturn (\n\t\t<div data-face-scan-stage={scanStage}>\n\t\t<LanguageContextProvider>\n\t\t\t<ConfigProvider config={config}>\n\t\t\t\t<ParamsContext.Provider\n\t\t\t\t\tvalue={{\n\t\t\t\t\t\tisError,\n\t\t\t\t\t\tisSuccess,\n\t\t\t\t\t\tshowLoader,\n\t\t\t\t\t\thasError,\n\t\t\t\t\t\terrorType,\n\t\t\t\t\t\tresetScanState,\n\t\t\t\t\t\tshowGuideCard,\n\t\t\t\t\t\tscanStage,\n\t\t\t\t\t\tvideoLoading,\n\t\t\t\t\t\tsetVideoLoading,\n\t\t\t\t\t\tvideoError,\n\t\t\t\t\t\tsetVideoError,\n\t\t\t\t\t\tgender,\n\t\t\t\t\t\tgetButtonText,\n\t\t\t\t\t\tisScanning,\n\t\t\t\t\t\tstartScan,\n\t\t\t\t\t\tisModelLoaded,\n\t\t\t\t\t\tonRetry,\n\t\t\t\t\t}}\n\t\t\t\t>\n\t\t\t\t\t<FaceScanStep webcamRef={webcamRef} canvasRef={canvasRef} />\n\t\t\t\t</ParamsContext.Provider>\n\t\t\t</ConfigProvider>\n\t\t</LanguageContextProvider>\n\t\t</div>\n\t);\n};\n"],"names":["preloadedDetector","isPreloading","preloadDetector","async","window","Promise","r","setTimeout","tf","poseDetection","all","import","setBackend","ready","detector","createDetector","SupportedModels","BlazePose","runtime","modelType","dummyCanvas","document","createElement","width","videoConstraints","ideal","max","height","ctx","getContext","fillStyle","fillRect","estimatePoses","e","console","warn","err","error","useFaceScan","faceScanId","onValidPose","onScanComplete","onModelReady","onStartRecording","shopDomain","isError","isSuccess","detectorRef","useRef","scanStage","setScanStage","useState","consecutiveValid","setConsecutiveValid","isModelLoaded","setIsModelLoaded","isScanningActive","setIsScanningActive","isInferencingRef","inferenceCanvasRef","utteranceRef","scanStageRef","consecutiveValidRef","validityBufferRef","lastSpokenMessageRef","lastSpokenTimeRef","voiceEnabledRef","lastPoseTrackingTimeRef","isIOS","navigator","test","userAgent","platform","maxTouchPoints","directionMessages","useMemo","debouncedTrackPoseDetection","fn","delay","timer","args","clearTimeout","debounce","payload","posthog","capture","trackPoseDetection","useCallback","faceKeypoints","bodyKeypoints","stage","headValid","bodyInvalid","consecutiveValidCount","now","Date","current","nose","leftEye","rightEye","leftMouth","rightMouth","faceKeypointScores","map","kp","filter","score","avgFaceScore","length","reduce","a","b","bodyKeypointScores","avgBodyScore","eyeDistance","Math","abs","noseToRight","noseToLeft","expectedPosition","timestamp","toISOString","data","JSON","stringify","parseFloat","toFixed","faceKeypointsDetected","bodyKeypointsDetected","noseToRightRatio","noseToLeftRatio","noseScore","leftEyeScore","rightEyeScore","leftMouthScore","rightMouthScore","startScanSequence","stageName","useEffect","log","initializeModels","disposeModelAndTf","faceScanDetector","webcamRef","canvasRef","readyState","vw","videoWidth","vh","videoHeight","ictx","drawImage","poses","keypoints","forEach","landmark","idx","point","x","y","push","clearRect","progress","min","radius","beginPath","strokeStyle","lineWidth","arc","PI","stroke","eyesToMouthVerticalDistance","faceTiltedness","faceIsTilted","faceIsVertical","frontalFace","fullLeft","fullRight","isHeadInPosition","slice","p","shift","Boolean","nextValid","nextStage","speechService","playAudio","voiceOverAssetsPath","completedStage","totalStages","nextSound","resetScan","speechSynthesis","cancel","enableVoiceCommands","silentUtterance","SpeechSynthesisUtterance","volume","speak","FaceScanErrorScreen","onRetry","loading","translate","useContext","LanguageContext","config","useConfig","_jsx","className","style","background","base","backgroundColor","children","_jsxs","Header","noTitle","fontFamily","heading","headingFontFamily","fontSize","headingFontSize","color","headingColor","fontWeight","headingFontWeight","LanguageKeys","scanFailed","subheading","subheadingFontFamily","subheadingFontSize","subheadingColor","subheadingFontWeight","clickToResetScan","SpecificButton","disabled","buttonText","postfixIcon","ArrowRight","buttonFunc","FaceScanGuide","videoLoading","setVideoLoading","videoError","setVideoError","gender","btnConfig","faceVisible","loadingVideo","videoLoadFailed","src","GenderType","Male","maleGlassesOffVideo","glassesOffVideo","autoPlay","loop","controls","muted","playsInline","onCanPlay","onLoadStart","onError","isDisabled","label","icon","onClick","FACE_SCAN_HEADSHOT","male","forward","female","type","left","right","smile","FaceScanStep","showLoader","hasError","errorType","resetScanState","showGuideCard","getButtonText","isScanning","startScan","ParamsContext","resolvedConfig","LoadingScreen","url","loader","loaderType","_Fragment","id","crossOrigin","preload","position","zIndex","undefined","ref","transform","opacity","FaceScanErrorType","Camera","Modal","testId","Drawer","open","anchor","onClose","event","reason","hideBackdrop","FaceScan","props","onScanSuccess","onScanError","onScanStart","onCaptureComplete","onUploadStart","onUploadEnd","onMeasurementSocketStart","onMeasurementSocketClose","userDetails","email","deviceFocalLength","bodyScanId","callbackUrl","token","mediaRecorderRef","recordedBlobsRef","streamRef","recordedFpsRef","drawFrameRafRef","recordingVideoElRef","setShowLoader","modelReady","setModelReady","setIsScanning","setShowGuideCard","setHasError","setErrorType","setFaceScanId","generateUuid","swan","getSwanService","supportedTypes","setSupportedTypes","currentVideoConstraints","setCurrentVideoConstraints","videoConstraintsExact","preferredVideoTypes","getPreferredMediaRecorderTypes","recordingMimeType","getRecordingMimeType","recordingExtension","getRecordingExtension","usePosthogPageview","stopRecording","cancelAnimationFrame","pause","srcObject","state","stop","uploadFinalVideo","Scan","videoFile","File","videoFps","getVideoFPS","fileSize","size","fileSizeMB","estimatedDuration","round","videoData","video_size_mb","video_size_bytes","video_fps","blob_count","estimated_duration_seconds","metaData","face_scan_id","focal_length","customer_store_url","scan_type","body_scan_id","callback_url","handleScanTimeCapture","eventName","uploadStartTime","startTime","res","fileUpload","faceScanFileUploader","file","arrayMetaData","objectKey","contentType","uploadEndTime","completionTime","uploadDuration","measurement","handlFaceScaneSocket","onPreopen","handleWebSocketCapture","faceScanID","connection","onOpen","onSuccess","startRecording","stream","settings","getVideoTracks","getSettings","canvas","videoEl","play","drawFrame","save","rotate","restore","requestAnimationFrame","recordingFps","frameRate","canvasStream","captureStream","mediaRecorderOptions","videoBitsPerSecond","mediaRecorder","mimeType","MediaRecorder","ondataavailable","onstop","start","status","resultType","mediaDevices","getUserMedia","video","then","catch","videoConstraintsFallback","isCameraAccessError","includes","name","getTracks","track","intervalId","setInterval","clearInterval","supported","getSupportedMediaRecorderTypes","videoTypes","LanguageContextProvider","ConfigProvider","Provider","value","reset"],"mappings":"mgBA6BA,IAAIA,EAAyC,KACzCC,GAAe,EAGZ,MAAMC,EAAkBC,UAE7B,GAAsB,oBAAXC,OAAwB,OAAO,KA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=require("react"),a=require("./Modal-HTYYx7sM.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-BmDNM8tt.js.map
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";var e=require("react/jsx-runtime"),t=require("react"),a=require("./Modal-DU2Jymve.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-D08ZA0zl.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,m]=t.useState(0),[g,h]=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(g),j=t.useRef([]),_=t.useRef(""),E=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),m=f.length>0?f.reduce((e,t)=>e+t,0)/f.length:0,g=a.map(e=>e[2]).filter(e=>e>0),h=g.length>0?g.reduce((e,t)=>e+t,0)/g.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(m.toFixed(3)),avgBodyScore:parseFloat(h.toFixed(3)),faceKeypointsDetected:f.length,bodyKeypointsDetected:g.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{m(0),h(0),F.current=0,C.current=0,j.current=[]}})()}},[l,d]),t.useEffect(()=>{F.current=f},[f]),t.useEffect(()=>{C.current=g},[g]),{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;h(e)}else h(Math.max(0,C.current-1));if(C.current>=2){n?.();const t=F.current+1;h(0),j.current=[],m(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:m,consecutiveValid:g,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}),m(0),h(0),x(!1),F.current=0,C.current=0,j.current=[],_.current="",E.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 my-[0] 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",{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?.(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] 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?.(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:m,resetScanState:g,showGuideCard:h,scanStage:p,videoLoading:y,setVideoLoading:S,videoError:x,setVideoError:v,gender:b,getButtonText:w,isScanning:F,startScan:C,isModelLoaded:j,isLandscape:_,onRetry:E}=t.useContext(a.ParamsContext),N=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:N?.style?.base?.backgroundColor},children:e.jsx(a.LoadingScreen,{url:N?.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 inset-0 z-[9999] common-ui-main",style:{background:"#fff"},children:e.jsx(a.Modal,{variant:"portrait",config:N})}),u&&!f&&e.jsx("div",{className:"fixed z-[9] common-ui-main w-full h-full",style:{background:N?.style?.base?.backgroundColor},children:e.jsx(a.LoadingScreen,{url:N?.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:N?.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)",visibility:_?"hidden":"visible"}}),e.jsx("canvas",{ref:s,width:a.videoConstraints.width.ideal,height:a.videoConstraints.height.ideal,style:{transform:"scaleX(-1)",opacity:"0"}})]})})}),!u&&f&&m===a.FaceScanErrorType.Camera&&e.jsx(a.Modal,{testId:"face-scan-camera-error-screen",config:N}),!u&&f&&m!==a.FaceScanErrorType.Camera&&e.jsx(l,{loading:u,onRetry:g}),h&&!f&&!u&&!_&&e.jsx(r.Drawer,{open:!0,className:"face-scan-small camera-draw",anchor:"bottom",onClose:(e,t)=>{},disablePortal:!0,hideBackdrop:!0,children:e.jsx(d,{stage:p,videoLoading:y,setVideoLoading:S,videoError:x,setVideoError:v,gender:b,btnConfig:{label:w(),onClick:F?g: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:m,onMeasurementSocketClose:g,config:h,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),_=t.useRef(0),E=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),[W,V]=t.useState(null),[K,U]=t.useState(a.generateUuid()),q=t.useMemo(()=>a.getSwanService(x),[x]),{isLandscape:B}=a.usePortraitLock(),{email:G,gender:J,deviceFocalLength:X,shopDomain:Q,callbackUrl:Y,bodyScanId:Z}=S,[ee,te]=t.useState([]),[ae,ne]=t.useState(a.videoConstraintsExact),re=t.useMemo(()=>a.getPreferredMediaRecorderTypes(),[]),oe=a.getRecordingMimeType(ee),se=a.getRecordingExtension(oe);a.usePosthogPageview();const ce=t.useCallback(()=>{console.log("Stopping recording..."),cancelAnimationFrame(_.current),E.current&&(E.current.pause(),E.current.srcObject=null,E.current=null),w.current&&"recording"===w.current.state&&w.current.stop(),w.current=null},[]),ie=async()=>{if(l?.(),F.current){if(0===F.current.length)return console.error("No video data recorded"),V(a.FaceScanErrorType.Scan),H(!0),void T(!1);d?.(),T(!0);const e=new File(F.current,`${K}.${se}`,{type:oe}),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:J},{face_scan_id:K},{focal_length:`${X}`},{customer_store_url:Q},{scan_type:"face_scan"},{body_scan_id:Z}];Y&&c.push({callback_url:Y}),a.handleScanTimeCapture({eventName:`${Q}/face_scan_meta_data`,faceScanId:K,email:G,data:JSON.stringify({metaData:c,videoData:s})});const i=Date.now();a.handleScanTimeCapture({eventName:`${Q}/face_scan_upload_start`,faceScanId:K,email:G,startTime:i});try{const t=await q.fileUpload.faceScanFileUploader({file:e,arrayMetaData:c,objectKey:K,email:G,contentType:e.type}),n=Date.now(),r=n-i;a.handleScanTimeCapture({eventName:`${Q}/face_scan_upload_complete`,faceScanId:K,email:G,completionTime:n,uploadDuration:r}),f?.(),console.log("✅ Upload successful",t);let o=!1;q.measurement.handlFaceScaneSocket({onPreopen:()=>{m?.(),a.handleWebSocketCapture({eventName:`${Q}/webSocket`,faceScanID:K,connection:"pre_open",type:"faceScan_recommendation",email:G})},faceScanId:K,onOpen:()=>{a.handleWebSocketCapture({eventName:`${Q}/webSocket`,faceScanID:K,connection:"open",type:"faceScan_recommendation",email:G})},onError:e=>{o=!0,a.handleWebSocketCapture({eventName:`${Q}/webSocket`,faceScanID:K,connection:"error",type:"faceScan_recommendation",email:G}),xe(e)},onSuccess:e=>{o=!0,a.handleWebSocketCapture({eventName:`${Q}/webSocket`,faceScanID:K,connection:"success",type:"faceScan_recommendation",email:G}),ve(e)},onClose:()=>{g?.(),a.handleWebSocketCapture({eventName:`${Q}/webSocket`,faceScanID:K,connection:"close",type:"faceScan_recommendation",email:G}),o||(a.posthog.capture(`${Q}/face_scan_ws_closed_without_result`,{faceScanID:K,email:G,type:"ws_close_no_result",reason:"Face scan WebSocket closed before delivering a result"}),xe({message:"Connection closed. Please try again."}))}})}catch(e){f?.(),xe(e)}}},le=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(),E.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),_.current=requestAnimationFrame(i)};_.current=requestAnimationFrame(i);const l=t.frameRate??10;j.current=l;const d=o.captureStream(l),u={videoBitsPerSecond:15e5};let f;ee.length>0&&(u.mimeType=ee[0]);try{f=new MediaRecorder(d,u)}catch(e){return console.error("MediaRecorder init failed:",e),V(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),ie()},f.start(100),w.current=f,console.log("Recording started successfully (portrait normalized)")},[ee,ie]),{faceScanDetector:de,scanStage:ue,setScanStage:fe,resetScan:me,isModelLoaded:ge,startScanSequence:he}=i({faceScanId:K,shopDomain:Q,isError:p,isSuccess:y,onScanComplete:()=>{ce()},onModelReady:()=>{R(!0)},onStartRecording:()=>{console.log("Stage 0 completed - starting recording for stages 1-3"),le()}}),pe=t.useCallback(()=>{ge&&(c?.(),fe(0),a.speechService.playAudio(`${a.voiceOverAssetsPath}face-scan-vos/Face-forward.mp3`),setTimeout(()=>{D(!0),setTimeout(()=>{he()},200)},200))},[fe,D,he,ge,c]),ye=t.useCallback(()=>{D(!1),P(!0),ce(),me(),s?.(),F.current=[],j.current=null,w.current&&(w.current=null),H(!1),V(null),fe(-1),U(a.generateUuid()),v.current&&C.current&&(v.current.srcObject=C.current,console.log("Camera stream restored after reset"))},[fe,D,P,ce,me,U]),Se=t.useRef(!1);t.useEffect(()=>{!B||Se.current||N||p||y||$||(a.speechService.stopAudio(),w.current&&(w.current.onstop=null,"recording"===w.current.state&&w.current.stop(),w.current=null),F.current=[],j.current=null,ye()),Se.current=B},[B,N,p,y,$,ye]);const xe=e=>{console.log(e,"ws error"),o?.(e),V(a.FaceScanErrorType.Scan),H(!0),T(!1),P(!1),a.handleScanTimeCapture({eventName:`${Q}/faceScan`,faceScanId:K,status:"failed",email:G,data:JSON.stringify(e)})},ve=e=>{console.log(e,"ws success"),e&&"intermediate"===e?.resultType&&a.handleScanTimeCapture({eventName:`${Q}/faceScan_success/intermediate`,faceScanId:K,status:"success",email:G,data:JSON.stringify(e)}),r?.(e)};t.useEffect(()=>{if(!p&&!y)return navigator.mediaDevices.getUserMedia&&navigator.mediaDevices.getUserMedia({video:ae}).then(e=>{C.current=e,v.current&&(v.current.srcObject=e)}).catch(e=>{if(console.error("Error accessing webcam:",e),ae===a.videoConstraintsExact)return void ne(a.videoConstraintsFallback);const t=["NotAllowedError","PermissionDeniedError","NotFoundError","DevicesNotFoundError","NotReadableError","TrackStartError"].includes(e?.name);V(t?a.FaceScanErrorType.Camera:a.FaceScanErrorType.Scan),H(!0)}),()=>{C.current&&C.current.getTracks().forEach(e=>e.stop())}},[p,y,ae]),t.useEffect(()=>{if(!k||!I)return;const e=setInterval(()=>{de(v,b)},500);return()=>clearInterval(e)},[de,k,I]);return console.log("Model ready:",k,"Has error:",$,"Is scanning:",I,"showLoader",N),t.useEffect(()=>{const e=a.getSupportedMediaRecorderTypes(re,a.videoTypes);te(e)},[re]),t.useEffect(()=>{fe(-1)},[]),e.jsx("div",{"data-face-scan-stage":ue,children:e.jsx(a.LanguageContextProvider,{children:e.jsx(a.ConfigProvider,{config:h,children:e.jsx(a.ParamsContext.Provider,{value:{isError:p,isSuccess:y,showLoader:N,hasError:$,errorType:W,resetScanState:ye,showGuideCard:M,scanStage:ue,videoLoading:A,setVideoLoading:L,videoError:O,setVideoError:z,gender:J,getButtonText:()=>I?a.LanguageKeys.reset:ge?a.LanguageKeys.start:a.LanguageKeys.loading,isScanning:I,startScan:pe,isModelLoaded:ge,isLandscape:B,onRetry:s},children:e.jsx(a.ShadowRoot,{children:e.jsx(u,{webcamRef:v,canvasRef:b})})})})})})},exports.preloadDetector=c;
|
|
2
|
-
//# sourceMappingURL=FaceScan-CNoW9DIE.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-CbZJwbLZ.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-CPf6-siO.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 _,M as I,f as k,h as E,i as M,j as C,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-BHfJVhRi.js";import{ArrowRight as U}from"lucide-react";import{Drawer as B}from"@mui/material";let A=null,q=!1;function J({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),E=n(w),M=n([]),C=n(""),D=n(0),T=n(!1),P=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]),j=c((t,a,n,o,r,c)=>{const i=Date.now();if(!(i-P.current<4e3)){P.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,$]),L=()=>{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(A)return A;if(q)for(;q;)if(await new Promise(e=>setTimeout(e,100)),A)return A;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 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 A=a,a}catch(e){return console.error("Failed to preload detector:",e),null}finally{q=!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,E.current=0,M.current=[]}})()}},[g,p]),i(()=>{k.current=S},[S]),i(()=>{E.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(E.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;M.current.push(i&&s),M.current.length>10&&M.current.shift();if(M.current.filter(Boolean).length>=2){const e=E.current+1;v(e)}else v(Math.max(0,E.current-1));if(E.current>=2){t?.();const n=k.current+1;v(0),M.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}`),L()}})()}j(n,c,k.current,i,s,E.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:E.current}),b(0),v(0),_(!1),k.current=0,E.current=0,M.current=[],C.current="",D.current=0,T.current=!1,I.current&&(speechSynthesis.cancel(),I.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:L,isScanningActive:N}}function G({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(U,{}),buttonFunc:()=>a?.()})]})]})})}function K({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 H=({webcamRef:n,canvasRef:o})=>{const{isError:r,isSuccess:c,showLoader:i,hasError:l,errorType:d,resetScanState:u,showGuideCard:f,scanStage:g,videoLoading:p,setVideoLoading:y,videoError:S,setVideoError:b,gender:w,getButtonText:v,isScanning:x,startScan:k,isModelLoaded:E,onRetry:M}=s(F),C=h();return r?e(G,{onRetry:M}):c?e("div",{className:"fixed z-[9] common-ui-main w-full h-full",style:{background:C?.style?.base?.backgroundColor},children:e(N,{url:C?.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:C?.style?.base?.backgroundColor},children:e(N,{url:C?.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:C?.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&&d===_.Camera&&e(I,{testId:"face-scan-camera-error-screen",config:C}),!i&&l&&d!==_.Camera&&e(G,{loading:i,onRetry:u}),f&&!l&&!i&&e(B,{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?u:k,isDisabled:i||!E,icon:e(x?U:a,{})}})})]})},X=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??"",I=n(null),U=n(null),B=n(null),A=n([]),q=n(null),G=n(null),[K,X]=o(!1),[Q,Y]=o(!1),[Z,ee]=o(!1),[te,ae]=o(!0),[ne,oe]=o(!1),[re,ce]=o(!1),[ie,se]=o(!1),[le,de]=o(null),[ue,me]=o(k()),fe=r(()=>E(N),[N]),{email:he,gender:ge,deviceFocalLength:pe,shopDomain:ye,callbackUrl:Se,bodyScanId:be}=x,[we,ve]=o([]),[xe,Fe]=o(M),Ne=r(()=>C(),[]),_e=D(we),Ie=T(_e);P();const ke=c(()=>{console.log("Stopping recording..."),B.current&&"recording"===B.current.state&&B.current.stop(),B.current=null},[]),Ee=async()=>{if(f?.(),A.current){if(0===A.current.length)return console.error("No video data recorded"),de(_.Scan),se(!0),void X(!1);h?.(),X(!0);const e=new File(A.current,`${ue}.${Ie}`,{type:_e}),t=G.current??await V(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:A.current.length,estimated_duration_seconds:o},c=[{gender:ge},{face_scan_id:ue},{focal_length:`${pe}`},{customer_store_url:ye},{scan_type:"face_scan"},{body_scan_id:be}];Se&&c.push({callback_url:Se}),O({eventName:`${ye}/face_scan_meta_data`,faceScanId:ue,email:he,data:JSON.stringify({metaData:c,videoData:r})});const i=Date.now();O({eventName:`${ye}/face_scan_upload_start`,faceScanId:ue,email:he,startTime:i});try{const t=await fe.fileUpload.faceScanFileUploader({file:e,arrayMetaData:c,objectKey:ue,email:he,contentType:e.type}),a=Date.now();O({eventName:`${ye}/face_scan_upload_complete`,faceScanId:ue,email:he,completionTime:a,uploadDuration:a-i}),g?.(),console.log("✅ Upload successful",t),fe.measurement.handlFaceScaneSocket({onPreopen:()=>{y?.(),W({eventName:`${ye}/webSocket`,faceScanID:ue,connection:"pre_open",type:"faceScan_recommendation",email:he})},faceScanId:ue,onOpen:()=>{W({eventName:`${ye}/webSocket`,faceScanID:ue,connection:"open",type:"faceScan_recommendation",email:he}),console.log("websocket connect open")},onError:e=>{W({eventName:`${ye}/webSocket`,faceScanID:ue,connection:"error",type:"faceScan_recommendation",email:he}),Le(e)},onSuccess:e=>{W({eventName:`${ye}/webSocket`,faceScanID:ue,connection:"success",type:"faceScan_recommendation",email:he}),Ve(e)},onClose:()=>{S?.(),console.log("websocket connect close"),W({eventName:`${ye}/webSocket`,faceScanID:ue,connection:"close",type:"faceScan_recommendation",email:he})}})}catch(e){g?.(),Le(e)}}},Me=c(()=>{const e=I.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;G.current=s;const l=o.captureStream(s),d={videoBitsPerSecond:15e5};let u;we.length>0&&(d.mimeType=we[0]);try{u=new MediaRecorder(l,d)}catch(e){return console.error("MediaRecorder init failed:",e),de(_.Scan),se(!0),void X(!1)}A.current=[],u.ondataavailable=e=>{e?.data&&e.data.size>0&&A.current&&A.current.push(e.data)},u.onstop=()=>{console.log("Recording stopped, total blobs:",A?.current?.length),Ee()},u.start(100),B.current=u,console.log("Recording started successfully (portrait normalized)")},[we,Ee]),{faceScanDetector:Ce,scanStage:De,setScanStage:Te,resetScan:Pe,isModelLoaded:Re,startScanSequence:ze}=J({faceScanId:ue,shopDomain:ye,isError:w,isSuccess:v,onScanComplete:()=>{ke()},onModelReady:()=>{Y(!0)},onStartRecording:()=>{console.log("Stage 0 completed - starting recording for stages 1-3"),Me()}}),$e=c(()=>{Re&&(m?.(),Te(0),d.playAudio(`${u}face-scan-vos/Face-forward.mp3`),setTimeout(()=>{ee(!0),setTimeout(()=>{ze()},200)},200))},[Te,ee,ze,Re,m]),je=c(()=>{ee(!1),ae(!0),ke(),Pe(),l?.(),A.current=[],G.current=null,B.current&&(B.current=null),se(!1),de(null),Te(-1),me(k()),I.current&&q.current&&(I.current.srcObject=q.current,console.log("Camera stream restored after reset"))},[Te,ee,ae,ke,Pe,me]),Le=e=>{console.log(e,"ws error"),s?.(e),de(_.Scan),se(!0),X(!1),ae(!1),O({eventName:`${ye}/faceScan`,faceScanId:ue,status:"failed",email:he,data:JSON.stringify(e)})},Ve=e=>{console.log(e,"ws success"),e&&"intermediate"===e?.resultType&&O({eventName:`${ye}/faceScan_success/intermediate`,faceScanId:ue,status:"success",email:he,data:JSON.stringify(e)}),a?.(e)};i(()=>{if(!w&&!v)return navigator.mediaDevices.getUserMedia&&navigator.mediaDevices.getUserMedia({video:xe}).then(e=>{q.current=e,I.current&&(I.current.srcObject=e)}).catch(e=>{if(console.error("Error accessing webcam:",e),xe===M)return void Fe(R);const t=["NotAllowedError","PermissionDeniedError","NotFoundError","DevicesNotFoundError","NotReadableError","TrackStartError"].includes(e?.name);de(t?_.Camera:_.Scan),se(!0)}),()=>{q.current&&q.current.getTracks().forEach(e=>e.stop())}},[w,v,xe]),i(()=>{if(!Q||!Z)return;const e=setInterval(()=>{Ce(I,U)},500);return()=>clearInterval(e)},[Ce,Q,Z]);return console.log("Model ready:",Q,"Has error:",ie,"Is scanning:",Z,"showLoader",K),i(()=>{const e=z(Ne,$);ve(e)},[Ne]),i(()=>{Te(-1)},[]),e("div",{"data-face-scan-stage":De,children:e(j,{children:e(L,{config:b,children:e(F.Provider,{value:{isError:w,isSuccess:v,showLoader:K,hasError:ie,errorType:le,resetScanState:je,showGuideCard:te,scanStage:De,videoLoading:ne,setVideoLoading:oe,videoError:re,setVideoError:ce,gender:ge,getButtonText:()=>Z?p.reset:Re?p.start:p.loading,isScanning:Z,startScan:$e,isModelLoaded:Re,onRetry:l},children:e(H,{webcamRef:I,canvasRef:U})})})})})};export{X as F};
|
|
2
|
-
//# sourceMappingURL=FaceScan-CQayY4q-.js.map
|