/** @format */ /** * External dependencies */ import { Component } from '@wordpress/element'; import PropTypes from 'prop-types'; import { uniqueId } from 'lodash'; /** * Internal dependencies */ import './setting.scss'; class Setting extends Component { renderInput = () => { const { handleChange, name, inputType, options, value } = this.props; const id = uniqueId( name ); switch ( inputType ) { case 'checkboxGroup': return options.map( optionGroup => optionGroup.options.length > 0 && (
{ optionGroup.label && ( { optionGroup.label } ) } { this.renderCheckboxOptions( optionGroup.options ) }
) ); case 'checkbox': return this.renderCheckboxOptions( options ); case 'text': default: return ( ); } }; renderCheckboxOptions( options ) { const { handleChange, name, value } = this.props; return options.map( option => { const id = uniqueId( name + '-' + option.value ); return ( ); } ); } render() { const { helpText, label, name } = this.props; return (
{ label }
{ this.renderInput() } { helpText && { helpText } }
); } } Setting.propTypes = { /** * Function assigned to the onChange of all inputs. */ handleChange: PropTypes.func.isRequired, /** * Optional help text displayed underneath the setting. */ helpText: PropTypes.oneOfType( [ PropTypes.string, PropTypes.array ] ), /** * Type of input to use; defaults to a text input. */ inputType: PropTypes.oneOf( [ 'checkbox', 'checkboxGroup', 'text' ] ), /** * Label used for describing the setting. */ label: PropTypes.string.isRequired, /** * Setting slug applied to input names. */ name: PropTypes.string.isRequired, /** * Array of options used for when the `inputType` allows multiple selections. */ options: PropTypes.arrayOf( PropTypes.shape( { /** * Input value for this option. */ value: PropTypes.string, /** * Label for this option or above a group for a group `inputType`. */ label: PropTypes.string, /** * Description used for screen readers. */ description: PropTypes.string, /** * Key used for a group `inputType`. */ key: PropTypes.string, /** * Nested options for a group `inputType`. */ options: PropTypes.array, } ) ), /** * The string value used for the input or array of items if the input allows multiselection. */ value: PropTypes.oneOfType( [ PropTypes.string, PropTypes.array ] ), }; export default Setting;