All files / RadioGroup RadioGroup.tsx

96.55% Statements 28/29
75% Branches 6/8
75% Functions 3/4
100% Lines 28/28

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248                                        176x   176x                                                                                                 176x 176x             176x     176x   176x             176x               24x   24x             3x   3x 3x           3x 3x         3x       24x         24x               24x       24x           67x                                           176x   176x                                                                     176x                                               176x   176x   176x   176x                
import _ from 'lodash';
import React from 'react';
import PropTypes from 'react-peek/prop-types';
import { lucidClassNames, uniqueName } from '../../util/style-helpers';
import {
	getFirst,
	findTypes,
	rejectTypes,
	omitProps,
	StandardProps,
	Overwrite,
} from '../../util/component-types';
import reducers, { IRadioGroupState } from './RadioGroup.reducers';
import { buildModernHybridComponent } from '../../util/state-management';
 
import RadioButtonLabeled, {
	IRadioButtonLabeledLabelProps,
} from '../RadioButtonLabeled/RadioButtonLabeled';
import RadioButton, { IRadioButtonProps } from '../RadioButton/RadioButton';
 
const cx = lucidClassNames.bind('&-RadioGroup');
 
const { func, node, number, string, bool } = PropTypes;
 
interface IRadioGroupPropsRaw extends StandardProps {
	/**
	 * Passed along to the \`RadioGroup.RadioButton\' children whose \'name\'
	 * props are ignored.
	 */
	name: string;
 
	/**
	 * Called when the user clicks on one of the child radio buttons or when
	 * they press the space key while one is in focus, and only called when the
	 * component is in the unselected state. \`props\` refers to the child
	 * \`RadioButton\` props.  Signature: \`(selectedIndex, { event, props }) => {}\`
	 */
	onSelect: (
		selectedIndex: string | number,
		{
			event,
			props,
		}: {
			event: React.MouseEvent;
			props: IRadioButtonProps;
		}
	) => void;
 
	/**
	 * Indicates which \`RadioGroup.RadioButton\' child is currently
	 * selected. The index of the last \`RadioGroup.RadioButton\` child with
	 * \'isSelected\' equal to true takes precedence over this prop.
	 */
	selectedIndex: number;
 
	/**
	 * Indicates whether all \`RadioGroup.RadioButton\' children should appear
	 * and act disabled by having a "greyed out" palette and ignoring user
	 * interactions.
	 */
	isDisabled: boolean;
}
 
type IRadioGroupProps = Overwrite<
	React.DetailedHTMLProps<
		React.HTMLAttributes<HTMLSpanElement>,
		HTMLSpanElement
	>,
	IRadioGroupPropsRaw
>;
 
const RadioGroupLabel = (props: IRadioButtonLabeledLabelProps) => null;
RadioGroupLabel.peek = {
	description: `
        Support radio button labels as \`RadioGroup.Label\` component which
        can be provided as a child of a \`RadioGroup.RadioButton\`
        component.
    `,
};
RadioGroupLabel.propTypes = {
	children: node,
};
RadioGroupLabel.displayName = 'RadioGroup.Label';
 
const defaultProps = {
	name: uniqueName(`${cx('&')}-`),
	onSelect: _.noop,
	selectedIndex: 0,
	isDisabled: false,
};
 
