{"version":3,"file":"WebGLGuard.Cz0BfuzQ.mjs","names":["useState","useRef","THREE.WebGLRenderer"],"sources":["https:/framerusercontent.com/modules/Tas1G3wra606Vt5Ckw93/EpoSZrLQNfZYaMsptJAQ/WebGLGuard.js"],"sourcesContent":["// Shared WebGL failure detection, fallback-image rendering, and bounded\n// auto-recovery for Three.js components in Framer.\n//\n// Import from any component in the same Framer project:\n//   import { useWebGLGuards, createGuardedRenderer, WebGLFallbackFrame,\n//            fallbackPropertyControls, FallbackProps } from \"./WebGLGuards\"\n//\n// WHY THIS EXISTS\n//\n// The obvious fallback pattern — `setWebglAvailable(false)` unmounting the\n// div that holds the canvas — does not work. The main effect's dependency\n// array does not contain that state, so React never runs its cleanup: the\n// renderer, the animation loop, and the observers all stay alive, and a\n// later recovery mounts a fresh empty div the canvas is never re-appended\n// to. Here the canvas container stays mounted permanently and the fallback\n// image is overlaid on top, so the mount ref is stable and a full rebuild\n// is always possible.\n//\n// It also does not catch most real failures. A white canvas is usually one\n// of: a context-loss event, a context the loss event never fired for, a\n// shader link error, or a GPU feature the effect silently depends on. Each\n// gets its own detection layer below, all funnelling into one entry point.\nimport{jsx as _jsx,jsxs as _jsxs}from\"react/jsx-runtime\";import{ControlType}from\"framer\";import{useEffect,useRef,useState}from\"react\";import*as THREE from\"three\";// Full rebuilds attempted after a failure before the component gives up and\n// stays on the fallback image for good.\nconst MAX_RECOVERY_ATTEMPTS=2;// Delay before a recovery rebuild — lets the browser settle after a GPU\n// process restart before we ask it for a new context.\nconst RECOVERY_DELAY_MS=600;// How often the tick polls isContextLost(). Every frame would also be fine;\n// this keeps the GL call off the hot path.\nconst WATCHDOG_FRAME_INTERVAL=16;// ---------------------------------------------------------------------------\n// Hook — owns the fallback state and the recovery budget\n// ---------------------------------------------------------------------------\nexport function useWebGLGuards(name=\"WebGL\"){const[webglAvailable,setWebglAvailable]=useState(true);// Bumping this forces the main effect to tear down and rebuild. A resume\n// is not enough: a restored context comes back with cleared render\n// targets, so any seed pass that ran once at init has been lost.\nconst[gpuEpoch,setGpuEpoch]=useState(0);const attemptsRef=useRef(0);const pendingRef=useRef(false);const timerRef=useRef(null);useEffect(()=>{return()=>{if(timerRef.current!==null){clearTimeout(timerRef.current);timerRef.current=null;}};},[]);const beginSession=()=>{// A rebuild triggered by a property change rather than by our own\n// recovery scheduler refreshes the budget, so editing props in the\n// Framer canvas can bring a stuck component back.\nif(!pendingRef.current)attemptsRef.current=0;pendingRef.current=false;let frames=0;const session={failed:false,destroyed:false,renderer:null,fail(reason,retryable){if(session.failed||session.destroyed)return;session.failed=true;console.warn(\"[\"+name+\"] showing fallback — \"+reason);session.renderer?.setAnimationLoop(null);if(!retryable)attemptsRef.current=MAX_RECOVERY_ATTEMPTS;setWebglAvailable(false);if(attemptsRef.current<MAX_RECOVERY_ATTEMPTS){attemptsRef.current+=1;pendingRef.current=true;if(timerRef.current!==null){clearTimeout(timerRef.current);}timerRef.current=window.setTimeout(()=>{timerRef.current=null;setGpuEpoch(prev=>prev+1);},RECOVERY_DELAY_MS);}else{console.warn(\"[\"+name+\"] recovery budget exhausted — staying on fallback\");}},halted(){return session.failed||session.destroyed;},shouldStop(){if(session.failed||session.destroyed)return true;// Three.js turns render() into a silent no-op once its\n// internal context-lost flag is set, so a loss whose event we\n// missed looks exactly like a frozen canvas. Polling catches\n// every case the event handler does not.\nframes++;if(frames%WATCHDOG_FRAME_INTERVAL===0){const gl=session.renderer?.getContext();if(!gl||gl.isContextLost()){session.fail(\"context lost (watchdog)\",true);return true;}}return false;},ready(){if(!session.failed)setWebglAvailable(true);},end(){session.destroyed=true;},rebuildNow(){// Only acts if a recovery rebuild was already scheduled, so\n// this can never restart an exhausted component.\nif(timerRef.current!==null){clearTimeout(timerRef.current);timerRef.current=null;setGpuEpoch(prev=>prev+1);}}};return session;};return{webglAvailable,gpuEpoch,beginSession};}export function createGuardedRenderer(session,options={}){// Own the canvas so the creation-error listener is attached BEFORE\n// Three.js asks for a context — webglcontextcreationerror fires\n// synchronously inside the WebGLRenderer constructor and would\n// otherwise be unobservable.\nconst canvas=document.createElement(\"canvas\");const handleCreationError=e=>{const status=e.statusMessage||\"unknown reason\";session.fail(\"context creation failed — \"+status,false);};canvas.addEventListener(\"webglcontextcreationerror\",handleCreationError);let renderer;try{renderer=new THREE.WebGLRenderer({...options.params||{},canvas});}catch(e){canvas.removeEventListener(\"webglcontextcreationerror\",handleCreationError);session.fail(\"WebGLRenderer construction threw — \"+String(e),false);return null;}session.renderer=renderer;const capError=checkCapabilities(renderer,options.requirements||{});if(capError){canvas.removeEventListener(\"webglcontextcreationerror\",handleCreationError);renderer.dispose();session.fail(capError,false);return null;}// Shader compile and link failures are otherwise silent — Three.js logs\n// to the console and carries on rendering nothing.\nif(renderer.debug){renderer.debug.checkShaderErrors=true;renderer.debug.onShaderError=()=>{session.fail(\"shader compile/link error\",false);};}const handleContextLost=e=>{// Mandatory — without preventDefault the browser will not attempt to\n// restore the context at all.\ne.preventDefault();session.fail(\"webglcontextlost\",true);};const handleContextRestored=()=>{session.rebuildNow();};canvas.addEventListener(\"webglcontextlost\",handleContextLost);canvas.addEventListener(\"webglcontextrestored\",handleContextRestored);const detach=()=>{canvas.removeEventListener(\"webglcontextcreationerror\",handleCreationError);canvas.removeEventListener(\"webglcontextlost\",handleContextLost);canvas.removeEventListener(\"webglcontextrestored\",handleContextRestored);if(renderer.debug)renderer.debug.onShaderError=null;};// Named requireCapabilities rather than require so the local binding\n// cannot shadow CommonJS require if this module is ever transpiled to\n// CJS. It is exposed on the returned object under the shorter name.\nconst requireCapabilities=req=>{const err=checkCapabilities(renderer,req);if(!err)return true;detach();renderer.dispose();if(canvas.parentNode)canvas.parentNode.removeChild(canvas);session.fail(err,false);return false;};return{renderer,detach,require:requireCapabilities};}// ---------------------------------------------------------------------------\n// Capability probe\n// ---------------------------------------------------------------------------\nexport function checkCapabilities(renderer,req){const gl=renderer.getContext();if(!gl)return\"no WebGL context\";const caps=renderer.capabilities;if(req.vertexTextures&&caps.maxVertexTextures<1){return\"GPU reports no vertex texture image units\";}// isWebGL2 is absent on Three.js builds that dropped WebGL 1 entirely,\n// so treat \"not explicitly false\" as WebGL 2.\nconst isWebGL2=caps.isWebGL2!==false;if(req.floatRenderTargets){// Rendering *to* a float format is an extension even on WebGL 2 and\n// is missing on a fair number of Android devices.\nconst ok=isWebGL2?renderer.extensions.has(\"EXT_color_buffer_float\")||renderer.extensions.has(\"EXT_color_buffer_half_float\"):renderer.extensions.has(\"OES_texture_half_float\")&&renderer.extensions.has(\"EXT_color_buffer_half_float\");if(!ok)return\"half-float render targets unsupported\";}if(req.floatDataTextures&&!isWebGL2&&!renderer.extensions.has(\"OES_texture_float\")){return\"float data textures unsupported\";}if(req.maxTextureSize&&req.maxTextureSize>caps.maxTextureSize){return\"required texture size \"+req.maxTextureSize+\" exceeds GPU maximum \"+caps.maxTextureSize;}return null;}// ---------------------------------------------------------------------------\n// Fallback frame — canvas container always mounted, image overlaid on top\n// ---------------------------------------------------------------------------\nexport function WebGLFallbackFrame({mountRef,showFallback,fallbackImage,fallbackFit=\"cover\",fallbackAlt=\"\",style}){// Warm the browser cache at mount rather than at crash time, so the swap\n// is instant instead of a flash of empty space.\nuseEffect(()=>{if(!fallbackImage)return;const img=new Image;img.src=fallbackImage;},[fallbackImage]);return /*#__PURE__*/_jsxs(\"div\",{style:{position:\"relative\",width:\"100%\",height:\"100%\",minWidth:100,minHeight:60,overflow:\"hidden\",...style},children:[/*#__PURE__*/_jsx(\"div\",{ref:mountRef,style:{position:\"absolute\",top:0,left:0,width:\"100%\",height:\"100%\",opacity:showFallback?0:1}}),showFallback&&fallbackImage?/*#__PURE__*/_jsx(\"img\",{src:fallbackImage,alt:fallbackAlt,draggable:false,style:{position:\"absolute\",top:0,left:0,width:\"100%\",height:\"100%\",objectFit:fallbackFit,pointerEvents:\"none\",userSelect:\"none\"}}):null]});}// ---------------------------------------------------------------------------\n// Property controls — spread into each component's addPropertyControls call\n// ---------------------------------------------------------------------------\nexport const fallbackPropertyControls={fallbackImage:{title:\"Fallback Image\",type:ControlType.Image,description:\"Shown instead of the canvas when WebGL is unavailable, the GPU context is lost, or the effect cannot render. Preloaded at mount so the swap is instant.\"},fallbackFit:{title:\"Fallback Fit\",type:ControlType.Enum,defaultValue:\"cover\",options:[\"cover\",\"contain\",\"fill\"],optionTitles:[\"Cover\",\"Contain\",\"Fill\"],displaySegmentedControl:true,description:\"How the fallback image fills the frame\"},fallbackAlt:{title:\"Fallback Alt\",type:ControlType.String,defaultValue:\"\",description:\"Alt text for the fallback image\"}};\nexport const __FramerMetadata__ = {\"exports\":{\"createGuardedRenderer\":{\"type\":\"function\",\"annotations\":{\"framerContractVersion\":\"1\"}},\"useWebGLGuards\":{\"type\":\"function\",\"annotations\":{\"framerContractVersion\":\"1\"}},\"GuardedRenderer\":{\"type\":\"tsType\",\"annotations\":{\"framerContractVersion\":\"1\"}},\"checkCapabilities\":{\"type\":\"function\",\"annotations\":{\"framerContractVersion\":\"1\"}},\"FallbackProps\":{\"type\":\"tsType\",\"annotations\":{\"framerContractVersion\":\"1\"}},\"fallbackPropertyControls\":{\"type\":\"variable\",\"annotations\":{\"framerContractVersion\":\"1\"}},\"FallbackFit\":{\"type\":\"tsType\",\"annotations\":{\"framerContractVersion\":\"1\"}},\"Requirements\":{\"type\":\"tsType\",\"annotations\":{\"framerContractVersion\":\"1\"}},\"GpuSession\":{\"type\":\"tsType\",\"annotations\":{\"framerContractVersion\":\"1\"}},\"WebGLFallbackFrame\":{\"type\":\"reactComponent\",\"name\":\"WebGLFallbackFrame\",\"slots\":[],\"annotations\":{\"framerContractVersion\":\"1\"}},\"__FramerMetadata__\":{\"type\":\"variable\"}}}\n//# sourceMappingURL=./WebGLGuard.map"],"mappings":"6PA+BA,SAAgB,EAAe,EAAK,QAAQ,CAAC,GAAK,CAAC,EAAe,GAAmBA,EAAS,EAAI,EAG7F,CAAC,EAAS,GAAaA,EAAS,CAAC,EAAQ,EAAYC,EAAO,CAAC,EAAQ,EAAWA,EAA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