import { useEffect } from 'react'; import { Radio, Checkbox, FormControlLabel, Card, CardContent, Typography } from '@mui/material'; import { resolveReferenceFields } from './utils'; export default function SelectableCard(props) { const { getPConnect, type, image: { imagePosition, imageSize, showImageDescription, imageField = '', imageDescription = '' }, dataSource, recordKey = '', className, cardLabel, hideFieldLabels = false, readOnly, disabled, readOnlyList = [], displayMode, radioBtnValue, onChange, onBlur, onClick, onKeyDown, additionalProps, testId, setIsRadioCardSelected, showNoValue = false } = props; const pConn = getPConnect(); if (showNoValue) return No Value; const cardDataSource = readOnly || displayMode === 'DISPLAY_ONLY' ? readOnlyList || [] : dataSource?.source; const imageDescriptionKey = showImageDescription ? imageDescription : undefined; const handleCardClick = event => { if (disabled || readOnly) return; // If the click landed on or inside a label/input, native behavior already handles it. if (event.target.closest?.('label, input')) return; // Find the radio/checkbox input inside this card and click it programmatically. const input = event.currentTarget.querySelector('input[type="radio"], input[type="checkbox"]'); if (input) input.click(); }; const radioItemSelected = type === 'radio' && (cardDataSource || []).some(item => radioBtnValue === item[recordKey]); useEffect(() => { if (type === 'radio' && setIsRadioCardSelected) { setIsRadioCardSelected(radioItemSelected); } }, [radioItemSelected, type, setIsRadioCardSelected]); return ( <> {(cardDataSource || []).map(item => { const resolvedFields = resolveReferenceFields(item, hideFieldLabels, recordKey, pConn); const commonProps = { id: item[recordKey], key: item[recordKey], fields: resolvedFields, label: item[cardLabel] }; const image = item[imageField] ? { src: item[imageField], alt: showImageDescription && imageDescriptionKey ? item[imageDescriptionKey] : '', style: { width: imageSize, objectPosition: imagePosition } } : undefined; const cardContent = ( {image && {image.alt}} {item[cardLabel]} {commonProps.fields.map((field, index) => ( {field.value} ))} ); if (displayMode === 'DISPLAY_ONLY') { return cardContent; } const component = (
{image && ( {image.alt} )}
{type === 'radio' ? ( } label={{item[cardLabel]}} /> ) : ( data[recordKey] === item[recordKey])} onChange={onChange} onBlur={onBlur} onClick={onClick} onKeyDown={onKeyDown} disabled={disabled || readOnly} {...additionalProps} /> } label={{item[cardLabel]}} /> )} {commonProps.fields.map((field, index) => (
{field.name &&
{field.name}
}
{field?.value?.props.value}
))}
); return component; })} ); }