@commercelayer/react-components
Version:
The Official Commerce Layer React Components
2 lines • 1.48 kB
JavaScript
"use client";
import{jsx as _jsx}from"react/jsx-runtime";import{useContext}from"react";import OrderContext from"../../context/OrderContext";import Parent from"../utils/Parent";import CommerceLayerContext from"../../context/CommerceLayerContext";import{getApplicationLink}from"../../utils/getApplicationLink";import{getDomain}from"../../utils/getDomain";import{getOrganizationConfig}from"../../utils/organization";export function CheckoutLink(props){const{label,hostedCheckout=!0,children,onClick,...p}=props,{order}=useContext(OrderContext),{accessToken,endpoint}=useContext(CommerceLayerContext);if(accessToken==null||endpoint==null)throw new Error("Cannot use `CheckoutLink` outside of `CommerceLayer`");const{domain,slug}=getDomain(endpoint),href=hostedCheckout&&order?.id?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?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?_jsx(Parent,{...parentProps,children}):_jsx("a",{href,onClick:handleClick,...p,children:label})}export default CheckoutLink;