const RadioGroup = (props: IRadioGroupProps) => {
	const {
		children,
		className,
		name,
		selectedIndex,
		isDisabled,
		...passThroughs
	} = props;
 
	const handleSelected = (
		isSelected: boolean,
		{
			event,
			props: childProps,
		}: { event: React.MouseEvent; props: IRadioButtonProps }
	) => {
		const { callbackId } = childProps;
 
		Eif (callbackId !== undefined) {
			const clickedRadioButtonProps = _.get(
				_.map(findTypes(props, RadioGroup.RadioButton), 'props'),
				callbackId
			);
			// If the `RadioGroup.RadioButton` child has an `onSelect` prop that is
			// a function, call that prior to calling the group's `onSelect` prop.
			Eif (_.isFunction(clickedRadioButtonProps.onSelect)) {
				clickedRadioButtonProps.onSelect(isSelected, {
					event,
					props: childProps,
				});
			}
			props.onSelect(callbackId, { event, props: childProps });
		}
	};
 
	const radioButtonChildProps = _.map(
		findTypes(props, RadioGroup.RadioButton),
		'props'
	);
 
	const selectedIndexFromChildren = _.findLastIndex(radioButtonChildProps, {
		isSelected: true,
	});
 
	// If there are any `RadioGroup.RadioButton` children with `isSelected`
	// equal to true, then the index of the last one should override the
	// value of the `selectedIndex` prop.
	const actualSelectedIndex =
		selectedIndexFromChildren !== -1
			? selectedIndexFromChildren
			: selectedIndex;
 
	return (
		<span
			{...omitProps(passThroughs, undefined, _.keys(RadioGroup.propTypes))}
			className={cx('&', className)}
		>
			{_.map(radioButtonChildProps, (radioButtonChildProp, index) => {
				return (
					<RadioButtonLabeled
						{...radioButtonChildProp}
						isDisabled={isDisabled || radioButtonChildProp.isDisabled}
						isSelected={actualSelectedIndex === index}
						key={index}
						callbackId={index}
						name={name}
						onSelect={handleSelected}
						Label={_.get(
							getFirst(radioButtonChildProp, RadioGroup.Label),
							'props',
							null
						)}
					/>
				);
			})}
			{rejectTypes(children, RadioGroup.RadioButton)}
		</span>
	);
};
 
RadioGroup.displayName = 'RadioGroup';
 
RadioGroup.propTypes = {
	children: node`
    			Should be instances of \`RadioGroup.RadioButton\` which supports the same
    			props as \`RadioButton\`.
    		`,
 
	className: string`
    			Appended to the component-specific class names set on the root element.
    		`,
 
	name: string`
    			Passed along to the \`RadioGroup.RadioButton\` children whose \`name\`
    			props are ignored.
    		`,
 
	onSelect: func`
    			Called when the user clicks on one of the child radio buttons or when
    			they press the space key while one is in focus, and only called when the
    			component is in the unselected state. \`props\` refers to the child
    			\`RadioButton\` props.  Signature: \`(selectedIndex, { event, props }) => {}\`
    		`,
 
	selectedIndex: number`
    			Indicates which of the \`RadioGroup.RadioButton\` children is currently
    			selected. The index of the last \`RadioGroup.RadioButton\` child with
    			\`isSelected\` equal to true takes precedence over this prop.
    		`,
 
	isDisabled: bool`
    			Indicates whether all \`RadioGroup.RadioButton\` children should appear
    			and act disabled by having a "greyed out" palette and ignoring user
    			interactions.
    		`,
};
 
RadioGroup.peek = {
	description: `
		This is a composite of the \`RadioButton\` component and the native
		\`label\` element.
`,
	notes: {
		overview: `
			A round two-state toggle with a label that explains the action or selection. This is a composite of \`RadioButton\` and the native
			\`label\` element.		`,
		intendedUse: `
			- Use radio button to allow users to select one item. Commonly used to select filters or settings. For interactions where users can select mutiple options, use \`CheckboxLabeled\`. 
			- Use radio buttons for 2-3 options where you want to expose all options.
			- Use \`SingleSelect\` for 3-10 options where it is not a priority to expose all options.
			- Use \`RadioGroup\` for horizontal lists of options. Use \`RadioButtonLabeled\` for vertical lists of options.
	`,
		technicalRecommendations: `
			- Use the styles on the parent container of \`RadioGroup\` to ensure only the radio buttons and their labels are clickable.
			- Any props that are not explicitly defined in \`propTypes\` are passed to the native radio button control.
		`,
	},
	categories: ['controls', 'toggles'],
	madeFrom: ['RadioButton'],
};
 
RadioGroup.defaultProps = defaultProps;
 
RadioGroup.reducers = reducers;
 
RadioGroup.RadioButton = RadioButton;
 
RadioGroup.Label = RadioGroupLabel;
 
export default buildModernHybridComponent<
	IRadioGroupProps,
	IRadioGroupState,
	typeof RadioGroup
>(RadioGroup, { reducers });
export { RadioGroup as RadioGroupDumb };