UNPKG

@hackplan/polaris

Version:

Shopify’s product component library

52 lines (51 loc) 2.62 kB
import React from 'react'; import { createUniqueIDFactory } from '@shopify/javascript-utilities/other'; import { classNames } from '../../utilities/css'; import { withAppProvider } from '../AppProvider'; import Checkbox from '../Checkbox'; import RadioButton from '../RadioButton'; import InlineError from '../InlineError'; import styles from './ChoiceList.scss'; const getUniqueID = createUniqueIDFactory('ChoiceList'); function ChoiceList({ title, titleHidden, allowMultiple, choices, selected, onChange = noop, error, name = getUniqueID(), }) { // 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 const ControlComponent = allowMultiple ? Checkbox : RadioButton; const finalName = allowMultiple ? `${name}[]` : name; const className = classNames(styles.ChoiceList, titleHidden && styles.titleHidden); const titleMarkup = title ? (<legend className={styles.Title}>{title}</legend>) : null; const choicesMarkup = choices.map((choice) => { const { value, label, helpText, disabled } = choice; function handleChange(checked) { onChange(updateSelectedChoices(choice, checked, selected, allowMultiple), name); } const isSelected = choiceIsSelected(choice, selected); const renderedChildren = choice.renderChildren ? choice.renderChildren(isSelected) : null; const children = renderedChildren ? (<div className={styles.ChoiceChildren}>{renderedChildren}</div>) : null; return (<li key={value}> <ControlComponent name={finalName} value={value} label={label} disabled={disabled} checked={choiceIsSelected(choice, selected)} helpText={helpText} onChange={handleChange}/> {children} </li>); }); const errorMarkup = error && (<div className={styles.ChoiceError}> <InlineError message={error} fieldID={finalName}/> </div>); return (<fieldset className={className} id={finalName} aria-invalid={error != null} aria-describedby={`${finalName}Error`}> {titleMarkup} <ul className={styles.Choices}>{choicesMarkup}</ul> {errorMarkup} </fieldset>); } function noop() { } function choiceIsSelected({ value }, selected) { return selected.indexOf(value) >= 0; } function updateSelectedChoices({ value }, checked, selected, allowMultiple = false) { if (checked) { return allowMultiple ? [...selected, value] : [value]; } return selected.filter((selectedChoice) => selectedChoice !== value); } export default withAppProvider()(ChoiceList);