@swan-admin/swan-web-component 1.0.101 → 1.0.103

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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"BodyScan-CYHSL6Tj.js","sources":["../src/utils/context/mediaContext.tsx","../src/Icons/SwitchIcon.tsx","../src/components/bodyScan/LevelScreen.tsx","../src/components/bodyScan/CameraScanChild.tsx","../src/customHooks/useTensorFlow.ts","../src/components/bodyScan/ScanningComponent.tsx","../src/components/bodyScan/AngleDetector.tsx","../src/components/Modal.tsx","../src/components/bodyScan/CameraPermission.tsx","../src/components/bodyScan/VideoPlayer.tsx","../src/components/bodyScan/ScanErrorMessage.tsx","../src/components/Signup.tsx","../src/components/bodyScan/BodyScanSteps.tsx","../src/components/bodyScan/BodyScan.tsx","../src/customHooks/useGyroSensor.ts"],"sourcesContent":["\"use client\"\nimport React, {\n createContext,\n Dispatch,\n ReactNode,\n SetStateAction,\n useEffect,\n useLayoutEffect,\n useMemo,\n useState,\n} from \"react\";\n\nexport const MEDIA_TYPES = {\n DESKTOP: \"DESKTOP\",\n TAB: \"TAB\",\n MOBILE: \"MOBILE\",\n};\n\ninterface MediaContextType {\n size: number[];\n setSize: Dispatch<SetStateAction<number[]>>;\n clearInputs: boolean;\n setClearInputs: Dispatch<SetStateAction<boolean>>;\n media: string;\n}\n\nexport const MediaContext = createContext<MediaContextType | undefined>(\n undefined\n);\n\nfunction MediaContextProvider({ children }: { children: ReactNode }) {\n const [size, setSize] = useState([window?.innerWidth, window?.innerHeight]);\n const [clearInputs, setClearInputs] = useState(false);\n\n const updateSize = () => {\n setSize([window?.innerWidth, window?.innerHeight]);\n };\n useEffect(() => {\n updateSize();\n }, []);\n useLayoutEffect(() => {\n window.addEventListener(\"resize\", updateSize);\n return () => window.removeEventListener(\"resize\", updateSize);\n }, [updateSize]);\n let media = MEDIA_TYPES.DESKTOP;\n if (size[0] > 768 && size[0] < 1024) {\n media = MEDIA_TYPES.TAB;\n }\n if (size[0] < 768) {\n media = MEDIA_TYPES.MOBILE;\n }\n\n const mediaDetails = useMemo(\n () => ({\n size,\n setSize,\n clearInputs,\n setClearInputs,\n media,\n }),\n [size, clearInputs, media]\n );\n\n return (\n <MediaContext.Provider value={mediaDetails}>\n {children}\n </MediaContext.Provider>\n );\n}\n\nexport default MediaContextProvider;\n","import React from \"react\";\n\nfunction SwitchIcon({ size = 16 }: { size?: number }) {\n return (\n <svg\n width={size}\n height={size}\n viewBox=\"0 0 25 25\"\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n >\n <path\n d=\"M22.6968 14.6968C22.6968 16.8185 21.8539 18.8533 20.3536 20.3536C18.8533 21.8539 16.8185 22.6968 14.6968 22.6968\"\n stroke=\"white\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n />\n <path\n d=\"M18.6968 11.6968V10.6968C18.6968 10.1663 18.4861 9.65764 18.111 9.28256C17.7359 8.90749 17.2272 8.69678 16.6968 8.69678C16.1663 8.69678 15.6576 8.90749 15.2826 9.28256C14.9075 9.65764 14.6968 10.1663 14.6968 10.6968\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n />\n <path\n d=\"M14.6968 10.6968V9.69678C14.6968 9.16634 14.4861 8.65764 14.111 8.28256C13.7359 7.90749 13.2272 7.69678 12.6968 7.69678C12.1663 7.69678 11.6576 7.90749 11.2826 8.28256C10.9075 8.65764 10.6968 9.16634 10.6968 9.69678V10.6968\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n />\n <path\n d=\"M10.6968 10.1968V4.69678C10.6968 4.16634 10.4861 3.65764 10.111 3.28256C9.73592 2.90749 9.22721 2.69678 8.69678 2.69678C8.16634 2.69678 7.65764 2.90749 7.28256 3.28256C6.90749 3.65764 6.69678 4.16634 6.69678 4.69678V14.6968\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n />\n <path\n d=\"M18.6969 11.6968C18.6969 11.1663 18.9076 10.6576 19.2827 10.2826C19.6577 9.90749 20.1664 9.69678 20.6969 9.69678C21.2273 9.69678 21.736 9.90749 22.1111 10.2826C22.4862 10.6576 22.6969 11.1663 22.6969 11.6968V14.6968C22.6969 16.8185 21.854 18.8533 20.3537 20.3536C18.8534 21.8539 16.8186 22.6968 14.6969 22.6968H12.6969C9.89688 22.6968 8.19688 21.8368 6.70688 20.3568L3.10688 16.7568C2.76282 16.3757 2.57847 15.8769 2.592 15.3637C2.60554 14.8505 2.81593 14.3621 3.1796 13.9997C3.54327 13.6373 4.03238 13.4287 4.54565 13.417C5.05892 13.4053 5.55704 13.5914 5.93688 13.9368L7.69688 15.6968\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n />\n </svg>\n );\n}\n\nexport default React.memo(SwitchIcon);\n","/* eslint-disable no-nested-ternary */\n\nimport React, { useCallback, useContext, useMemo } from \"react\";\nimport Header from \"../Header\";\nimport cn from \"clsx\";\nimport { LevelScreenProps } from \"../../types/interfaces\";\nimport SwitchIcon from \"../../Icons/SwitchIcon\";\nimport { LanguageContext } from \"../../utils/context/languageContext\";\nimport { LanguageKeys } from \"../../utils/languageKeys\";\n\nfunction LevelScreen({ angle, countdown, isScanning, isInTargetRange, stabilityScore, children, config }: LevelScreenProps) {\n\tconst { translate } = useContext(LanguageContext) || {};\n\n\tconst getProximityToTarget = useCallback(() => {\n\t\tif (angle < 80) return Math.max(0, Math.min(100, (angle - 60) * 10));\n\t\tif (angle > 95) return Math.max(0, Math.min(100, (105 - angle) * 10));\n\t\treturn 100;\n\t}, [angle]);\n\n\tconst backgroundColor = useMemo(() => {\n\t\tif (isScanning) return config?.style?.angleDetector?.successAngleBackground || \"#4f46e5\";\n\n\t\tconst proximity = getProximityToTarget();\n\t\tif (proximity === 0) return config?.style?.angleDetector?.successAngleLowBackground || \"#ffffff\";\n\t\tif (proximity === 100) return config?.style?.angleDetector?.successAngleBackground || \"#4f46e5\";\n\n const r = Math.round(255 - (255 - 139) * (proximity / 100));\n const g = Math.round(255 - (255 - 92) * (proximity / 100));\n const b = Math.round(255 - (255 - 246) * (proximity / 100));\n return `rgb(${r}, ${g}, ${b})`;\n }, [isScanning, getProximityToTarget]);\n\n\tconst handelTextColour = useCallback((isLight: boolean, proximity: number) => {\n\t\tif (proximity > 70) {\n\t\t\treturn isLight ? `text-[${config?.style?.angleDetector?.successAngleTextLightColor}]/70` : `text-[${config?.style?.angleDetector?.successAngleTextLightColor}]`;\n\t\t}\n\t\treturn isLight ? `text-[${config?.style?.angleDetector?.successAngleTextLightColor}]/40` : `text-[${config?.style?.angleDetector?.successAngleTextDarkColor}]/70`;\n\t}, []);\n\n\tconst getTextColor = useCallback(\n\t\t(isLight = false) => {\n\t\t\tconst proximity = getProximityToTarget();\n\t\t\tif (isScanning) return `text-[${config?.style?.angleDetector?.successAngleTextLightColor}]`;\n\t\t\treturn handelTextColour(isLight, proximity);\n\t\t},\n\t\t[isScanning, getProximityToTarget],\n\t);\n\n\tconst handelColourCode = useCallback((isLight: boolean, proximity: number) => {\n\t\tif (proximity > 70) {\n\t\t\treturn isLight ? config?.style?.angleDetector?.successAngleTextLightColor : config?.style?.angleDetector?.successAngleTextLightColor;\n\t\t}\n\t\treturn isLight ? config?.style?.angleDetector?.successAngleTextLightColor : config?.style?.angleDetector?.successAngleTextDarkColor;\n\t}, []);\n\tconst getColorCode = useCallback(\n\t\t(isLight = false) => {\n\t\t\tconst proximity = getProximityToTarget();\n\t\t\tif (isScanning) return config?.style?.angleDetector?.successAngleTextLightColor;\n\t\t\treturn handelColourCode(isLight, proximity);\n\t\t},\n\t\t[isScanning, getProximityToTarget],\n\t);\n\tconst cd = countdown;\n\tfunction fixVh() {\n\t\tdocument.documentElement.style.setProperty(\"--real-vh\", window.innerHeight + \"px\");\n\t}\n\tfixVh();\n\twindow.addEventListener(\"resize\", fixVh);\n\treturn (\n\t\t<div\n\t\t\tclassName=\"flex w-screen flex-col items-center h-[var(--real-vh)] overflow-hidden touch-none justify-center transition-all duration-300 max-w-[28rem] mx-auto\"\n\t\t\tstyle={{ backgroundColor }}\n\t\t\t// onDoubleClick={onDoubleClick}\n\t\t>\n\t\t\t<div className=\"flex justify-start fixed top-[.5rem] max-w-[28rem] mx-auto w-full px-[1rem]\">\n\t\t\t\t<div className=\"flex justify-start \">\n\t\t\t\t\t<Header noTitle resolvedConfig={config} />\n\t\t\t\t</div>\n\t\t\t</div>\n\t\t\t{cd !== null ? (\n\t\t\t\t<div\n\t\t\t\t\tclassName=\"relative flex h-[6rem] w-[6rem] items-center justify-center rounded-[9999px] bg-[#fff]/20 transition-all duration-300\"\n\t\t\t\t\tstyle={{\n\t\t\t\t\t\tborder: `2px solid ${getColorCode()}`,\n\t\t\t\t\t}}\n\t\t\t\t>\n\t\t\t\t\t<div\n\t\t\t\t\t\tclassName={`text-[3rem] font-bold text-[${getColorCode()}]`}\n\t\t\t\t\t\tstyle={{\n\t\t\t\t\t\t\tfontFamily: config?.style?.base?.baseFontFamily || \"Inter, sans-serif\",\n color: getColorCode(),\n\t\t\t\t\t\t}}\n\t\t\t\t\t>\n\t\t\t\t\t\t{cd}\n\t\t\t\t\t</div>\n\t\t\t\t</div>\n\t\t\t) : isScanning ? (\n\t\t\t\t<div className=\"relative flex flex-col items-center justify-center\">\n\t\t\t\t\t<div className=\"relative flex h-16 w-16 items-center justify-center rounded-[9999px] border-2 bg-[#fff]/30 border-[#fff]\">\n\t\t\t\t\t\t<div className=\"h-4 w-4 rounded-[9999px] animate-pulse bg-[#fff]/80\" />\n\t\t\t\t\t</div>\n\t\t\t\t\t{children}\n\t\t\t\t</div>\n\t\t\t) : (\n\t\t\t\t<div\n\t\t\t\t\tclassName={cn(\"relative flex h-[4rem] w-[4rem] items-center justify-center rounded-[9999px] \", isInTargetRange ? \"bg-[#fff]/20 border-[#fff]\" : \"bg-[#fff]/10 border-[#fff]\")}\n\t\t\t\t\tstyle={{\n\t\t\t\t\t\ttransform: `translateY(${(90 - angle) * 3}px)`,\n\t\t\t\t\t\ttransition: \"transform 0.2s ease-out\",\n\t\t\t\t\t\tborder: `2px solid ${getColorCode()}`,\n\t\t\t\t\t}}\n\t\t\t\t>\n\t\t\t\t\t<div className={`h-[1rem] w-[1rem] rounded-[9999px] bg-[${getColorCode()}]/80`}\n style={{\n\t\t\t\t\t\tbackgroundColor: `${getColorCode()}B3`,\n\t\t\t\t\t}}\n />\n\t\t\t\t\t<div\n\t\t\t\t\t\t// className=\" text-[#fff]\"\n\t\t\t\t\t\tclassName={cn(\"mt-[.5rem] text-center w-[180px] flex-col flex items-center absolute top-[60px]\", getTextColor())}\n style={{\n\t\t\t\t\t\tcolor: getColorCode(),\n\t\t\t\t\t}}\n\t\t\t\t\t>\n\t\t\t\t\t\t<SwitchIcon size={30} />\n\t\t\t\t\t\t<p\n\t\t\t\t\t\t\tstyle={{\n\t\t\t\t\t\t\t\tfontFamily: config?.style?.base?.baseFontFamily || \"Inter, sans-serif\",\n\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t{\" \"}\n\t\t\t\t\t\t\t{translate?.(LanguageKeys.startLevelCheck)}\n\t\t\t\t\t\t\t<br />\n\t\t\t\t\t\t</p>\n\t\t\t\t\t</div>\n\t\t\t\t</div>\n\t\t\t)}\n\n\t\t\t{cd !== null && (\n\t\t\t\t<div className=\"absolute bottom-[8rem] text-center\">\n\t\t\t\t\t<div\n\t\t\t\t\t\tclassName={cn(\"text-sm font-medium px-4 py-1.5 bg-black/20 rounded-[9999px] mt-8\", getTextColor())}\n\t\t\t\t\t\tstyle={{\n\t\t\t\t\t\t\tfontFamily: config?.style?.base?.baseFontFamily || \"Inter, sans-serif\",\n color: getColorCode(),\n\t\t\t\t\t\t}}\n\t\t\t\t\t>\n\t\t\t\t\t\t{translate?.(LanguageKeys.leavePhone)}\n\t\t\t\t\t</div>\n\t\t\t\t</div>\n\t\t\t)}\n\t\t\t{isInTargetRange && cd === null && !isScanning && (\n\t\t\t\t<div className=\"absolute bottom-[8rem] w-[12rem]\">\n\t\t\t\t\t<div\n\t\t\t\t\t\tclassName={`h-[.375rem] w-full bg-[${getColorCode()}]/20 rounded-[9999px] overflow-hidden`}\n\t\t\t\t\t\tstyle={{\n\t\t\t\t\t\t\tbackgroundColor: `${getColorCode()}33`, // 20% opacity\n\t\t\t\t\t\t}}\n\t\t\t\t\t>\n\t\t\t\t\t\t<div\n\t\t\t\t\t\t\tclassName={`h-full bg-[${getColorCode()}]/70 transition-all duration-300 rounded-[9999px]`}\n\t\t\t\t\t\t\tstyle={{\n\t\t\t\t\t\t\t\twidth: `${angle}%`,\n\t\t\t\t\t\t\t\tbackgroundColor: `${getColorCode()}B3`,\n\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t/>\n\t\t\t\t\t</div>\n\t\t\t\t</div>\n\t\t\t)}\n\n {cd === null && !isScanning && (\n <div className=\"absolute bottom-[5rem] text-center\">\n <div className={cn(\"text-[1.5rem] font-light\", getTextColor())}\n style={{\n\t\t\t\t\t\tcolor: getColorCode(),\n\t\t\t\t\t}}\n >\n {Math.round(angle)}°\n </div>\n </div>\n )}\n\n\t\t\t{cd === null && !isScanning && (\n\t\t\t\t<div className=\"absolute bottom-[2rem] text-center max-w-[20rem] mx-auto\">\n\t\t\t\t\t<div\n\t\t\t\t\t\tclassName={cn(\"text-[.75rem] opacity-50\", getTextColor())}\n\t\t\t\t\t\tstyle={{\n\t\t\t\t\t\t\tfontFamily: config?.style?.base?.baseFontFamily || \"Inter, sans-serif\",\n color: getColorCode(),\n\t\t\t\t\t\t}}\n\t\t\t\t\t>\n\t\t\t\t\t\t{translate?.(LanguageKeys.placePhoneUpright)}\n\t\t\t\t\t</div>\n\t\t\t\t</div>\n\t\t\t)}\n\t\t</div>\n\t);\n}\nexport default React.memo(LevelScreen);\n","import { useContext } from \"react\";\nimport Webcam from \"react-webcam\";\nimport { CameraScanChildProps } from \"../../types/interfaces\";\nimport { MEDIA_TYPES, MediaContext } from \"../../utils/context/mediaContext\";\nimport { LanguageContext } from \"../../utils/context/languageContext\";\nimport { pauseIcon, videoConstraints, voiceOverAssetsPath } from \"../../utils/constants\";\nimport SpecificButton from \"../../atoms/specificButton/SpecificButton\";\nimport { LanguageKeys } from \"../../utils/languageKeys\";\nimport { X } from \"lucide-react\";\n\n\n\nfunction CameraScanChild({\n handleShowStreamCamera,\n loadingCam,\n handleUserMedia,\n handlePause,\n pause,\n recordingStarted,\n startSendingVideoFrames,\n showPause,\n webcamRef,\n resetDetector,\n config,\n}: CameraScanChildProps) {\n const { media } = useContext(MediaContext) || {};\n const { translate } = useContext(LanguageContext) || {};\n\n return (\n <div className=\"App w-screen h-[100vh] relative \">\n <span\n onClick={() => {\n handleShowStreamCamera();\n resetDetector();\n }}\n className=\"fixed right-[20px] top-[20px] z-[999]\"\n >\n <X className=\"text-[#fff]\" />\n </span>\n\n <div className=\"w-full h-full overflow-hidden \">\n {media === MEDIA_TYPES.MOBILE && (\n <Webcam\n audio={false}\n ref={webcamRef}\n screenshotQuality={1}\n videoConstraints={videoConstraints}\n mirrored\n screenshotFormat=\"image/jpeg\"\n onUserMedia={handleUserMedia}\n style={{\n position: \"fixed\",\n top: 0,\n bottom: 0,\n zIndex: 0,\n width: \"100%\",\n height: \"100%\",\n objectFit: \"cover\",\n }}\n />\n )}\n </div>\n\n <div className=\"fixed bottom-[30px] w-full z-[999] flex flex-col gap-4 items-center justify-center\">\n {showPause && (\n <SpecificButton\n className=\"!w-[180px] !h-[40px] !py-[0] mx-auto \"\n prefix={pauseIcon}\n buttonText={translate?.(LanguageKeys.pause)}\n buttonFunc={handlePause}\n resolvedConfig={config}\n btnSecondary\n />\n )}\n\n {pause ? (\n <div>\n <SpecificButton\n className=\"!w-[180px] !h-[40px] !py-[0] mx-auto\"\n buttonText={translate?.(LanguageKeys.restart)}\n buttonFunc={handleShowStreamCamera}\n resolvedConfig={config}\n btnSecondary\n />\n </div>\n ) : !recordingStarted ? (\n <SpecificButton\n className={`!w-[180px] !h-[40px] !py-[0] mx-auto !bg-[#ffffff] !text-[#000000] ${\n loadingCam ? \"!opacity-50\" : \"\"\n }`}\n buttonText={translate?.(LanguageKeys.startScan)}\n buttonFunc={startSendingVideoFrames}\n disabled={loadingCam}\n resolvedConfig={config}\n />\n ) : null}\n </div>\n\n <audio\n id=\"audioElement\"\n crossOrigin=\"anonymous\"\n preload=\"auto\"\n style={{\n position: \"absolute\",\n zIndex: -99999,\n }}\n src={`${voiceOverAssetsPath}scanAudioInstructions/silence.mp3`}\n />\n </div>\n );\n}\n\nexport default CameraScanChild;\n","import { useState, useRef, useEffect } from \"react\";\n// We keep this, but we will make it optional in the logic below\n\ntype KeypointTuple = [number, number, number];\n\n// GLOBAL SINGLETONS (Persist across component re-mounts)\n// This prevents reloading the heavy model if the user navigates away and back.\nlet globalLoadingPromise: Promise<boolean> | null = null;\nlet globalDetector: any = null;\nlet globalPoseLib: any = null;\n\nexport default function useTensorFlow() {\n const [consecutiveFronts, setConsecutiveFronts] = useState(0);\n const [spinPhase, setSpinPhase] = useState(0);\n const [isLoaded, setIsLoaded] = useState(false);\n\n const spinPhaseRef = useRef(0);\n const consecutiveFrontsRef = useRef(0);\n const mounted = useRef(true);\n\n useEffect(() => {\n mounted.current = true; // Reset on mount\n\n // 1. If already loaded globally, just use it.\n if (globalDetector) {\n setIsLoaded(true);\n return;\n }\n\n // 2. If not loading, start the process.\n if (!globalLoadingPromise) {\n globalLoadingPromise = loadDependenciesGlobal();\n }\n\n // 3. Wait for the global promise to resolve.\n globalLoadingPromise.then((success) => {\n if (success && mounted.current) {\n setIsLoaded(true);\n }\n });\n\n return () => {\n mounted.current = false;\n };\n }, []);\n\n /**\n * Loads TensorFlow/MediaPipe dynamically.\n * This logic is ISOLATED from the server.\n */\n async function loadDependenciesGlobal(): Promise<boolean> {\n // GUARDRAIL 1: Strict Environment Check\n // Ensure we are in a browser environment with media capabilities\n if (\n typeof window === 'undefined' || \n typeof navigator === 'undefined'\n ) {\n return false;\n }\n \n try {\n console.log(\"Starting TensorFlow preload...\");\n \n // GUARDRAIL 2: Dynamic Imports\n // These heavy modules are only fetched by the browser, never the server.\n const [poseLib, tfjsCore, tfjsBackend] = await Promise.all([\n import(\"@tensorflow-models/pose-detection\"),\n import(\"@tensorflow/tfjs-core\"),\n import(\"@tensorflow/tfjs-backend-webgl\") // Triggers backend registration side-effect\n ]);\n \n globalPoseLib = poseLib;\n \n // Explicitly set the backend to WebGL for performance\n await tfjsCore.setBackend('webgl');\n await tfjsCore.ready();\n console.log(\"TensorFlow backend ready (WebGL)\");\n\n // GUARDRAIL 3: Zero-Config Asset Loading\n // If TENSORFLOW_SOLUTION_PATH fails or is missing, we must fallback \n // to a CDN so the user doesn't have to copy files manually.\n const modelConfig = {\n runtime: \"mediapipe\",\n modelType: \"full\",\n solutionPath:\"https://cdn.jsdelivr.net/npm/@mediapipe/pose\", // Fallback for Zero Config\n } as const;\n\n try {\n globalDetector = await globalPoseLib.createDetector(\n globalPoseLib.SupportedModels.BlazePose,\n modelConfig\n );\n console.log(\"MediaPipe detector created successfully\");\n } catch (mediapipeError) {\n console.warn(\"MediaPipe failed, falling back to TFJS runtime:\", mediapipeError);\n \n // Fallback to TFJS runtime (slower but works without external assets)\n globalDetector = await globalPoseLib.createDetector(\n globalPoseLib.SupportedModels.BlazePose,\n {\n runtime: \"tfjs\",\n modelType: \"full\",\n }\n );\n console.log(\"TFJS detector created successfully\");\n }\n \n return true;\n } catch (error) {\n console.error(\"Failed to load TensorFlow dependencies:\", error);\n globalLoadingPromise = null; // Reset so retry is possible\n return false;\n }\n }\n\n function isFrontFrame(body: KeypointTuple[]) {\n // Guardrail: Ensure points exist before filtering\n if (!body || body.length === 0) return false;\n return body.filter((p) => p[2] > 0.7).length === 22;\n }\n\n const poseDetector = async (callback: () => void, webcamRef: any) => {\n // GUARDRAIL 4: Runtime Safety\n // Check if everything is truly ready before calculating\n if (!globalDetector || !mounted.current || !webcamRef?.current?.video) {\n return;\n }\n \n // Check if video is actually playing and has data\n const video = webcamRef.current.video;\n if (video.readyState < 2) return; \n\n try {\n const poses = await globalDetector.estimatePoses(\n video,\n { flipHorizontal: false }\n );\n\n if (!poses || !poses.length) return;\n\n const keypoints = poses[0].keypoints;\n \n // Standardize keypoints\n const body: KeypointTuple[] = keypoints\n .slice(11) // Ignore face keypoints (0-10)\n .map((kp: any) => [\n kp.x > 0 && kp.x < 720 ? kp.x : -1,\n kp.y > 0 && kp.y < 1280 ? kp.y : -1,\n kp.score ?? 0,\n ]);\n\n if (spinPhaseRef.current === 0 && !isFrontFrame(body)) {\n setConsecutiveFronts((prev) => prev + 1);\n }\n\n if (spinPhaseRef.current === 1 && isFrontFrame(body)) {\n setConsecutiveFronts((prev) => prev + 1);\n }\n\n if (spinPhaseRef.current === 2) callback();\n } catch (err) {\n console.error(\"Pose detection error:\", err);\n }\n };\n\n useEffect(() => {\n consecutiveFrontsRef.current = consecutiveFronts;\n if (consecutiveFronts > 6 && spinPhaseRef.current < 2) {\n setSpinPhase((s) => s + 1);\n setConsecutiveFronts(0);\n }\n }, [consecutiveFronts]);\n\n useEffect(() => {\n spinPhaseRef.current = spinPhase;\n }, [spinPhase]);\n\n const resetDetector = () => {\n spinPhaseRef.current = 0;\n consecutiveFrontsRef.current = 0;\n setConsecutiveFronts(0);\n setSpinPhase(0);\n };\n\n const retryLoading = async () => {\n if (!globalDetector && !globalLoadingPromise) {\n globalLoadingPromise = loadDependenciesGlobal();\n const success = await globalLoadingPromise;\n if (success && mounted.current) {\n setIsLoaded(true);\n }\n }\n };\n\n return { \n poseDetector, \n isLoaded,\n spinPhase,\n resetDetector,\n retryLoading\n };\n}","/* eslint-disable no-use-before-define */\nimport React, { useCallback, useContext, useEffect, useRef, useState } from \"react\";\nimport CameraScanChild from \"./CameraScanChild\";\nimport posthog from \"posthog-js\";\nimport Webcam from \"react-webcam\";\nimport { ScanningComponentProps } from \"../../types/interfaces\";\nimport useTensorFlow from \"../../customHooks/useTensorFlow\";\nimport ParamsContext from \"../../utils/context/paramsContext\";\nimport { generateUuid, getCurrentTimeInSeconds, handleScanTimeCapture, rescanSupportCaptureEvent } from \"../../utils/utils\";\nimport speechService from \"../../utils/service/speechService\";\nimport swan from \"../../utils/service/swanService\";\nimport { videoTypes, voiceOverAssetsPath } from \"../../utils/constants\";\n\nlet id: string | null = null;\nlet audioTimeoutId: number | undefined | NodeJS.Timeout;\nlet lastVideoPlayed: {\n\tskipCount: number;\n\tno_of_times_skipped: number;\n\taudioName: string;\n} | null = null;\n\nfunction ScanningComponent({ setIsScanLocked, resetDetector, scanID, setIsVideoUploaded, setScanFailsError, setScanStartTime, setScanUniqueKey, userDetails, config }: ScanningComponentProps) {\n\tconst { gender, heightInCm, email, shopDomain } = userDetails;\n\tconst webcamRef = useRef<Webcam | null>(null);\n\tconst mediaRecorderRef = useRef<MediaRecorder | null>(null);\n\tconst [recordedChunks, setRecordedChunks] = useState<Blob[]>([]);\n\tconst [loadingCam, setLoadingCam] = useState(true);\n\tconst [recordingStarted, setRecordingStarted] = useState(false);\n\tconst [faceDone, setFaceDone] = useState(false);\n\tconst [mediaRecorderStopped, setMediaRecorderStopped] = useState(true);\n\tconst [isScanning, setIsScanning] = useState(false);\n\tconst captureVideoTimeOutHandle = useRef<number | null | NodeJS.Timeout>(null);\n\tconst [audioSource, setAudioSource] = useState(\"\");\n\tconst [audioSourceList, setAudioSourceList] = useState<string[]>([]);\n\tconst [emptyAudioSource, setEmptyAudioSource] = useState(\"\");\n\tconst [startAgain, setStartAgain] = useState(false);\n\tconst [showRestart, setRestart] = useState(false);\n\tconst [pause, setPause] = useState(false);\n\tconst [events, setEvents] = useState<any>([]);\n\tconst [showPause, setShowPause] = useState(false);\n\tconst allowAudioToPlay = useRef(true);\n\tconst { poseDetector } = useTensorFlow();\n\tconst firstScan = useRef(true);\n\tconst poseStoppedRef = useRef(false);\n\tconst [supportedTypes, setSupportedTypes] = useState<string[]>([]);\n\n\tlet counter = 0;\n\n\tconst { setStartGyro, handleFileUpload, setUploadLoading } = useContext(ParamsContext);\n\n\tconst handleShowStreamCamera = () => {\n\t\tposeStoppedRef.current = false;\n\t\tclearTimeout(audioTimeoutId);\n\t\tif (captureVideoTimeOutHandle.current) clearTimeout(captureVideoTimeOutHandle.current);\n\t\tsetScanUniqueKey(generateUuid());\n\t\tsetScanFailsError(\"\");\n\t\tsetUploadLoading?.(false);\n\t\tsetRecordedChunks([]);\n\t\tsetLoadingCam(true);\n\t\tsetRecordingStarted(false);\n\t\tsetFaceDone(false);\n\t\tsetMediaRecorderStopped(true);\n\t\tsetIsScanning(false);\n\t\tcaptureVideoTimeOutHandle.current = null;\n\t\tsetAudioSource(\"\");\n\t\tsetAudioSourceList([]);\n\t\tsetEmptyAudioSource(\"\");\n\t\tsetStartAgain(!startAgain);\n\t\tsetStartGyro(false);\n\t\tspeechService.stopAudio();\n\t\tsetRestart(false);\n\t\tsetPause(false);\n\t\tcounter = 0;\n\t\tif (mediaRecorderRef.current !== null) {\n\t\t\tmediaRecorderRef.current.stop();\n\t\t}\n\n\t\tevents.forEach((el: any) => {\n\t\t\tif (mediaRecorderRef.current) mediaRecorderRef.current.removeEventListener(\"dataavailable\", el);\n\t\t});\n\n\t\tsetEvents([]);\n\t\tallowAudioToPlay.current = true;\n\t\tsetShowPause(false);\n\t\tsetIsVideoUploaded(false);\n\t};\n\n\tconst handleUserMedia = useCallback(() => {\n\t\tsetTimeout(() => {\n\t\t\tsetLoadingCam(false);\n\t\t}, 1000);\n\t}, []);\n\n\tconst handleReScan = useCallback(() => {\n\t\trescanSupportCaptureEvent({\n\t\t\teventName: `${shopDomain}/rescan`,\n\t\t\temail,\n\t\t\tscanID: scanID,\n\t\t\theight: heightInCm,\n\t\t\tgender,\n\t\t\tstatus: false,\n\t\t});\n\t\tallowAudioToPlay.current = false;\n\t\thandleShowStreamCamera();\n\t\tstartSendingVideoFrames();\n\t}, [handleShowStreamCamera, scanID, email]);\n\n\tconst handlePause = useCallback(() => {\n\t\tallowAudioToPlay.current = false;\n\t\tsetPause(true);\n\t\tsetShowPause(false);\n\t\tif (captureVideoTimeOutHandle.current) clearTimeout(captureVideoTimeOutHandle.current);\n\t\tif (mediaRecorderRef.current) {\n\t\t\tmediaRecorderRef.current.pause();\n\t\t}\n\t\tspeechService.stopAudio();\n\t\tswan.poseDetection.disconnect();\n\t\tcounter = 0;\n\t\tif (mediaRecorderRef.current) {\n\t\t\tmediaRecorderRef.current.stop();\n\t\t}\n\t\tevents.forEach((el: any) => {\n\t\t\tif (mediaRecorderRef.current) mediaRecorderRef.current.removeEventListener(\"dataavailable\", el);\n\t\t});\n\t\tsetEvents([]);\n\t\tclearTimeout(audioTimeoutId);\n\t}, [mediaRecorderRef, events, speechService, allowAudioToPlay]);\n\n\t// const supportedTypes = videoTypes.filter((type) => MediaRecorder.isTypeSupported(type));\n\n\tconst stopRecording = useCallback(async () => {\n\t\tallowAudioToPlay.current = true;\n\t\tawait speechService.playAudio(`${voiceOverAssetsPath}SpotOn.mp3`);\n\t\tsetPause(false);\n\t\tsetShowPause(false);\n\t\tif (captureVideoTimeOutHandle.current) clearTimeout(captureVideoTimeOutHandle.current);\n\t\tsetRecordingStarted(false);\n\t}, [captureVideoTimeOutHandle, speechService]);\n\n\tconst handleSocket = useCallback(async () => {\n\t\ttry {\n\t\t\tid = await swan.poseDetection.connect();\n\n\t\t\tposthog.capture(`${shopDomain}/pose_detection_connected`, {\n\t\t\t\tscanID: scanID,\n\t\t\t\temail,\n\t\t\t\tid,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tconsole.log(error, \"while connecting websocket\");\n\t\t}\n\t}, [scanID, shopDomain, email]);\n\n\tconst handleSpinDataAvailable = useCallback(\n\t\t({ data }: BlobEvent) => {\n\t\t\tif (data && data.size > 0 && allowAudioToPlay.current) {\n\t\t\t\tsetRecordedChunks((prev) => prev.concat(data));\n\t\t\t\tif (!poseStoppedRef.current && webcamRef.current) {\n\t\t\t\t\tposeStoppedRef.current = true;\n\t\t\t\t\tposeDetector(() => {\n\t\t\t\t\t\tstopRecording();\n\t\t\t\t\t\thandleScanTimeCapture({\n\t\t\t\t\t\t\teventName: `${shopDomain}/tensorFlow`,\n\t\t\t\t\t\t\tscanID: scanID,\n\t\t\t\t\t\t\temail,\n\t\t\t\t\t\t\tmessage: \"recording stopped by tensorflow \",\n\t\t\t\t\t\t});\n\t\t\t\t\t}, webcamRef);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\t[stopRecording, handleScanTimeCapture, shopDomain, scanID, email, webcamRef],\n\t);\n\n\tconst playAudio = useCallback(async () => {\n\t\tif (audioSourceList.length > 0 && allowAudioToPlay.current) {\n\t\t\tawait speechService.playAudio(voiceOverAssetsPath + audioSourceList[audioSourceList.length - 1]);\n\t\t\tif (allowAudioToPlay.current) {\n\t\t\t\taudioTimeoutId = setTimeout(playAudio, 2000);\n\t\t\t}\n\t\t}\n\t}, [audioSourceList, allowAudioToPlay]);\n\n\tconst handleStartCaptureClick = useCallback(() => {\n\t\tif (mediaRecorderRef && mediaRecorderRef.current) {\n\t\t\tmediaRecorderRef.current.stop();\n\t\t}\n\t\tsetRecordingStarted(true);\n\t\ttry {\n\t\t\tif (webcamRef && webcamRef.current && webcamRef.current.stream) {\n\t\t\t\tconst mediaRecorderOptions = {\n\t\t\t\t\tmimeType: supportedTypes[0],\n\t\t\t\t};\n\t\t\t\tmediaRecorderRef.current = new MediaRecorder(webcamRef.current.stream, mediaRecorderOptions);\n\t\t\t\tmediaRecorderRef.current.addEventListener(\"dataavailable\", handleSpinDataAvailable);\n\n\t\t\t\tsetEvents([...events, handleSpinDataAvailable]);\n\t\t\t\tmediaRecorderRef.current.start(1000);\n\t\t\t\tsetMediaRecorderStopped(false);\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tconsole.log(\"error while using media recorder\", e);\n\t\t}\n\t}, [webcamRef, supportedTypes, handleSpinDataAvailable, events]);\n\n\tconst postPoseProcess = useCallback(async () => {\n\t\tif (captureVideoTimeOutHandle.current) {\n\t\t\tclearTimeout(captureVideoTimeOutHandle.current);\n\t\t}\n\t\thandleStartCaptureClick();\n\t\tif (allowAudioToPlay.current) {\n\t\t\tcaptureVideoTimeOutHandle.current = setTimeout(async () => {\n\t\t\t\tif (allowAudioToPlay.current) {\n\t\t\t\t\tawait speechService.playAudio(`${voiceOverAssetsPath}SpotOn.mp3`);\n\t\t\t\t\tsetRecordingStarted(false);\n\t\t\t\t}\n\t\t\t}, 15000);\n\t\t}\n\t\tsetFaceDone(true);\n\t\tif (allowAudioToPlay.current) {\n\t\t\tawait speechService.playAudio(`${voiceOverAssetsPath}Spin.mp3`);\n\t\t}\n\t}, [handleStartCaptureClick, allowAudioToPlay, speechService]);\n\n\tconst handleDataAvailable = useCallback(\n\t\t({ data }: BlobEvent) => {\n\t\t\tif (data.size > 0 && swan.poseDetection.connected()) {\n\t\t\t\tswan.poseDetection.poseStatus(async (data) => {\n\t\t\t\t\tif (data && data.audio && data.audio.length > 0) {\n\t\t\t\t\t\tconst audio = document.querySelector(\"#audioElement\") as HTMLAudioElement | null;\n\t\t\t\t\t\tif (data.status === true && data.sid === id) {\n\t\t\t\t\t\t\tif (counter < 2) {\n\t\t\t\t\t\t\t\tif (counter === 0 && audio?.paused) {\n\t\t\t\t\t\t\t\t\tawait speechService.playAudio(voiceOverAssetsPath + data.audio);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcounter += 1;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tsetEmptyAudioSource(data.audio);\n\t\t\t\t\t\t\t\tclearTimeout(audioTimeoutId);\n\t\t\t\t\t\t\t\tswan.poseDetection.disconnect();\n\t\t\t\t\t\t\t\tsetTimeout(postPoseProcess, 1000);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tcounter = 0;\n\t\t\t\t\t\t\tif (audio?.paused && (!lastVideoPlayed || lastVideoPlayed?.audioName !== data.audio)) {\n\t\t\t\t\t\t\t\tlastVideoPlayed = {\n\t\t\t\t\t\t\t\t\tskipCount: 2,\n\t\t\t\t\t\t\t\t\tno_of_times_skipped: 0,\n\t\t\t\t\t\t\t\t\taudioName: data.audio,\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\tspeechService.playAudio(voiceOverAssetsPath + data.audio);\n\t\t\t\t\t\t\t} else if (lastVideoPlayed?.audioName === data.audio && audio?.paused) {\n\t\t\t\t\t\t\t\tif (lastVideoPlayed && lastVideoPlayed.no_of_times_skipped >= lastVideoPlayed.skipCount) {\n\t\t\t\t\t\t\t\t\tlastVideoPlayed.no_of_times_skipped = 0;\n\t\t\t\t\t\t\t\t\tspeechService.playAudio(voiceOverAssetsPath + data.audio);\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tif (lastVideoPlayed) lastVideoPlayed.no_of_times_skipped += 1;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tif (webcamRef?.current && webcamRef.current.getScreenshot() !== null) {\n\t\t\t\t\tswan.poseDetection.videoEmit({\n\t\t\t\t\t\timage: webcamRef.current.getScreenshot() || \"\",\n\t\t\t\t\t\tscanId: scanID,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\t[webcamRef, scanID, swan, id, counter, postPoseProcess, speechService],\n\t);\n\n\tconst startSendingVideoFrames = useCallback(async () => {\n\t\tsetIsScanning(true);\n\t\tsetStartGyro(true);\n\t\tif (firstScan.current) {\n\t\t\tfirstScan.current = false;\n\t\t\thandleScanTimeCapture({\n\t\t\t\teventName: \"scan started\",\n\t\t\t\tscanID: scanID,\n\t\t\t\tstatus: \"success\",\n\t\t\t\temail,\n\t\t\t});\n\t\t}\n\t\tsetScanStartTime(getCurrentTimeInSeconds());\n\t\tsetLoadingCam(true);\n\t\tif (allowAudioToPlay.current) {\n\t\t\tawait speechService.playAudio(`${voiceOverAssetsPath}StartScan.mp3`);\n\t\t}\n\t\tif (allowAudioToPlay.current) {\n\t\t\tawait speechService.playAudio(`${voiceOverAssetsPath}LiftArmsAndHoldAtHip.mp3`);\n\t\t}\n\t\tif (allowAudioToPlay.current) {\n\t\t\tsetIsScanning(false);\n\t\t\tsetRecordingStarted(true);\n\t\t\tsetRestart(true);\n\t\t\tsetShowPause(true);\n\t\t\thandleUserMedia();\n\t\t}\n\t\ttry {\n\t\t\tif (webcamRef && webcamRef.current && webcamRef.current.stream && allowAudioToPlay.current) {\n\t\t\t\tconst mediaRecorderOptions = {\n\t\t\t\t\tmimeType: supportedTypes[0],\n\t\t\t\t};\n\t\t\t\tif (allowAudioToPlay.current) {\n\t\t\t\t\tmediaRecorderRef.current = new MediaRecorder(webcamRef.current.stream, mediaRecorderOptions);\n\t\t\t\t}\n\t\t\t\tif (allowAudioToPlay.current && mediaRecorderRef.current) {\n\t\t\t\t\tmediaRecorderRef.current.addEventListener(\"dataavailable\", handleDataAvailable);\n\t\t\t\t}\n\n\t\t\t\tsetEvents([...events, handleDataAvailable]);\n\t\t\t\tif (mediaRecorderRef.current) mediaRecorderRef.current.start(1000);\n\t\t\t\tsetMediaRecorderStopped(false);\n\t\t\t\tif (allowAudioToPlay.current) {\n\t\t\t\t\taudioTimeoutId = setTimeout(playAudio, 2000);\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (err) {\n\t\t\tconsole.log(\"error ----------\", err);\n\t\t}\n\t}, [webcamRef, supportedTypes, handleDataAvailable, events, playAudio, allowAudioToPlay]);\n\n\tuseEffect(() => {\n\t\tif (shopDomain) {\n\t\t\tsetIsScanLocked(true);\n\t\t\thandleSocket();\n\t\t}\n\t\treturn () => {\n\t\t\tif (id) {\n\t\t\t\tswan.poseDetection.disconnect();\n\t\t\t\tposthog.capture(`${shopDomain}/pose_detection_disconnected`, {\n\t\t\t\t\tscanID: scanID,\n\t\t\t\t\temail,\n\t\t\t\t\tid,\n\t\t\t\t});\n\t\t\t}\n\t\t\tevents.forEach((el: any) => {\n\t\t\t\tmediaRecorderRef?.current?.removeEventListener(\"dataavailable\", el);\n\t\t\t});\n\t\t};\n\t}, [startAgain, shopDomain]);\n\tuseEffect(() => {\n\t\taudioSourceList.push(audioSource);\n\t}, [audioSource]);\n\n\tuseEffect(() => {\n\t\tsetAudioSourceList([]);\n\t}, [emptyAudioSource]);\n\tuseEffect(() => {\n\t\tconst bypassChecksToBackup = recordedChunks.length && recordedChunks.length > 0;\n\t\tif (!mediaRecorderStopped && bypassChecksToBackup && !recordingStarted && allowAudioToPlay.current && !pause) {\n\t\t\tif (mediaRecorderRef && mediaRecorderRef.current) {\n\t\t\t\tif (!recordingStarted) {\n\t\t\t\t\tmediaRecorderRef.current.stop();\n\t\t\t\t\tsetMediaRecorderStopped(true);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}, [mediaRecorderStopped, recordingStarted, recordedChunks, pause]);\n\n\tuseEffect(() => {\n\t\tconst bypassChecksToBackup = recordedChunks.length && recordedChunks.length > 0;\n\t\tif (!mediaRecorderStopped && bypassChecksToBackup && !recordingStarted) {\n\t\t\tif (mediaRecorderRef && mediaRecorderRef.current && allowAudioToPlay.current && !pause) {\n\t\t\t\tif (!recordingStarted) {\n\t\t\t\t\tconst videoFile = new File(recordedChunks, `${scanID}.webm`, {\n\t\t\t\t\t\ttype: \"video/webm\",\n\t\t\t\t\t});\n\t\t\t\t\tsetUploadLoading?.(true);\n\t\t\t\t\tsetScanFailsError(\"\");\n\t\t\t\t\thandleFileUpload?.(videoFile);\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tconsole.log(\"No video found to upload\");\n\t\t}\n\t}, [mediaRecorderStopped, recordingStarted, recordedChunks, pause, mediaRecorderRef, allowAudioToPlay]);\n\tuseEffect(() => {\n\t\tif (typeof MediaRecorder !== \"undefined\") {\n\t\t\tconst supported = videoTypes.filter((type) => MediaRecorder.isTypeSupported(type));\n\t\t\tsetSupportedTypes(supported);\n\t\t}\n\t}, []);\n\tuseEffect(() => {\n\t\thandleShowStreamCamera();\n\t}, []);\n\n\treturn (\n\t\t<CameraScanChild\n\t\t\tresetDetector={resetDetector}\n\t\t\thandleShowStreamCamera={handleShowStreamCamera}\n\t\t\tloadingCam={loadingCam}\n\t\t\thandlePause={handlePause}\n\t\t\tshowRestart={showRestart}\n\t\t\tpause={pause}\n\t\t\thandleReScan={handleReScan}\n\t\t\trecordingStarted={recordingStarted}\n\t\t\tisScanning={isScanning}\n\t\t\tstartSendingVideoFrames={startSendingVideoFrames}\n\t\t\tfaceDone={faceDone}\n\t\t\tstopRecording={stopRecording}\n\t\t\tshowPause={showPause}\n\t\t\twebcamRef={webcamRef}\n\t\t\thandleUserMedia={handleUserMedia}\n\t\t\tconfig={config}\n\t\t/>\n\t);\n}\n\nexport default React.memo(ScanningComponent);\n","/* eslint-disable no-use-before-define */\n\nimport { useEffect, useState, useRef } from \"react\";\nimport { IOSDeviceOrientationEvent } from \"../../customHooks/useGyroSensor\";\nimport LevelScreen from \"./LevelScreen\";\nimport ScanningComponent from \"./ScanningComponent\";\nimport { AngleDetectorProps } from \"../../types/interfaces\";\n\nexport default function AngleDetector({\n scanID,\n userDetails,\n setIsVideoUploaded,\n setScanFailsError,\n setScanStartTime,\n setScanUniqueKey,\n config,\n}: AngleDetectorProps) {\n const [angle, setAngle] = useState(90);\n const [calibrationOffset, setCalibrationOffset] = useState(0);\n const [countdown, setCountdown] = useState<number | null>(null);\n const [isScanning, setIsScanning] = useState(false);\n const [stabilityScore, setStabilityScore] = useState(0);\n const lastAnglesRef = useRef<number[]>([]);\n const [isScanLocked, setIsScanLocked] = useState(false);\n const calibratedAngle = angle - calibrationOffset;\n const isInTargetRange = calibratedAngle >= 80 && calibratedAngle <= 95;\n\n const resetDetector = () => {\n setAngle(90);\n setCalibrationOffset(0);\n setCountdown(null);\n setIsScanning(false);\n setStabilityScore(0);\n setIsScanLocked(false);\n lastAnglesRef.current = [];\n };\n\n useEffect(() => {\n if (typeof window !== \"undefined\" && window.DeviceOrientationEvent) {\n const handleOrientation = (event: DeviceOrientationEvent) => {\n if (event.beta !== null) {\n let newAngle = Math.abs(event.beta);\n if (event.gamma !== null) {\n newAngle *= Math.cos((event.gamma * Math.PI) / 180);\n }\n newAngle = Math.max(0, Math.min(180, newAngle));\n setAngle(newAngle);\n }\n };\n\n const requestPermission = async () => {\n const DeviceOrientation =\n DeviceOrientationEvent as unknown as IOSDeviceOrientationEvent;\n\n if (\n DeviceOrientation &&\n typeof DeviceOrientation.requestPermission === \"function\"\n ) {\n try {\n const permission = await DeviceOrientation.requestPermission();\n if (permission === \"granted\") {\n // wrappedHandler = timeout(handleOrientation, 2000);\n window.addEventListener(\"deviceorientation\", handleOrientation);\n }\n } catch (e) {\n console.error(\"Permission error\", e);\n }\n } else {\n // wrappedHandler = handleOrientation;\n window.addEventListener(\"deviceorientation\", handleOrientation);\n }\n\n return () => {\n if (handleOrientation) {\n window.removeEventListener(\"deviceorientation\", handleOrientation);\n }\n };\n };\n\n document.addEventListener(\"click\", requestPermission, { once: true });\n }\n }, []);\n\n useEffect(() => {\n lastAnglesRef.current = [\n ...lastAnglesRef.current.slice(-4),\n calibratedAngle,\n ];\n\n if (lastAnglesRef.current.length >= 5) {\n const variation =\n Math.max(...lastAnglesRef.current) - Math.min(...lastAnglesRef.current);\n if (isInTargetRange && variation < 2) {\n setStabilityScore((prev) => Math.min(100, prev + 10));\n } else {\n setStabilityScore((prev) => Math.max(0, prev - 20));\n }\n }\n\n if (!isInTargetRange && (countdown !== null || isScanning)) {\n resetCountdown();\n }\n }, [calibratedAngle, isInTargetRange, countdown, isScanning]);\n\n\tuseEffect(() => {\n\t\tif (stabilityScore >= 100 && countdown === null && !isScanning ) {\n\t\t\tstartCountdown();\n\t\t}\n\t\tif (stabilityScore < 50 && countdown !== null) {\n\t\t\tresetCountdown();\n\t\t}\n\t}, [stabilityScore, countdown, isScanning]);\n\n const startCountdown = () => {\n setCountdown(3);\n const timer = setInterval(() => {\n setCountdown((prev) => {\n if (prev === null || prev <= 1) {\n clearInterval(timer);\n setIsScanning(true);\n return null;\n }\n return prev - 1;\n });\n }, 1000);\n };\n\n const resetCountdown = () => {\n setCountdown(null);\n if (!isScanLocked) {\n setIsScanning(false);\n }\n };\n\n\n return (\n <LevelScreen\n angle={calibratedAngle}\n countdown={countdown}\n isScanning={isScanning}\n isInTargetRange={isInTargetRange}\n stabilityScore={stabilityScore}\n config={config}\n >\n {isScanning && (\n <ScanningComponent\n setIsScanLocked={setIsScanLocked}\n resetDetector={resetDetector}\n scanID={scanID}\n userDetails={userDetails}\n setIsVideoUploaded={setIsVideoUploaded}\n setScanFailsError={setScanFailsError}\n setScanStartTime={setScanStartTime}\n setScanUniqueKey={setScanUniqueKey}\n config={config}\n />\n )}\n </LevelScreen>\n );\n}\n","import { useContext } from \"react\";\nimport {Dialog} from \"@mui/material\";\nimport { getBrowserName } from \"../utils/utils\";\nimport { LanguageContext } from \"../utils/context/languageContext\";\nimport { LanguageKeys } from \"../utils/languageKeys\";\nimport { Config } from \"../types/interfaces\";\n\nfunction Modal({ message, config }: { message?: string; config?: Config }) {\n const { translate } = useContext(LanguageContext) || {};\n\n\n\n return (\n <Dialog open className=\"confirm-modal\">\n <div className=\"modal-main\">\n <div className=\"text-center\">\n {message ? (\n <>\n <h2\n style={{\n fontFamily:\n config?.style?.heading?.headingFontFamily ||\n \"SeriouslyNostalgic Fn\",\n fontSize: config?.style?.heading?.headingFontSize || \"32px\",\n color: config?.style?.heading?.headingColor || \"#000\",\n fontWeight:\n config?.style?.heading?.headingFontWeight || \"normal\",\n }}\n >\n {translate?.(LanguageKeys.cameraAlreadyInUse)}\n </h2>\n <p\n className=\"mt-[0.5rem] text-sm\"\n style={{\n fontFamily:\n config?.style?.base?.baseFontFamily || \"Inter, sans-serif\",\n fontSize: config?.style?.base?.baseFontSize || \"16px\",\n color: config?.style?.base?.baseTextColor || \"#000\",\n }}\n >\n {translate?.(LanguageKeys.tryClosingBrowser)}\n </p>\n </>\n ) : (\n <>\n <h2\n style={{\n fontFamily:\n config?.style?.heading?.headingFontFamily ||\n \"SeriouslyNostalgic Fn\",\n fontSize: config?.style?.heading?.headingFontSize || \"32px\",\n color: config?.style?.heading?.headingColor || \"#000\",\n fontWeight:\n config?.style?.heading?.headingFontWeight || \"normal\",\n }}\n >\n {translate?.(LanguageKeys.checkCameraSettings)}\n </h2>\n <p\n className=\"mt-[0.5rem] text-sm\"\n style={{\n fontFamily:\n config?.style?.base?.baseFontFamily || \"Inter, sans-serif\",\n fontSize: config?.style?.base?.baseFontSize || \"16px\",\n color: config?.style?.base?.baseTextColor || \"#000\",\n }}\n >{`${translate?.(\n LanguageKeys.setting\n )} > ${getBrowserName()} > ${translate?.(\n LanguageKeys.enableCameraPermissions\n )}`}</p>\n </>\n )}\n </div>\n </div>\n </Dialog>\n );\n}\n\nexport default Modal;\n","import { useEffect, useState, useRef, useCallback, Dispatch, SetStateAction } from \"react\";\nimport Webcam from \"react-webcam\";\nimport Modal from \"../Modal\";\nimport LoadingScreen from \"../LoadingScreen\";\nimport { checkCameraPermission } from \"../../utils/utils\";\nimport { videoConstraints } from \"../../utils/constants\";\n\n\nfunction CameraPermission({ setShowDrawer, config,loader }: { setShowDrawer?: Dispatch<SetStateAction<boolean>>; config?: any,loader?:string }) {\n\tconst [showDeniedModal, setShowDeniedModal] = useState({\n\t\tdisabled: false,\n\t\tmessage: \"\",\n\t});\n\tconst [loading, setLoading] = useState(true);\n\tconst webcamRef = useRef(null);\n\n\tconst handleCameraPermission = useCallback(async () => {\n\t\tconst permission = await checkCameraPermission();\n\t\tsetShowDeniedModal(permission);\n\t\tsetLoading(false);\n\t}, []);\n\n\tuseEffect(() => {\n\t\thandleCameraPermission();\n\t}, []);\n\n\tif (loading) {\n\t\treturn <LoadingScreen url={loader} />\n\t}\n\n\tif (showDeniedModal?.disabled) {\n\t\treturn <Modal config={config} message={showDeniedModal?.message} />;\n\t}\n\treturn (\n\t\t<Webcam\n\t\t\taudio={false}\n\t\t\tref={webcamRef}\n\t\t\tscreenshotQuality={1}\n\t\t\tvideoConstraints={videoConstraints}\n\t\t\tmirrored\n\t\t\tonUserMedia={() => setShowDrawer?.(true)}\n\t\t\tscreenshotFormat=\"image/jpeg\"\n\t\t\tstyle={{\n\t\t\t\tposition: \"relative\",\n\t\t\t\ttop: 0,\n\t\t\t\tbottom: 0,\n\t\t\t\tzIndex: 0,\n\t\t\t\twidth: \"100%\",\n\t\t\t\theight: \"100%\",\n\t\t\t\tobjectFit: \"cover\",\n\t\t\t}}\n\t\t/>\n\t);\n}\n\nexport default CameraPermission;\n","\nimport React, { useEffect, useRef } from \"react\";\nimport videojs from \"video.js\";\nimport type Player from \"video.js/dist/types/player\";\n// import \"video.js/dist/video-js.css\";\nimport { videoPoster } from \"../../utils/constants\";\n\nfunction VideoPlayer({ link, onReady, wrapperClassName = \"[&_video]:rounded-t-[20px] w-full h-full\" }: { link?: string; wrapperClassName?: string; onReady?: (args: Player) => void }) {\n\tconst videoReference = useRef<HTMLVideoElement | null>(null);\n\tconst playerReference = useRef<Player | null>(null);\n\n\tlet videoJsOptions: any = {\n\t\tautoplay: true,\n\t\tcontrols: false,\n\t\tresponsive: true,\n\t\tfluid: true,\n\t\tmuted: true,\n\t\tnavigationUI: \"hide\",\n\t\tpreload: \"metadata\",\n\t\tposter: videoPoster,\n\t};\n\n\tuseEffect(() => {\n\t\tif (!playerReference.current && link && videoReference?.current) {\n\t\t\tconst player = videojs(videoReference.current, {\n\t\t\t\t...videoJsOptions,\n\t\t\t});\n\t\t\tplayer.ready(() => {\n\t\t\t\tplayerReference.current = player;\n\n\t\t\t\tconst updatedOptions = {\n\t\t\t\t\t...videoJsOptions,\n\t\t\t\t\tsources: [{ src: link, type: \"application/x-mpegURL\" }],\n\t\t\t\t};\n\n\t\t\t\tplayer.autoplay(updatedOptions.autoplay);\n\t\t\t\tplayer.src(updatedOptions.sources);\n\n\t\t\t\tonReady?.(player);\n\t\t\t});\n\t\t}\n\t}, [link, videoReference]);\n\n\tuseEffect(() => {\n\t\tconst player = playerReference.current;\n\t\treturn () => {\n\t\t\tif (player && !player.isDisposed()) {\n\t\t\t\tplayer.dispose();\n\t\t\t\tplayerReference.current = null;\n\t\t\t}\n\t\t};\n\t}, [playerReference]);\n\n\treturn (\n\t\t<div className={wrapperClassName}>\n\t\t\t<video ref={videoReference} muted className=\"video-js\" playsInline onDrag={(e) => e.preventDefault()} />\n\t\t</div>\n\t);\n}\nexport default VideoPlayer;\n","import { useContext, useState } from \"react\";\nimport {Dialog} from \"@mui/material\";\nimport { LanguageContext } from \"../../utils/context/languageContext\";\nimport Header from \"../Header\";\nimport VideoPlayer from \"./VideoPlayer\";\nimport { ScanErrorMessageProps } from \"../../types/interfaces\";\nimport { generateUuid, handleErrorMessage } from \"../../utils/utils\";\nimport { GENDER, VIDEO_POSTER_GENDER_BASED } from \"../../utils/constants\";\nimport SpecificButton from \"../../atoms/specificButton/SpecificButton\";\nimport { LanguageKeys } from \"../../utils/languageKeys\";\nimport { X } from \"lucide-react\";\n\nfunction ScanErrorMessage({ scanFailsError, serverAtCapacity = false, onNext, gender, setScanUniqueKey, resolvedConfig, setIsVideoUploaded }: ScanErrorMessageProps) {\n\tconst { translate } = useContext(LanguageContext) || {};\n\tconst [showModal, setShowModal] = useState(false);\n\n\tconst handleBtnClick = () => {\n\t\tif (onNext) {\n\t\t\tonNext?.();\n\t\t} else {\n\t\t\tsetScanUniqueKey(generateUuid());\n\t\t}\n\t\tsetIsVideoUploaded(false);\n\t};\n\n\tconst handleShowModal = () => {\n\t\tsetShowModal(!showModal);\n\t};\n\n\n\treturn (\n\t\t<>\n\t\t\t<div className=\"flex flex-col h-full max-w-[28rem] mx-auto w-full rounded-t-[20px] overflow-y-auto\" style={{ background: resolvedConfig?.style?.base?.backgroundColor }}>\n\t\t\t\t<div className=\"w-full max-w-[28rem] mx-auto pt-[1rem] px-[1rem]\">\n\t\t\t\t\t<Header noTitle resolvedConfig={resolvedConfig} />\n\t\t\t\t</div>\n\t\t\t\t<div className=\"flex-1\">\n\t\t\t\t\t{/* <VideoPlayer link={gender ? GENDER[gender].PRE_LINK : GENDER.male.PRE_LINK} /> */}\n\t\t\t\t\t{scanFailsError && (\n\t\t\t\t\t\t<div className=\"px-[1rem]\">\n\t\t\t\t\t\t\t<h2\n\t\t\t\t\t\t\t\tclassName=\"text-center\"\n\t\t\t\t\t\t\t\tstyle={{\n\t\t\t\t\t\t\t\t\tfontFamily: resolvedConfig?.style?.heading?.headingFontFamily || \"SeriouslyNostalgic Fn\",\n\t\t\t\t\t\t\t\t\tfontSize: resolvedConfig?.style?.heading?.headingFontSize || \"32px\",\n\t\t\t\t\t\t\t\t\tcolor: resolvedConfig?.style?.heading?.headingColor || \"#000\",\n\t\t\t\t\t\t\t\t\tfontWeight: resolvedConfig?.style?.heading?.headingFontWeight || \"normal\",\n\t\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t{translate?.(LanguageKeys.issueWithScan)}\n\t\t\t\t\t\t\t</h2>\n\t\t\t\t\t\t\t<p\n\t\t\t\t\t\t\t\tstyle={{\n\t\t\t\t\t\t\t\t\tfontFamily: resolvedConfig?.style?.base?.baseFontFamily || \"Inter, sans-serif\",\n\t\t\t\t\t\t\t\t\tfontSize: resolvedConfig?.style?.base?.baseFontSize || \"16px\",\n\t\t\t\t\t\t\t\t\tcolor: resolvedConfig?.style?.base?.baseTextColor || \"#1E1E1E\",\n\t\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t{translate?.(LanguageKeys.reason)}\n\t\t\t\t\t\t\t</p>\n\t\t\t\t\t\t\t<p\n\t\t\t\t\t\t\t\tstyle={{\n\t\t\t\t\t\t\t\t\tfontFamily: resolvedConfig?.style?.base?.baseFontFamily || \"Inter, sans-serif\",\n\t\t\t\t\t\t\t\t\tfontSize: resolvedConfig?.style?.base?.baseFontSize || \"16px\",\n\t\t\t\t\t\t\t\t\tcolor: resolvedConfig?.style?.base?.baseTextColor || \"#1E1E1E\",\n\t\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t{handleErrorMessage(scanFailsError)}\n\t\t\t\t\t\t\t</p>\n\n\t\t\t\t\t\t\t<img className=\"my-[0.5rem] aspect-[2/1.4] w-full object-cover\" onClick={handleShowModal} src={VIDEO_POSTER_GENDER_BASED[gender]} alt=\"icon\" />\n\t\t\t\t\t\t</div>\n\t\t\t\t\t)}\n\t\t\t\t\t{serverAtCapacity && (\n\t\t\t\t\t\t<div className=\"p-[1rem] text-center\">\n\t\t\t\t\t\t\t<h3\n\t\t\t\t\t\t\t\tstyle={{\n\t\t\t\t\t\t\t\t\tfontFamily: resolvedConfig?.style?.heading?.headingFontFamily || \"SeriouslyNostalgic Fn\",\n\t\t\t\t\t\t\t\t\tfontSize: resolvedConfig?.style?.heading?.headingFontSize || \"32px\",\n\t\t\t\t\t\t\t\t\tcolor: resolvedConfig?.style?.heading?.headingColor || \"#000\",\n\t\t\t\t\t\t\t\t\tfontWeight: resolvedConfig?.style?.heading?.headingFontWeight || \"normal\",\n\t\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t{translate?.(LanguageKeys.serverAtCapacity)}\n\t\t\t\t\t\t\t</h3>\n\t\t\t\t\t\t\t<p\n\t\t\t\t\t\t\t\tclassName=\"text-base mt-[0.5rem]\"\n\t\t\t\t\t\t\t\tstyle={{\n\t\t\t\t\t\t\t\t\tfontFamily: resolvedConfig?.style?.base?.baseFontFamily || \"Inter, sans-serif\",\n\t\t\t\t\t\t\t\t\tfontSize: resolvedConfig?.style?.base?.baseFontSize || \"16px\",\n\t\t\t\t\t\t\t\t\tcolor: resolvedConfig?.style?.base?.baseTextColor || \"#1E1E1E\",\n\t\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t{translate?.(LanguageKeys.serverAtCapacityDescription)}\n\t\t\t\t\t\t\t</p>\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{scanFailsError && (\n\t\t\t\t\t<div className=\"p-[1rem] flex gap-[0.5rem]\">\n\t\t\t\t\t\t<SpecificButton disabled={false} buttonText={translate?.(LanguageKeys.scanAgain)} className=\"!shadow-none\" buttonFunc={handleBtnClick} resolvedConfig={resolvedConfig} />\n\t\t\t\t\t</div>\n\t\t\t\t)}\n\t\t\t</div>\n\t\t\t{showModal && (\n\t\t\t\t<Dialog className=\"w-screen h-screen video-modal\" onClose={handleShowModal} open={showModal}>\n\t\t\t\t\t<div className=\"flex justifyEnd \">\n\t\t\t\t\t\t<span className=\"closeBtn\" onClick={handleShowModal}>\n\t\t\t\t\t\t\t<X className=\"absolute right-[8px] top-[8px] text-white z-[9]\" />\n\t\t\t\t\t\t</span>\n\t\t\t\t\t</div>\n\t\t\t\t\t<div className=\"aspect-video object-cover rounded-[20px] \">\n\t\t\t\t\t\t<VideoPlayer link={gender ? GENDER[gender].PRE_LINK : GENDER.male.PRE_LINK} wrapperClassName=\"w-screen h-screen fixed top-[0] left-[0]\" />\n\t\t\t\t\t</div>\n\t\t\t\t</Dialog>\n\t\t\t)}\n\t\t</>\n\t);\n}\n\nexport default ScanErrorMessage;\n","import { useCallback, useContext, useEffect, useState } from \"react\";\nimport {Box,Drawer} from \"@mui/material\";\nimport { posthog } from \"posthog-js\";\nimport Header from \"./Header\";\nimport CameraPermission from \"./bodyScan/CameraPermission\";\nimport { UserDetails } from \"../types/interfaces\";\nimport { CLOTHING_BANNER_SCAN, CLOTHING_CUSTOM_FIT_SCAN, CLOTHING_CUSTOM_SCAN, maleMeasurementProgress, measurementProgress } from \"../utils/constants\";\nimport { GenderType } from \"../utils/enums\";\nimport SpecificButton from \"../atoms/specificButton/SpecificButton\";\nimport { LanguageContext } from \"../utils/context/languageContext\";\nimport { LanguageKeys } from \"../utils/languageKeys\";\nimport swan from \"../utils/service/swanService\";\n\nfunction SignUp({\n\tscanId,\n\tuserDetails,\n\tconfig,\n\tisFaceScan,\n\tisVideoUploadedCorrect,\n\tisMeasurementAvailable,\n\tonScanSuccess,\n\tisSuccess,\n}: {\n\tconfig?: any;\n\tisFaceScan: boolean;\n\tscanId: string;\n\tisVideoUploadedCorrect?: boolean;\n\tisMeasurementAvailable?: boolean;\n\tuserDetails: UserDetails;\n\tonScanSuccess?: () => void;\n\tisSuccess?: boolean;\n}) {\n\tconst { gender, shopDomain, heightInCm, deviceFocalLength, userName, email, scanType } = userDetails;\n\tconst isCustom = [CLOTHING_CUSTOM_SCAN, CLOTHING_BANNER_SCAN, CLOTHING_CUSTOM_FIT_SCAN].includes(scanType);\n\tconst [showDrawer, setShowDrawer] = useState(true);\n\tconst handlePostHogEvent = () => {\n\t\tposthog.capture(shopDomain, {\n\t\t\tscanID: scanId,\n\t\t\temail: email,\n\t\t\theight: heightInCm,\n\t\t\tfocalLength: deviceFocalLength,\n\t\t\tclothesFit: \"0\",\n\t\t\tgender: gender,\n\t\t});\n\t};\n\n\tconst handleSignUp = useCallback(async () => {\n\t\ttry {\n\t\t\tif (isCustom) {\n\t\t\t\tawait swan.auth.addUser({\n\t\t\t\t\tscanId,\n\t\t\t\t\temail,\n\t\t\t\t\tname: userName,\n\t\t\t\t\tgender,\n\t\t\t\t\theight: heightInCm,\n\t\t\t\t});\n\t\t\t}\n\t\t\thandlePostHogEvent();\n\t\t} catch (error) {\n\t\t\tconsole.log(error);\n\t\t}\n\t}, [isCustom]);\n\n\tconst { translate } = useContext(LanguageContext) || {};\n\n\tuseEffect(() => {\n\t\tif (isVideoUploadedCorrect) {\n\t\t\thandleSignUp();\n\t\t}\n\t}, [isVideoUploadedCorrect]);\n\n\tconst showNextButton = isSuccess || (isFaceScan ? isMeasurementAvailable && isVideoUploadedCorrect : isVideoUploadedCorrect || isMeasurementAvailable);\n\n\treturn (\n\t\t<Box className=\"flex h-full w-full flex-col \">\n\t\t\t<div className=\"h-full w-full flex-col items-center justify-center flex\">\n\t\t\t\t<CameraPermission loader={config?.loader} setShowDrawer={setShowDrawer} />\n\t\t\t\t<Drawer\n\t\t\t\t\topen={showDrawer}\n\t\t\t\t\tonClose={(_, 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\tclassName=\"camera-drawer\"\n\t\t\t\t\tanchor=\"bottom\"\n\t\t\t\t>\n\t\t\t\t\t<div\n\t\t\t\t\t\tclassName=\"max-w-[28rem] mx-auto w-full h-full flex text-center flex-col justify-between items-center bg-primary rounded-t-[30px] p-[1rem]\"\n\t\t\t\t\t\tstyle={{ background: config?.style?.base?.backgroundColor }}\n\t\t\t\t\t>\n\t\t\t\t\t\t<div className=\"w-full h-full flex flex-col\">\n\t\t\t\t\t\t\t<Header title={translate?.(LanguageKeys.measurementsBeingTaken)} resolvedConfig={config} />\n\t\t\t\t\t\t\t<div className=\"flex items-center justify-center flex-1\">\n\t\t\t\t\t\t\t\t<video preload=\"auto\" className=\"max-h-[calc(100vh-450px)] mx-auto w-full object-contain border-none\" muted loop autoPlay playsInline>\n\t\t\t\t\t\t\t\t\t<source src={gender === GenderType.Male ? maleMeasurementProgress : measurementProgress} type=\"video/mp4\" />\n\t\t\t\t\t\t\t\t</video>\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t{showNextButton && <SpecificButton resolvedConfig={config} className=\"!w-[180px] mx-auto\" buttonText={translate?.(LanguageKeys.next)} buttonFunc={onScanSuccess && onScanSuccess} />}\n\t\t\t\t\t\t</div>\n\t\t\t\t\t</div>\n\t\t\t\t</Drawer>\n\t\t\t</div>\n\t\t</Box>\n\t);\n}\nexport default SignUp;\n","\"use client\";\nimport { useContext, useEffect } from \"react\";\nimport AngleDetector from \"./AngleDetector\";\nimport CameraPermission from \"./CameraPermission\";\nimport Modal from \"../Modal\";\nimport { Drawer } from \"@mui/material\";\nimport ScanErrorMessage from \"./ScanErrorMessage\";\nimport LoadingScreen from \"../LoadingScreen\";\nimport SignUp from \"../Signup\";\nimport { LanguageContext } from \"../../utils/context/languageContext\";\nimport { useLocalConfig } from \"../../config/useLocalConfig\";\nimport ParamsContext from \"../../utils/context/paramsContext\";\n\nexport const BodyScanSteps = () => {\n\tconst {\n\t\tuserDetails,\n\t\tconfig,\n\t\tonRetry,\n\t\tisError,\n\t\tisSuccess,\n\t\tonScanSuccess,\n\t\tgender,\n\t\tscanUniqueKey,\n\t\tscanFailsError,\n\t\tsetScanUniqueKey,\n\t\tsetIsVideoUploaded,\n\t\tisMeasurementAvailable,\n\t\tisVideoUploadedCorrect,\n\t\tloading,\n\t\tshowDeniedModal,\n\t\tuploadLoading,\n\t\tsetStartGyro,\n\t\thandleFileUpload,\n\t\tsetUploadLoading,\n\t\tsetScanFailsError,\n\t\tsetScanStartTime,\n\t\thandleShowStreamCamera,\n\t} = useContext(ParamsContext);\n\tconst { setPreferredLanguage } = useContext(LanguageContext) || {};\n\tconst resolvedConfig = useLocalConfig(config);\n\n\tuseEffect(() => {\n\t\tsetPreferredLanguage?.(resolvedConfig?.language);\n\t}, [resolvedConfig]);\n\n\tif (isError) {\n\t\treturn (\n\t\t\t<>\n\t\t\t\t<CameraPermission />\n\t\t\t\t<Drawer\n\t\t\t\t\tanchor=\"bottom\"\n\t\t\t\t\topen={true}\n\t\t\t\t\tclassName=\"camera-drawer\"\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>\n\t\t\t\t\t<ScanErrorMessage\n\t\t\t\t\t\tscanFailsError={scanFailsError || isError}\n\t\t\t\t\t\tonNext={() => {\n\t\t\t\t\t\t\t// onRetry?.();\n\t\t\t\t\t\t\t// handleShowStreamCamera();\n\t\t\t\t\t\t}}\n\t\t\t\t\t\tsetScanUniqueKey={setScanUniqueKey}\n\t\t\t\t\t\tgender={gender}\n\t\t\t\t\t\tresolvedConfig={resolvedConfig}\n\t\t\t\t\t\tsetIsVideoUploaded={setIsVideoUploaded}\n\t\t\t\t\t/>\n\t\t\t\t</Drawer>\n\t\t\t</>\n\t\t);\n\t}\n\n\tif (isSuccess) {\n\t\treturn (\n\t\t\t<SignUp\n\t\t\t\tisFaceScan={false}\n\t\t\t\tscanId={scanUniqueKey}\n\t\t\t\tisMeasurementAvailable={isMeasurementAvailable}\n\t\t\t\tuserDetails={userDetails}\n\t\t\t\t// onComplete={onComplete}\n\t\t\t\tisVideoUploadedCorrect={isVideoUploadedCorrect}\n\t\t\t\tconfig={resolvedConfig}\n\t\t\t\tisSuccess={isSuccess}\n\t\t\t/>\n\t\t);\n\t}\n\n\tif (loading) {\n\t\treturn (\n\t\t\t<div className=\"flex top-0 !mt-0 left-0 z-[999] bg-opacity-80 bg-[#1b1b1b] absolute justify-center items-center w-full h-full\">\n\t\t\t\t<LoadingScreen url={resolvedConfig?.loader} />\n\t\t\t</div>\n\t\t);\n\t}\n\tif (showDeniedModal.disabled) {\n\t\treturn <Modal />;\n\t}\n\n\tif (!uploadLoading && !scanFailsError) {\n\t\treturn (\n\t\t\t<AngleDetector\n\t\t\t\tconfig={resolvedConfig}\n\t\t\t\tscanID={scanUniqueKey}\n\t\t\t\tuserDetails={userDetails}\n\t\t\t\tsetIsVideoUploaded={setIsVideoUploaded}\n\t\t\t\tsetScanFailsError={setScanFailsError}\n\t\t\t\tsetScanStartTime={setScanStartTime}\n\t\t\t\tsetScanUniqueKey={setScanUniqueKey}\n\t\t\t/>\n\t\t);\n\t}\n\tif ((uploadLoading || isMeasurementAvailable) && !scanFailsError) {\n\t\treturn (\n\t\t\t<SignUp\n\t\t\t\tisFaceScan={false}\n\t\t\t\tscanId={scanUniqueKey}\n\t\t\t\tisMeasurementAvailable={isMeasurementAvailable}\n\t\t\t\tuserDetails={userDetails}\n\t\t\t\tonScanSuccess={onScanSuccess}\n\t\t\t\tisVideoUploadedCorrect={isVideoUploadedCorrect}\n\t\t\t\tconfig={resolvedConfig}\n\t\t\t/>\n\t\t);\n\t}\n\treturn (\n\t\t<>\n\t\t\t<CameraPermission />\n\t\t\t<Drawer\n\t\t\t\tanchor=\"bottom\"\n\t\t\t\topen\n\t\t\t\tclassName=\"camera-drawer\"\n\t\t\t\tonClose={(event, reason) => {\n\t\t\t\t\tif (reason === \"backdropClick\") {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}}\n\t\t\t>\n\t\t\t\t<ScanErrorMessage\n\t\t\t\t\tscanFailsError={scanFailsError}\n\t\t\t\t\tonNext={() => {\n\t\t\t\t\t\tonRetry?.();\n\t\t\t\t\t\thandleShowStreamCamera();\n\t\t\t\t\t}}\n\t\t\t\t\tsetScanUniqueKey={setScanUniqueKey}\n\t\t\t\t\tgender={gender}\n\t\t\t\t\tresolvedConfig={resolvedConfig}\n\t\t\t\t\tsetIsVideoUploaded={setIsVideoUploaded}\n\t\t\t\t/>\n\t\t\t</Drawer>\n\t\t</>\n\t);\n};\n","\"use client\";\n\"use client\";\nimport { useCallback, useEffect, useState } from \"react\";\nimport posthog from \"posthog-js\";\nimport useGyroSensor from \"../../customHooks/useGyroSensor\";\nimport { checkCameraPermission, createObjectMetadataArray, generateUuid, getCurrentTimeInSeconds, handleErrorMessage, handleScanTimeCapture, handleWebSocketCapture } from \"../../utils/utils\";\nimport LanguageContextProvider from \"../../utils/context/languageContext\";\nimport swan from \"../../utils/service/swanService\";\nimport { posthogPublicHost, posthogPublicKey } from \"../../utils/constants\";\nimport ParamsContext from \"../../utils/context/paramsContext\";\nimport MediaContextProvider from \"../../utils/context/mediaContext\";\nimport { BodyScanProps } from \"../../bodyScan\";\nimport { BodyScanSteps } from \"./BodyScanSteps\";\n\nconst clothesFit = \"0\";\n\nexport const BodyScan: React.FC<BodyScanProps> = ({ userDetails, config, onRetry, onScanError, isError, isSuccess, onScanSuccess }) => {\n\tconst { gender, scanType, shopDomain, heightInCm, email, deviceFocalLength, deviceModelName, callbackUrl } = userDetails;\n\tconst [uploadLoading, setUploadLoading] = useState(false);\n\tconst [isVideoUploadedCorrect, setIsVideoUploadedCorrect] = useState(false);\n\tconst [isMeasurementAvailable, setIsMeasurementAvailable] = useState(false);\n\tconst [showDeniedModal, setShowDeniedModal] = useState({\n\t\tdisabled: false,\n\t\tmessage: \"\",\n\t});\n\tconst [scanFailsError, setScanFailsError] = useState(\"\");\n\tconst [isVideoUploaded, setIsVideoUploaded] = useState(false);\n\tconst [loading, setLoading] = useState(true);\n\tconst [startGyro, setStartGyro] = useState(false);\n\tconst [scanUniqueKey, setScanUniqueKey] = useState(\"\");\n\tconst [scanStartTime, setScanStartTime] = useState<number | null>(getCurrentTimeInSeconds());\n\tconst { gyroData } = useGyroSensor(startGyro);\n\n\tconst handleShowStreamCamera = useCallback(() => {\n\t\tsetScanUniqueKey(generateUuid());\n\t\tsetScanFailsError(\"\");\n\t\tsetUploadLoading(false);\n\t\tsetIsVideoUploaded(false);\n\t}, []);\n\n\tconst onError = (data: any) => {\n\t\tonScanError({ ...data, message: handleErrorMessage(data) });\n\t\tclearScanStartTimeAndScanId();\n\t\tsetIsMeasurementAvailable(false);\n\t\tsetScanFailsError(data);\n\t\tsetIsVideoUploadedCorrect(false);\n\t\thandleScanTimeCapture({\n\t\t\teventName: `${shopDomain}/measurement_failed/fit-view`,\n\t\t\tscanID: scanUniqueKey,\n\t\t\tstatus: \"failed\",\n\t\t\temail,\n\t\t\tmessage: handleErrorMessage(data),\n\t\t});\n\t\tif (scanStartTime)\n\t\t\thandleScanTimeCapture({\n\t\t\t\teventName: `${shopDomain}/scan_completion_time`,\n\t\t\t\tscanID: scanUniqueKey,\n\t\t\t\tstatus: \"failed\",\n\t\t\t\tcompletionTime: getCurrentTimeInSeconds() - scanStartTime,\n\t\t\t\temail,\n\t\t\t});\n\t};\n\n\tconst clearScanStartTimeAndScanId = () => {\n\t\tsetScanStartTime(null);\n\t\tsetScanUniqueKey(\"\");\n\t};\n\n\tconst onSuccess = useCallback(\n\t\tasync (data: any) => {\n\t\t\tif (data && data?.scanStatus === \"success\" && data?.resultType === \"intermediate\" && data?.code === 200) {\n\t\t\t\thandleScanTimeCapture({\n\t\t\t\t\teventName: `${shopDomain}/measurement_success/intermediate`,\n\t\t\t\t\tscanID: scanUniqueKey,\n\t\t\t\t\tstatus: \"success\",\n\t\t\t\t\temail,\n\t\t\t\t});\n\t\t\t\t// onScanSuccess?.(data);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tclearScanStartTimeAndScanId();\n\t\t\tconst scanIdToSet = scanUniqueKey;\n\t\t\tsetIsMeasurementAvailable(true);\n\t\t\thandleScanTimeCapture({\n\t\t\t\teventName: `${shopDomain}/measurement_success/fit-view`,\n\t\t\t\tscanID: scanIdToSet,\n\t\t\t\tstatus: \"success\",\n\t\t\t\temail,\n\t\t\t});\n\t\t\tif (scanStartTime)\n\t\t\t\thandleScanTimeCapture({\n\t\t\t\t\teventName: `${shopDomain}/scan_completion_time`,\n\t\t\t\t\tscanID: scanIdToSet,\n\t\t\t\t\tstatus: \"success\",\n\t\t\t\t\tcompletionTime: getCurrentTimeInSeconds() - scanStartTime,\n\t\t\t\t\temail,\n\t\t\t\t});\n\t\t},\n\t\t[scanType, shopDomain, scanUniqueKey],\n\t);\n\n\tconst handleMeasurementRecommendation = (scanId?: string) => {\n\t\tsetIsMeasurementAvailable(false);\n\t\tsetScanFailsError(\"\");\n\t\tsetIsVideoUploadedCorrect(false);\n\t\tswan.measurement.handleMeasurementSocket({\n\t\t\tscanId: scanId || scanUniqueKey,\n\t\t\tonOpen: () => {\n\t\t\t\thandleWebSocketCapture({\n\t\t\t\t\teventName: `${shopDomain}/webSocket`,\n\t\t\t\t\tscanID: scanUniqueKey,\n\t\t\t\t\tconnection: \"open\",\n\t\t\t\t\ttype: \"measurement_recommendation\",\n\t\t\t\t\temail,\n\t\t\t\t});\n\t\t\t},\n\t\t\tonClose: () =>\n\t\t\t\thandleWebSocketCapture({\n\t\t\t\t\teventName: `${shopDomain}/webSocket`,\n\t\t\t\t\tscanID: scanUniqueKey,\n\t\t\t\t\tconnection: \"close\",\n\t\t\t\t\ttype: \"measurement_recommendation\",\n\t\t\t\t\temail,\n\t\t\t\t}),\n\t\t\tonError: (err) => {\n\t\t\t\tonError(err);\n\t\t\t\thandleWebSocketCapture({\n\t\t\t\t\teventName: `${shopDomain}/webSocket`,\n\t\t\t\t\tscanID: scanUniqueKey,\n\t\t\t\t\tconnection: \"error\",\n\t\t\t\t\ttype: \"measurement_recommendation\",\n\t\t\t\t\temail,\n\t\t\t\t});\n\t\t\t},\n\t\t\tonSuccess: (data) => {\n\t\t\t\thandleWebSocketCapture({\n\t\t\t\t\teventName: `${shopDomain}/webSocket`,\n\t\t\t\t\tscanID: scanUniqueKey,\n\t\t\t\t\tconnection: \"success\",\n\t\t\t\t\ttype: \"measurement_recommendation\",\n\t\t\t\t\temail,\n\t\t\t\t});\n\t\t\t\tonSuccess(data);\n\t\t\t},\n\t\t});\n\t};\n\n\tconst handleFileUpload = useCallback(\n\t\tasync (file: File) => {\n\t\t\tconst arrayMetaData = createObjectMetadataArray({\n\t\t\t\tgender,\n\t\t\t\tfocal_length: `${deviceFocalLength}`,\n\t\t\t\theight: `${heightInCm}`,\n\t\t\t\tcustomer_store_url: shopDomain,\n\t\t\t\tclothes_fit: clothesFit,\n\t\t\t\tscan_type: scanType,\n\t\t\t\tcallback_url: callbackUrl || \"https://example.com/webhook\",\n\t\t\t});\n\t\t\thandleScanTimeCapture({\n\t\t\t\teventName: `${shopDomain}/body_scan_meta_data`,\n\t\t\t\tscanID: scanUniqueKey,\n\t\t\t\temail,\n\t\t\t\tdata: JSON.stringify(arrayMetaData),\n\t\t\t});\n\t\t\ttry {\n\t\t\t\tawait swan.fileUpload.uploadFileFrontend({\n\t\t\t\t\tfile,\n\t\t\t\t\tarrayMetaData,\n\t\t\t\t\tscanId: scanUniqueKey,\n\t\t\t\t\temail,\n\t\t\t\t});\n\t\t\t\tawait swan.fileUpload.setDeviceInfo({\n\t\t\t\t\tmodel: deviceModelName,\n\t\t\t\t\tdetection: \"manual\",\n\t\t\t\t\tgyro: gyroData,\n\t\t\t\t\tscanId: scanUniqueKey,\n\t\t\t\t});\n\t\t\t\tconsole.log(\"video successfully uploaded\");\n\t\t\t\tsetIsVideoUploaded(false);\n\t\t\t\thandleScanTimeCapture({\n\t\t\t\t\teventName: `${shopDomain}/scan_success`,\n\t\t\t\t\tscanID: scanUniqueKey,\n\t\t\t\t\tstatus: \"success\",\n\t\t\t\t\temail,\n\t\t\t\t\tdata: JSON.stringify(arrayMetaData),\n\t\t\t\t});\n\t\t\t\thandleScanTimeCapture({\n\t\t\t\t\teventName: \"scan finished\",\n\t\t\t\t\tscanID: scanUniqueKey,\n\t\t\t\t\tstatus: \"success\",\n\t\t\t\t\temail,\n\t\t\t\t});\n\t\t\t\tsetScanStartTime(getCurrentTimeInSeconds());\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tsetIsVideoUploaded(true);\n\t\t\t\t}, 3000);\n\t\t\t} catch (error) {\n\t\t\t\thandleScanTimeCapture({\n\t\t\t\t\teventName: \"scan finished\",\n\t\t\t\t\tscanID: scanUniqueKey,\n\t\t\t\t\tstatus: \"failed\",\n\t\t\t\t\temail,\n\t\t\t\t\tmessage: handleErrorMessage(error),\n\t\t\t\t});\n\t\t\t\thandleScanTimeCapture({\n\t\t\t\t\teventName: `${shopDomain}/scan_failed`,\n\t\t\t\t\tscanID: scanUniqueKey,\n\t\t\t\t\tstatus: \"failed\",\n\t\t\t\t\temail,\n\t\t\t\t\tmessage: handleErrorMessage(error),\n\t\t\t\t\tdata: JSON.stringify(arrayMetaData),\n\t\t\t\t});\n\t\t\t\tsetScanFailsError(handleErrorMessage(error));\n\t\t\t\tsetIsVideoUploaded(false);\n\t\t\t\tconsole.log(error, \"video upload failed\");\n\t\t\t} finally {\n\t\t\t\tsetStartGyro(false);\n\t\t\t}\n\t\t},\n\t\t[scanUniqueKey, gyroData],\n\t);\n\tconst checkMeasurementStatus = useCallback(\n\t\tasync (scanId: string) => {\n\t\t\ttry {\n\t\t\t\tconst res = await swan.measurement.getMeasurementResult(scanId);\n\t\t\t\tconst isMeasured = res?.data?.isMeasured;\n\t\t\t\tconst tempScanStartTime = scanStartTime || getCurrentTimeInSeconds();\n\t\t\t\tconst currentTimeInSeconds = getCurrentTimeInSeconds();\n\t\t\t\tconst fiveMinutesInSeconds = 5 * 60;\n\t\t\t\tsetLoading(false);\n\t\t\t\tif (isMeasured === false) {\n\t\t\t\t\tclearScanStartTimeAndScanId();\n\t\t\t\t\tsetScanUniqueKey(generateUuid());\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tsetUploadLoading(true);\n\t\t\t\tif (isMeasured === true) {\n\t\t\t\t\tawait onSuccess(null);\n\t\t\t\t} else if (isMeasured === null && tempScanStartTime > currentTimeInSeconds + fiveMinutesInSeconds) {\n\t\t\t\t\tonError(res?.data?.error);\n\t\t\t\t} else {\n\t\t\t\t\thandleMeasurementRecommendation(scanId);\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tconsole.log(error);\n\t\t\t\tclearScanStartTimeAndScanId();\n\t\t\t\tsetScanUniqueKey(generateUuid());\n\t\t\t\tsetUploadLoading(false);\n\t\t\t}\n\t\t},\n\t\t[onError, onSuccess, setScanUniqueKey],\n\t);\n\n\tconst handleCameraPermission = useCallback(async () => {\n\t\tif (+heightInCm < 152.4 || +heightInCm > 213.36) {\n\t\t\tonScanError({\n\t\t\t\tmessage: \"Height must be between 152.4cm (5ft) and 213.36cm (7ft)\",\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tconst permission = await checkCameraPermission();\n\t\tif (permission.disabled) {\n\t\t\thandleScanTimeCapture({\n\t\t\t\teventName: `${shopDomain}/camera_activation`,\n\t\t\t\tscanID: scanUniqueKey,\n\t\t\t\tstatus: \"failed\",\n\t\t\t\temail,\n\t\t\t});\n\t\t\tsetLoading(false);\n\t\t} else {\n\t\t\tconst scanId = scanUniqueKey;\n\t\t\tif (scanId) {\n\t\t\t\tcheckMeasurementStatus(scanId);\n\t\t\t} else {\n\t\t\t\tsetLoading(false);\n\t\t\t}\n\t\t\thandleScanTimeCapture({\n\t\t\t\teventName: `${shopDomain}/camera_activation`,\n\t\t\t\tscanID: scanUniqueKey,\n\t\t\t\tstatus: \"success\",\n\t\t\t\temail,\n\t\t\t});\n\t\t}\n\t\tsetShowDeniedModal(permission);\n\t\tsetScanFailsError(\"\");\n\t\tsetIsVideoUploaded(false);\n\t}, [checkMeasurementStatus, email, scanUniqueKey, setScanUniqueKey, shopDomain]);\n\n\tuseEffect(() => {\n\t\tposthog.init(posthogPublicKey, { api_host: posthogPublicHost });\n\t\tposthog.capture(\"$pageview\");\n\t}, []);\n\n\tuseEffect(() => {\n\t\tif (isError || isSuccess) return;\n\t\tif (shopDomain) {\n\t\t\thandleCameraPermission();\n\t\t}\n\t}, [shopDomain, heightInCm, isError, isSuccess]);\n\n\tuseEffect(() => {\n\t\tif (isError || isSuccess) return;\n\t\tif (isVideoUploaded && shopDomain && scanUniqueKey) {\n\t\t\thandleMeasurementRecommendation();\n\t\t}\n\t}, [isVideoUploaded, shopDomain, scanUniqueKey, isError, isSuccess]);\n\treturn (\n\t\t<LanguageContextProvider>\n\t\t\t<MediaContextProvider>\n\t\t\t\t<ParamsContext.Provider\n\t\t\t\t\tvalue={{\n\t\t\t\t\t\tuserDetails,\n\t\t\t\t\t\tconfig,\n\t\t\t\t\t\tonRetry,\n\t\t\t\t\t\tonScanError,\n\t\t\t\t\t\tisError,\n\t\t\t\t\t\tisSuccess,\n\t\t\t\t\t\tonScanSuccess,\n\t\t\t\t\t\tgender,\n\t\t\t\t\t\tscanUniqueKey,\n\t\t\t\t\t\tscanFailsError,\n\t\t\t\t\t\tsetScanUniqueKey,\n\t\t\t\t\t\tsetIsVideoUploaded,\n\t\t\t\t\t\tisMeasurementAvailable,\n\t\t\t\t\t\tisVideoUploadedCorrect,\n\t\t\t\t\t\tloading,\n\t\t\t\t\t\tshowDeniedModal,\n\t\t\t\t\t\tuploadLoading,\n\t\t\t\t\t\tsetStartGyro,\n\t\t\t\t\t\thandleFileUpload,\n\t\t\t\t\t\tsetUploadLoading,\n\t\t\t\t\t\thandleShowStreamCamera,\n\t\t\t\t\t\tsetScanFailsError,\n\t\t\t\t\t\tsetScanStartTime,\n\t\t\t\t\t}}\n\t\t\t\t>\n\t\t\t\t\t<BodyScanSteps />\n\t\t\t\t</ParamsContext.Provider>\n\t\t\t</MediaContextProvider>\n\t\t</LanguageContextProvider>\n\t);\n};\n","import { useCallback, useEffect, useState } from \"react\";\n\ninterface GyroDataItem {\n alpha?: string;\n beta?: string;\n gamma?: string;\n timestamp?: string;\n}\n\nexport interface IOSDeviceOrientationEvent extends DeviceOrientationEvent {\n requestPermission?: () => Promise<PermissionState>;\n}\n\nfunction useGyroSensor(startGyro: boolean) {\n const [gyroData, setGyroData] = useState<GyroDataItem[]>([]);\n const [permissionGranted, setPermissionGranted] = useState(false);\n\n const handleOrientation = useCallback((event: DeviceOrientationEvent) => {\n try {\n const { alpha, beta, gamma } = event;\n setGyroData((prev: GyroDataItem[]) => [\n ...prev,\n {\n alpha: alpha?.toString() || undefined,\n beta: beta?.toString() || undefined,\n gamma: gamma?.toString() || undefined,\n timestamp: new Date().toISOString(),\n },\n ]);\n } catch (error) {\n console.log(error);\n }\n }, []);\n\n const requestPermission = useCallback(async () => {\n const DeviceOrientation =\n DeviceOrientationEvent as unknown as IOSDeviceOrientationEvent;\n\n if (\n typeof DeviceOrientation !== \"undefined\" &&\n typeof DeviceOrientation.requestPermission === \"function\"\n ) {\n try {\n const response = await DeviceOrientation.requestPermission();\n if (response === \"granted\") {\n setPermissionGranted(true);\n } else {\n console.warn(\"Device orientation permission denied.\");\n }\n } catch (error) {\n console.error(\"Error requesting device orientation permission:\", error);\n }\n } else {\n // Permission not required on non-iOS devices\n setPermissionGranted(true);\n }\n }, []);\n\n useEffect(() => {\n if (startGyro && permissionGranted) {\n window.addEventListener(\"deviceorientation\", handleOrientation);\n } else {\n setGyroData([]);\n }\n return () => {\n window.removeEventListener(\"deviceorientation\", handleOrientation);\n };\n }, [startGyro, permissionGranted, handleOrientation]);\n\n useEffect(() => {\n if (startGyro) {\n requestPermission();\n }\n }, [startGyro, requestPermission]);\n\n return { gyroData };\n}\n\nexport default useGyroSensor;\n"],"names":["MEDIA_TYPES","MediaContext","createContext","undefined","MediaContextProvider","children","size","setSize","useState","window","innerWidth","innerHeight","clearInputs","setClearInputs","updateSize","useEffect","useLayoutEffect","addEventListener","removeEventListener","media","mediaDetails","useMemo","_jsx","Provider","value","SwitchIcon","React","memo","_jsxs","width","height","viewBox","fill","xmlns","d","stroke","strokeWidth","strokeLinecap","strokeLinejoin","LevelScreen","angle","countdown","isScanning","isInTargetRange","stabilityScore","config","translate","useContext","LanguageContext","getProximityToTarget","useCallback","Math","max","min","backgroundColor","style","angleDetector","successAngleBackground","proximity","successAngleLowBackground","round","handelTextColour","isLight","successAngleTextLightColor","successAngleTextDarkColor","getTextColor","handelColourCode","getColorCode","cd","fixVh","document","documentElement","setProperty","className","Header","noTitle","resolvedConfig","border","fontFamily","base","baseFontFamily","color","cn","transform","transition","LanguageKeys","startLevelCheck","leavePhone","placePhoneUpright","CameraScanChild","handleShowStreamCamera","loadingCam","handleUserMedia","handlePause","pause","recordingStarted","startSendingVideoFrames","showPause","webcamRef","resetDetector","onClick","X","Webcam","audio","ref","screenshotQuality","videoConstraints","mirrored","screenshotFormat","onUserMedia","position","top","bottom","zIndex","objectFit","SpecificButton","prefix","pauseIcon","buttonText","buttonFunc","btnSecondary","restart","startScan","disabled","id","crossOrigin","preload","src","voiceOverAssetsPath","globalLoadingPromise","globalDetector","globalPoseLib","audioTimeoutId","lastVideoPlayed","ScanningComponent","setIsScanLocked","scanID","setIsVideoUploaded","setScanFailsError","setScanStartTime","setScanUniqueKey","userDetails","gender","heightInCm","email","shopDomain","useRef","mediaRecorderRef","recordedChunks","setRecordedChunks","setLoadingCam","setRecordingStarted","faceDone","setFaceDone","mediaRecorderStopped","setMediaRecorderStopped","setIsScanning","captureVideoTimeOutHandle","audioSource","setAudioSource","audioSourceList","setAudioSourceList","emptyAudioSource","setEmptyAudioSource","startAgain","setStartAgain","showRestart","setRestart","setPause","events","setEvents","setShowPause","allowAudioToPlay","poseDetector","consecutiveFronts","setConsecutiveFronts","spinPhase","setSpinPhase","isLoaded","setIsLoaded","spinPhaseRef","consecutiveFrontsRef","mounted","async","loadDependenciesGlobal","navigator","console","log","poseLib","tfjsCore","tfjsBackend","Promise","all","import","setBackend","ready","modelConfig","runtime","modelType","solutionPath","createDetector","SupportedModels","BlazePose","mediapipeError","warn","error","isFrontFrame","body","length","filter","p","current","then","success","s","callback","video","readyState","poses","estimatePoses","flipHorizontal","keypoints","slice","map","kp","x","y","score","prev","err","retryLoading","useTensorFlow","firstScan","poseStoppedRef","supportedTypes","setSupportedTypes","counter","setStartGyro","handleFileUpload","setUploadLoading","ParamsContext","clearTimeout","generateUuid","speechService","stopAudio","stop","forEach","el","setTimeout","handleReScan","rescanSupportCaptureEvent","eventName","status","swan","poseDetection","disconnect","stopRecording","playAudio","handleSocket","connect","posthog","capture","handleSpinDataAvailable","data","concat","handleScanTimeCapture","message","handleStartCaptureClick","stream","mediaRecorderOptions","mimeType","MediaRecorder","start","e","postPoseProcess","handleDataAvailable","connected","poseStatus","querySelector","sid","paused","audioName","no_of_times_skipped","skipCount","getScreenshot","videoEmit","image","scanId","getCurrentTimeInSeconds","push","bypassChecksToBackup","videoFile","File","type","supported","videoTypes","isTypeSupported","AngleDetector","setAngle","calibrationOffset","setCalibrationOffset","setCountdown","setStabilityScore","lastAnglesRef","isScanLocked","calibratedAngle","DeviceOrientationEvent","handleOrientation","event","beta","newAngle","abs","gamma","cos","PI","requestPermission","DeviceOrientation","once","variation","resetCountdown","startCountdown","timer","setInterval","clearInterval","Modal","Dialog","open","_Fragment","heading","headingFontFamily","fontSize","headingFontSize","headingColor","fontWeight","headingFontWeight","cameraAlreadyInUse","baseFontSize","baseTextColor","tryClosingBrowser","checkCameraSettings","setting","getBrowserName","enableCameraPermissions","CameraPermission","setShowDrawer","loader","showDeniedModal","setShowDeniedModal","loading","setLoading","handleCameraPermission","permission","checkCameraPermission","LoadingScreen","url","VideoPlayer","link","onReady","wrapperClassName","videoReference","playerReference","videoJsOptions","autoplay","controls","responsive","fluid","muted","navigationUI","poster","videoPoster","player","videojs","updatedOptions","sources","isDisposed","dispose","playsInline","onDrag","preventDefault","ScanErrorMessage","scanFailsError","serverAtCapacity","onNext","showModal","setShowModal","handleShowModal","background","issueWithScan","reason","handleErrorMessage","VIDEO_POSTER_GENDER_BASED","alt","serverAtCapacityDescription","scanAgain","onClose","GENDER","PRE_LINK","male","SignUp","isFaceScan","isVideoUploadedCorrect","isMeasurementAvailable","onScanSuccess","isSuccess","deviceFocalLength","userName","scanType","isCustom","CLOTHING_CUSTOM_SCAN","CLOTHING_BANNER_SCAN","CLOTHING_CUSTOM_FIT_SCAN","includes","showDrawer","handleSignUp","auth","addUser","name","focalLength","clothesFit","showNextButton","Box","Drawer","_","anchor","title","measurementsBeingTaken","loop","autoPlay","GenderType","Male","maleMeasurementProgress","measurementProgress","next","BodyScanSteps","onRetry","isError","scanUniqueKey","uploadLoading","setPreferredLanguage","useLocalConfig","language","BodyScan","onScanError","deviceModelName","callbackUrl","setIsVideoUploadedCorrect","setIsMeasurementAvailable","isVideoUploaded","startGyro","scanStartTime","gyroData","setGyroData","permissionGranted","setPermissionGranted","alpha","toString","timestamp","Date","toISOString","useGyroSensor","onError","clearScanStartTimeAndScanId","completionTime","onSuccess","scanStatus","resultType","code","scanIdToSet","handleMeasurementRecommendation","measurement","handleMeasurementSocket","onOpen","handleWebSocketCapture","connection","file","arrayMetaData","createObjectMetadataArray","focal_length","customer_store_url","clothes_fit","scan_type","callback_url","JSON","stringify","fileUpload","uploadFileFrontend","setDeviceInfo","model","detection","gyro","checkMeasurementStatus","res","getMeasurementResult","isMeasured","tempScanStartTime","currentTimeInSeconds","fiveMinutesInSeconds","init","posthogPublicKey","api_host","posthogPublicHost","LanguageContextProvider"],"mappings":"qrBAYO,MAAMA,GACF,UADEA,GAEN,MAFMA,GAGH,SAWGC,GAAeC,OAC1BC,GAGF,SAASC,IAAqBC,SAAEA,IAC9B,MAAOC,EAAMC,GAAWC,EAAS,CAACC,QAAQC,WAAYD,QAAQE,eACvDC,EAAaC,GAAkBL,GAAS,GAEzCM,EAAa,KACjBP,EAAQ,CAACE,QAAQC,WAAYD,QAAQE,eAEvCI,EAAU,KACRD,KACC,IACHE,EAAgB,KACdP,OAAOQ,iBAAiB,SAAUH,GAC3B,IAAML,OAAOS,oBAAoB,SAAUJ,IACjD,CAACA,IACJ,IAAIK,EAAQnB,GACRM,EAAK,GAAK,KAAOA,EAAK,GAAK,OAC7Ba,EAAQnB,IAENM,EAAK,GAAK,MACZa,EAAQnB,IAGV,MAAMoB,EAAeC,EACnB,KAAA,CACEf,OACAC,UACAK,cACAC,iBACAM,UAEF,CAACb,EAAMM,EAAaO,IAGtB,OACEG,EAACrB,GAAasB,SAAQ,CAACC,MAAOJ,EAAYf,SACvCA,GAGP,CClBA,IAAAoB,GAAeC,EAAMC,KAhDrB,UAAoBrB,KAAEA,EAAO,KAC3B,OACEsB,EAAA,MAAA,CACEC,MAAOvB,EACPwB,OAAQxB,EACRyB,QAAQ,YACRC,KAAK,OACLC,MAAM,6BAA4B5B,SAAA,CAElCiB,EAAA,OAAA,CACEY,EAAE,mHACFC,OAAO,QACPC,YAAY,IACZC,cAAc,QACdC,eAAe,UAEjBhB,EAAA,OAAA,CACEY,EAAE,0NACFC,OAAO,eACPC,YAAY,IACZC,cAAc,QACdC,eAAe,UAEjBhB,EAAA,OAAA,CACEY,EAAE,kOACFC,OAAO,eACPC,YAAY,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OAAQ,UACR5G,SAED,CACD2M,EAAmBI,GACnBrN,EAAkB,IAClBD,GAAmB,IACjB,CAACiW,GAAwB1V,EAAOoS,EAAexS,EAAkBK,IAoBpE,OAlBAlI,EAAU,KACTqP,EAAQ6O,KAAKC,EAAkB,CAAEC,SAAUC,IAC3ChP,EAAQC,QAAQ,cACd,IAEHtP,EAAU,KACLoa,GAAWhC,GACXlQ,GACH6M,MAEC,CAAC7M,EAAYF,EAAYoS,EAAShC,IAErCpY,EAAU,KACLoa,GAAWhC,GACX4C,GAAmB9S,GAAcmS,GACpCgC,MAEC,CAACrB,EAAiB9S,EAAYmS,EAAeD,EAAShC,IAExD7X,EAAC+d,EAAuB,CAAAhf,SACvBiB,EAAClB,GAAoB,CAAAC,SACpBiB,EAAC0N,EAAczN,SAAQ,CACtBC,MAAO,CACNqH,cACAhG,SACAqY,UACAQ,cACAP,UACAhC,YACAD,gBACApQ,SACAsS,gBACAxD,iBACAhP,mBACAH,qBACAwQ,yBACAD,yBACApD,UACAF,kBACA2F,gBACAxM,eACAC,oBACAC,mBACArJ,yBACAgD,oBACAC,oBACAtI,SAEDiB,EAAC2Z,GAAa,CAAA"}
@@ -0,0 +1,2 @@
1
+ "use strict";var e=require("react/jsx-runtime"),t=require("react"),a=require("posthog-js"),n=require("./LoadingScreen-Dc0DGpTP.js"),o=require("lucide-react"),s=require("@mui/material");let r=null,c=!1;function i({faceScanId:e,onValidPose:o,onScanComplete:s,onModelReady:i,onStartRecording:l,shopDomain: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(null),b=t.useRef(f),w=t.useRef(h),C=t.useRef([]),F=t.useRef(""),j=t.useRef(0),_=t.useRef(!1),N=t.useRef(0),E="undefined"!=typeof navigator&&(/iPad|iPhone|iPod/.test(navigator.userAgent)||"MacIntel"===navigator.platform&&navigator.maxTouchPoints>1),T=t.useMemo(()=>["Face front","Turn head fully left","Turn head fully right","Smile facing front"],[]),k=t.useMemo(()=>function(e,t){let a;return(...n)=>{a&&clearTimeout(a),a=setTimeout(()=>e(...n),t)}}(e=>{a.posthog.capture(`${d}/face_scan_pose_detection`,e)},4e3),[d]),I=t.useCallback((t,a,n,o,s,r)=>{const c=Date.now();if(!(c-N.current<4e3)){N.current=c;try{const c=t[0]||[0,0,0],i=t[2]||[0,0,0],l=t[5]||[0,0,0],d=t[9]||[0,0,0],u=t[10]||[0,0,0],f=t.map(e=>e[2]).filter(e=>e>0),g=f.length>0?f.reduce((e,t)=>e+t,0)/f.length:0,h=a.map(e=>e[2]).filter(e=>e>0),m=h.length>0?h.reduce((e,t)=>e+t,0)/h.length:0,p=Math.abs(i[0]-l[0]),y=c[0]-l[0],S=i[0]-c[0];let x="frontal";1===n?x="left":2===n?x="right":3===n&&(x="frontal_smile");const v={faceScanId:e,stage:n,timestamp:(new Date).toISOString(),data:JSON.stringify({headValid:o,bodyInvalid:s,consecutiveValid:r,avgFaceScore:parseFloat(g.toFixed(3)),avgBodyScore:parseFloat(m.toFixed(3)),faceKeypointsDetected:f.length,bodyKeypointsDetected:h.length,eyeDistance:parseFloat(p.toFixed(2)),noseToRightRatio:parseFloat((y/p).toFixed(3)),noseToLeftRatio:parseFloat((S/p).toFixed(3)),noseScore:parseFloat(c[2].toFixed(3)),leftEyeScore:parseFloat(i[2].toFixed(3)),rightEyeScore:parseFloat(l[2].toFixed(3)),leftMouthScore:parseFloat(d[2].toFixed(3)),rightMouthScore:parseFloat(u[2].toFixed(3)),expectedPosition:x})};k(v)}catch(e){console.warn("Failed to track pose detection:",e)}}},[e,k]),D=()=>{a.posthog.capture(`${d}/face_scan_detection_started`,{faceScanId:e,stage:b.current,timestamp:(new Date).toISOString(),stageName:T[b.current]}),setTimeout(()=>{x(!0)},1500)},L=async()=>{if("undefined"!=typeof window)try{console.log("Initializing Face Scan...");const e=await(async()=>{if("undefined"==typeof window)return null;if(r)return r;if(c)for(;c;)if(await new Promise(e=>setTimeout(e,100)),r)return r;c=!0;try{const[e,t]=await Promise.all([import("@tensorflow/tfjs"),Promise.resolve().then(function(){return require("./pose-detection.esm-DuVevgDD.js")})]);await e.setBackend("webgl"),await e.ready();const a=await t.createDetector(t.SupportedModels.BlazePose,{runtime:"tfjs",modelType:"full"}),o=document.createElement("canvas");o.width=n.videoConstraints.width,o.height=n.videoConstraints.height;const s=o.getContext("2d");if(s){s.fillStyle="black",s.fillRect(0,0,o.width,o.height);try{await a.estimatePoses(o)}catch(e){console.warn("Warmup frame failed (non-fatal):",e)}}return r=a,a}catch(e){return console.error("Failed to preload detector:",e),null}finally{c=!1}})();e&&(u.current=e,console.log("Face scan model loaded successfully"),y(!0),i?.())}catch(e){console.error("Error initializing face scan:",e)}};return t.useEffect(()=>(L(),()=>{(async()=>{try{y(!1)}catch(e){console.error("Error disposing resources:",e)}finally{g(0),m(0),b.current=0,w.current=0,C.current=[]}})()}),[]),t.useEffect(()=>{b.current=f},[f]),t.useEffect(()=>{w.current=h},[h]),{faceScanDetector:async(t,r)=>{if(u.current&&t.current&&p&&S&&!(t.current.readyState<2))try{const c=await u.current.estimatePoses(t.current);if(c.length>0){const t=[],i=[];if(c[0].keypoints.forEach((e,a)=>{const n=e.score??0,o=[e.x??-1,e.y??-1,n];a<=10?t.push(o):i.push(o)}),r?.current){const e=r.current.getContext("2d"),{width:t,height:a}=r.current;if(e){e.clearRect(0,0,t,a);const n=Math.min(w.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 u=((e,t)=>{if(!t[0]||!t[2]||!t[5]||t[0][2]<.2||t[2][2]<.2||t[5][2]<.2)return!1;const a=.5*(t[10][1]+t[9][1])-.5*(t[5][1]+t[2][1]),n=(.5*(t[10][1]+t[9][1])-t[0][1])/a,o=n>.7||n<.3,s=Math.abs(t[2][1]-t[5][1])<.5*a&&Math.abs(t[9][1]-t[10][1])<.5*a,r=t[2][0]-t[5][0],c=t[0][0]-t[5][0],i=c>.4*r&&c<.6*r,l=c>.85*r,d=t[2][0]-t[0][0]>.85*r;switch(e){case 0:case 3:return!o&&s&&i;case 1:return!o&&s&&l;case 2:return!o&&s&&d;default:return!1}})(b.current,t),f=i.slice(2).filter(e=>e[2]>.7).length<=2;C.current.push(u&&f),C.current.length>10&&C.current.shift();if(C.current.filter(Boolean).length>=2){const e=w.current+1;m(e)}else m(Math.max(0,w.current-1));if(w.current>=2){o?.();const t=b.current+1;m(0),C.current=[],g(t),x(!1),(async()=>{if(await n.speechService.playAudio(`${n.voiceOverAssetsPath}face-scan-vos/Sound-effect.mp3`),a.posthog.capture(`${d}/face_scan_detection_stage_completed`,{faceScanId:e,completedStage:b.current,nextStage:t,timestamp:(new Date).toISOString(),totalStages:4,stageName:T[b.current]}),1===t&&l&&l(),t>=4)s?.();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 n.speechService.playAudio(`${n.voiceOverAssetsPath}face-scan-vos/${e}`),D()}})()}I(t,i,b.current,u,f,w.current)}}catch(e){console.error("Pose detection error:",e)}},scanStage:f,setScanStage:g,consecutiveValid:h,isModelLoaded:p,resetScan:()=>{a.posthog.capture(`${d}/face_scan_reset`,{faceScanId:e,stage:b.current,timestamp:(new Date).toISOString(),stageName:T[b.current],consecutiveValid:w.current}),g(0),m(0),x(!1),b.current=0,w.current=0,C.current=[],F.current="",j.current=0,_.current=!1,v.current&&(speechSynthesis.cancel(),v.current=null)},enableVoiceCommands:()=>{if(_.current=!0,"undefined"!=typeof window&&E&&"speechSynthesis"in window){const e=new SpeechSynthesisUtterance("");e.volume=0,speechSynthesis.speak(e)}},startScanSequence:D,isScanningActive:S}}function l({resetScanState:a,loading:s,config:r}){const{translate:c}=t.useContext(n.LanguageContext)||{};return e.jsx("div",{className:"fixed top-[0] left-[0] z-[999] flex justify-center items-center w-full h-full",style:{background:r?.style?.base?.backgroundColor},children:e.jsxs("div",{className:"flex flex-col w-full items-center p-[1rem] rounded-lg ",children:[e.jsx(n.Header,{noTitle:!0,resolvedConfig:r}),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: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:c?.(n.LanguageKeys.scanFailed)}),e.jsx("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:c?.(n.LanguageKeys.clickToResetScan)}),e.jsx(n.SpecificButton,{disabled:s,className:"w-full h-[45px] shadow-[0px_1px_2px_0px_#00000040] text-[16px]",buttonText:c?.(n.LanguageKeys.resetScan),postfixIcon:e.jsx(o.ArrowRight,{}),buttonFunc:()=>a?.(),resolvedConfig:r})]})]})})}function d({stage:a,videoLoading:o,setVideoLoading:s,videoError:r,setVideoError:c,gender:i,config:l,btnConfig:d}){const{translate:u}=t.useContext(n.LanguageContext)||{};return-1===a?e.jsxs("div",{className:"text-center p-[16px] w-full h-full",style:{background:l?.style?.base?.backgroundColor},children:[e.jsxs("div",{className:"w-full",children:[e.jsx(n.Header,{noTitle:!0,resolvedConfig:l}),e.jsx("h2",{style:{fontFamily:l?.style?.heading?.headingFontFamily||"SeriouslyNostalgic Fn",fontSize:l?.style?.heading?.headingFontSize||"32px",color:l?.style?.heading?.headingColor||"#000",fontWeight:l?.style?.heading?.headingFontWeight||"normal"},children:u?.(n.LanguageKeys.faceVisible)}),o&&e.jsx("div",{className:"mb-4 flex items-center justify-center",style:{fontFamily:l?.style?.subheading?.subheadingFontFamily||"'Inter', sans-serif",fontSize:l?.style?.subheading?.subheadingFontSize||"14px",color:l?.style?.subheading?.subheadingColor||"#4b5563",fontWeight:l?.style?.subheading?.subheadingFontWeight||"normal"},children:u?.(n.LanguageKeys.loadingVideo)}),r&&e.jsx("div",{className:"mb-4 text-red-600",style:{fontFamily:l?.style?.subheading?.subheadingFontFamily||"'Inter', sans-serif",fontSize:l?.style?.subheading?.subheadingFontSize||"14px",color:"#ff0000",fontWeight:l?.style?.subheading?.subheadingFontWeight||"normal"},children:u?.(n.LanguageKeys.videoLoadFailed)}),!r&&e.jsx("div",{className:" w-[100px] mx-auto",children:e.jsx("video",{src:i===n.GenderType.Male?n.maleGlassesOffVideo:n.glassesOffVideo,autoPlay:!0,loop:!0,controls:!1,muted:!0,playsInline:!0,className:"h-full w-full object-contain border-none",onCanPlay:()=>s(!1),onLoadStart:()=>s(!0),onError:()=>c(!0),"aria-label":"Instructional video: Please remove your glasses before starting the scan."})})]}),e.jsx("div",{className:"flex justify-center w-full p-[1rem]",children:e.jsx(n.SpecificButton,{disabled:d.isDisabled,className:"!w-[60px] !h-[35px] !py-0 !px-0",buttonText:u?.(d.label),postfixIcon:d?.icon,buttonFunc:d.onClick,resolvedConfig:l})})]}):e.jsx("div",{className:"text-center p-[16px] w-full h-full",style:{background:l?.style?.base?.backgroundColor},children:e.jsxs("div",{className:"w-full",children:[e.jsx(n.Header,{noTitle:!0,resolvedConfig:l}),e.jsx("h3",{className:"mb-[0.5rem]",style:{fontFamily:l?.style?.heading?.headingFontFamily||"SeriouslyNostalgic Fn",fontSize:l?.style?.heading?.headingFontSize||"32px",color:l?.style?.heading?.headingColor||"#000",fontWeight:l?.style?.heading?.headingFontWeight||"normal"},children:u?.(n.directionMessages[a])}),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===a?"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===n.GenderType.Male?n.FACE_SCAN_HEADSHOT.male.forward:n.FACE_SCAN_HEADSHOT.female.forward,type:"video/mp4"})})}),e.jsx("div",{className:` w-[120px] overflow-hidden ${1===a?"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===n.GenderType.Male?n.FACE_SCAN_HEADSHOT.male.left:n.FACE_SCAN_HEADSHOT.female.left,type:"video/mp4"})})}),e.jsx("div",{className:` w-[120px] overflow-hidden ${2===a?"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===n.GenderType.Male?n.FACE_SCAN_HEADSHOT.male.right:n.FACE_SCAN_HEADSHOT.female.right,type:"video/mp4"})})}),e.jsx("div",{className:` w-[120px] overflow-hidden ${3===a?"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===n.GenderType.Male?n.FACE_SCAN_HEADSHOT.male.smile:n.FACE_SCAN_HEADSHOT.female.smile,type:"video/mp4"})})})]})]})})}const u=({webcamRef:a,canvasRef:r})=>{const{isError:c,isSuccess:i,showLoader:u,hasError:f,resetScanState:g,showGuideCard:h,scanStage:m,videoLoading:p,setVideoLoading:y,videoError:S,setVideoError:x,gender:v,getButtonText:b,isScanning:w,startScan:C,isModelLoaded:F,config:j}=t.useContext(n.ParamsContext),_=n.useLocalConfig(j),{setPreferredLanguage:N}=t.useContext(n.LanguageContext)||{};return t.useEffect(()=>{N?.(_?.language)},[_]),c?e.jsx(l,{config:_}):i?e.jsx("div",{className:"fixed z-[9] w-full h-full",style:{background:_?.style?.base?.backgroundColor},children:e.jsx(n.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] w-full h-full",style:{background:_?.style?.base?.backgroundColor},children:e.jsx(n.LoadingScreen,{url:_?.loader,loaderType:"black"})}),e.jsx("div",{className:"h-full flex-col 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:a,autoPlay:!0,playsInline:!0,muted:!0,width:n.videoConstraints.width,height:n.videoConstraints.height,className:"w-full h-full object-cover fixed left-0 top-0 z-0",style:{transform:"scaleX(-1)"}}),e.jsx("canvas",{ref:r,width:n.videoConstraints.width,height:n.videoConstraints.height,style:{transform:"scaleX(-1)",opacity:"0"}})]})})}),!u&&f&&e.jsx(l,{loading:u,resetScanState:g,config:_}),h&&!f&&!u&&e.jsx(s.Drawer,{open:!0,className:"face-scan-small camera-draw",anchor:"bottom",onClose:(e,t)=>{},hideBackdrop:!0,children:e.jsx(d,{stage:m,videoLoading:p,setVideoLoading:y,videoError:S,setVideoError:x,gender:v,config:_,btnConfig:{label:b(),onClick:w?g:C,isDisabled:u||!F,icon:w?e.jsx(o.ArrowRight,{}):e.jsx(e.Fragment,{})}})})]})};exports.FaceScan=({userDetails:o,onScanSuccess:s,onScanError:r,onRetry:c,config:l,isError:d,isSuccess:f,onUpload:g})=>{const h=t.useRef(null),m=t.useRef(null),p=t.useRef(null),y=t.useRef([]),S=t.useRef(null),[x,v]=t.useState(!1),[b,w]=t.useState(!1),[C,F]=t.useState(!1),[j,_]=t.useState(!0),[N,E]=t.useState(!1),[T,k]=t.useState(!1),[I,D]=t.useState(!1),[L,R]=t.useState(n.generateUuid()),{email:M,gender:P,deviceFocalLength:A,shopDomain:O,callbackUrl:z}=o,[$,H]=t.useState([]),V=t.useCallback(()=>{console.log("Stopping recording..."),p.current&&"recording"===p.current.state&&p.current.stop(),p.current=null},[]),W=async()=>{if(y.current){if(0===y.current.length)return console.error("No video data recorded"),D(!0),void v(!1);g?.(),v(!0);const e=new File(y.current,`${L}.webm`,{type:"video/webm"}),t=e.size,a=(t/1048576).toFixed(2),o=Math.round(t/1e4),s={video_size_mb:parseFloat(a),video_size_bytes:t,blob_count:y.current.length,estimated_duration_seconds:o},r=[{gender:P},{face_scan_id:L},{focal_length:`${A}`},{customer_store_url:O},{scan_type:"face_scan"},{callback_url:z||"https://example.com/webhook"}];console.log(r,"metadat"),n.handleScanTimeCapture({eventName:`${O}/face_scan_meta_data`,faceScanId:L,email:M,data:JSON.stringify({metaData:r,videoData:s})});const c=Date.now();n.handleScanTimeCapture({eventName:`${O}/face_scan_upload_start`,faceScanId:L,email:M,startTime:c});try{const t=await n.swan.fileUpload.faceScanFileUploader({file:e,arrayMetaData:r,objectKey:L,email:M,contentType:e.type}),a=Date.now(),o=a-c;n.handleScanTimeCapture({eventName:`${O}/face_scan_upload_complete`,faceScanId:L,email:M,completionTime:a,uploadDuration:o}),console.log("✅ Upload successful",t),n.swan.measurement.handlFaceScaneSocket({faceScanId:L,onOpen:()=>{n.handleWebSocketCapture({eventName:`${O}/webSocket`,faceScanID:L,connection:"open",type:"faceScan_recommendation",email:M}),console.log("websocket connect open")},onError:e=>{n.handleWebSocketCapture({eventName:`${O}/webSocket`,faceScanID:L,connection:"error",type:"faceScan_recommendation",email:M}),Z(e)},onSuccess:e=>{n.handleWebSocketCapture({eventName:`${O}/webSocket`,faceScanID:L,connection:"success",type:"faceScan_recommendation",email:M}),ee(e)},onClose:()=>{console.log("websocket connect close"),n.handleWebSocketCapture({eventName:`${O}/webSocket`,faceScanID:L,connection:"close",type:"faceScan_recommendation",email:M})}})}catch(e){Z(e)}}},K=t.useCallback(()=>{const e=h.current?.srcObject;if(!e)return;const t=e.getVideoTracks()[0].getSettings(),{width:a=n.videoConstraints.width,height:o=n.videoConstraints.height}=t,s=document.createElement("canvas"),r=s.getContext("2d");a>o?(s.width=o,s.height=a):(s.width=a,s.height=o);const c=document.createElement("video");c.srcObject=e,c.muted=!0,c.playsInline=!0,c.play();const i=()=>{a>o?(r?.save(),r?.translate(s.width,0),r?.rotate(Math.PI/2),r?.drawImage(c,0,0,o,a),r?.restore()):r?.drawImage(c,0,0,a,o),requestAnimationFrame(i)};i();const l=s.captureStream(30),d=$.length>0?{mimeType:$[0]}:{};let u;try{u=new MediaRecorder(l,d)}catch(e){return console.error("MediaRecorder init failed:",e),D(!0),void v(!1)}y.current=[],u.ondataavailable=e=>{e?.data&&e.data.size>0&&y.current&&y.current.push(e.data)},u.onstop=()=>{console.log("Recording stopped, total blobs:",y?.current?.length),W()},u.start(100),p.current=u,console.log("Recording started successfully (portrait normalized)")},[$,W]),{faceScanDetector:q,scanStage:U,setScanStage:B,resetScan:G,isModelLoaded:J,startScanSequence:X}=i({faceScanId:L,shopDomain:O,onScanComplete:()=>{V()},onModelReady:()=>{w(!0)},onStartRecording:()=>{console.log("Stage 0 completed - starting recording for stages 1-3"),K()}}),Q=t.useCallback(()=>{J&&(B(0),n.speechService.playAudio(`${n.voiceOverAssetsPath}face-scan-vos/Face-forward.mp3`),setTimeout(()=>{F(!0),setTimeout(()=>{X()},200)},200))},[B,F,X,J]),Y=t.useCallback(()=>{F(!1),_(!0),V(),G(),c?.(),y.current=[],p.current&&(p.current=null),D(!1),B(-1),R(n.generateUuid()),h.current&&S.current&&(h.current.srcObject=S.current,console.log("Camera stream restored after reset"))},[B,F,_,V,G,R]),Z=e=>{console.log(e,"ws error"),r?.(e),D(!0),v(!1),_(!1),n.handleScanTimeCapture({eventName:`${O}/faceScan`,faceScanId:L,status:"failed",email:M,data:JSON.stringify(e)})},ee=e=>{console.log(e,"ws success"),e&&"intermediate"===e?.resultType&&n.handleScanTimeCapture({eventName:`${O}/faceScan_success/intermediate`,faceScanId:L,status:"success",email:M,data:JSON.stringify(e)}),s?.(e)};t.useEffect(()=>{if(!d&&!f)return navigator.mediaDevices.getUserMedia&&navigator.mediaDevices.getUserMedia({video:n.videoConstraints}).then(e=>{S.current=e,h.current&&(h.current.srcObject=e)}).catch(e=>console.error("Error accessing webcam:",e)),()=>{S.current&&S.current.getTracks().forEach(e=>e.stop())}},[d,f]),t.useEffect(()=>{if(!b||!C)return;const e=setInterval(()=>{q(h,m)},500);return()=>clearInterval(e)},[q,b,C]);return console.log("Model ready:",b,"Has error:",I,"Is scanning:",C,"showLoader",x),t.useEffect(()=>{if("undefined"!=typeof MediaRecorder){const e=n.videoTypes.filter(e=>MediaRecorder.isTypeSupported(e));H(e)}},[]),t.useEffect(()=>{B(-1)},[d,f]),t.useEffect(()=>{a.init(n.posthogPublicKey,{api_host:n.posthogPublicHost}),a.capture("$pageview")},[]),e.jsx(n.LanguageContextProvider,{children:e.jsx(n.ParamsContext.Provider,{value:{isError:d,isSuccess:f,showLoader:x,hasError:I,resetScanState:Y,showGuideCard:j,scanStage:U,videoLoading:N,setVideoLoading:E,videoError:T,setVideoError:k,gender:P,getButtonText:()=>C?n.LanguageKeys.reset:J?n.LanguageKeys.start:n.LanguageKeys.loading,isScanning:C,startScan:Q,isModelLoaded:J,config:l},children:e.jsx(u,{webcamRef:h,canvasRef:m})})})};
2
+ //# sourceMappingURL=FaceScan-Cgis7rhD.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"FaceScan-Cgis7rhD.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 \"posthog-js\";\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: number | NodeJS.Timeout;\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 = videoConstraints.width;\n dummyCanvas.height = videoConstraints.height;\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}: {\n faceScanId: string;\n onValidPose?: () => void;\n onScanComplete?: () => void;\n onModelReady?: () => void;\n onStartRecording: () => void;\n shopDomain: string;\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 \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 try {\n const poses = await detectorRef.current.estimatePoses(webcamRef.current);\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 }\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 initializeModels();\n return () => {\n disposeModelAndTf();\n };\n }, []);\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 { Config } from \"../../types/interfaces\";\n\nfunction FaceScanErrorScreen({ resetScanState, loading, config }: { resetScanState?: () => void; loading?: boolean; config?: Config }) {\n\tconst { translate } = useContext(LanguageContext) || {};\n\n\treturn (\n\t\t<div className=\"fixed 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 resolvedConfig={config} />\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\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={() => resetScanState?.()}\n\t\t\t\t\t\tresolvedConfig={config}\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 { FaceScanGuideProps } from \"../../types/interfaces\";\nimport 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\";\n\nfunction FaceScanGuide({ stage, videoLoading, setVideoLoading, videoError, setVideoError, gender, config, btnConfig }: FaceScanGuideProps) {\n\tconst { translate } = useContext(LanguageContext) || {};\n\n\n\n\tif (stage === -1) {\n\t\treturn (\n\t\t\t<div className=\"text-center 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 resolvedConfig={config} />\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\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\tresolvedConfig={config}\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 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 resolvedConfig={config} />\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{/* <p>We'll guide you to take 6 selfies </p> */}\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, useEffect } 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 { ArrowRight } from \"lucide-react\";\nimport { LanguageContext } from \"../../utils/context/languageContext\";\nimport { useLocalConfig } from \"../../config/useLocalConfig\";\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\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\tconfig,\n\t} = useContext(ParamsContext);\n\tconst resolvedConfig = useLocalConfig(config);\n\n\tconst { setPreferredLanguage } = useContext(LanguageContext) || {};\n\tuseEffect(() => {\n\t\tsetPreferredLanguage?.(resolvedConfig?.language);\n\t}, [resolvedConfig]);\n\tif (isError) {\n\t\treturn <FaceScanErrorScreen config={resolvedConfig} />;\n\t}\n\tif (isSuccess) {\n\t\treturn (\n\t\t\t<div className=\"fixed z-[9] w-full h-full\" style={{ background: resolvedConfig?.style?.base?.backgroundColor }}>\n\t\t\t\t{/* <Asset genderType={gender} /> */}\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] 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 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}\n\t\t\t\t\t\t\theight={videoConstraints.height}\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} height={videoConstraints.height} 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 && <FaceScanErrorScreen loading={showLoader} resetScanState={resetScanState} config={resolvedConfig} />}\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\tconfig={resolvedConfig}\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, } from \"react\";\nimport posthog from \"posthog-js\";\nimport { FaceScanProps } from \"../../types/interfaces\";\nimport { generateUuid, handleScanTimeCapture, handleWebSocketCapture } from \"../../utils/utils\";\nimport { posthogPublicHost, posthogPublicKey, videoConstraints, videoTypes, voiceOverAssetsPath } from \"../../utils/constants\";\nimport swan from \"../../utils/service/swanService\";\nimport speechService from \"../../utils/service/speechService\";\nimport useFaceScan from \"../../customHooks/useFaceScan\";\nimport { LanguageKeys } from \"../../utils/languageKeys\";\nimport LanguageContextProvider from \"../../utils/context/languageContext\";\nimport FaceScanStep from \"./FaceScanStep\";\nimport ParamsContext from \"../../utils/context/paramsContext\";\n\nexport const FaceScan: React.FC<FaceScanProps> = ({ userDetails, onScanSuccess, onScanError, onRetry, config, isError, isSuccess,onUpload }) => {\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 [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 [faceScanId, setFaceScanId] = useState(generateUuid());\n\tconst { email, gender, deviceFocalLength, shopDomain, callbackUrl } = userDetails;\n\tconst [supportedTypes, setSupportedTypes] = useState<string[]>([]);\n\t\n\tconst stopRecording = useCallback(() => {\n\t\tconsole.log(\"Stopping recording...\");\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\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\tsetHasError(true);\n\t\t\t\tsetShowLoader(false);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tonUpload?.();\n\t\t\tsetShowLoader(true);\n\t\t\tconst videoFile = new File(recordedBlobsRef.current, `${faceScanId}.webm`, {\n\t\t\t\ttype: \"video/webm\",\n\t\t\t});\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\tblob_count: recordedBlobsRef.current.length,\n\t\t\t\testimated_duration_seconds: estimatedDuration,\n\t\t\t};\n\n\t\t\tconst metaData = [\n\t\t\t\t{ gender: gender },\n\t\t\t\t{ face_scan_id: faceScanId },\n\t\t\t\t{\n\t\t\t\t\tfocal_length: `${deviceFocalLength}`,\n\t\t\t\t},\n\t\t\t\t{ customer_store_url: shopDomain },\n\t\t\t\t{ scan_type: \"face_scan\" },\n\t\t\t\t{ callback_url: callbackUrl || \"https://example.com/webhook\" },\n\t\t\t];\n\t\t\tconsole.log(metaData,\"metadat\");\n\t\t\t\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\n\t\t\t\tconsole.log(\"✅ Upload successful\", res);\n\t\t\t\tswan.measurement.handlFaceScaneSocket({\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\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\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\tconst { width = videoConstraints.width, height = videoConstraints.height } = 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\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\trequestAnimationFrame(drawFrame);\n\t\t};\n\t\tdrawFrame();\n\n\t\tconst canvasStream = canvas.captureStream(30); // 30fps\n\t\tconst mediaRecorderOptions = supportedTypes.length > 0 ? { mimeType: supportedTypes[0] } : {};\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\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\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\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]);\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\tif (mediaRecorderRef.current) {\n\t\t\tmediaRecorderRef.current = null;\n\t\t}\n\t\tsetHasError(false);\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\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: videoConstraints })\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) => console.error(\"Error accessing webcam:\", err));\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]);\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\tif (typeof MediaRecorder !== \"undefined\") {\n\t\t\tconst supported = videoTypes.filter((type) => MediaRecorder.isTypeSupported(type));\n\t\t\tsetSupportedTypes(supported);\n\t\t}\n\t}, []);\n\tuseEffect(() => {\n\t\tsetScanStage(-1);\n\t\tif (isError || isSuccess) return;\n\t}, [isError, isSuccess]);\n\n\tuseEffect(() => {\n\t\tposthog.init(posthogPublicKey, { api_host: posthogPublicHost });\n\t\tposthog.capture(\"$pageview\");\n\t}, []);\n\n return (\n\t\t<LanguageContextProvider>\n\t\t\t<ParamsContext.Provider value={{isError,isSuccess,showLoader,hasError,resetScanState,showGuideCard,scanStage,videoLoading,setVideoLoading,videoError,setVideoError,gender,getButtonText,isScanning,startScan,isModelLoaded,config}}>\n\t\t\t<FaceScanStep webcamRef={webcamRef} canvasRef={canvasRef}/>\n\t\t\t</ParamsContext.Provider>\n\t\t</LanguageContextProvider>\n\t )\n};\n"],"names":["preloadedDetector","isPreloading","useFaceScan","faceScanId","onValidPose","onScanComplete","onModelReady","onStartRecording","shopDomain","detectorRef","useRef","scanStage","setScanStage","useState","consecutiveValid","setConsecutiveValid","isModelLoaded","setIsModelLoaded","isScanningActive","setIsScanningActive","utteranceRef","scanStageRef","consecutiveValidRef","validityBufferRef","lastSpokenMessageRef","lastSpokenTimeRef","voiceEnabledRef","lastPoseTrackingTimeRef","isIOS","navigator","test","userAgent","platform","maxTouchPoints","directionMessages","useMemo","debouncedTrackPoseDetection","fn","delay","timer","args","clearTimeout","setTimeout","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","error","console","warn","startScanSequence","stageName","initializeModels","async","window","log","detector","Promise","r","tf","poseDetection","all","import","setBackend","ready","createDetector","SupportedModels","BlazePose","runtime","modelType","dummyCanvas","document","createElement","width","videoConstraints","height","ctx","getContext","fillStyle","fillRect","estimatePoses","e","err","preloadDetector","useEffect","disposeModelAndTf","faceScanDetector","webcamRef","canvasRef","readyState","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","max","nextStage","speechService","playAudio","voiceOverAssetsPath","completedStage","totalStages","nextSound","resetScan","speechSynthesis","cancel","enableVoiceCommands","silentUtterance","SpeechSynthesisUtterance","volume","speak","FaceScanErrorScreen","resetScanState","loading","config","translate","useContext","LanguageContext","_jsx","className","style","background","base","backgroundColor","children","_jsxs","Header","noTitle","resolvedConfig","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","isError","isSuccess","showLoader","hasError","showGuideCard","getButtonText","isScanning","startScan","ParamsContext","useLocalConfig","setPreferredLanguage","language","LoadingScreen","url","loader","loaderType","_Fragment","id","crossOrigin","preload","position","zIndex","undefined","ref","transform","opacity","Drawer","open","anchor","onClose","event","reason","hideBackdrop","userDetails","onScanSuccess","onScanError","onRetry","onUpload","mediaRecorderRef","recordedBlobsRef","streamRef","setShowLoader","modelReady","setModelReady","setIsScanning","setShowGuideCard","setHasError","setFaceScanId","generateUuid","email","deviceFocalLength","callbackUrl","supportedTypes","setSupportedTypes","stopRecording","state","stop","uploadFinalVideo","videoFile","File","fileSize","size","fileSizeMB","estimatedDuration","round","videoData","video_size_mb","video_size_bytes","blob_count","estimated_duration_seconds","metaData","face_scan_id","focal_length","customer_store_url","scan_type","callback_url","handleScanTimeCapture","eventName","uploadStartTime","startTime","res","swan","fileUpload","faceScanFileUploader","file","arrayMetaData","objectKey","contentType","uploadEndTime","uploadDuration","completionTime","measurement","handlFaceScaneSocket","onOpen","handleWebSocketCapture","faceScanID","connection","onSuccess","startRecording","stream","srcObject","settings","getVideoTracks","getSettings","canvas","videoEl","play","drawFrame","save","rotate","drawImage","restore","requestAnimationFrame","canvasStream","captureStream","mediaRecorderOptions","mimeType","mediaRecorder","MediaRecorder","ondataavailable","onstop","start","status","resultType","mediaDevices","getUserMedia","video","then","catch","getTracks","track","intervalId","setInterval","clearInterval","supported","videoTypes","isTypeSupported","init","posthogPublicKey","api_host","posthogPublicHost","LanguageContextProvider","Provider","value","reset"],"mappings":"yLA6BA,IAAIA,EAAyC,KACzCC,GAAe,EAiEn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mN,EAAAA,wBAAuB,CAAA7M,SACvBN,EAAAA,IAAC8E,EAAAA,cAAcsI,SAAQ,CAACC,MAAO,CAAC/I,UAAQC,YAAUC,aAAWC,WAAS/E,iBAAegF,gBAAclQ,YAAU2N,eAAaC,kBAAgBC,aAAWC,gBAAcC,SAAOoC,cAzBtJ,IACjBC,EAAmBxD,EAAAA,aAAakM,MAC/BzY,EACEuM,EAAAA,aAAa2K,MADO3K,EAAAA,aAAazB,QAuBiJiF,aAAWC,YAAUhQ,gBAAc+K,UAAOU,SAClON,EAAAA,IAACqE,EAAY,CAAC/H,UAAWA,EAAWC,UAAWA"}
@@ -0,0 +1,2 @@
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 l,{posthog as d}from"posthog-js";import{s as u,v as f,a as h,L as g,H as m,b as p,S as y,m as S,g as b,G as w,d as v,F as x,P as F,u as N,c as _,e as I,f as k,p as M,h as C,i as T,j as D,k as P,l as E}from"./LoadingScreen-B0wN1CQk.js";import{ArrowRight as z}from"lucide-react";import{Drawer as $}from"@mui/material";let j=null,L=!1;function R({faceScanId:e,onValidPose:t,onScanComplete:a,onModelReady:s,onStartRecording:l,shopDomain:g}){const m=n(null),[p,y]=o(0),[S,b]=o(0),[w,v]=o(!1),[x,F]=o(!1),N=n(null),_=n(p),I=n(S),k=n([]),M=n(""),C=n(0),T=n(!1),D=n(0),P="undefined"!=typeof navigator&&(/iPad|iPhone|iPod/.test(navigator.userAgent)||"MacIntel"===navigator.platform&&navigator.maxTouchPoints>1),E=r(()=>["Face front","Turn head fully left","Turn head fully right","Smile facing front"],[]),z=r(()=>function(e,t){let a;return(...n)=>{a&&clearTimeout(a),a=setTimeout(()=>e(...n),t)}}(e=>{d.capture(`${g}/face_scan_pose_detection`,e)},4e3),[g]),$=c((t,a,n,o,r,c)=>{const i=Date.now();if(!(i-D.current<4e3)){D.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],f=t.map(e=>e[2]).filter(e=>e>0),h=f.length>0?f.reduce((e,t)=>e+t,0)/f.length:0,g=a.map(e=>e[2]).filter(e=>e>0),m=g.length>0?g.reduce((e,t)=>e+t,0)/g.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(h.toFixed(3)),avgBodyScore:parseFloat(m.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(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})};z(w)}catch(e){console.warn("Failed to track pose detection:",e)}}},[e,z]),R=()=>{d.capture(`${g}/face_scan_detection_started`,{faceScanId:e,stage:_.current,timestamp:(new Date).toISOString(),stageName:E[_.current]}),setTimeout(()=>{F(!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(j)return j;if(L)for(;L;)if(await new Promise(e=>setTimeout(e,100)),j)return j;L=!0;try{const[e,t]=await Promise.all([import("@tensorflow/tfjs"),import("./pose-detection.esm-ZdVkbzCQ.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=h.width,n.height=h.height;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 j=a,a}catch(e){return console.error("Failed to preload detector:",e),null}finally{L=!1}})();e&&(m.current=e,console.log("Face scan model loaded successfully"),v(!0),s?.())}catch(e){console.error("Error initializing face scan:",e)}};return i(()=>(V(),()=>{(async()=>{try{v(!1)}catch(e){console.error("Error disposing resources:",e)}finally{y(0),b(0),_.current=0,I.current=0,k.current=[]}})()}),[]),i(()=>{_.current=p},[p]),i(()=>{I.current=S},[S]),{faceScanDetector:async(n,o)=>{if(m.current&&n.current&&w&&x&&!(n.current.readyState<2))try{const r=await m.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(I.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}})(_.current,n),s=c.slice(2).filter(e=>e[2]>.7).length<=2;k.current.push(i&&s),k.current.length>10&&k.current.shift();if(k.current.filter(Boolean).length>=2){const e=I.current+1;b(e)}else b(Math.max(0,I.current-1));if(I.current>=2){t?.();const n=_.current+1;b(0),k.current=[],y(n),F(!1),(async()=>{if(await u.playAudio(`${f}face-scan-vos/Sound-effect.mp3`),d.capture(`${g}/face_scan_detection_stage_completed`,{faceScanId:e,completedStage:_.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(`${f}face-scan-vos/${e}`),R()}})()}$(n,c,_.current,i,s,I.current)}}catch(e){console.error("Pose detection error:",e)}},scanStage:p,setScanStage:y,consecutiveValid:S,isModelLoaded:w,resetScan:()=>{d.capture(`${g}/face_scan_reset`,{faceScanId:e,stage:_.current,timestamp:(new Date).toISOString(),stageName:E[_.current],consecutiveValid:I.current}),y(0),b(0),F(!1),_.current=0,I.current=0,k.current=[],M.current="",C.current=0,T.current=!1,N.current&&(speechSynthesis.cancel(),N.current=null)},enableVoiceCommands:()=>{if(T.current=!0,"undefined"!=typeof window&&P&&"speechSynthesis"in window){const e=new SpeechSynthesisUtterance("");e.volume=0,speechSynthesis.speak(e)}},startScanSequence:R,isScanningActive:x}}function V({resetScanState:a,loading:n,config:o}){const{translate:r}=s(g)||{};return e("div",{className:"fixed 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(m,{noTitle:!0,resolvedConfig:o}),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,{disabled:n,className:"w-full h-[45px] shadow-[0px_1px_2px_0px_#00000040] text-[16px]",buttonText:r?.(p.resetScan),postfixIcon:e(z,{}),buttonFunc:()=>a?.(),resolvedConfig:o})]})]})})}function O({stage:a,videoLoading:n,setVideoLoading:o,videoError:r,setVideoError:c,gender:i,config:l,btnConfig:d}){const{translate:u}=s(g)||{};return-1===a?t("div",{className:"text-center p-[16px] w-full h-full",style:{background:l?.style?.base?.backgroundColor},children:[t("div",{className:"w-full",children:[e(m,{noTitle:!0,resolvedConfig:l}),e("h2",{style:{fontFamily:l?.style?.heading?.headingFontFamily||"SeriouslyNostalgic Fn",fontSize:l?.style?.heading?.headingFontSize||"32px",color:l?.style?.heading?.headingColor||"#000",fontWeight:l?.style?.heading?.headingFontWeight||"normal"},children:u?.(p.faceVisible)}),n&&e("div",{className:"mb-4 flex items-center justify-center",style:{fontFamily:l?.style?.subheading?.subheadingFontFamily||"'Inter', sans-serif",fontSize:l?.style?.subheading?.subheadingFontSize||"14px",color:l?.style?.subheading?.subheadingColor||"#4b5563",fontWeight:l?.style?.subheading?.subheadingFontWeight||"normal"},children:u?.(p.loadingVideo)}),r&&e("div",{className:"mb-4 text-red-600",style:{fontFamily:l?.style?.subheading?.subheadingFontFamily||"'Inter', sans-serif",fontSize:l?.style?.subheading?.subheadingFontSize||"14px",color:"#ff0000",fontWeight:l?.style?.subheading?.subheadingFontWeight||"normal"},children:u?.(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,{disabled:d.isDisabled,className:"!w-[60px] !h-[35px] !py-0 !px-0",buttonText:u?.(d.label),postfixIcon:d?.icon,buttonFunc:d.onClick,resolvedConfig:l})})]}):e("div",{className:"text-center p-[16px] w-full h-full",style:{background:l?.style?.base?.backgroundColor},children:t("div",{className:"w-full",children:[e(m,{noTitle:!0,resolvedConfig:l}),e("h3",{className:"mb-[0.5rem]",style:{fontFamily:l?.style?.heading?.headingFontFamily||"SeriouslyNostalgic Fn",fontSize:l?.style?.heading?.headingFontSize||"32px",color:l?.style?.heading?.headingColor||"#000",fontWeight:l?.style?.heading?.headingFontWeight||"normal"},children:u?.(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 W=({webcamRef:n,canvasRef:o})=>{const{isError:r,isSuccess:c,showLoader:l,hasError:d,resetScanState:u,showGuideCard:f,scanStage:m,videoLoading:p,setVideoLoading:y,videoError:S,setVideoError:b,gender:w,getButtonText:v,isScanning:x,startScan:I,isModelLoaded:k,config:M}=s(F),C=N(M),{setPreferredLanguage:T}=s(g)||{};return i(()=>{T?.(C?.language)},[C]),r?e(V,{config:C}):c?e("div",{className:"fixed z-[9] w-full h-full",style:{background:C?.style?.base?.backgroundColor},children:e(_,{url:C?.loader,loaderType:"black"})}):t(a,{children:[e("audio",{id:"audioElement",crossOrigin:"anonymous",preload:"auto",style:{position:"absolute",zIndex:-99999},src:void 0}),l&&d&&e("div",{className:"fixed z-[9] w-full h-full",style:{background:C?.style?.base?.backgroundColor},children:e(_,{url:C?.loader,loaderType:"black"})}),e("div",{className:"h-full flex-col 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:h.width,height:h.height,className:"w-full h-full object-cover fixed left-0 top-0 z-0",style:{transform:"scaleX(-1)"}}),e("canvas",{ref:o,width:h.width,height:h.height,style:{transform:"scaleX(-1)",opacity:"0"}})]})})}),!l&&d&&e(V,{loading:l,resetScanState:u,config:C}),f&&!d&&!l&&e($,{open:!0,className:"face-scan-small camera-draw",anchor:"bottom",onClose:(e,t)=>{},hideBackdrop:!0,children:e(O,{stage:m,videoLoading:p,setVideoLoading:y,videoError:S,setVideoError:b,gender:w,config:C,btnConfig:{label:v(),onClick:x?u:I,isDisabled:l||!k,icon:e(x?z:a,{})}})})]})},U=({userDetails:t,onScanSuccess:a,onScanError:r,onRetry:s,config:d,isError:g,isSuccess:m,onUpload:y})=>{const S=n(null),b=n(null),w=n(null),v=n([]),x=n(null),[N,_]=o(!1),[z,$]=o(!1),[j,L]=o(!1),[V,O]=o(!0),[U,B]=o(!1),[A,J]=o(!1),[q,G]=o(!1),[K,H]=o(I()),{email:X,gender:Q,deviceFocalLength:Y,shopDomain:Z,callbackUrl:ee}=t,[te,ae]=o([]),ne=c(()=>{console.log("Stopping recording..."),w.current&&"recording"===w.current.state&&w.current.stop(),w.current=null},[]),oe=async()=>{if(v.current){if(0===v.current.length)return console.error("No video data recorded"),G(!0),void _(!1);y?.(),_(!0);const e=new File(v.current,`${K}.webm`,{type:"video/webm"}),t=e.size,a=(t/1048576).toFixed(2),n=Math.round(t/1e4),o={video_size_mb:parseFloat(a),video_size_bytes:t,blob_count:v.current.length,estimated_duration_seconds:n},r=[{gender:Q},{face_scan_id:K},{focal_length:`${Y}`},{customer_store_url:Z},{scan_type:"face_scan"},{callback_url:ee||"https://example.com/webhook"}];console.log(r,"metadat"),D({eventName:`${Z}/face_scan_meta_data`,faceScanId:K,email:X,data:JSON.stringify({metaData:r,videoData:o})});const c=Date.now();D({eventName:`${Z}/face_scan_upload_start`,faceScanId:K,email:X,startTime:c});try{const t=await P.fileUpload.faceScanFileUploader({file:e,arrayMetaData:r,objectKey:K,email:X,contentType:e.type}),a=Date.now();D({eventName:`${Z}/face_scan_upload_complete`,faceScanId:K,email:X,completionTime:a,uploadDuration:a-c}),console.log("✅ Upload successful",t),P.measurement.handlFaceScaneSocket({faceScanId:K,onOpen:()=>{E({eventName:`${Z}/webSocket`,faceScanID:K,connection:"open",type:"faceScan_recommendation",email:X}),console.log("websocket connect open")},onError:e=>{E({eventName:`${Z}/webSocket`,faceScanID:K,connection:"error",type:"faceScan_recommendation",email:X}),ge(e)},onSuccess:e=>{E({eventName:`${Z}/webSocket`,faceScanID:K,connection:"success",type:"faceScan_recommendation",email:X}),me(e)},onClose:()=>{console.log("websocket connect close"),E({eventName:`${Z}/webSocket`,faceScanID:K,connection:"close",type:"faceScan_recommendation",email:X})}})}catch(e){ge(e)}}},re=c(()=>{const e=S.current?.srcObject;if(!e)return;const t=e.getVideoTracks()[0].getSettings(),{width:a=h.width,height:n=h.height}=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=o.captureStream(30),l=te.length>0?{mimeType:te[0]}:{};let d;try{d=new MediaRecorder(s,l)}catch(e){return console.error("MediaRecorder init failed:",e),G(!0),void _(!1)}v.current=[],d.ondataavailable=e=>{e?.data&&e.data.size>0&&v.current&&v.current.push(e.data)},d.onstop=()=>{console.log("Recording stopped, total blobs:",v?.current?.length),oe()},d.start(100),w.current=d,console.log("Recording started successfully (portrait normalized)")},[te,oe]),{faceScanDetector:ce,scanStage:ie,setScanStage:se,resetScan:le,isModelLoaded:de,startScanSequence:ue}=R({faceScanId:K,shopDomain:Z,onScanComplete:()=>{ne()},onModelReady:()=>{$(!0)},onStartRecording:()=>{console.log("Stage 0 completed - starting recording for stages 1-3"),re()}}),fe=c(()=>{de&&(se(0),u.playAudio(`${f}face-scan-vos/Face-forward.mp3`),setTimeout(()=>{L(!0),setTimeout(()=>{ue()},200)},200))},[se,L,ue,de]),he=c(()=>{L(!1),O(!0),ne(),le(),s?.(),v.current=[],w.current&&(w.current=null),G(!1),se(-1),H(I()),S.current&&x.current&&(S.current.srcObject=x.current,console.log("Camera stream restored after reset"))},[se,L,O,ne,le,H]),ge=e=>{console.log(e,"ws error"),r?.(e),G(!0),_(!1),O(!1),D({eventName:`${Z}/faceScan`,faceScanId:K,status:"failed",email:X,data:JSON.stringify(e)})},me=e=>{console.log(e,"ws success"),e&&"intermediate"===e?.resultType&&D({eventName:`${Z}/faceScan_success/intermediate`,faceScanId:K,status:"success",email:X,data:JSON.stringify(e)}),a?.(e)};i(()=>{if(!g&&!m)return navigator.mediaDevices.getUserMedia&&navigator.mediaDevices.getUserMedia({video:h}).then(e=>{x.current=e,S.current&&(S.current.srcObject=e)}).catch(e=>console.error("Error accessing webcam:",e)),()=>{x.current&&x.current.getTracks().forEach(e=>e.stop())}},[g,m]),i(()=>{if(!z||!j)return;const e=setInterval(()=>{ce(S,b)},500);return()=>clearInterval(e)},[ce,z,j]);return console.log("Model ready:",z,"Has error:",q,"Is scanning:",j,"showLoader",N),i(()=>{if("undefined"!=typeof MediaRecorder){const e=k.filter(e=>MediaRecorder.isTypeSupported(e));ae(e)}},[]),i(()=>{se(-1)},[g,m]),i(()=>{l.init(M,{api_host:C}),l.capture("$pageview")},[]),e(T,{children:e(F.Provider,{value:{isError:g,isSuccess:m,showLoader:N,hasError:q,resetScanState:he,showGuideCard:V,scanStage:ie,videoLoading:U,setVideoLoading:B,videoError:A,setVideoError:J,gender:Q,getButtonText:()=>j?p.reset:de?p.start:p.loading,isScanning:j,startScan:fe,isModelLoaded:de,config:d},children:e(W,{webcamRef:S,canvasRef:b})})})};export{U as F};
2
+ //# sourceMappingURL=FaceScan-ChAn2cB2.js.map