@salla.sa/twilight-components
Version:
Salla Web Component
4 lines • 6.02 kB
JavaScript
/*!
* Crafted with ❤ by Salla
*/
import{r as t,h as a,F as s,a as e}from"./p-Dbv0I4re.js";const i=class{constructor(a){t(this,a),this.isMobileAllowed=!0,this.isEmailRequired=!1,this.supportWebAuth=!0,this.withoutReload=!1,this.source="",this.htmlElement=document.documentElement,this.messages=[],this.isClosable=!0,this.iframeLoaded=!1,this.scrolling="no",this.direction=document.dir,this.canRenderIframe=!1,salla.event.on("login::open",(t=>{this.isEmailAllowed||this.isMobileAllowed?(this.source=t?.source??!1,this.withoutReload=t?.withoutReload??this.withoutReload,this.open(t),this.openModal()):salla.logger.warn("Please enable atleast one login type to use this component.")})),salla.event.on("modal::close",(t=>{this.iframe&&this.sendMessageToIframe({source:"login",type:"modal_closed",data:t})})),salla.onReady((()=>{this.api=salla.config.get("store.api"),this.storeId=salla.config.get("store.id")}))}componentDidLoad(){window.addEventListener("message",(t=>{if("login"!=t.data.source)return;if(!this.inline&&!this.canRenderIframe)return;salla.log("salla-account:: recived an event",t.data);let a=t.data?.type?.replace("iframe::",""),s=t.data.message;if("ready"==a)return s.isPasskeyPage?void this.createPassKey.postMessage({source:"login",type:"init_passkey_page",data:{token:salla.storage.get("token"),store_id:salla.config.get("store.id"),locale:salla.config.get("user.language_code"),redirect:salla.config.get("store.url")}},salla.config.get("login.url")):void this.handleIframeReadyAction();if("height"==a)return this.iframe.height=s?.height+"px";if("storage"==a)return this.handleIframeStorageAction(s);if("scrolling"==a)return this.scrolling=s,void(this.isClosable=!1);if("direction"==a)return document.dir=this.direction=s?"rtl":"ltr";if("notify"==a)return salla.notify[s.type](s.message);if("authenticated"==a||"authenticated_web_auth"==a)return!s?.withoutClose&&this.close(),salla.auth.api.handlAfterAuthenticatedResponse(s,this.supportWebAuth).then((()=>!(s?.withoutReload||this.withoutReload)&&setTimeout((()=>window.location.reload()),1e3)));if("dispatchEvent"!=a||"auth::verified"!=s.event){if("dispatchEvent"==a)return salla.event.emit(s.event,...s.payload);if("reload"==a)return s?.withClose&&this.modal.close(),window.location.reload();if("open_page"===a)return window.location.href=s.url;if("open_passkey_page"!==a)return"guest-checkout"===a?this.handleGuestCheckout():void("close"==a&&this.close());this.createPassKey=window.open(`${salla.config.get("login.url")}/create-passkey`)}else salla.log("Ignored dispatchEvent `auth::verified` from iframe")})),this.observeDarkModeChanges(),setTimeout((()=>Salla.event.emit("salla-login::ready")),1)}async open(t=null){return salla.config.isGuest()?this.modal.open():this.withoutReload?void 0:location.reload()}close(){Salla.event.emit("salla-login::closing"),this.modal.close(),this.iframeLoaded=!1,this.canRenderIframe=!1,this.host.dispatchEvent(new CustomEvent("salla-login:closed",{cancelable:!0,bubbles:!0,detail:null})),Salla.event.emit("salla-login::closed")}handleIframeReadyAction(){this.sendInitMessage(),this.sendMessageToIframe({source:"login",type:"width",data:document.body.clientWidth})}observeDarkModeChanges(){new MutationObserver((t=>{t.forEach((t=>{"class"===t.attributeName&&this.sendMessageToIframe({source:"login",type:"darkMode",data:{isDark:!!this.htmlElement.classList.contains("dark")}})}))})).observe(this.htmlElement,{attributes:!0})}async handleIframeStorageAction(t){let a,s=salla.storage.get("cart.user_id"),e=!1;if(Object.entries(t).filter((t=>!Salla.storage.get(t[0]))).forEach((([t,i])=>{salla.log("Shared storage from accounts domain",t,i);let l="string"==typeof i?i?.replace(/^"|"$/g,""):i;salla.storage.set(t,l),"token"===t&&(a=l),"user"===t&&s&&l.id!==s&&(e=!0)})),a){this.modal.close(),Salla.auth.event.tokenFetched(a);try{await Salla.api.cart.assign()}catch(t){Salla.log("Error on assign after handle iframe",t)}e&&Salla.cart.reset();try{!Salla.auth.api.isSessionless()&&await Salla.auth.api.request("auth/jwt"),Salla.auth.api.canRedirect()?setTimeout((()=>window.location.reload()),100):await Salla.auth.event.loggedIn({data:{token:a}}).then((()=>Salla.auth.api.afterUserLogin()))}catch(t){this.modal.open(),Salla.log("Error on request auth/jwt after handle iframe",t)}}else e&&Salla.cart.reset()}sendMessageToIframe(t){if(this.iframe)return this.iframe.contentWindow.postMessage(t,"*")}sendInitMessage(){let t=this.headers;try{t="string"==typeof t?JSON.parse(t):t}catch(a){console.error("Failed to parse headers!",this.headers,a),t=void 0}const a={user:salla.storage.get("user"),s_translations:salla.storage.get("s_translations"),token:salla.storage.get("token")};a.user||delete a.user,a.s_translations||delete a.s_translations,a.token||delete a.token,this.sendMessageToIframe({source:"login",type:"init",data:{id:this.storeId,lang:salla.lang.locale,isDark:!!this.htmlElement.classList.contains("dark"),apiUrl:this.api?.replace(/\/+$/,""),supportWebAuth:this.supportWebAuth,withoutReload:this.withoutReload,inline:this.inline,settings:salla.config.all(),headers:t,storage:a}})}async handleGuestCheckout(){if(this.modal.close(),salla.config.isGuest())return await salla.api.cart.syncGuestCart(),salla.cart.submit(!0)}openModal(){this.canRenderIframe||(this.canRenderIframe=!0),this.modal.open()}render(){return this.inline?this.getLoginDom():a("salla-modal",{class:"s-login-modal",ref:t=>this.modal=t,width:"xs"},this.getLoginDom())}getLoginDom(){if(this.canRenderIframe)return a(s,null,a("iframe",{src:`${salla.config.get("login.url","https://accounts.salla.com")}?src=${this.source}`,title:"Salla Login",class:"hide-scroll",loading:"lazy",ref:t=>{this.iframe=t},allow:"publickey-credentials-get; publickey-credentials-create",scrolling:this.scrolling,frameborder:"0",width:"100%"}))}get host(){return e(this)}};i.style="iframe{-moz-transition:height 0.3s;-ms-transition:height 0.3s;-o-transition:height 0.3s;-webkit-transition:height 0.3s;transition:height 0.3s;width:100%}";export{i as salla_login_modal}