UNPKG

@privy-io/react-auth

Version:

React client for the Privy Auth API

104 lines (96 loc) • 9.73 kB
import{jsx as e,jsxs as r}from"react/jsx-runtime";import o from"@heroicons/react/20/solid/CheckIcon";import t from"@heroicons/react/24/outline/EnvelopeIcon";import i from"@heroicons/react/24/outline/PhoneIcon";import{useState as n,useEffect as a}from"react";import{isMobile as s}from"react-device-detect";import{styled as c}from"styled-components";import{H as l}from"./Layouts-BlFm53ED.mjs";import{L as d}from"./Link-DJ5gq9Di.mjs";import{u as p,q as m}from"./context-WTldtXS8.mjs";import{u,e as f,b as v,k as h}from"./internal-context-Z-fyxadS.mjs";import{a as y,u as g}from"./get-is-unified-wallet-Boa8DYrQ.mjs";import{s as x}from"./shouldProceedtoEmbeddedWalletCreationFlow-BMF_3TVv.mjs";import{S as b}from"./ScreenLayout-DTmQLGPf.mjs";import"@privy-io/js-sdk-core";import"tinycolor2";import"ofetch";import"@privy-io/are-addresses-equal";import"./index-BBRkihRn.mjs";import"uuid";import"jose";import"eventemitter3";import"./useActiveWallet-3RHPIBxJ.mjs";import"zustand";import"./use-export-wallet-CV4p7L0b.mjs";import"viem/utils";import"./useWallets-CR0z5IIt.mjs";import"./events-context-CI0iqAXA.mjs";import"viem";import"./getPublicClient-B4uPLKn-.mjs";import"@coinbase/wallet-sdk";import"@privy-io/ethereum";import"mipd";import"@privy-io/popup";import"./paths-3HW55qZg.mjs";import"./usePrivy-6nkpbErN.mjs";import"@scure/base";import"@headlessui/react";import"@walletconnect/ethereum-provider";import"@privy-io/urls";import"./PrivyPluginContext-2QN2dVUw.mjs";import"./getEmbeddedConnectedWallet-JzK4iD-L.mjs";import"js-cookie";import"./frame-uzTmvtww.mjs";import"@privy-io/routes";import"x402/client";import"@privy-io/api-base";import"viem/accounts";import"./use-sign-with-user-signer-Do5Oi_rb.mjs";import"./ModalHeader-D8-mhjp4.mjs";import"@heroicons/react/24/outline/ArrowLeftIcon";import"@heroicons/react/24/outline/ArrowRightIcon";import"@heroicons/react/24/outline/QuestionMarkCircleIcon";import"@heroicons/react/24/outline/XMarkIcon";import"./Screen-Bp-TN9gb.mjs";import"./index-Dq_xe9dz.mjs";const E=({contactMethod:c,authFlow:p,appName:m="Privy",whatsAppEnabled:u=!1,onBack:f,onCodeSubmit:v,onResend:h,errorMessage:y,success:g=!1,resendCountdown:x=0,onInvalidInput:E,onClearError:w})=>{let[A,T]=n(S);a((()=>{y||T(S)}),[y]);let k=async e=>{e.preventDefault();let r=e.currentTarget.value.replace(" ","");if(""===r)return;if(isNaN(Number(r)))return void E?.("Code should be numeric");w?.();let o=Number(e.currentTarget.name?.charAt(5)),t=[...r||[""]].slice(0,C-o),i=[...A.slice(0,o),...t,...A.slice(o+t.length)];T(i);let n=Math.min(Math.max(o+t.length,0),C-1);if(!isNaN(Number(e.currentTarget.value))){let e=document.querySelector(`input[name=code-${n}]`);e?.focus()}if(i.every((e=>e&&!isNaN(+e)))){let e=document.querySelector(`input[name=code-${n}]`);e?.blur(),await(v?.(i.join("")))}};/*#__PURE__*/return e(b,{title:"Enter confirmation code",subtitle:/*#__PURE__*/r("span","email"===p?{children:["Please check ",/*#__PURE__*/e(M,{children:c})," for an email from privy.io and enter your code below."]}:{children:["Please check ",/*#__PURE__*/e(M,{children:c})," for a",u?" WhatsApp":""," message from ",m," and enter your code below."]}),icon:"email"===p?t:i,onBack:f,showBack:!0,helpText:/*#__PURE__*/r(L,{children:[/*#__PURE__*/r("span",{children:["Didn't get ","email"===p?"an email":"a message","?"]}),x?/*#__PURE__*/r(R,{children:[/*#__PURE__*/e(o,{color:"var(--privy-color-foreground)",strokeWidth:1.33,height:"12px",width:"12px"}),/*#__PURE__*/e("span",{children:"Code sent"})]}):/*#__PURE__*/e(d,{as:"button",size:"sm",onClick:h,children:"Resend code"})]}),children:/*#__PURE__*/e(N,{children:/*#__PURE__*/e(l,{children:/*#__PURE__*/r(_,{children:[/*#__PURE__*/e("div",{children:A.map(((r,o)=>/*#__PURE__*/e("input",{name:`code-${o}`,type:"text",value:A[o],onChange:k,onKeyUp:e=>{"Backspace"===e.key&&(e=>{if(w?.(),T([...A.slice(0,e),"",...A.slice(e+1)]),e>0){let r=document.querySelector(`input[name=code-${e-1}]`);r?.focus()}})(o)},inputMode:"numeric",autoFocus:0===o,pattern:"[0-9]",className:`${g?"success":""} ${y?"fail":""}`,autoComplete:s?"one-time-code":"off"},o)))}),/*#__PURE__*/e(I,{$fail:!!y,$success:g,children:/*#__PURE__*/e("span",{children:"Invalid or expired verification code"===y?"Incorrect code":y||(g?"Success!":"")})})]})})})})};let C=6,S=Array(6).fill("");var w,A,T=((w=T||{})[w.RESET_AFTER_DELAY=0]="RESET_AFTER_DELAY",w[w.CLEAR_ON_NEXT_VALID_INPUT=1]="CLEAR_ON_NEXT_VALID_INPUT",w),k=((A=k||{})[A.EMAIL=0]="EMAIL",A[A.SMS=1]="SMS",A);const j={component:()=>{let{navigate:r,lastScreen:o,navigateBack:t,setModalData:i,onUserCloseViaDialogOrKeybindRef:s}=y(),c=p(),{closePrivyModal:l,resendEmailCode:d,resendSmsCode:b,getAuthMeta:C,loginWithCode:S,updateWallets:w,createAnalyticsEvent:A}=u(),{authenticated:T,logout:k,user:j}=g(),{whatsAppEnabled:N}=p(),[_,I]=n(!1),[L,R]=n(null),[M,D]=n(null),[O,P]=n(0);s.current=()=>null;let U=C()?.email?0:1,W=0===U?C()?.email||"":C()?.phoneNumber||"",F=m-500;a((()=>{if(O){let e=setTimeout((()=>{P(O-1)}),1e3);return()=>clearTimeout(e)}}),[O]),a((()=>{if(T&&_&&j){if(c?.legal.requireUsersAcceptTerms&&!j.hasAcceptedTerms){let e=setTimeout((()=>{r("AffirmativeConsentScreen")}),F);return()=>clearTimeout(e)}if(x(j,c.embeddedWallets)){let e=setTimeout((()=>{i({createWallet:{onSuccess:()=>{},onFailure:e=>{console.error(e),A({eventName:"embedded_wallet_creation_failure_logout",payload:{error:e,screen:"AwaitingPasswordlessCodeScreen"}}),k()},callAuthOnSuccessOnClose:!0}}),r("EmbeddedWalletOnAccountCreateScreen")}),F);return()=>clearTimeout(e)}{w();let e=setTimeout((()=>l({shouldCallAuthOnSuccess:!0,isSuccess:!0})),m);return()=>clearTimeout(e)}}}),[T,_,j]),a((()=>{if(L&&0===M){let e=setTimeout((()=>{R(null),D(null);let e=document.querySelector("input[name=code-0]");e?.focus()}),1400);return()=>clearTimeout(e)}}),[L,M]);/*#__PURE__*/return e(E,{contactMethod:W,authFlow:0===U?"email":"sms",appName:c?.name,whatsAppEnabled:N,onBack:()=>t(),onCodeSubmit:async e=>{try{await S(e),I(!0)}catch(e){if(e instanceof f&&e.privyErrorCode===v.INVALID_CREDENTIALS)R("Invalid or expired verification code"),D(0);else if(e instanceof f&&e.privyErrorCode===v.CANNOT_LINK_MORE_OF_TYPE)R(e.message);else{if(e instanceof f&&e.privyErrorCode===v.USER_LIMIT_REACHED)return console.error(new h(e).toString()),void r("UserLimitReachedScreen");if(e instanceof f&&e.privyErrorCode===v.USER_DOES_NOT_EXIST)return void r("AccountNotFoundScreen");if(e instanceof f&&e.privyErrorCode===v.LINKED_TO_ANOTHER_USER)return i({errorModalData:{error:e,previousScreen:o??"AwaitingPasswordlessCodeScreen"}}),void r("ErrorScreen",!1);if(e instanceof f&&e.privyErrorCode===v.DISALLOWED_PLUS_EMAIL)return i({inlineError:{error:e}}),void r("ConnectOrCreateScreen",!1);if(e instanceof f&&e.privyErrorCode===v.ACCOUNT_TRANSFER_REQUIRED&&e.data?.data?.nonce)return i({accountTransfer:{nonce:e.data?.data?.nonce,account:W,displayName:e.data?.data?.account?.displayName,linkMethod:0===U?"email":"sms",embeddedWalletAddress:e.data?.data?.otherUser?.embeddedWalletAddress}}),void r("LinkConflictScreen");R("Issue verifying code"),D(0)}}},onResend:async()=>{P(30),0===U?await d():await b()},errorMessage:L||void 0,success:_,resendCountdown:O,onInvalidInput:e=>{R(e),D(1)},onClearError:()=>{1===M&&(R(null),D(null))}})}};let N=c.div` display: flex; flex-direction: column; align-items: center; justify-content: center; margin: auto; gap: 16px; flex-grow: 1; width: 100%; `,_=c.div` display: flex; flex-direction: column; width: 100%; gap: 12px; > div:first-child { display: flex; justify-content: center; gap: 0.5rem; width: 100%; border-radius: var(--privy-border-radius-sm); > input { border: 1px solid var(--privy-color-foreground-4); background: var(--privy-color-background); border-radius: var(--privy-border-radius-sm); padding: 8px 10px; height: 48px; width: 40px; text-align: center; font-size: 18px; font-weight: 600; color: var(--privy-color-foreground); transition: all 0.2s ease; } > input:focus { border: 1px solid var(--privy-color-foreground); box-shadow: 0 0 0 1px var(--privy-color-foreground); } > input:invalid { border: 1px solid var(--privy-color-error); } > input.success { border: 1px solid var(--privy-color-border-success); background: var(--privy-color-success-bg); } > input.fail { border: 1px solid var(--privy-color-border-error); background: var(--privy-color-error-bg); animation: shake 180ms; animation-iteration-count: 2; } } @keyframes shake { 0% { transform: translate(1px, 0px); } 33% { transform: translate(-1px, 0px); } 67% { transform: translate(-1px, 0px); } 100% { transform: translate(1px, 0px); } } `,I=c.div` line-height: 20px; min-height: 20px; font-size: 14px; font-weight: 400; color: ${e=>e.$success?"var(--privy-color-success-dark)":e.$fail?"var(--privy-color-error-dark)":"transparent"}; display: flex; justify-content: center; width: 100%; text-align: center; `,L=c.div` display: flex; gap: 8px; align-items: center; justify-content: center; width: 100%; color: var(--privy-color-foreground-2); `,R=c.div` display: flex; align-items: center; justify-content: center; border-radius: var(--privy-border-radius-sm); padding: 2px 8px; gap: 4px; background: var(--privy-color-background-2); color: var(--privy-color-foreground-2); `,M=c.span` font-weight: 500; word-break: break-all; color: var(--privy-color-foreground); `;export{j as AwaitingPasswordlessCodeScreen,E as AwaitingPasswordlessCodeScreenView,j as default};