@i-novus/ui-core
Version:
Базовые UI компоненты
55 lines (54 loc) • 2.56 kB
JavaScript
import { jsx as _jsx } from "react/jsx-runtime";
import { Children, createContext, forwardRef, useCallback, useContext, useEffect, useMemo, useState, } from 'react';
import classNames from 'classnames';
import omit from 'lodash/omit';
import { useConfigProvider } from '../../core';
export const RadioGroupContext = createContext(null);
export const useRadioGroupContext = () => {
const radioGroupContext = useContext(RadioGroupContext);
if (!radioGroupContext) {
throw new Error('useRadioGroupContext должен быть использован в рамках <RadioGroupContext.Provider>');
}
return radioGroupContext;
};
const initialGroupValue = '';
export const RadioGroup = forwardRef((props, ref) => {
const { children, defaultValue, value, onChange, onBlur, prefix, className, disabled, readOnly, name, visible = true, direction = 'horizontal', ...restProps } = props;
const { getPrefix } = useConfigProvider();
const prefixCls = getPrefix(prefix);
const [groupValue, setGroupValue] = useState(value || defaultValue || initialGroupValue);
useEffect(() => {
if (value) {
setGroupValue(value);
}
}, [value]);
const onRadioChange = useCallback((optionId, event) => {
if (onChange) {
onChange(optionId, event);
}
else {
setGroupValue(optionId);
}
// @ts-ignore
onBlur?.(event);
}, [onBlur, onChange]);
const isRadioButtonGroup = useMemo(() => {
const displayNames = Children.map(children, (child) => child?.type?.displayName);
const radioButtons = displayNames?.filter(displayName => displayName === 'RadioButton');
return !!radioButtons?.length;
}, [children]);
const radioGroupClassName = useMemo(() => classNames(`${prefixCls}-radio-group`, `${prefixCls}-radio-group_${direction}`, isRadioButtonGroup && `${prefixCls}-radio-group_buttons`, className), [prefixCls, direction, isRadioButtonGroup, className]);
const radioGroupContextValue = useMemo(() => ({
onChange: onRadioChange,
value: groupValue,
defaultValue,
disabled,
readOnly,
name,
}), [defaultValue, disabled, groupValue, name, onRadioChange, readOnly]);
if (!visible) {
return null;
}
return (_jsx("div", { ...omit(restProps, 'title'), className: radioGroupClassName, ref: ref, children: _jsx(RadioGroupContext.Provider, { value: radioGroupContextValue, children: children }) }));
});
RadioGroup.displayName = 'RadioGroup';