import { usePendingActions, useCheckoutSession } from '@ollie-shop/react';
import type { ActionType } from '@ollie-shop/react';
import styles from './styles.module.css';
const TOTALIZER_ACTIONS: ActionType[] = [
'UPDATE_ITEMS_QUANTITY',
'REMOVE_ITEMS',
'UPDATE_SHIPPING_PACKAGES',
'UPDATE_PAYMENT_METHODS',
];
function isUpdatingTotalizers(pendingActions: ActionType[]): boolean {
return pendingActions.some((action) =>
TOTALIZER_ACTIONS.includes(action)
);
}
function formatCurrency(value: number, currency: string, locale: string): string {
return new Intl.NumberFormat(locale, {
style: 'currency',
currency,
}).format(value / 100);
}
function CheckoutTotalizer() {
const { session } = useCheckoutSession();
const { pendingActions } = usePendingActions();
const { totals, locale } = session;
const isUpdating = isUpdatingTotalizers(pendingActions);
const formatPrice = (price: number) =>
formatCurrency(price, locale.currency, locale.locale);
return (
<div className={styles.container}>
<div className={styles.row}>
<span>Subtotal</span>
{isUpdating ? (
<span className={styles.skeleton} />
) : (
<span>{formatPrice(totals.subtotal)}</span>
)}
</div>
<div className={styles.row}>
<span>Shipping</span>
{isUpdating ? (
<span className={styles.skeleton} />
) : (
<span>{formatPrice(totals.shipping)}</span>
)}
</div>
<div className={`${styles.row} ${styles.total}`}>
<span>Total</span>
{isUpdating ? (
<span className={styles.skeletonLarge} />
) : (
<span>{formatPrice(totals.total)}</span>
)}
</div>
</div>
);
}