@engie-group/fluid-design-system-react
Version:
Fluid Design System React
58 lines (55 loc) • 2.98 kB
JavaScript
import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
import React__default, { useId, useState, useEffect } from 'react';
import { Utils } from '../../utils/util.js';
import { NJIcon } from '../icon/NJIcon.js';
const NJToggle = React__default.forwardRef((props, ref) => {
const { id: propsId, label, scale, variant, values = { off: false, on: true }, className, children, isColorInherited, onChange, tabIndex, handleIcon, ...rest } = props;
let customIcon;
const id = propsId ?? useId();
const isChecked = props.checked;
const [isToggleChecked, setIsToggleChecked] = useState(!!isChecked);
const [inputValue, setInputValue] = useState(isChecked ? values.on : values.off);
useEffect(() => {
setInputValue(isChecked ? values.on : values.off);
setIsToggleChecked(!!isChecked);
}, [isChecked]);
const onInputChange = (e) => {
const isCheck = e.target.checked;
const inputVal = isCheck ? values.on : values.off;
setIsToggleChecked(isCheck);
setInputValue(inputVal);
if (onChange && typeof onChange === 'function')
onChange(e, isCheck, inputVal);
};
const classes = Utils.classNames('nj-toggle', {
[`nj-toggle--${scale}`]: scale && scale !== 'md',
[`nj-toggle--${variant}`]: variant && variant !== 'brand',
['nj-toggle--disabled']: props.disabled,
['nj-toggle--inherit']: isColorInherited
}, className);
if (children !== undefined) {
React__default.Children.forEach(children, (child) => {
const typedChild = child;
if (!typedChild) {
return;
}
if (React__default.isValidElement(typedChild)) {
if ('data-child-name' in typedChild.props &&
typedChild.props['data-child-name'] === 'njToggleIcon') {
customIcon = typedChild;
}
}
});
}
const getIconWithUpdateClassName = () => {
if (!customIcon) {
return;
}
const className = Utils.classNames(customIcon.props.className, 'nj-toggle__icon');
return React__default.cloneElement(customIcon, { className });
};
const input = (jsx("input", { ...rest, ref: ref, type: "checkbox", checked: isToggleChecked, id: id, value: inputValue.toString(), role: "switch", onChange: onInputChange, tabIndex: tabIndex }));
return (jsx("div", { className: classes, children: children || label || customIcon ? (jsxs("label", { htmlFor: id, children: [input, customIcon ? getIconWithUpdateClassName() : children, customIcon ? jsx("span", { className: "nj-sr-only", children: label }) : label, handleIcon && jsx(NJIcon, { name: handleIcon, className: "nj-toggle__handle-icon" })] })) : (jsxs(Fragment, { children: [input, handleIcon && jsx(NJIcon, { name: handleIcon, className: "nj-toggle__handle-icon" })] })) }));
});
NJToggle.displayName = 'NJToggle';
export { NJToggle };