All files / components/SearchableSelect SearchableSelect.jsx

91.84% Statements 45/49
80.85% Branches 38/47
100% Functions 9/9
91.49% Lines 43/47
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 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394                      120x                       120x                 120x                                                                                                                                                                                                                                 120x                         26x                   12x 1x     11x 9x     2x 4x 4x 4x       8x 3x     5x           26x                           1x       1x   1x 3x     1x                                       66x   66x                             66x                       26x           26x     26x 3x 9x   9x   3x                       57x     60x   26x                                         26x           26x       26x   26x 26x 26x 26x   26x                                                                                                                  
import React from 'react';
import _ from 'lodash';
import { createClass, findTypes, getFirst } from '../../util/component-types';
import { lucidClassNames } from '../../util/style-helpers';
import { partitionText } from '../../util/text-manipulation';
import * as reducers from './SearchableSelect.reducers';
import CaretIcon from '../Icon/CaretIcon/CaretIcon';
import DropMenu from '../DropMenu/DropMenu';
import LoadingIcon from '../Icon/LoadingIcon/LoadingIcon';
import SearchField from '../SearchField/SearchField';
 
const cx = lucidClassNames.bind('&-SearchableSelect');
 
const {
	any,
	bool,
	func,
	node,
	number,
	object,
	shape,
	string,
	oneOfType,
} = React.PropTypes;
 
/**
 *
 * {"categories": ["controls", "selectors"], "madeFrom": ["DropMenu", "SearchField"]}
 *
 * A selector control (like native `<select>`) which is used to select a single option from a dropdown list using a SearchField.
 * Supports option groups with and without labels.
 */
