2022-02-10 11:59:43 +00:00
|
|
|
/**
|
|
|
|
* External dependencies
|
|
|
|
*/
|
2024-05-31 03:49:36 +00:00
|
|
|
import clsx from 'clsx';
|
2022-02-10 11:59:43 +00:00
|
|
|
import { useInstanceId } from '@wordpress/compose';
|
2024-04-10 09:54:05 +00:00
|
|
|
import { useMemo } from '@wordpress/element';
|
|
|
|
|
2022-02-10 11:59:43 +00:00
|
|
|
/**
|
|
|
|
* Internal dependencies
|
|
|
|
*/
|
|
|
|
import RadioControlOption from './option';
|
|
|
|
import type { RadioControlProps } from './types';
|
|
|
|
import './style.scss';
|
|
|
|
|
|
|
|
const RadioControl = ( {
|
|
|
|
className = '',
|
|
|
|
id,
|
2023-02-27 10:52:38 +00:00
|
|
|
selected = '',
|
2022-07-01 17:50:44 +00:00
|
|
|
onChange,
|
2022-02-10 11:59:43 +00:00
|
|
|
options = [],
|
2023-08-08 10:56:19 +00:00
|
|
|
disabled = false,
|
2024-04-10 09:54:05 +00:00
|
|
|
highlightChecked = false,
|
2022-02-10 11:59:43 +00:00
|
|
|
}: RadioControlProps ): JSX.Element | null => {
|
|
|
|
const instanceId = useInstanceId( RadioControl );
|
|
|
|
const radioControlId = id || instanceId;
|
|
|
|
|
2024-04-10 09:54:05 +00:00
|
|
|
const selectedOptionNumber = useMemo( () => {
|
|
|
|
return options.findIndex( ( option ) => option.value === selected );
|
|
|
|
}, [ options, selected ] );
|
|
|
|
|
2022-02-10 11:59:43 +00:00
|
|
|
if ( ! options.length ) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
|
|
|
return (
|
|
|
|
<div
|
2024-05-31 03:49:36 +00:00
|
|
|
className={ clsx(
|
2022-02-10 11:59:43 +00:00
|
|
|
'wc-block-components-radio-control',
|
2024-04-10 09:54:05 +00:00
|
|
|
{
|
|
|
|
'wc-block-components-radio-control--highlight-checked--first-selected':
|
|
|
|
highlightChecked && selectedOptionNumber === 0,
|
|
|
|
'wc-block-components-radio-control--highlight-checked--last-selected':
|
|
|
|
highlightChecked &&
|
|
|
|
selectedOptionNumber === options.length - 1,
|
|
|
|
'wc-block-components-radio-control--highlight-checked':
|
|
|
|
highlightChecked,
|
|
|
|
},
|
2022-02-10 11:59:43 +00:00
|
|
|
className
|
|
|
|
) }
|
|
|
|
>
|
|
|
|
{ options.map( ( option ) => (
|
|
|
|
<RadioControlOption
|
2024-04-10 09:54:05 +00:00
|
|
|
highlightChecked={ highlightChecked }
|
2022-02-10 11:59:43 +00:00
|
|
|
key={ `${ radioControlId }-${ option.value }` }
|
|
|
|
name={ `radio-control-${ radioControlId }` }
|
|
|
|
checked={ option.value === selected }
|
|
|
|
option={ option }
|
|
|
|
onChange={ ( value: string ) => {
|
|
|
|
onChange( value );
|
|
|
|
if ( typeof option.onChange === 'function' ) {
|
|
|
|
option.onChange( value );
|
|
|
|
}
|
|
|
|
} }
|
2023-08-08 10:56:19 +00:00
|
|
|
disabled={ disabled }
|
2022-02-10 11:59:43 +00:00
|
|
|
/>
|
|
|
|
) ) }
|
|
|
|
</div>
|
|
|
|
);
|
|
|
|
};
|
|
|
|
|
|
|
|
export default RadioControl;
|
|
|
|
export { default as RadioControlOption } from './option';
|
|
|
|
export { default as RadioControlOptionLayout } from './option-layout';
|