UNPKG

@cimpress/react-components

Version:
62 lines (61 loc) 3.03 kB
var __rest = (this && this.__rest) || function (s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; }; import React from 'react'; import debounce from 'lodash.debounce'; import { css, cx } from '@emotion/css'; import { useMemoizedId } from '../utils'; import { RadioIcon } from './RadioIcon'; import cvar from '../theme/cvar'; import { useRadioGroupContext } from './RadioGroup'; export const RADIO_NAME = 'CimRadio'; const disabledStyle = css ` cursor: not-allowed; color: ${cvar('color-icon-disabled')}; `; const radioLabel = css ` display: flex; align-items: center; &:has(input:checked) { --crc-radio-icon-display: block; } `; const radioIcon = css ` margin-right: ${cvar('spacing-8')}; `; const radioInput = css ` display: none; `; export const Radio = (props) => { var _a; const { id, name, checked, label, value, disabled = false, backgroundColor, className = '', onCheck, onBlur, onFocus, style } = props, rest = __rest(props, ["id", "name", "checked", "label", "value", "disabled", "backgroundColor", "className", "onCheck", "onBlur", "onFocus", "style"]); const { onChange: radioGroupOnChange, name: radioGroupName, selected: radioGroupSelected, } = (_a = useRadioGroupContext()) !== null && _a !== void 0 ? _a : {}; // `undefined` in case of uncontrolled radio const isChecked = checked !== null && checked !== void 0 ? checked : (radioGroupSelected != null ? radioGroupSelected === value : undefined); const debouncedChange = debounce((e, debouncedValue) => { onCheck === null || onCheck === void 0 ? void 0 : onCheck(e, debouncedValue); radioGroupOnChange === null || radioGroupOnChange === void 0 ? void 0 : radioGroupOnChange(e, debouncedValue); }, 200, { leading: true, trailing: false, }); const handleChange = (e) => { e.persist(); debouncedChange(e, value); }; const inputId = useMemoizedId({ id }); return (React.createElement("label", { className: cx('crc-radio', className, radioLabel, { [disabledStyle]: disabled }), htmlFor: inputId, style: style }, React.createElement(RadioIcon, { className: radioIcon, color: disabled ? cvar('color-icon-disabled') : cvar('color-button-primary'), backgroundColor: backgroundColor }), React.createElement("input", Object.assign({ id: inputId, className: radioInput, name: name !== null && name !== void 0 ? name : radioGroupName, type: "radio", disabled: disabled, checked: isChecked, value: value, onBlur: onBlur, onFocus: onFocus, onChange: handleChange }, rest)), label)); }; Radio.displayName = RADIO_NAME; //# sourceMappingURL=Radio.js.map