UNPKG

@commercelayer/react-components

Version:
2 lines 1.81 kB
"use client"; "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.CheckoutLink=CheckoutLink;const tslib_1=require("tslib"),jsx_runtime_1=require("react/jsx-runtime"),react_1=require("react"),OrderContext_1=tslib_1.__importDefault(require("../../context/OrderContext")),Parent_1=tslib_1.__importDefault(require("../utils/Parent")),CommerceLayerContext_1=tslib_1.__importDefault(require("../../context/CommerceLayerContext")),getApplicationLink_1=require("../../utils/getApplicationLink"),getDomain_1=require("../../utils/getDomain"),organization_1=require("../../utils/organization");function CheckoutLink(props){const{label,hostedCheckout=!0,children,onClick,...p}=props,{order}=(0,react_1.useContext)(OrderContext_1.default),{accessToken,endpoint}=(0,react_1.useContext)(CommerceLayerContext_1.default);if(accessToken==null||endpoint==null)throw new Error("Cannot use `CheckoutLink` outside of `CommerceLayer`");const{domain,slug}=(0,getDomain_1.getDomain)(endpoint),href=hostedCheckout&&order?.id?(0,getApplicationLink_1.getApplicationLink)({slug,orderId:order?.id,accessToken,applicationType:"checkout",domain}):order?.checkout_url??"",parentProps={checkoutUrl:order?.checkout_url,hostedCheckout,label,href,...p};function handleClick(e){e.preventDefault(),e.stopPropagation();const currentHref=e.currentTarget.href;accessToken&&endpoint&&order?.id?(0,organization_1.getOrganizationConfig)({accessToken,endpoint,params:{accessToken,slug,orderId:order?.id}}).then(config=>{config?.links?.checkout?window.open(config.links.checkout,"_top"):window.open(currentHref,"_top")}):window.open(currentHref,"_top")}return children?(0,jsx_runtime_1.jsx)(Parent_1.default,{...parentProps,children}):(0,jsx_runtime_1.jsx)("a",{href,onClick:handleClick,...p,children:label})}exports.default=CheckoutLink;