@shopgate/engage
Version:
Shopgate's ENGAGE library.
94 lines (90 loc) • 2.51 kB
JavaScript
import React, { Fragment, useLayoutEffect, useEffect, useMemo } from 'react';
import PropTypes from 'prop-types';
import { css } from 'glamor';
import { useCheckoutContext } from "../../hooks/common";
import Button from "../../components/PaymentMethodButton";
import { loadWebSdk, usePaypal } from "./sdk";
import { jsx as _jsx, Fragment as _Fragment } from "react/jsx-runtime";
const styles = {
button: css({
' .paypal-mark': {
' img': {
height: 25,
background: 'transparent'
},
background: 'transparent',
border: 'none',
margin: 0,
padding: 0
}
}).toString()
};
/**
* Paypal
* @param {Object} props Props
* @returns {JSX}
*/
const PaypalButton = ({
settings,
onChange,
activePaymentMeta: activeFundingSource,
active
}) => {
const {
setLocked,
order
} = useCheckoutContext();
const paypal = usePaypal();
// Initialize paypal sdk.
useEffect(() => {
if (!settings || !order) return;
/** Async handler */
const handler = async () => {
setLocked(true);
try {
await loadWebSdk(settings, order);
} catch (e) {
//
}
setLocked(false);
};
handler();
}, [order, setLocked, settings]);
// Create paypal markers (just logic-less logos for each payment method).
const marks = useMemo(() => {
if (!paypal) return [];
return paypal.getFundingSources().map(fundingSource => {
const mark = window.paypal.Marks({
fundingSource
});
if (!mark.isEligible()) return null;
return [mark, fundingSource];
}).filter(m => !!m);
}, [paypal]);
// Render marks to dom once ready.
useLayoutEffect(() => {
requestAnimationFrame(() => {
marks.forEach(([mark], index) => {
mark.render(`#sg-paypal-button-${index}`);
});
}, []);
}, [marks]);
return /*#__PURE__*/_jsx(_Fragment, {
children: marks.map(([, fundingSource], index) => {
const isButtonActive = fundingSource === paypal.FUNDING.PAYPAL && !activeFundingSource ? active : active && fundingSource === activeFundingSource;
return /*#__PURE__*/_jsx(Button, {
onChange: () => onChange(fundingSource),
active: isButtonActive,
children: /*#__PURE__*/_jsx("div", {
id: `sg-paypal-button-${index}`,
className: styles.button
})
}, fundingSource);
})
});
};
PaypalButton.defaultProps = {
settings: null,
activePaymentMeta: null
};
export default PaypalButton;