All files / SearchableMultiSelect SearchableMultiSelect.tsx

92.48% Statements 123/133
81.53% Branches 53/65
77.77% Functions 21/27
95.34% Lines 123/129

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 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 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994                                                                                              2x   2x     2x 2x 2x 2x 2x               2x 2x 2x           2x 2x             2x   2x 2x             2x 2x 2x 2x     2x 2x 2x         2x 2x 2x                       2x   2x 2x         2x 2x 2x 2x                           2x       2x                                                   2x                                                                                                                                     2x                                           2x 2x                       2x 2x 2x 2x 2x 2x 2x 2x 2x   2x                                                                                                                                                                                                                                                                                                     33x                   5x   5x   5x 4x     1x 1x       33x                       4x   4x   4x         4x   7x     4x       4x           33x                   1x         1x           33x             1x     33x                     1x   1x         1x 1x     1x   1x 1x       1x           1x                         33x   33x                                                     33x 276x           276x                                     33x             289x 289x                                               33x             33x             33x   33x       33x   33x   38x     33x   229x       33x                                     7x           54x         235x       33x 33x                               33x                                 33x   33x 33x         33x     33x                 33x   33x                                                                                                                                                     6x     51x   6x 3x             3x                                           8x             8x                                                         3x       25x           25x 17x 17x             17x                                             8x                                                    
/* eslint-disable react/prop-types */
import _, { omit } from 'lodash';
import React from 'react';
import PropTypes from 'prop-types';
import { lucidClassNames } from '../../util/style-helpers';
import { buildModernHybridComponent } from '../../util/state-management';
import { partitionText, propsSearch } from '../../util/text-manipulation';
import {
	StandardProps,
	getFirst,
	findTypes,
	rejectTypes,
	addSpecialOmittedProps,
} from '../../util/component-types';
import {
	SearchFieldDumb as SearchField,
	ISearchFieldProps,
} from '../SearchField/SearchField';
import {
	IDropMenuProps,
	IDropMenuState,
	IDropMenuOptionProps,
	IDropMenuOptionGroupProps,
	IOptionsData,
	DropMenuDumb as DropMenu,
} from '../DropMenu/DropMenu';
import LoadingIcon from '../Icon/LoadingIcon/LoadingIcon';
import CheckboxLabeled from '../CheckboxLabeled/CheckboxLabeled';
import Selection, {
	ISelectionProps,
	ISelectionLabelProps,
} from '../Selection/Selection';
import { Validation } from '../Validation/Validation';
 
import * as reducers from './SearchableMultiSelect.reducers';
 
const {
	any,
	arrayOf,
	bool,
	func,
	number,
	oneOfType,
	shape,
	string,
	oneOf,
	node,
} = PropTypes;
 
const cx = lucidClassNames.bind('&-SearchableMultiSelect');
 
/** SearchableMultiSelect.SelectionOption */
const SelectionOption = (_props: ISelectionProps): null => null;
SelectionOption.displayName = 'SearchableMultiSelect.Option.Selection';
SelectionOption.propTypes = Selection.propTypes;
SelectionOption.propName = 'Selection';
SelectionOption.peek = {
	description: `
		Customizes the rendering of the Option when it is selected
		and is displayed instead of the Placeholder.
	`,
};
 
/** SearchableMultiSelect.Option.Selected */
const Selected = (_props: { children?: React.ReactNode }): null => null;
Selected.displayName = 'SearchableMultiSelect.Option.Selected';
Selected.peek = {
	description: `
		Customizes the rendering of the Option when it is selected
		and is displayed instead of the Placeholder.
	`,
};
Selected.propName = 'Selected';
Selected.propTypes = {};
 
/** SearchableMultiSelect.OptionGroup */
interface ISearchableSingleSelectOptionGroupProps
	extends IDropMenuOptionGroupProps {
	Selected?: React.ReactNode;
}
const OptionGroup = (_props: ISearchableSingleSelectOptionGroupProps): null =>
	null;
