@beamimpact/web-sdk
Version:
The Beam SDK enables brands to connect with their customers over shared values, not transactional discounts, to build stronger loyalty. Our integration achieves this by allowing customers to (a) choose a nonprofit where the brand will donate part of their
232 lines (220 loc) • 23.1 kB
JavaScript
import{h as x,f as w,y as c,g as f,t as E,q as T,m as M,k as B}from"../chunks/lit-iNN5L_Qk.esm.js";import{d as F,i as W}from"../chunks/lodash-P8OIs-at.esm.js";import{u as h,A as I,d as b,a as _,_ as k,i as p}from"../chunks/localize-m-_ESmpk.esm.js";import{D as U,f as K,W as N,i as O,S as R}from"../chunks/routes-o1QpF40R.esm.js";import{p as j}from"../chunks/progress-bar-PMU_xI3L.esm.js";import{p as H}from"../chunks/promo-pill-label-P1X4xeAx.esm.js";import{c as q,d as G,e as v}from"../chunks/enforce-config-ZyPq_4CF.esm.js";import{_ as V}from"../chunks/loading-template-t4fFsYtr.esm.js";import{b as $,g as J,d as P}from"../chunks/events-6Z5MkCRr.esm.js";import{logger as Q}from"../utils/logger.js";import{createScopedLocalStorage as X}from"../utils/local-storage.js";import{c as Y}from"../chunks/responsive-2lC2Wrtg.esm.js";import{B as Z}from"../chunks/cart-contents-h60geKWa.esm.js";import{getExternalCartId as ee,getBeamCartId as te}from"../utils/cart.js";import"../chunks/beam-errors-P-Lu07Ce.esm.js";import"../chunks/vendor-GKiOHg2N.esm.js";import"../utils/cookies.js";class oe extends x{static get styles(){return w`
:host {
}
.notification-blip {
background-color: var(--beam-notificationBlip-color-background, #000);
border-radius: 50%;
width: 12px;
height: 12px;
display: flex;
justify-content: center;
align-items: center;
font-size: 12px;
}
`}render(){return c`<div
class="notification-blip-container"
part="notification-blip-container"
aria-label="Notification Blip"
>
<span class="notification-blip" part="notification-blip" role="button" tabindex="0" aria-hidden="true"></span>
</div>`}}customElements.get("beam-notification-blip")||customElements.define("beam-notification-blip",oe);const ie={"--beam-notificationBlip-color-background":"#000"},m={en:{beamAttribution:()=>"Powered by Beam",ctaTitle:()=>"Choose your impact",ctaPromoPrefixMessage:()=>"At no extra cost,",ctaPromoMessage:({donationPercentage:n="1"}={})=>`select a nonprofit and ${n}% of your purchase will be donated.`,ctaMessage:({donationPercentage:n="1"}={})=>`At no extra cost, select a nonprofit and ${n}% of your purchase will be donated.`,inlineSeparator:()=>": "},fr:{beamAttribution:()=>"Optimis\xE9 par Beam",ctaTitle:()=>"Choisissez votre cause",ctaPromoPrefixMessage:()=>"",ctaPromoMessage:()=>"",ctaMessage:({donationPercentage:n="1"}={})=>`Sans frais suppl\xE9mentaires, choisissez un organisme \xE0 but non lucratif et ${n} % lui sera vers\xE9 en votre nom.`,inlineSeparator:()=>" : "},de:{beamAttribution:()=>"Unterst\xFCtzt von Beam",ctaTitle:()=>"W\xE4hle deinen Impact",ctaPromoPrefixMessage:()=>"",ctaPromoMessage:()=>"",ctaMessage:({donationPercentage:n="1"}={})=>`Ohne zus\xE4tzliche Kosten, w\xE4hle eine der gemeinn\xFCtzigen Organisationen und spende ${n}% deines Einkaufs`,inlineSeparator:()=>": "},es:{beamAttribution:()=>"Ofrecido por Beam",ctaTitle:()=>"Elige tu contribuci\xF3n",ctaPromoPrefixMessage:()=>"",ctaPromoMessage:()=>"",ctaMessage:({donationPercentage:n="1"}={})=>`Sin coste adicional, elige una organizaci\xF3n sin fines de lucro y donaremos ${n}% de tu compra.`,inlineSeparator:()=>": "},it:{beamAttribution:()=>"Gestito da Beam",ctaTitle:()=>"Scegli dove fare la differenza",ctaPromoPrefixMessage:()=>"",ctaPromoMessage:()=>"",ctaMessage:({donationPercentage:n="1"}={})=>`Senza costi aggiuntivi, seleziona un'organizzazione no-profit a cui devolvere l\u2019${n}% del tuo acquisto`,inlineSeparator:()=>": "},pl:{beamAttribution:()=>"Wspierany przez Beam",ctaTitle:()=>"Wybierz inicjatyw\u0119, kt\xF3r\u0105 chcesz wesprze\u0107",ctaPromoPrefixMessage:()=>"",ctaPromoMessage:()=>"",ctaMessage:({donationPercentage:n="1"}={})=>`Bez \u017Cadnych dodatkowych koszt\xF3w wybierz organizacj\u0119, kt\xF3rej przeka\u017Cesz ${n}% warto\u015Bci Twoich zakup\xF3w!`,inlineSeparator:()=>": "}};var ne=Object.defineProperty,ae=Object.getOwnPropertyDescriptor,d=(n,t,e,i)=>{for(var o=i>1?void 0:i?ae(t,e):t,a=n.length-1,r;a>=0;a--)(r=n[a])&&(o=(i?r(t,e,o):r(o))||o);return i&&o&&ne(t,e,o),o};class l extends x{constructor(){super(...arguments),this.baseUrl=U,this.selectedNonprofitId=null,this.lang="en",this.debug=!1,this.draftConfig=!1,this.isMobile=window.innerWidth<768,this.enableNonprofitDeselection=!1,this.didTryToCreateNewSelectionFromCache=!1,this.getChainNonprofits=async()=>{v(["apiKey"],this);const t=this.cart?.content?{schema:this.cart?.schema,content:this.cart?.content}:void 0,e=await K({baseUrl:this.baseUrl,apiRoot:"/api/v3",headers:{authorization:`Api-Key ${this.apiKey}`},requestBody:{storeId:this.storeId,widgetName:N.select_nonprofit,postalCode:this.postalCode,countryCode:this.countryCode,version:"1.0.0",lang:this.configLang,options:{config:{draftConfig:this.draftConfig}},cart:t}});return this.enableNonprofitDeselection=!!e.config.enableNonprofitDeselection,this.selectedNonprofitId!==null&&this.selectedNonprofitId&&!e.nonprofits.map(i=>i.nonprofit.id).includes(this.selectedNonprofitId)&&(this.selectedNonprofitId=null,await this.postSelectNonprofit({selectedNonprofitId:null}),this.localStorage.setItem("nonprofit",null)),e.store?.id&&e.store.id!==this.storeId&&(this.storeId=e.store.id),await this.createNewSelectionForCachedNonprofit(),this.localStorage.setItemJson("chainNonprofits",{createdAt:new Date,data:e}),e},this.postSelectNonprofit=async({selectedNonprofitId:t})=>{v(["apiKey","storeId"],this);const e=ee("cart",{apiKey:this.apiKey}),i=te(Z,{apiKey:this.apiKey}),o=await O({baseUrl:this.baseUrl,headers:{authorization:`Api-Key ${this.apiKey}`},requestBody:{nonprofitId:t,selectionId:this.selectionId,storeId:this.storeId,cartId:e||void 0,beamCartId:i||void 0,postalCode:this.postalCode,countryCode:this.countryCode}});this.selectionId=o?.selectionId,this.localStorage.setItem("transaction",this.selectionId),this.localStorage.setItem("nonprofit",t),this.localStorage.setItem("nonprofit_selected_at",new Date().toISOString()),await this.updateComplete;const a=this.getNonprofitById(t);t!==null&&this.dispatchEvent(new $({selectedNonprofitId:t,selectionId:this.selectionId,nonprofitName:a?.nonprofit?.name??null,source:N.select_nonprofit})),t===null&&this.dispatchEvent(new J({newNonprofitId:null,selectionId:this.selectionId}))},this.nonprofitListDataController=new I(this,this.getChainNonprofits),this.selectionDataController=new I(this,this.postSelectNonprofit),this.localStorage=X(this),this.handleCartChange=t=>{this.cart=t.detail},this.makeHandleSelect=(t,e,i)=>async o=>{const a=this.selectedNonprofitId;if(o instanceof KeyboardEvent){let r=null;switch(o.key){case"ArrowUp":case"ArrowLeft":e===0?r=i[i.length-1]:r=i[e-1],o.preventDefault();break;case"ArrowRight":case"ArrowDown":e===i.length-1?r=i[0]:r=i[e+1],o.preventDefault();break;case"Enter":case" ":o.preventDefault();break;default:return}if(r){a!=null&&(this.selectedNonprofitId=r.nonprofit.id);const g=this.renderRoot.querySelector(`[data-value="${r.nonprofit.id}"]`);g!==null&&(g.tabIndex=0,g.focus());return}}if(o.currentTarget instanceof HTMLElement)if(a===t)if(this.enableNonprofitDeselection)this.selectedNonprofitId=null,this.localStorage.setItem("nonprofit",null);else return;else this.selectedNonprofitId=t;await this.selectionDataController.exec({selectedNonprofitId:this.selectedNonprofitId})},this.evaluateBreakPoints=F(()=>{this.isMobile=window.innerWidth<768},50,{maxWait:50,leading:!0})}get configLang(){return R[this.lang]||"en"}getNonprofitById(t){return t?this.nonprofitListDataController?.data?.nonprofits.find(e=>e.nonprofit.id===t):null}async connectedCallback(){super.connectedCallback(),this.nonprofitListDataController.loading=!0,window.addEventListener(P.eventName,this.handleCartChange),window.addEventListener("resize",this.evaluateBreakPoints)}async firstUpdated(){await this.restoreStateFromCache()}async updated(t){const e=["baseUrl","storeId","apiKey","countryCode","postalCode","cart","lang"];for(const i of e)if(t.has(i)){await this.nonprofitListDataController.exec();break}}disconnectedCallback(){window.removeEventListener(P.eventName,this.handleCartChange),window.removeEventListener("resize",this.evaluateBreakPoints),super.disconnectedCallback()}async restoreStateFromCache(){try{const t=new Date().valueOf();this.cart=this.localStorage.getItemJson("cart")??void 0;const e=30*24*60*60*1e3,i=this.localStorage.getItem("nonprofit_selected_at")??0,o=t>new Date(i).valueOf()+e;o?o&&this.selectedNonprofitId!==null&&(await this.postSelectNonprofit({selectedNonprofitId:null}),this.localStorage.setItem("nonprofit",null)):(this.selectedNonprofitId=parseInt(this.localStorage.getItem("nonprofit")||"")||null,this.selectionId=this.localStorage.getItem("transaction")??void 0);const{createdAt:a=0,data:r}=this.localStorage.getItemJson("chainNonprofits")||{},g=2*60*60*1e3;!(t>new Date(a).valueOf()+g)&&this.nonprofitListDataController.loading&&(this.nonprofitListDataController.data=r,this.nonprofitListDataController.loading=!1)}catch(t){Q.error(t)}}async createNewSelectionForCachedNonprofit(){if(v(["apiKey"],this),!(!this.storeId||this.didTryToCreateNewSelectionFromCache))try{if(this.didTryToCreateNewSelectionFromCache=!0,this.selectedNonprofitId){this.selectionId||await this.selectionDataController.exec({selectedNonprofitId:this.selectedNonprofitId});const t=this.getNonprofitById(this.selectedNonprofitId);this.dispatchEvent(new $({selectedNonprofitId:this.selectedNonprofitId,selectionId:this.selectionId,nonprofitName:t?.nonprofit?.name,source:N.select_nonprofit}))}}catch{}}get cssVariables(){const t={"--beam-fontFamily":"inherit","--beam-fontStyle":"inherit","--beam-fontSize":"inherit","--beam-textColor":"inherit","--beam-backgroundColor":"inherit",...j,"--beam-SelectNonprofit-title-textAlign":"inherit","--beam-SelectNonprofit-description-textAlign":"inherit","--beam-SelectNonprofit-maxWidth":"800px","--beam-SelectNonprofit-options-marginTop":"0px","--beam-SelectNonprofit-options-iconHeight":"24px","--beam-SelectNonprofit-options-padding":"10px","--beam-SelectNonprofit-options-borderRadius":"0px","--beam-SelectNonprofit-options-borderColor":"currentColor","--beam-SelectNonprofit-options--selected-borderColor":"currentColor","--beam-SelectNonprofit-options-backgroundColor":"transparent","--beam-SelectNonprofit-options-gap":"8px","--beam-SelectNonprofit-options--selected-backgroundColor":"currentColor","--beam-SelectNonprofit-details-marginTop":"10px","--beam-SelectNonprofit-details-borderRadius":"0px","--beam-SelectNonprofit-details-borderColor":"currentColor","--beam-SelectNonprofit-details-backgroundColor":"inherit","--beam-SelectNonprofit-details-padding":"10px",...b("--beam-SelectNonprofit-title",{fontSize:"1.25em",fontWeight:"bold"}),"--beam-SelectNonprofit-header-inline-lineHeight":"inherit",...b("--beam-SelectNonprofit-title-inline",{fontWeight:"bold"}),"--beam-SelectNonprofit-title-inline-textTransform":"none","--beam-SelectNonprofit-title-block-margin-right":"8px",...b("--beam-SelectNonprofit-description",{marginTop:"0.5em"}),...b("--beam-SelectNonprofit-description-inline"),...b("--beam-SelectNonprofit-details-cause",{fontSize:"0.85em",fontWeight:"bold"}),...b("--beam-SelectNonprofit-details-beamAttribution",{fontSize:"0.85em"}),...b("--beam-SelectNonprofit-details-impactDescription",{fontSize:"1em",marginTop:"10px"}),"--beam-SelectNonprofit-details-nonprofitName-fontWeight":"bold","--beam-SelectNonprofit-details-nonprofitName-fontStyle":"inherit","--beam-SelectNonprofit-details-fundingProgress-marginTop":"10px",...b("--beam-SelectNonprofit-details-fundingProgressLabel",{fontSize:"0.85em"}),...ie,...H,"--beam-SelectNonprofit-promo-block-header-justifyContent":"initial","--beam-SelectNonprofit-notification-blip-top":"4px","--beam-SelectNonprofit-notification-blip-left":"50%"},e=this.nonprofitListDataController?.data?.config?.web?.theme||{},i={...t,...e};return Object.assign(Object.create({toCSS(){return _(this)}}),i)}render(){const{selectedNonprofitId:t}=this,{data:e,loading:i}=this.nonprofitListDataController;if(i&&!e)return V();if(this.nonprofitListDataController.error)return this.debug?k({error:this.nonprofitListDataController.error}):"";if(this.selectionDataController.error&&this.debug)return k({error:this.selectionDataController.error});const o=e?.nonprofits||[],a=o.find(s=>s.nonprofit.id===t)||null,r=!!e?.config?.web?.promo,g=o.some(s=>!s.promo||!s.promo.isActive),y=this.cssVariables["--beam-SelectNonprofit-title-textAlign"]==="center",C=c`<h3 class="title-block d-none d-lg-block" part="title" id="beam-SelectNonprofit-title">
${p(this.configLang,e?.config?.web?.title||"")||m[this.configLang].ctaTitle()}
</h3>`,L=()=>r?c`<div
class="${this.isMobile?y?"block-header-promo-pill-center-block-container-responsive":"block-header-promo-pill-container-responsive":y?"block-header-promo-pill-center-block-container-responsive":"block-header-promo-pill-container"}"
style="${this.isMobile?"display: flex":""}"
>
${C}
<beam-promo-info-pill .promo=${e?.config?.web?.promo}></beam-promo-info-pill>
</div>`:C;return c`
<style>
:host {
${this.cssVariables.toCSS()}
}
</style>
<div part="heading">
${L()}
<p class="description" part="description">
<span class="d-none d-lg-inline">
${r?c`<span style="font-weight:bold">
${p(this.configLang,e?.config?.web?.promoDescriptionPrefix||"")||m[this.configLang].ctaPromoPrefixMessage()}
</span>
<span>
${p(this.configLang,e?.config?.web?.promoDescription||"")||m[this.configLang].ctaPromoMessage()}
</span>`:c`<span>
${p(this.configLang,e?.config?.web?.description||"")||m[this.configLang].ctaMessage()}
</span>`}
</span>
<div class="d-lg-none header-inline">
<span class="title-inline" part="title">
${(p(this.configLang,e?.config?.web?.title||"")||m[this.configLang].ctaTitle())+m[this.configLang].inlineSeparator()}
</span>
<span class="description-inline" part="description">
${r?c`<span style="font-weight:bold">
${p(this.configLang,e?.config?.web?.promoDescriptionPrefix||"")||m[this.configLang].ctaPromoPrefixMessage()}
</span>
<span>
${p(this.configLang,e?.config?.web?.promoDescription||"")||m[this.configLang].ctaPromoMessage()}
</span>`:c`<span
>${p(this.configLang,e?.config?.web?.description||"")||m[this.configLang].ctaMessage()}
</span>`}
</div>
</p>
</div>
<div
class="options"
part="options"
role="radiogroup"
aria-labelledby="beam-SelectNonprofit-title"
style="display: flex; gap: var(--beam-SelectNonprofit-options-gap); margin: 10px 0 0 0;"
>
${T(o,s=>s.nonprofit.id,({nonprofit:s,promo:D},S)=>{const u=t===s.id,z=u||a==null&&S===0,A=D?.isActive&&e?.config.web.promo&&g;return c`
<div
class="option"
part="option"
role="radio"
tabindex="${z?0:-1}"
data-value=${s.id}
aria-checked=${u}
@click=${this.makeHandleSelect(s.id,S,o)}
@keydown=${this.makeHandleSelect(s.id,S,o)}
aria-label="${p(this.configLang,s.cause||"")}"
style="${M({cursor:"pointer",flex:"1",textAlign:"center",lineHeight:"1",marginTop:"var(--beam-SelectNonprofit-options-marginTop, 0px)",padding:"var(--beam-SelectNonprofit-options-padding, 10px)",borderWidth:"var(--beam-SelectNonprofit-options-borderWidth, 1px)",borderStyle:"solid",position:"relative",borderRadius:"var(--beam-SelectNonprofit-options-borderRadius, 0)",borderColor:u?s.causeColor||"var(--beam-SelectNonprofit-options--selected-borderColor, currentColor)":"var(--beam-SelectNonprofit-options-borderColor, currentColor)",backgroundColor:u?s.causeColor||"var(--beam-SelectNonprofit-options--selected-backgroundColor, currentColor)":"var(--beam-SelectNonprofit-options-backgroundColor, transparent)"})}"
>
<img
src="${u?s.causeIconSelectedUrl:s.causeIconUrl}"
alt=""
role="presentation"
style="
height: var(--beam-SelectNonprofit-options-iconHeight, 24px);
user-select: none;
vertical-align: -webkit-baseline-middle;
"
/>
${A?c`<beam-notification-blip></beam-notification-blip>`:c``}
</div>
`})}
</div>
${a!=null?c`
<div
class="details"
part="details"
style="
border: 1px solid var(--beam-SelectNonprofit-details-borderColor);
border-radius: var(--beam-SelectNonprofit-details-borderRadius);
background-color: var(--beam-SelectNonprofit-details-backgroundColor);
padding: var(--beam-SelectNonprofit-details-padding);
margin-top: var(--beam-SelectNonprofit-details-marginTop);
"
aria-label="Funding information for selected nonprofit ${a.nonprofit?.name}. Powered by Beam"
>
<div
style="display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap-reverse"
>
<span
class="details-cause"
style="flex: 0 1; white-space: nowrap; ${h("--beam-SelectNonprofit-details-cause")}"
>
${a?.promo?.isActive&&g?e?.config.web.promo?.["promo-cause-alt-text"]||a.nonprofit.cause:p(this.configLang,a.nonprofit.cause||"")}
</span>
<div aria-hidden="true">
<span
class="details-beamAttribution"
aria-hidden="true"
style="flex: 0 1; white-space: nowrap; ${h("--beam-SelectNonprofit-details-beamAttribution")}"
>
${m[this.configLang].beamAttribution()}
</span>
</div>
</div>
<p class="details-impactDescription">
${B(p(this.configLang,a.impact.description||""))}
</p>
<div
style="display: flex; margin-top: var(--beam-SelectNonprofit-details-fundingProgress-marginTop); align-items: center;"
>
<beam-progress-bar
value="${a.impact.goalProgressPercentage}"
style="flex: 1 0;"
></beam-progress-bar>
<span
class="details-fundingProgressLabel"
style="${h("--beam-SelectNonprofit-details-fundingProgressLabel")} white-space: nowrap; text-align: right; flex: 0 1; margin-left: 15px;"
>
${p(this.configLang,a.impact.goalProgressText)}
</span>
</div>
</div>
`:""}
`}}l.tagName="beam-select-nonprofit",l.styles=[q,Y,w`
:host {
display: block;
max-width: var(--beam-SelectNonprofit-maxWidth, 800px);
font-family: var(--beam-fontFamily);
font-style: var(--beam-fontStyle);
font-size: var(--beam-fontSize);
background-color: var(--beam-backgroundColor);
color: var(--beam-textColor);
word-break: normal;
}
.details-impactDescription {
${h("--beam-SelectNonprofit-details-impactDescription")}
}
.details-impactDescription .nonprofitName {
font-weight: var(--beam-SelectNonprofit-details-nonprofitName-fontWeight);
font-style: var(--beam-SelectNonprofit-details-nonprofitName-fontStyle, inherit);
}
/* Note: title/description display is responsive */
.title-block {
margin-right: var(--beam-SelectNonprofit-title-block-margin-right);
${h("--beam-SelectNonprofit-title")}
text-align: var(--beam-SelectNonprofit-title-textAlign);
}
.header-inline {
line-height: var(--beam-SelectNonprofit-header-inline-lineHeight);
}
.title-inline {
font-size: var(--beam-SelectNonprofit-title-inline-fontSize);
font-weight: var(--beam-SelectNonprofit-title-inline-fontWeight);
color: var(--beam-SelectNonprofit-title-inline-color);
font-family: var(--beam-SelectNonprofit-title-inline-fontFamily);
text-transform: var(--beam-SelectNonprofit-title-inline-textTransform);
}
.description-inline {
font-family: var(--beam-SelectNonprofit-description-inline-fontFamily);
font-weight: var(--beam-SelectNonprofit-description-inline-fontWeight);
color: var(--beam-SelectNonprofit-description-inline-color);
text-transform: var(--beam-SelectNonprofit-description-inline-textTransform);
font-size: var(--beam-SelectNonprofit-description-inline-fontSize);
}
.description {
${h("--beam-SelectNonprofit-description")}
text-align: var(--beam-SelectNonprofit-description-textAlign);
}
.block-header-promo-pill-container {
display: flex;
align-items: center;
justify-content: var(--beam-SelectNonprofit-promo-block-header-justifyContent);
}
.block-header-promo-pill-container-responsive {
flex-direction: column;
align-items: flex-start;
}
.block-header-promo-pill-center-block-container-responsive {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
.block-header-promo-pill-container-responsive beam-promo-info-pill {
order: -1;
}
.block-header-promo-pill-center-block-container-responsive beam-promo-info-pill {
order: -1;
}
beam-notification-blip::part(notification-blip-container) {
position: absolute;
top: var(--beam-SelectNonprofit-notification-blip-top);
left: var(--beam-SelectNonprofit-notification-blip-left);
}
`],d([f({type:String})],l.prototype,"baseUrl",2),d([f({type:String})],l.prototype,"apiKey",2),d([f({type:Number,reflect:!0})],l.prototype,"storeId",2),d([f({type:String})],l.prototype,"countryCode",2),d([f({type:String})],l.prototype,"postalCode",2),d([f({attribute:!1,hasChanged:(n,t)=>!W(n,t)})],l.prototype,"cart",2),d([f({type:Number,reflect:!0})],l.prototype,"selectedNonprofitId",2),d([f({type:String})],l.prototype,"lang",2),d([f({type:Boolean})],l.prototype,"debug",2),d([f({type:Boolean})],l.prototype,"draftConfig",2),d([E()],l.prototype,"isMobile",2),G(l);export{l as BeamSelectNonprofit};
//# sourceMappingURL=select-nonprofit.js.map