import { type KeyboardEventHandler, useRef } from 'react'; import { slottableComponent } from '../HOC/slottableComponent'; import { useKeyboardKey } from '../../../hooks/useKeyboardKey'; import { Label } from '../Label/Label'; import classnames from 'classnames'; import { CustomInput } from '../../Input/Input'; import type { InterpretedOption } from '../../../use-lunatic/props/propOptions'; export type Props = { id: string; onKeyDown?: (v: { key: string; index: number }) => void; checkboxStyle?: boolean; shortcut?: boolean; disabled?: boolean; readOnly?: boolean; index?: number; labelledBy?: string; codeModality?: string; invalid?: boolean; detailAlwaysDisplayed?: boolean; } & InterpretedOption; function LunaticRadioOption({ checked, disabled, readOnly, checkboxStyle, onKeyDown, index, shortcut, codeModality, id, invalid, labelledBy, description, label, onDetailChange, detailAlwaysDisplayed, detailLabel, detailMaxLength, detailValue, onCheck, onUncheck, }: Props) { const divEl = useRef(null); const isEnabled = !disabled && !readOnly; const isRadio = !checkboxStyle; const hasDetail = !!onDetailChange; const onClickOption = () => { if (!isEnabled || !onCheck || checked) { // for checkboxStyle=true (only used by CheckboxOne) , we allow uncheck if (checkboxStyle && onUncheck) { onUncheck(); } return; } onCheck(); }; const handleKeyDown: KeyboardEventHandler = (e) => { onKeyDown?.({ key: e.key, index: index ?? -1 }); divEl.current?.blur(); }; const hasKeyboardShortcut = Boolean(shortcut && codeModality && isEnabled); useKeyboardKey( codeModality ? [codeModality] : [], (e) => { e.preventDefault(); onClickOption(); }, hasKeyboardShortcut, false // disable shortcut when editing a field ); return (
{hasDetail && (checked || detailAlwaysDisplayed) && ( )}
); } export const RadioOption = slottableComponent( 'RadioOption', LunaticRadioOption );