import { Item, ItemContent, ItemDescription, ItemTitle } from '@components/common/ui/Item.js'; import { RadioGroup, RadioGroupItem } from '@components/common/ui/RadioGroup.js'; import { Skeleton } from '@components/common/ui/Skeleton.js'; import { useCheckout } from '@components/frontStore/checkout/CheckoutContext.js'; import { _ } from '@evershop/evershop/lib/locale/translate/_'; import React from 'react'; interface PaymentMethod { code: string; name: string; cost?: { value: number; text: string; }; description?: string; } // Skeleton component for loading state function PaymentMethodSkeleton() { return (
{[1, 2, 3, 4].map((index) => (
))}
); } export function PaymentMethods({ methods, isLoading }: { methods: PaymentMethod[]; isLoading?: boolean; }) { const { form, registeredPaymentComponents } = useCheckout(); const { formState, watch, setValue } = form; const selectedPaymentMethod = watch('paymentMethod'); const getPaymentComponent = (methodCode: string) => { return registeredPaymentComponents[methodCode] || null; }; const renderComponent = ( component: React.ComponentType | undefined, props: any ) => { return component ? React.createElement(component, props) : null; }; return (
{_('Pick a payment method')} {isLoading ? ( ) : ( <>
{methods?.length === 0 ? (
{_('No payment methods available')}
) : ( { setValue('paymentMethod', value); }} > {methods.map((method: PaymentMethod) => { const isSelected = selectedPaymentMethod === method.code; const component = getPaymentComponent(method.code); return ( // Whole-box click selects (Base UI radios only // react to pointer events on their [role="radio"] // element, so the box needs its own handler). The // guard skips the radio itself (double-fire) and // any control inside the embedded payment form. { if ( (e.target as HTMLElement).closest( 'input, button, a, select, textarea, iframe, [role="radio"]' ) ) { return; } if (!isSelected) { setValue('paymentMethod', method.code); } }} className={`cursor-pointer ${ isSelected ? 'border-primary' : '' }`} > {/* The row is a {/* Not clamped: a method's form may hold more than ItemDescription's two lines (#1175). */} {component?.formRenderer && isSelected && ( {renderComponent(component.formRenderer, { isSelected })} )} ); })} )}
{formState.errors.paymentMethod && (
{formState.errors.paymentMethod?.message?.toString() || _('Please select a payment method')}
)} )}
); }