UNPKG

@shopify/polaris

Version:

Shopify’s product component library

94 lines (85 loc) 3.04 kB
import React$1 from 'react'; import { useUniqueId } from '../../utilities/unique-id/hooks.js'; import { classNames } from '../../utilities/css.js'; import { errorTextID, InlineError as InlineError$1 } from '../InlineError/InlineError.js'; import { Checkbox as Checkbox$1 } from '../Checkbox/Checkbox.js'; import { RadioButton as RadioButton$1 } from '../RadioButton/RadioButton.js'; import styles from './ChoiceList.scss.js'; function ChoiceList({ title, titleHidden, allowMultiple, choices, selected, onChange = noop, error, disabled = false, name: nameProp }) { // Type asserting to any is required for TS3.2 but can be removed when we update to 3.3 // see https://github.com/Microsoft/TypeScript/issues/28768 var ControlComponent = allowMultiple ? Checkbox$1 : RadioButton$1; var name = useUniqueId('ChoiceList', nameProp); var finalName = allowMultiple ? "".concat(name, "[]") : name; var className = classNames(styles.ChoiceList, titleHidden && styles.titleHidden); var titleMarkup = title ? /*#__PURE__*/React$1.createElement("legend", { className: styles.Title }, title) : null; var choicesMarkup = choices.map(choice => { var { value, label, helpText, disabled: choiceDisabled, describedByError } = choice; function handleChange(checked) { onChange(updateSelectedChoices(choice, checked, selected, allowMultiple), name); } var isSelected = choiceIsSelected(choice, selected); var renderedChildren = choice.renderChildren ? choice.renderChildren(isSelected) : null; var children = renderedChildren ? /*#__PURE__*/React$1.createElement("div", { className: styles.ChoiceChildren }, renderedChildren) : null; return /*#__PURE__*/React$1.createElement("li", { key: value }, /*#__PURE__*/React$1.createElement(ControlComponent, { name: finalName, value: value, label: label, disabled: choiceDisabled || disabled, checked: choiceIsSelected(choice, selected), helpText: helpText, onChange: handleChange, ariaDescribedBy: error && describedByError ? errorTextID(finalName) : null }), children); }); var errorMarkup = error && /*#__PURE__*/React$1.createElement("div", { className: styles.ChoiceError }, /*#__PURE__*/React$1.createElement(InlineError$1, { message: error, fieldID: finalName })); return /*#__PURE__*/React$1.createElement("fieldset", { className: className, id: finalName, "aria-invalid": error != null }, titleMarkup, /*#__PURE__*/React$1.createElement("ul", { className: styles.Choices }, choicesMarkup), errorMarkup); } function noop() {} function choiceIsSelected({ value }, selected) { return selected.includes(value); } function updateSelectedChoices({ value }, checked, selected, allowMultiple = false) { if (checked) { return allowMultiple ? [...selected, value] : [value]; } return selected.filter(selectedChoice => selectedChoice !== value); } export { ChoiceList };