OptionGroup.displayName = 'SearchableMultiSelect.OptionGroup';
OptionGroup.peek = {
	description: `
		A special kind of \`Option\` that is always rendered at the top of
		the menu and has an \`optionIndex\` of \`null\`. Useful for
		unselect.
	`,
};
OptionGroup.propName = 'OptionGroup';
OptionGroup.propTypes = DropMenu.OptionGroup.propTypes;
OptionGroup.defaultProps = DropMenu.OptionGroup.defaultProps;
OptionGroup.Selected = Selected;
 
/** SearchableMultiSelect.SearchField */
const SearchFieldComponent = (_props: ISearchFieldProps): null => null;
SearchFieldComponent.displayName = 'SearchableMultiSelect.SearchField';
SearchFieldComponent.peek = {
	description: `
		Passes props through to the \`Search Field\`.
	`,
};
SearchFieldComponent.propName = 'SearchField';
SearchFieldComponent.propTypes = SearchField.propTypes;
SearchFieldComponent.defaultProps = SearchField.defaultProps;
 
/** Option Child Component */
type ISearchableMultiSelectOptionSelectionProps = Partial<ISelectionProps>;
export interface ISearchableMultiSelectOptionProps
	extends IDropMenuOptionProps {
	Selection?: ISearchableMultiSelectOptionSelectionProps;
	description?: string;
	name?: string;
	Selected?: React.ReactNode;
}
 
const Option = (_props: ISearchableMultiSelectOptionProps): null => null;
 
Option.displayName = 'SearchableMultiSelect.Option';
Option.peek = {
	description: `
		A selectable option in the list.
	`,
};
Option.Selection = SelectionOption;
Option.Selected = Selected;
Option.propName = 'Option';
Option.propTypes = {
	/**
		Customizes the rendering of the Option when it is selected and is
		displayed instead of the Placeholder.
  */
	Selected: any,
	/**
        Uses a Selection object for custom rendering of the selected option
    */
	Selection: any,
	value: string,
	filterText: string,
	...DropMenu.Option.propTypes,
};
Option.defaultProps = DropMenu.Option.defaultProps;
 
/** SearchableMultiSelect */
/** TODO: Remove these prop constants when the component is converted to a functional component */
const props = [
	'children',
	'className',
	'isDisabled',
	'isLoading',
	'maxMenuHeight',
	'onSearch',
	'onSelect',
	'onRemoveAll',
	'optionFilter',
	'searchText',
	'selectedIndices',
	'DropMenu',
	'Option',
	'responsiveMode',
	'hasRemoveAll',
	'hasSelections',
	'hasSelectAll',
	'selectAllText',
	'Error',
	'FixedOption',
	'NullOption',
	'OptionGroup',
	'SearchField',
	'Label',
];
const nonPassThroughs = addSpecialOmittedProps(props, true);
 
export type Size = 'large' | 'medium' | 'small';
 
export interface ISearchableMultiSelectProps extends StandardProps {
	isDisabled?: boolean;
	isLoading: boolean;
	maxMenuHeight?: string | null;
	hasRemoveAll: boolean;
	hasSelectAll?: boolean;
	selectAllText?: string;
	hasSelections?: boolean;
	searchText: string;
	initialState?: any;
	responsiveMode: Size;
	selectedIndices?: number[];
	SearchField?: React.ReactNode;
	DropMenu: IDropMenuProps;
	Option?: ISearchableMultiSelectOptionProps;
	OptionGroup?: IDropMenuOptionGroupProps;
	SelectionLabel?: ISelectionLabelProps;
	Error?: React.ReactNode;
 
	onSelect: (
		optionIndices: number[] | number,
		{
			props,
			event,
		}: {
			props: IDropMenuOptionProps | undefined;
			event: React.KeyboardEvent | React.MouseEvent;
		}
	) => void;
 
	onSearch: (
		searchText: string,
		firstVisibleIndex: number | null,
		{
			props,
			event,
		}: {
			props: IDropMenuOptionProps;
			event: React.KeyboardEvent | React.MouseEvent;
		}
	) => void;
 
