UNPKG

@commercelayer/react-components

Version:
2 lines 1.75 kB
"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{publish}from"../../utils/events";import{getOrganizationConfig}from"../../utils/organization";export function CartLink(props){const{label,children,type,customDomain,...p}=props,{order,createOrder}=useContext(OrderContext),{accessToken,endpoint}=useContext(CommerceLayerContext);if(accessToken==null)throw new Error("Cannot use `CartLink` outside of `CommerceLayer`");if(endpoint==null)throw new Error("Cannot use `CartLink` outside of `CommerceLayer`");const{domain,slug}=getDomain(endpoint),href=slug&&order?.id?getApplicationLink({slug,orderId:order?.id,accessToken,domain,applicationType:"cart",customDomain}):void 0,handleClick=async event=>{if(event.preventDefault(),type!=="mini")if(order?.id){const config=await getOrganizationConfig({accessToken,endpoint,params:{orderId:order?.id,accessToken,slug}});location.href=config?.links?.cart??href??""}else{const orderId=await createOrder({}),config=await getOrganizationConfig({accessToken,endpoint,params:{orderId:order?.id,accessToken,slug}});slug&&(location.href=config?.links?.cart??getApplicationLink({slug,orderId,accessToken,domain,applicationType:"cart",customDomain}))}else publish("open-cart")},parentProps={handleClick,label,href,orderId:order?.id,accessToken,...p};return accessToken?children?_jsx(Parent,{...parentProps,children}):_jsx("a",{href,onClick:e=>{handleClick(e)},...p,children:label}):null}export default CartLink;