@chayns-components/core
Version:
A set of beautiful React components for developing your own applications with chayns.
75 lines • 2.94 kB
JavaScript
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { useKeyboardFocusHighlighting } from '../../hooks/useKeyboardFocusHighlighting';
import { useUuid } from '../../hooks/uuid';
import { getHeightOfSingleTextLine } from '../../utils/calculate';
import { StyledCheckbox, StyledCheckboxBox, StyledCheckboxBoxWrapper, StyledCheckboxInput, StyledCheckboxLabel } from './Checkbox.styles';
const Checkbox = ({
children,
isChecked,
isDisabled,
labelClassName,
onChange,
shouldShowAsSwitch,
borderRadius,
colors,
shouldShowCentered = false,
shouldChangeOnLabelClick = true,
shouldEnableKeyboardHighlighting
}) => {
const [isActive, setIsActive] = useState(isChecked ?? false);
const [checkboxTop, setCheckboxTop] = useState(undefined);
const checkboxBoxRef = useRef(null);
const checkboxRootRef = useRef(null);
const handleChange = useCallback(event => {
setIsActive(event.target.checked);
if (typeof onChange === 'function') {
onChange(event);
}
}, [onChange]);
const uuid = useUuid();
useEffect(() => {
if (checkboxRootRef.current && !shouldShowCentered) {
const singleLineHeight = getHeightOfSingleTextLine({
container: checkboxRootRef.current
});
const boxHeight = checkboxBoxRef.current?.getBoundingClientRect().height ?? 0;
setCheckboxTop((singleLineHeight - boxHeight) / 2);
}
}, [shouldShowCentered]);
const shouldShowKeyboardHighlighting = useKeyboardFocusHighlighting(shouldEnableKeyboardHighlighting && !isDisabled);
return /*#__PURE__*/React.createElement(StyledCheckbox, {
ref: checkboxRootRef
}, /*#__PURE__*/React.createElement(StyledCheckboxInput, {
$shouldShowKeyboardHighlighting: shouldShowKeyboardHighlighting,
checked: isChecked,
disabled: isDisabled,
id: uuid,
onChange: handleChange,
type: "checkbox"
}), /*#__PURE__*/React.createElement(StyledCheckboxBoxWrapper, {
$shouldShowAsSwitch: shouldShowAsSwitch,
style: {
top: shouldShowCentered ? '50%' : checkboxTop,
transform: shouldShowCentered ? 'translateY(-50%)' : undefined
}
}, /*#__PURE__*/React.createElement(StyledCheckboxBox, {
htmlFor: uuid,
ref: checkboxBoxRef,
$isChecked: isChecked ?? isActive,
$isDisabled: isDisabled,
$shouldShowAsSwitch: shouldShowAsSwitch,
$checkedBackgroundColor: colors?.checkedBackgroundColor,
$uncheckedBackgroundColor: colors?.uncheckedBackgroundColor,
$borderRadius: borderRadius,
$borderColor: colors?.borderColor
})), /*#__PURE__*/React.createElement(StyledCheckboxLabel, {
className: labelClassName,
$isDisabled: isDisabled,
$shouldChangeOnLabelClick: shouldChangeOnLabelClick,
$shouldShowAsSwitch: shouldShowAsSwitch,
htmlFor: shouldChangeOnLabelClick ? uuid : undefined
}, children));
};
Checkbox.displayName = 'Checkbox';
export default Checkbox;
//# sourceMappingURL=Checkbox.js.map