	optionFilter: (searchValue: string, props: any) => boolean;
 
	onRemoveAll: ({
		props,
		event,
	}: {
		props: IDropMenuOptionProps;
		event: React.KeyboardEvent | React.MouseEvent;
	}) => void;
}
 
export interface ISearchableMultiSelectState {
	DropMenu: IDropMenuState;
	selectedIndices: number[];
	searchText: string | null;
	optionGroups: IDropMenuOptionGroupProps[];
	flattenedOptionsData: IOptionsData[];
	ungroupedOptionData: IOptionsData[];
	optionGroupDataLookup: { [key: number]: IOptionsData[] };
}
 
const defaultProps = {
	isDisabled: false,
	isLoading: false,
	hasRemoveAll: true,
	hasSelections: true,
	hasSelectAll: false,
	selectAllText: 'Select All',
	searchText: '',
	responsiveMode: 'large' as const,
	selectedIndices: [],
	DropMenu: DropMenu.defaultProps,
	Error: null,
	optionFilter: propsSearch,
	onSearch: _.noop,
	onRemoveAll: _.noop,
	onSelect: _.noop,
};
 
class SearchableMultiSelect extends React.Component<
	ISearchableMultiSelectProps,
	ISearchableMultiSelectState
> {
	static displayName = 'SearchableMultiSelect';
	static peek = {
		description: `A control used to select multiple options from a dropdown list using a \`SearchField\`.`,
		categories: ['controls', 'selectors'],
		madeFrom: [
			'Checkbox',
			'SearchField',
			'DropMenu',
			'LoadingIcon',
			'Selection',
		],
	};
 
	static defaultProps = defaultProps;
	static reducers = reducers;
	static Option = Option;
	static OptionGroup = OptionGroup;
	static SearchField = SearchFieldComponent;
	static NullOption = DropMenu.NullOption;
	static FixedOption = DropMenu.FixedOption;
	static DropMenu = DropMenu;
	static SelectionLabel = Selection.Label;
 
	static propTypes = {
		/**
			Should be instances of \`SearchableMultiSelect.Option\`. Other direct
			child elements will not render.
		*/
		children: node,
 
		/**
			Appended to the component-specific class names set on the root element.
		*/
		className: string,
 
		/**
			Disables the control from being clicked or focused.
		*/
		isDisabled: bool,
 
		/**
			Displays a LoadingIcon to allow for asynchronous loading of options.
		*/
		isLoading: bool,
 
		/**
			The max height of the fly-out menu.
		*/
		maxMenuHeight: oneOfType([number, string]),
 
		onSearch: func /**
			Called when the user enters a value to search for; the set of visible
			Options will be filtered using the value.  Signature: \`(searchText,
			firstVisibleIndex, {props, event}) => {}\` \`searchText\` is the value
			from the \`SearchField\` and \`firstVisibleIndex\` is the index of the
			first option that will be visible after filtering.
		*/,
 
		/**
			Called when an option is selected.  Signature: \`(optionIndex, {props,
			event}) => {}\` \`optionIndex\` is the new \`selectedIndex\` or \`null\`.
		*/
		onSelect: func,
 
		/**
			Called when the user clicks to remove all selections.  Signature:
			\`({props, event}) => {}\`.
		*/
		onRemoveAll: 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\`.  Signature: \`(searchText, optionProps) => {}\` If \`true\`
			is returned, the 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,
 
		/**
			An array of currently selected \`SearchableMultiSelect.Option\` indices
			or \`null\` if nothing is selected.
		*/
		selectedIndices: arrayOf(number),
 
		/**
			Object of DropMenu props which are passed through to the underlying
			DropMenu component.
		*/
		DropMenu: shape(DropMenu.propTypes),
 
		Option: any /**
			*Child Element* - These are menu options. 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.  It also support the \`Selection\` prop that can be used to
			forward along props to the underlying \`Selection\` component.
		*/,
 
		/**
			Adjusts the display of this component. This should typically be driven by
			screen size. Currently \`small\` and \`large\` are explicitly handled by
			this component.
		*/
		responsiveMode: oneOf(['small', 'medium', 'large']),
 
		/**
			Controls the visibility of the "remove all" button that's shown with the
			selected items.
		*/
		hasRemoveAll: bool,
 
		/**
			Controls the visibility of the \`Selection\` component that appears below
			the search field.
		*/
		hasSelections: bool,
 
		/**
			Controls whether to show a "Select All" option.
		*/
		hasSelectAll: bool,
 
		/**
			The select all text.
		*/
		selectAllText: string,
 
		/**
			In most cases this will be a string, but it also accepts any valid React
			element. If this is a falsey value, then no error message will be
			displayed.  If this is the literal \`true\`, it will add the
			\`-is-error\` class to the wrapper div, but not render the
			\`-error-content\` \`div\`.
    */
		Error: any,
 
		FixedOption: any /**
			*Child Element* - A special kind of \`Option\` that is always rendered at the top of
			the menu.
		*/,
 
		NullOption: any /**
			*Child Element* - A special kind of \`Option\` that is always rendered at
			the top of the menu and has an \`optionIndex\` of \`null\`. Useful for
			unselect.
		*/,
 
		OptionGroup: 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.
    */,
 
		SearchField: any /**
			*Child Element* - The visual Search element that the user can pass text
			to.
		*/,
 
		Label: any /**
			*Child Element* - A custom label used as header text when options are
			selected.
		*/,
	};
 
	handleDropMenuSelect = (
		optionIndex: number | null,
		{
			event,
			props,
		}: {
			props: IDropMenuOptionProps | undefined;
			event: React.KeyboardEvent | React.MouseEvent;
		}
	): void => {
		const { onSelect } = this.props;
 
		event.preventDefault();
 
		if (optionIndex === 0) {
			return this.handleSelectAll({ event, props });
		}
		// this index is decremented to account for the "Select All" Option
		if (optionIndex) {
			return onSelect(optionIndex - 1, { event, props });
		}
	};
 
	handleSelectAll = ({
		event,
		props,
	}: {
		event: React.KeyboardEvent | React.MouseEvent;
		props: IDropMenuOptionProps | undefined;
	}): void => {
		// This is needed otherwise clicking the checkbox will double fire this
		// event _and_ the `handleDropMenuSelect` handler
		const {
			props: { selectedIndices, onSelect },
			state: { flattenedOptionsData },
		} = this;
 
		event.preventDefault();
 
		const visibleOptions = _.reject(
			flattenedOptionsData,
			'optionProps.isHidden'
		);
 
		const [selected, unselected] = _.partition(
			visibleOptions,
			({ optionIndex }) => _.includes(selectedIndices, optionIndex)
		);
 
		const indices = _.isEmpty(unselected)
			? _.map(selected, 'optionIndex')
			: _.map(unselected, 'optionIndex');
 
		return onSelect(indices, {
			props: props,
			event,
		});
	};
 
	handleSelectionRemove = ({
		event,
		props,
		props: { callbackId: optionIndex },
	}: {
		event: React.KeyboardEvent | React.MouseEvent;
		props: any;
	}): void => {
		// We don't want to send the consumer the selection's props so we have to
		// lookup the option they clicked and send its props along
		const selectedOptionProps = _.get(
			findTypes(this.props, SearchableMultiSelect.Option),
			`[${optionIndex}].props`
		);
 
		return this.props.onSelect(optionIndex, {
			event,
			props: selectedOptionProps,
		});
	};
 
	handleRemoveAll = ({
		event,
		props,
	}: {
		event: React.KeyboardEvent | React.MouseEvent;
		props: IDropMenuOptionProps;
	}): void => {
		this.props.onRemoveAll({ event, props });
	};
 
	handleSearch = (
		searchText: string,
		{ event }: { event: React.KeyboardEvent | React.MouseEvent }
	): void => {
		const {
			props,
			props: {
				onSearch,
				optionFilter,
				DropMenu: { onExpand },
			},
		} = this;
 
		const options = _.map(
			findTypes(props, SearchableMultiSelect.Option),
			'props'
		);
 
		const firstVisibleIndex = _.findIndex(options, (option) => {
			return optionFilter(searchText, option);
		});
 
		const trueIndex = firstVisibleIndex === -1 ? -1 : firstVisibleIndex + 1;
 
		const firstVisibleProps = options[trueIndex];
		const dropMenuProps = this.props.DropMenu;
 
		// Just an extra call to make sure the search results show up when a user
		// is typing
		onExpand &&
			onExpand({
				event,
				props: dropMenuProps,
			});
 
		return onSearch(searchText, trueIndex, {
			event,
			props: firstVisibleProps,
		});
	};
 
	UNSAFE_componentWillMount(): void {
		// preprocess the options data before rendering
		const {
			optionGroups,
			flattenedOptionsData,
			ungroupedOptionData,
			optionGroupDataLookup,
		} = DropMenu.preprocessOptionData(this.props, SearchableMultiSelect);
 
		this.setState({
			optionGroups,
			flattenedOptionsData,
			ungroupedOptionData,
			optionGroupDataLookup,
		});
	}
 
	UNSAFE_componentWillReceiveProps(
		nextProps: ISearchableMultiSelectProps
	): void {
		// only preprocess options data when it changes (via new props) - better performance than doing this each render
		const {
			optionGroups,
			flattenedOptionsData,
			ungroupedOptionData,
			optionGroupDataLookup,
		} = DropMenu.preprocessOptionData(nextProps, SearchableMultiSelect);
 
		this.setState({
			optionGroups,
			flattenedOptionsData,
			ungroupedOptionData,
			optionGroupDataLookup,
		});
	}
 
	renderUnderlinedChildren = (childText: string, searchText: string): any => {
		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,
	}: {
		optionProps: ISearchableMultiSelectOptionProps;
		optionIndex: number;
	}): React.ReactElement => {
		const { searchText, selectedIndices, isLoading, optionFilter } = this.props;
		return (
			<DropMenu.Option
				key={'SearchableMultiSelectOption' + optionIndex}
				{..._.omit(optionProps, ['children', 'Selected', 'filterText'])}
				isHidden={!optionFilter(searchText, optionProps)}
				isDisabled={optionProps.isDisabled || isLoading}
			>
				<CheckboxLabeled
					className={cx('&-CheckboxLabeled')}
					callbackId={optionIndex.toString()}
					isSelected={_.includes(selectedIndices, optionIndex)}
				>
					<CheckboxLabeled.Label>
						{_.isString(optionProps.children)
							? this.renderUnderlinedChildren(optionProps.children, searchText)
							: _.isFunction(optionProps.children)
							? React.createElement(optionProps.children, { searchText })
							: optionProps.children}
					</CheckboxLabeled.Label>
				</CheckboxLabeled>
			</DropMenu.Option>
		);
	};
 
	renderOptions = (): React.ReactElement[] | React.ReactElement | null => {
		const {
			searchText,
			isLoading,
			hasSelectAll,
			selectedIndices,
			selectAllText,
		} = this.props;
 
		const {
			optionGroups,
			optionGroupDataLookup,
			ungroupedOptionData,
			flattenedOptionsData,
		} = this.state;
 
		const visibleOptions = _.reject(
			flattenedOptionsData,
			'optionProps.isHidden'
		);
		const isAllOptionsHidden = _.isEmpty(visibleOptions);
 
		const isEveryVisibleOptionSelected = _.every(
			visibleOptions,
			({ optionIndex }) => _.includes(selectedIndices, optionIndex)
		);
 
		const isAnyVisibleOptionSelected = _.some(
			visibleOptions,
			({ optionIndex }) => _.includes(selectedIndices, optionIndex)
		);
 
		// 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 dropMenuOptions = [
			<DropMenu.FixedOption
				className={cx('&-Option-select-all')}
				key={'SearchableMultiSelectOption-select-all'}
				isHidden={!hasSelectAll}
				isDisabled={isLoading}
			>
				<CheckboxLabeled
					className={cx('&-CheckboxLabeled')}
					isSelected={isEveryVisibleOptionSelected}
					isIndeterminate={
						!isEveryVisibleOptionSelected && isAnyVisibleOptionSelected
					}
				>
					<CheckboxLabeled.Label>{selectAllText}</CheckboxLabeled.Label>
				</CheckboxLabeled>
			</DropMenu.FixedOption>,
		].concat(
			_.map(optionGroups, (optionGroupProps, optionGroupIndex) => (
				<DropMenu.OptionGroup
					key={'SearchableMultiSelectOptionGroup' + optionGroupIndex}
					{..._.omit(optionGroupProps, 'children', 'Selected')}
				>
					{optionGroupProps.children}
					{_.map(optionGroupDataLookup[optionGroupIndex], (option) =>
						this.renderOption(option)
					)}
				</DropMenu.OptionGroup>
			)).concat(
				// then render all the ungrouped options at the end
				_.map(ungroupedOptionData, (option) => this.renderOption(option))
			)
		);
 
		if (!isAllOptionsHidden || _.isEmpty(searchText)) {
			return dropMenuOptions;
		}
 
		if (!isLoading) {
			return (
				<DropMenu.Option isDisabled>
					<span className={cx('&-noresults')}>
						No results match "{searchText}"
					</span>
				</DropMenu.Option>
			);
		}
 
		return null;
	};
 
	render = () => {
		const {
			props,
			props: {
				className,
				isLoading,
				isDisabled,
				maxMenuHeight,
				selectedIndices,
				DropMenu: dropMenuProps,
				DropMenu: { optionContainerStyle },
				responsiveMode,
				searchText,
				hasRemoveAll,
				hasSelections,
				...passThroughs
			},
		} = this;
		const { optionGroupDataLookup, optionGroups, ungroupedOptionData } =
			this.state;
		const searchFieldProps = _.get(
			getFirst(props, SearchableMultiSelect.SearchField),
			'props',
			{}
		);
		const errorChildProps = _.first(
			_.map(findTypes(props, Validation.Error), 'props')
		);
		const selectionLabel = _.get(
			getFirst(props, SearchableMultiSelect.SelectionLabel),
			'props',
			{}
		) || (
			<SearchableMultiSelect.SelectionLabel>
				Selected
			</SearchableMultiSelect.SelectionLabel>
		);
		const isSmall = responsiveMode === 'small';
 
		return (
			<div
				{...(omit(passThroughs, nonPassThroughs) as any)}
				className={cx('&', className)}
			>
				<DropMenu
					{...dropMenuProps}
					selectedIndices={null}
					className={cx(
						'&-DropMenu',
						{
							'&-DropMenu-is-small': isSmall,
						},
						dropMenuProps.className
					)}
					optionContainerStyle={_.assign(
						{},
						optionContainerStyle,
						!_.isNil(maxMenuHeight) ? { maxHeight: maxMenuHeight } : null
					)}
					isDisabled={isDisabled}
					onSelect={this.handleDropMenuSelect}
					ContextMenu={{
						alignmentOffset: -13,
						directonOffset: -1,
						minWidthOffset: -28,
					}}
				>
					<DropMenu.Control>
						<SearchField
							{...searchFieldProps}
							autoComplete={searchFieldProps.autoComplete || 'off'}
							isDisabled={isDisabled}
							className={cx(
								'&-search',
								{
									'&-search-is-small': isSmall,
									'&-search-is-error':
										errorChildProps && errorChildProps.children,
								},
								searchFieldProps.className
							)}
							value={searchText}
							onChange={this.handleSearch}
						/>
					</DropMenu.Control>
					{isLoading ? (
						<DropMenu.Option
							key='SearchableMultiSelectLoading'
							className={cx('&-loading')}
							isDisabled
						>
							<LoadingIcon />
						</DropMenu.Option>
					) : null}
					{this.renderOptions()}
				</DropMenu>
 
				{hasSelections && !_.isEmpty(selectedIndices) ? (
					<div className={cx('&-Selection-padding')}>
						<Selection
							className={cx('&-Selection-section')}
							isBold
							hasBackground
							kind='container'
							onRemove={this.handleRemoveAll}
							responsiveMode={responsiveMode}
							isRemovable={hasRemoveAll}
						>
							<Selection.Label>
								{selectionLabel.children ? selectionLabel.children : 'Selected'}
							</Selection.Label>
							{_.map(
								optionGroupDataLookup,
								(groupedOptionsData: any[], optionGroupIndex: number) => {
									const selectedGroupedOptions = _.filter(
										groupedOptionsData,
										({ optionIndex }) =>
											_.includes(selectedIndices, optionIndex)
									);
									if (!_.isEmpty(selectedGroupedOptions)) {
										const selectedOptionGroupChildren = _.get(
											getFirst(
												optionGroups[optionGroupIndex],
												SearchableMultiSelect.OptionGroup.Selected
											),
											'props.children'
										);
										return (
											<Selection
												className={cx('&-Selection-group')}
												key={'optionGroup-' + optionGroupIndex}
												responsiveMode={responsiveMode}
												isRemovable={false}
												isBold
												kind='container'
											>
												<Selection.Label>
													{!_.isNil(selectedOptionGroupChildren)
														? selectedOptionGroupChildren
														: _.first(
																rejectTypes(
																	optionGroups[optionGroupIndex].children,
																	SearchableMultiSelect.Option
																)
														  )}
												</Selection.Label>
												{_.map(
													selectedGroupedOptions,
													({ optionIndex, optionProps }) => {
														const selectionProps = _.get(
															getFirst(
																optionProps,
																SearchableMultiSelect.Option.Selection
															),
															'props'
														);
														return (
															<Selection
																key={optionIndex}
																{...selectionProps}
																callbackId={optionIndex}
																responsiveMode={responsiveMode}
																onRemove={this.handleSelectionRemove}
															>
																<Selection.Label>
																	{_.get(
																		getFirst(
																			optionProps,
																			SearchableMultiSelect.Option.Selected
																		),
																		'props.children'
																	) ||
																		(_.isFunction(optionProps.children)
																			? React.createElement(
																					optionProps.children
																			  )
																			: optionProps.children)}
																</Selection.Label>
															</Selection>
														);
													}
												)}
											</Selection>
										);
									}
									return null;
								}
							)}
							{_.map(selectedIndices, (selectedIndex) => {
								const selectedUngroupedOptionData = _.find(
									ungroupedOptionData,
									{
										optionIndex: selectedIndex,
									}
								);
								if (selectedUngroupedOptionData) {
									const { optionProps } = selectedUngroupedOptionData;
									const selectionProps = _.get(
										getFirst(
											optionProps,
											SearchableMultiSelect.Option.Selection
										),
										'props'
									);
									return (
										<Selection
											key={selectedIndex}
											{...selectionProps}
											callbackId={selectedIndex}
											responsiveMode={responsiveMode}
											onRemove={this.handleSelectionRemove}
										>
											<Selection.Label>
												{_.get(
													getFirst(
														optionProps,
														SearchableMultiSelect.Option.Selected
													),
													'props.children'
												) ||
													(_.isFunction(optionProps.children)
														? React.createElement(optionProps.children)
														: optionProps.children)}
											</Selection.Label>
										</Selection>
									);
								}
								return null;
							})}
						</Selection>
					</div>
				) : null}
				{errorChildProps &&
				errorChildProps.children &&
				errorChildProps.children !== true ? (
					<div
						{...omit(errorChildProps, ['initialState', 'callbackId'])}
						className={cx('&-error-content')}
					>
						{errorChildProps.children}
					</div>
				) : null}
			</div>
		);
	};
}
 
export default buildModernHybridComponent<
	ISearchableMultiSelectProps,
	ISearchableMultiSelectState,
	typeof SearchableMultiSelect
>(SearchableMultiSelect as any, { reducers });
export { SearchableMultiSelect as SearchableMultiSelectDumb };