@nafr/echo-ui
Version:
A UI library born for WAA
35 lines (34 loc) • 2.23 kB
JavaScript
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { forwardRef, useCallback, useContext, useEffect, useState } from 'react';
import { usePropsWithGroup } from '../../../lib/hooks';
import { cn } from '../../../lib/utils';
import { RadioGroupContext } from './context';
import { useStyle } from './styles';
import { COLOR, SIZE } from './constants';
export const Radio = forwardRef((props, ref) => {
const groupContext = useContext(RadioGroupContext);
const isInGroup = groupContext !== null;
const { value, checked: _checked = false, disabled = false, size = SIZE, color = COLOR, classNames, styles, children, onChange, onClick, onMouseEnter, onMouseLeave, ...restProps } = usePropsWithGroup(props, groupContext);
const [localChecked, setLocalChecked] = useState(_checked);
useEffect(() => {
if (!isInGroup)
setLocalChecked(_checked);
}, [_checked]);
const handleChange = useCallback((e) => {
if (disabled)
return;
if (!isInGroup)
setLocalChecked(e.target.checked);
const opt = { value, nativeEvent: e };
if (isInGroup)
groupContext.onChange?.(opt);
else
onChange?.(opt);
}, [onChange, disabled, groupContext]);
const checked = isInGroup ? groupContext.value === value : localChecked;
const { base, wrapper, button, thumb, label } = useStyle({ checked, size, disabled });
return (_jsxs("label", { ref: ref, "data-checked": checked, "data-disabled": disabled, className: cn(base(), isInGroup && groupContext.classNames?.radio, restProps.className), style: {
...(isInGroup && groupContext.styles?.radio),
...restProps.style,
}, onMouseEnter: onMouseEnter, onMouseLeave: onMouseLeave, children: [_jsxs("span", { className: cn(wrapper()), children: [_jsx("input", { ...restProps, type: "radio", checked: checked, disabled: disabled, onClick: onClick, onChange: handleChange, className: cn(button()) }), _jsx("span", { className: cn(thumb()), style: { backgroundColor: disabled ? 'var(--echo-muted)' : color } })] }), _jsx("div", { className: cn(label(), classNames?.label), style: styles?.label, children: children })] }));
});