UNPKG

@marsidev/react-turnstile

Version:

Cloudflare Turnstile integration for React.

2 lines 6.06 kB
'use client'; import{forwardRef as e,useCallback as t,useEffect as n,useImperativeHandle as r,useMemo as i,useRef as a,useState as o}from"react";import{jsx as s}from"react/jsx-runtime";var c=e(({as:e=`div`,...t},n)=>s(e,{...t,ref:n}));const l=`https://challenges.cloudflare.com/turnstile/v0/api.js`,u=`cf-turnstile-script`,d=`cf-turnstile`,f=`onloadTurnstileCallback`,p=e=>!!document.getElementById(e),m=({render:e=`explicit`,onLoadCallbackName:t=f,scriptOptions:{nonce:n=``,defer:r=!0,async:i=!0,id:a=``,appendTo:o,onError:s,crossOrigin:c=``}={}})=>{let u=a||`cf-turnstile-script`;if(p(u))return;let d=document.createElement(`script`);d.id=u,d.src=`${l}?onload=${t}&render=${e}`,!document.querySelector(`script[src="${d.src}"]`)&&(d.defer=!!r,d.async=!!i,n&&d.setAttribute(`nonce`,n),c&&(d.crossOrigin=c),s&&(d.onerror=s,delete window[t]),(o===`body`?document.body:document.getElementsByTagName(`head`)[0]).appendChild(d))},h={normal:{width:300,height:65},compact:{width:150,height:140},invisible:{width:0,height:0,overflow:`hidden`},flexible:{minWidth:300,width:`100%`,height:65}};function g(e){if(e!==`invisible`)return e}function _(e=u){let[t,r]=o(!1);return n(()=>{let t=()=>{p(e)&&r(!0)},n=new MutationObserver(t);return n.observe(document,{childList:!0,subtree:!0}),t(),()=>{n.disconnect()}},[e]),t}let v=`unloaded`,y;const b=new Promise((e,t)=>{y={resolve:e,reject:t},v===`ready`&&e(void 0)}),x=(e=f)=>(v===`unloaded`&&(v=`loading`,window[e]=()=>{y.resolve(),v=`ready`,delete window[e]}),b),S=e((e,l)=>{let{scriptOptions:u,options:d={},siteKey:f,onWidgetLoad:p,onSuccess:y,onExpire:b,onError:S,onBeforeInteractive:C,onAfterInteractive:w,onUnsupported:T,onTimeout:E,onLoadScript:D,id:O,style:k,as:A=`div`,injectScript:j=!0,rerenderOnCallbackChange:M=!1,...N}=e,P=d.size,F=i(()=>{if(P===void 0)return{};let e=h[P];return d.appearance===`interaction-only`?{...e,height:`auto`}:e},[P,d.appearance]),I=d.execution===`execute`?h.invisible:F,[L,R]=o(I),z=a(null),[B,V]=o(!1),H=a(void 0),U=a(!1),W=O||`cf-turnstile`,G=a({onSuccess:y,onError:S,onExpire:b,onBeforeInteractive:C,onAfterInteractive:w,onUnsupported:T,onTimeout:E});n(()=>{M||(G.current={onSuccess:y,onError:S,onExpire:b,onBeforeInteractive:C,onAfterInteractive:w,onUnsupported:T,onTimeout:E})});let K=u?.id||`cf-turnstile-script`,q=_(K),J=u?.onLoadCallbackName||`onloadTurnstileCallback`,Y=i(()=>({sitekey:f,action:d.action,cData:d.cData,theme:d.theme||`auto`,language:d.language||`auto`,tabindex:d.tabIndex,"response-field":d.responseField,"response-field-name":d.responseFieldName,size:g(P),retry:d.retry||`auto`,"retry-interval":d.retryInterval||8e3,"refresh-expired":d.refreshExpired||`auto`,"refresh-timeout":d.refreshTimeout||`auto`,execution:d.execution||`render`,appearance:d.appearance||`always`,"feedback-enabled":d.feedbackEnabled??!0,callback:e=>{U.current=!0,M?y?.(e):G.current.onSuccess?.(e)},"error-callback":M?S:(...e)=>G.current.onError?.(...e),"expired-callback":M?b:(...e)=>G.current.onExpire?.(...e),"before-interactive-callback":M?C:(...e)=>G.current.onBeforeInteractive?.(...e),"after-interactive-callback":M?w:(...e)=>G.current.onAfterInteractive?.(...e),"unsupported-callback":M?T:(...e)=>G.current.onUnsupported?.(...e),"timeout-callback":M?E:(...e)=>G.current.onTimeout?.(...e)}),[d.action,d.appearance,d.cData,d.execution,d.language,d.refreshExpired,d.responseField,d.responseFieldName,d.retry,d.retryInterval,d.tabIndex,d.theme,d.feedbackEnabled,d.refreshTimeout,f,P,M,M?y:null,M?S:null,M?b:null,M?C:null,M?w:null,M?T:null,M?E:null]),X=t(()=>typeof window<`u`&&!!window.turnstile,[]);return n(function(){j&&!B&&(x(J),m({onLoadCallbackName:J,scriptOptions:{...u,id:K}}))},[j,B,u,K,J]),n(function(){v!==`ready`&&x(J).then(()=>V(!0)).catch(console.error)},[J]),n(function(){if(!z.current||!B)return;let e=!1;return(async()=>{if(e||!z.current)return;let t=window.turnstile.render(z.current,Y);H.current=t,R(I),H.current&&p?.(H.current)})(),()=>{e=!0,H.current&&(window.turnstile.remove(H.current),U.current=!1)}},[W,B,Y,I]),r(l,()=>{let{turnstile:e}=window;return{getResponse(){if(!e?.getResponse||!H.current||!X()){console.warn(`Turnstile has not been loaded`);return}return e.getResponse(H.current)},async getResponsePromise(e=3e4,t=100){return new Promise((n,r)=>{let i,a=async()=>{if(U.current&&window.turnstile&&H.current)try{let e=window.turnstile.getResponse(H.current);return i&&clearTimeout(i),e?n(e):r(Error(`No response received`))}catch(e){return i&&clearTimeout(i),console.warn(`Failed to get response`,e),r(Error(`Failed to get response`))}i||=setTimeout(()=>{i&&clearTimeout(i),r(Error(`Timeout`))},e),await new Promise(e=>setTimeout(e,t)),await a()};a()})},reset(){if(!e?.reset||!H.current||!X()){console.warn(`Turnstile has not been loaded`);return}R(I);try{U.current=!1,e.reset(H.current)}catch(e){console.warn(`Failed to reset Turnstile widget ${H.current}`,e)}},remove(){if(!e?.remove||!H.current||!X()){console.warn(`Turnstile has not been loaded`);return}R(h.invisible),U.current=!1,e.remove(H.current),H.current=null},render(){if(!e?.render||!z.current||!X()||H.current){console.warn(`Turnstile has not been loaded or container not found`);return}let t=e.render(z.current,Y);return H.current=t,H.current&&p?.(H.current),R(I),t},execute(){if(d.execution!==`execute`){console.warn(`Execution mode is not set to "execute"`);return}if(!e?.execute||!z.current||!H.current||!X()){console.warn(`Turnstile has not been loaded or container not found`);return}e.execute(z.current),R(F)},isExpired(){return!e?.isExpired||!H.current||!X()?(console.warn(`Turnstile has not been loaded`),!1):e.isExpired(H.current)}}},[H,d.execution,Y,z,X,B,p,I,F]),n(()=>{if(B||!q)return;if(window.turnstile){V(!0);return}let e=setInterval(()=>{window.turnstile&&(V(!0),clearInterval(e))},50);return()=>{clearInterval(e)}},[B,q]),n(()=>{R(I)},[I]),n(()=>{!q||typeof D!=`function`||D()},[q]),s(c,{ref:z,as:A,id:W,style:{...L,...k},...N})});S.displayName=`Turnstile`;export{d as DEFAULT_CONTAINER_ID,f as DEFAULT_ONLOAD_NAME,u as DEFAULT_SCRIPT_ID,l as SCRIPT_URL,S as Turnstile};