const SearchableSelect = createClass({
	displayName: 'SearchableSelect',
 
	reducers,
 
	components: {
		/**
		 * Content this is displayed when nothing is selected.
		 */
		Placeholder: createClass({
			displayName: 'SearchableSelect.Placeholder',
			propName: 'Placeholder',
		}),
		/**
		 * A selectable option in the list.
		 */
		Option: createClass({
			displayName: 'SearchableSelect.Option',
			propName: 'Option',
			propTypes: DropMenu.Option.propTypes,
		}),
		/**
		 * Groups `Option`s together with a non-selectable heading.
		 */
		OptionGroup: createClass({
			displayName: 'SearchableSelect.OptionGroup',
			propName: 'OptionGroup',
			propTypes: DropMenu.OptionGroup.propTypes,
		}),
		SearchField,
	},
 
	propTypes: {
		/**
		 * Should be instances of {`SearchableSelect.Placeholder`, `SearchableSelect.Option`, `SearchableSelect.OptionGroup`}. Other direct child elements will not render.
		 */
		children: node,
		/**
		 * Appended to the component-specific class names set on the root elements. Applies to *both* the control and the flyout menu.
		 */
		className: string,
		/**
		 * Styles that are passed through to root element.
		 */
		style: object,
		/**
		 * Allows user to reset the `optionIndex` to `null` if they select the placeholder at the top of the options list.
		 * If `false`, it will not render the placeholder in the menu.
		 */
		hasReset: bool,
		/**
		 * Disables the SearchableSelect from being clicked or focused.
		 */
		isDisabled: bool,
		/**
		 * Displays a centered LoadingIcon to allow for asynchronous loading of options.
		 */
		isLoading: bool,
		/**
		 * Applies primary color styling to the control when an item is selected. Defaults to true.
		 */
		isSelectionHighlighted: bool,
		/**
		 * The max height of the fly-out menu.
		 */
		maxMenuHeight: oneOfType([number, string]),
		/**
		 * Called when the user enters a value to search for; the set of visible Options will be filtered using the value.
		 * Has the signature `(searchText, firstVisibleIndex, {props, event}) => {}` where `searchText` is the value from the `SearchField` and `firstVisibleIndex` is the index of the first option that will be visible after filtering.
		 */
		onSearch: func,
		/**
		 * Called when an option is selected.
		 * Has the signature `(optionIndex, {props, event}) => {}` where `optionIndex` is the new `selectedIndex` or `null`.
		 */
		onSelect: func,
		/**
		 * The function that will be run against each Option's props to determine whether it should be visible or not.
		 * The default behavior of the function is to match, ignoring case, against any text node descendant of the `Option`.
		 *
		 * Has the signature `(searchText, optionProps)`
		 * If `true`, option will be visible. If `false`, the option will not be visible.
		 */
		optionFilter: func,
		/**
		 * The current search text to filter the list of options by.
		 */
		searchText: string,
		/**
		 * The currently selected `SearchableSelect.Option` index or `null` if nothing is selected.
		 */
		selectedIndex: number,
		/**
		 * Object of DropMenu props which are passed thru to the underlying DropMenu component.
		 */
		DropMenu: shape(DropMenu.propTypes),
		/**
		 * *Child Element* - The content rendered in the control when there is no option is selected. Also rendered in the option list to remove current selection.
		 */
		Placeholder: any,
		/**
		 * *Child Element* - These are menu options. The `optionIndex` is in-order of rendering regardless of group nesting, starting with index `0`.
		 * Each `Option` may be passed a prop called `isDisabled` to disable selection of that `Option`.
		 * Any other props pass to Option will be available from the `onSelect` handler.
		 */
		Option: any,
		/**
		 * *Child Element* - Used to group `Option`s within the menu. Any non-`Option`s passed in will be rendered as a label for the group.
		 */
		OptionGroup: any,
	},
 
	getDefaultProps() {
		return {
			hasReset: true,
			isSelectionHighlighted: true,
			isDisabled: false,
			isLoading: false,
			optionFilter: this.defaultOptionFilter,
			searchText: null,
			selectedIndex: null,
			DropMenu: DropMenu.getDefaultProps(),
		};
	},
 
	getInitialState() {
		return {
			optionGroups: [],
			flattenedOptionsData: [],
			ungroupedOptionData: [],
			optionGroupDataLookup: {},
		}
	},
 
	statics: {
		getCombinedChildText(node) {
			if (!node.children) {
				return '';
			}
 
			if (_.isString(node.children)) {
				return node.children;
			}
 
			return node.children
							.filter(child => !_.isString(child))
							.map(child => this.getCombinedChildText(child.props))
							.reduce(((combinedText, childText) => combinedText + childText), _.find(node.children, _.isString) || '');
		},
 
		defaultOptionFilter(searchText, optionProps) {
			if (!searchText) {
				return true;
			}
 
			return new RegExp(_.escapeRegExp(searchText), 'i').test(SearchableSelect.getCombinedChildText(optionProps));
		},
	},
 
	componentWillMount() {
		// preprocess the options data before rendering
		this.setState(DropMenu.preprocessOptionData(this.props, SearchableSelect));
	},
 
	componentWillReceiveProps(nextProps) {
		// only preprocess options data when it changes (via new props) - better performance than doing this each render
		this.setState(DropMenu.preprocessOptionData(nextProps, SearchableSelect));
	},
 
	handleSearch(searchText) {
		const {
			props: {
				onSearch,
				optionFilter,
			},
		} = this;
 
		const {
			flattenedOptionsData,
		} = this.state;
 
		const firstVisibleIndex = _.get(_.find(flattenedOptionsData, ({optionProps}) => {
			return optionFilter(searchText, optionProps);
		}), 'optionIndex');
 
		onSearch(searchText, firstVisibleIndex);
	},
 
	renderUnderlinedChildren(childText, searchText) {
		const [pre, match, post] = partitionText(childText, new RegExp(_.escapeRegExp(searchText), 'i'), searchText.length);
 
		return (
			[
				pre && <span key='pre' className={cx('&-Option-underline-pre')}>{pre}</span>,
				match && <span key='match' className={cx('&-Option-underline-match')}>{match}</span>,
				post && <span key='post' className={cx('&-Option-underline-post')}>{post}</span>,
			]
		);
	},
 
	renderOption(optionProps, optionIndex) {
		const {
			isLoading,
			optionFilter,
			searchText,
		} = this.props;
 
		Iif (searchText) {
			return (
				<DropMenu.Option
					isDisabled={isLoading}
					isHidden={!optionFilter(searchText, optionProps)}
					key={'SearchableSelectOption' + optionIndex}
					{..._.omit(optionProps, ['children'])}
				>
					{_.isString(optionProps.children) ?
						this.renderUnderlinedChildren(optionProps.children, searchText)
						: optionProps.children}
				</DropMenu.Option>
			);
		}
 
		return (
			<DropMenu.Option
				isDisabled={isLoading}
				key={'SearchableSelectOption' + optionIndex}
				{...optionProps}
			/>
		);
	},
 
	renderOptions() {
		const {
			searchText,
		} = this.props;
 
		const {
			optionGroups,
			optionGroupDataLookup,
			ungroupedOptionData,
		} = this.state;
 
		// for each option group passed in, render a DropMenu.OptionGroup, any label will be included in it's children, render each option inside the group
		const options = _.map(optionGroups, (optionGroupProps, optionGroupIndex) => {
			const childOptions = _.map(_.get(optionGroupDataLookup, optionGroupIndex), ({ optionProps, optionIndex }) => (
				this.renderOption(optionProps, optionIndex)
			));
			const visibleChildrenCount = _.filter(childOptions, option => !option.props.isHidden).length;
 
			return (
				<DropMenu.OptionGroup
					isHidden={visibleChildrenCount === 0}
					key={'SearchableSelectOptionGroup' + optionGroupIndex}
					{...optionGroupProps}
				>
					{optionGroupProps.children}
					{childOptions}
				</DropMenu.OptionGroup>
			);
		// then render all the ungrouped options at the end
		}).concat(_.map(ungroupedOptionData, ({ optionProps, optionIndex }) => (
			this.renderOption(optionProps, optionIndex)
		)));
 
		const visibleOptionsCount = _.filter(options, option => !option.props.isHidden).length;
 
		return (
			visibleOptionsCount > 0 ? options : <DropMenu.Option isDisabled><span className={cx('&-noresults')}>No results match "{searchText}"</span></DropMenu.Option>
		);
	},
 
	render() {
		const {
			props,
				props: {
				style,
				className,
				hasReset,
				isDisabled,
				isLoading,
				isSelectionHighlighted,
				maxMenuHeight,
				searchText,
				selectedIndex,
				onSelect,
				DropMenu: dropMenuProps,
			},
		} = this;
 
		const {
			direction,
			optionContainerStyle,
			isExpanded,
		} = dropMenuProps;
 
		const {
			flattenedOptionsData,
		} = this.state;
 
		const searchFieldProps = _.get(getFirst(props, SearchField, <SearchField />), 'props');
		const placeholderProps = _.first(_.map(findTypes(this.props, SearchableSelect.Placeholder), 'props'));
		const placeholder = _.get(placeholderProps, 'children', 'Select');
		const isItemSelected = _.isNumber(selectedIndex);
 
		return (
			<DropMenu
				{...dropMenuProps}
				className={cx('&', className)}
				optionContainerStyle={_.assign({}, optionContainerStyle, !_.isNil(maxMenuHeight) ? { maxHeight: maxMenuHeight } : null)}
				isDisabled={isDisabled}
				isLoading={isLoading}
				onSelect={onSelect}
				selectedIndices={isItemSelected ? [selectedIndex] : []}
				style={style}
			>
				<DropMenu.Control>
					<div
						tabIndex={0}
						className={cx('&-Control', {
							'&-Control-is-highlighted': (!isDisabled && isItemSelected && isSelectionHighlighted) || (isExpanded && isSelectionHighlighted),
							'&-Control-is-selected': (!isDisabled && isItemSelected && isSelectionHighlighted) || (isExpanded && isSelectionHighlighted),
							'&-Control-is-expanded': isExpanded,
							'&-Control-is-disabled': isDisabled,
						})
					}>
						<span
							{...(!isItemSelected ? placeholderProps : null)}
							className={cx(
									'&-Control-content',
									(!isItemSelected ? _.get(placeholderProps, 'className') : null)
							)}
						>
							{isItemSelected ? flattenedOptionsData[selectedIndex].optionProps.children : placeholder}
						</span>
						<CaretIcon direction={isExpanded ? direction : 'down'} />
					</div>
				</DropMenu.Control>
				<DropMenu.Header className={cx('&-Search-container')}>
					<SearchField
						{...searchFieldProps}
						onChange={this.handleSearch}
						value={searchText}
					/>
				</DropMenu.Header>
				{
					isLoading &&
					<DropMenu.Option key='SearchableSelectLoading' className={cx('&-Loading')} isDisabled>
						<LoadingIcon />
					</DropMenu.Option>
				}
				{
					hasReset && isItemSelected &&
					<DropMenu.NullOption {...placeholderProps}>{placeholder}</DropMenu.NullOption>
				}
				{this.renderOptions()}
			</DropMenu>
		);
	},
});
 
export default SearchableSelect;