|
| 1 | +import React, { useRef, useState } from 'react'; |
| 2 | + |
| 3 | +import BaseChoiceInput from '@ids-internal/partials/BaseChoiceInput'; |
| 4 | +import { createCssClassNames } from '@ibexa/ids-core/helpers/cssClassNames'; |
| 5 | +import withStateChecked from '@ids-internal/hoc/withStateChecked'; |
| 6 | + |
| 7 | +import { AltRadioProps } from './AltRadio.types'; |
| 8 | + |
| 9 | +const AltRadio = ({ className = '', label, ...restProps }: AltRadioProps) => { |
| 10 | + const { checked = false, disabled = false, error = false, onBlur, onChange, onFocus, onInput } = restProps; |
| 11 | + const inputRef = useRef<HTMLInputElement>(null); |
| 12 | + const [isFocused, setIsFocused] = useState(false); |
| 13 | + const altRadioClassName = createCssClassNames({ |
| 14 | + 'ids-alt-radio': true, |
| 15 | + [className]: true, |
| 16 | + }); |
| 17 | + const altRadioTileClassName = createCssClassNames({ |
| 18 | + 'ids-alt-radio__tile': true, |
| 19 | + 'ids-alt-radio__tile--checked': checked, |
| 20 | + 'ids-alt-radio__tile--disabled': disabled, |
| 21 | + 'ids-alt-radio__tile--error': error, |
| 22 | + 'ids-alt-radio__tile--focused': isFocused, |
| 23 | + }); |
| 24 | + const onTileClick = () => { |
| 25 | + inputRef.current?.focus(); |
| 26 | + |
| 27 | + if (!checked) { |
| 28 | + onChange?.(true); |
| 29 | + onInput?.(true); |
| 30 | + } |
| 31 | + }; |
| 32 | + const onInputFocus = (event: React.FocusEvent<HTMLInputElement>) => { |
| 33 | + setIsFocused(true); |
| 34 | + onFocus?.(event); |
| 35 | + }; |
| 36 | + const onInputBlur = (event: React.FocusEvent<HTMLInputElement>) => { |
| 37 | + setIsFocused(false); |
| 38 | + onBlur?.(event); |
| 39 | + }; |
| 40 | + |
| 41 | + return ( |
| 42 | + <div className={altRadioClassName}> |
| 43 | + <div className="ids-alt-radio__source"> |
| 44 | + <BaseChoiceInput {...restProps} onBlur={onInputBlur} onFocus={onInputFocus} ref={inputRef} type="radio" /> |
| 45 | + </div> |
| 46 | + <div className={altRadioTileClassName} onClick={onTileClick} role="button"> |
| 47 | + {label} |
| 48 | + </div> |
| 49 | + </div> |
| 50 | + ); |
| 51 | +}; |
| 52 | + |
| 53 | +export default AltRadio; |
| 54 | + |
| 55 | +export const AltRadioStateful = withStateChecked(AltRadio); |
0 commit comments