lucid-ui
Version:
A UI component library from AppNexus.
426 lines (425 loc) • 23.3 kB
JavaScript
/* eslint-disable react/prop-types */
import _ from 'lodash';
import React from 'react';
import PropTypes from 'react-peek/prop-types';
import { lucidClassNames } from '../../util/style-helpers';
import { buildModernHybridComponent } from '../../util/state-management';
import { partitionText, propsSearch } from '../../util/text-manipulation';
import { omitProps, getFirst, findTypes, rejectTypes, } from '../../util/component-types';
import { SearchFieldDumb as SearchField, } from '../SearchField/SearchField';
import { DropMenuDumb as DropMenu, } from '../DropMenu/DropMenu';
import LoadingIcon from '../Icon/LoadingIcon/LoadingIcon';
import CheckboxLabeled from '../CheckboxLabeled/CheckboxLabeled';
import Selection 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');
const SelectionOption = (_props) => 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.
`,
};
const Selected = (_props) => 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 = {};
const OptionGroup = (_props) => 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;
const SearchFieldComponent = (_props) => 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;
const Option = (_props) => 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 = {
Selected: any `
Customizes the rendering of the Option when it is selected and is
displayed instead of the Placeholder.
`,
Selection: any `
Uses a Selection object for custom rendering of the selected option
`,
value: string,
filterText: string,
...DropMenu.Option.propTypes,
};
Option.defaultProps = DropMenu.Option.defaultProps;
const defaultProps = {
isDisabled: false,
isLoading: false,
hasRemoveAll: true,
hasSelections: true,
hasSelectAll: false,
selectAllText: 'Select All',
searchText: '',
responsiveMode: 'large',
selectedIndices: [],
DropMenu: DropMenu.defaultProps,
Error: null,
optionFilter: propsSearch,
onSearch: _.noop,
onRemoveAll: _.noop,
onSelect: _.noop,
};
class SearchableMultiSelect extends React.Component {
constructor() {
super(...arguments);
this.handleDropMenuSelect = (optionIndex, { event, props, }) => {
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 });
}
};
this.handleSelectAll = ({ event, props, }) => {
// 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,
});
};
this.handleSelectionRemove = ({ event, props, props: { callbackId: optionIndex }, }) => {
// 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,
});
};
this.handleRemoveAll = ({ event, props, }) => {
this.props.onRemoveAll({ event, props });
};
this.handleSearch = (searchText, { event }) => {
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 firstVisibleProps = options[firstVisibleIndex];
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, firstVisibleIndex, {
event,
props: firstVisibleProps,
});
};
this.renderUnderlinedChildren = (childText, searchText) => {
const [pre, match, post] = partitionText(childText, new RegExp(_.escapeRegExp(searchText), 'i'), searchText.length);
return [
pre && (React.createElement("span", { key: 'pre', className: cx('&-Option-underline-pre') }, pre)),
match && (React.createElement("span", { key: 'match', className: cx('&-Option-underline-match') }, match)),
post && (React.createElement("span", { key: 'post', className: cx('&-Option-underline-post') }, post)),
];
};
this.renderOption = ({ optionProps, optionIndex, }) => {
const { searchText, selectedIndices, isLoading, optionFilter } = this.props;
return (React.createElement(DropMenu.Option, Object.assign({ key: 'SearchableMultiSelectOption' + optionIndex }, _.omit(optionProps, ['children', 'Selected', 'filterText']), { isHidden: !optionFilter(searchText, optionProps), isDisabled: optionProps.isDisabled || isLoading }),
React.createElement(CheckboxLabeled, { className: cx('&-CheckboxLabeled'), callbackId: optionIndex.toString(), isSelected: _.includes(selectedIndices, optionIndex) },
React.createElement(CheckboxLabeled.Label, null, _.isString(optionProps.children)
? this.renderUnderlinedChildren(optionProps.children, searchText)
: _.isFunction(optionProps.children)
? React.createElement(optionProps.children, { searchText })
: optionProps.children))));
};
this.renderOptions = () => {
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 = [
React.createElement(DropMenu.FixedOption, { className: cx('&-Option-select-all'), key: 'SearchableMultiSelectOption-select-all', isHidden: !hasSelectAll, isDisabled: isLoading },
React.createElement(CheckboxLabeled, { className: cx('&-CheckboxLabeled'), isSelected: isEveryVisibleOptionSelected, isIndeterminate: !isEveryVisibleOptionSelected && isAnyVisibleOptionSelected },
React.createElement(CheckboxLabeled.Label, null, selectAllText))),
].concat(_.map(optionGroups, (optionGroupProps, optionGroupIndex) => (React.createElement(DropMenu.OptionGroup, Object.assign({ key: 'SearchableMultiSelectOptionGroup' + optionGroupIndex }, _.omit(optionGroupProps, 'children', 'Selected')),
optionGroupProps.children,
_.map(optionGroupDataLookup[optionGroupIndex], option => this.renderOption(option))))).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 (React.createElement(DropMenu.Option, { isDisabled: true },
React.createElement("span", { className: cx('&-noresults') },
"No results match \"",
searchText,
"\"")));
}
return null;
};
this.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', {}) || (React.createElement(SearchableMultiSelect.SelectionLabel, null, "Selected"));
const isSmall = responsiveMode === 'small';
return (React.createElement("div", Object.assign({}, omitProps(passThroughs, undefined, _.keys(SearchableMultiSelect.propTypes)), { className: cx('&', className) }),
React.createElement(DropMenu, Object.assign({}, 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,
} }),
React.createElement(DropMenu.Control, null,
React.createElement(SearchField, Object.assign({}, 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 }))),
isLoading ? (React.createElement(DropMenu.Option, { key: 'SearchableMultiSelectLoading', className: cx('&-loading'), isDisabled: true },
React.createElement(LoadingIcon, null))) : null,
this.renderOptions()),
hasSelections && !_.isEmpty(selectedIndices) ? (React.createElement("div", { className: cx('&-Selection-padding') },
React.createElement(Selection, { className: cx('&-Selection-section'), isBold: true, hasBackground: true, kind: 'container', onRemove: this.handleRemoveAll, responsiveMode: responsiveMode, isRemovable: hasRemoveAll },
React.createElement(Selection.Label, null, selectionLabel.children ? selectionLabel.children : 'Selected'),
_.map(optionGroupDataLookup, (groupedOptionsData, optionGroupIndex) => {
const selectedGroupedOptions = _.filter(groupedOptionsData, ({ optionIndex }) => _.includes(selectedIndices, optionIndex));
if (!_.isEmpty(selectedGroupedOptions)) {
const selectedOptionGroupChildren = _.get(getFirst(optionGroups[optionGroupIndex], SearchableMultiSelect.OptionGroup.Selected), 'props.children');
return (React.createElement(Selection, { className: cx('&-Selection-group'), key: 'optionGroup-' + optionGroupIndex, responsiveMode: responsiveMode, isRemovable: false, isBold: true, kind: 'container' },
React.createElement(Selection.Label, null, !_.isNil(selectedOptionGroupChildren)
? selectedOptionGroupChildren
: _.first(rejectTypes(optionGroups[optionGroupIndex].children, SearchableMultiSelect.Option))),
_.map(selectedGroupedOptions, ({ optionIndex, optionProps }) => {
const selectionProps = _.get(getFirst(optionProps, SearchableMultiSelect.Option.Selection), 'props');
return (React.createElement(Selection, Object.assign({ key: optionIndex }, selectionProps, { callbackId: optionIndex, responsiveMode: responsiveMode, onRemove: this.handleSelectionRemove }),
React.createElement(Selection.Label, null, _.get(getFirst(optionProps, SearchableMultiSelect.Option.Selected), 'props.children') ||
(_.isFunction(optionProps.children)
? React.createElement(optionProps.children)
: optionProps.children))));
})));
}
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 (React.createElement(Selection, Object.assign({ key: selectedIndex }, selectionProps, { callbackId: selectedIndex, responsiveMode: responsiveMode, onRemove: this.handleSelectionRemove }),
React.createElement(Selection.Label, null, _.get(getFirst(optionProps, SearchableMultiSelect.Option.Selected), 'props.children') ||
(_.isFunction(optionProps.children)
? React.createElement(optionProps.children)
: optionProps.children))));
}
return null;
})))) : null,
errorChildProps &&
errorChildProps.children &&
errorChildProps.children !== true ? (React.createElement("div", Object.assign({}, omitProps(errorChildProps, undefined), { className: cx('&-error-content') }), errorChildProps.children)) : null));
};
}
UNSAFE_componentWillMount() {
// 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) {
// 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,
});
}
}
SearchableMultiSelect.displayName = 'SearchableMultiSelect';
SearchableMultiSelect.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',
],
};
SearchableMultiSelect.defaultProps = defaultProps;
SearchableMultiSelect.reducers = reducers;
SearchableMultiSelect.Option = Option;
SearchableMultiSelect.OptionGroup = OptionGroup;
SearchableMultiSelect.SearchField = SearchFieldComponent;
SearchableMultiSelect.NullOption = DropMenu.NullOption;
SearchableMultiSelect.FixedOption = DropMenu.FixedOption;
SearchableMultiSelect.DropMenu = DropMenu;
SearchableMultiSelect.SelectionLabel = Selection.Label;
SearchableMultiSelect.propTypes = {
children: node `
Should be instances of \`SearchableMultiSelect.Option\`. Other direct
child elements will not render.
`,
className: string `
Appended to the component-specific class names set on the root element.
`,
isDisabled: bool `
Disables the control from being clicked or focused.
`,
isLoading: bool `
Displays a LoadingIcon to allow for asynchronous loading of options.
`,
maxMenuHeight: oneOfType([number, string]) `
The max height of the fly-out menu.
`,
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.
`,
onSelect: func `
Called when an option is selected. Signature: \`(optionIndex, {props,
event}) => {}\` \`optionIndex\` is the new \`selectedIndex\` or \`null\`.
`,
onRemoveAll: func `
Called when the user clicks to remove all selections. Signature:
\`({props, event}) => {}\`.
`,
optionFilter: 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.
`,
searchText: string `
The current search text to filter the list of options by.
`,
selectedIndices: arrayOf(number) `
An array of currently selected \`SearchableMultiSelect.Option\` indices
or \`null\` if nothing is selected.
`,
DropMenu: shape(DropMenu.propTypes) `
Object of DropMenu props which are passed through to the underlying
DropMenu component.
`,
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.
`,
responsiveMode: oneOf(['small', 'medium', 'large']) `
Adjusts the display of this component. This should typically be driven by
screen size. Currently \`small\` and \`large\` are explicitly handled by
this component.
`,
hasRemoveAll: bool `
Controls the visibility of the "remove all" button that's shown with the
selected items.
`,
hasSelections: bool `
Controls the visibility of the \`Selection\` component that appears below
the search field.
`,
hasSelectAll: bool `
Controls whether to show a "Select All" option.
`,
selectAllText: string `
The select all text.
`,
Error: any `
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\`.
`,
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.
`,
};
export default buildModernHybridComponent(SearchableMultiSelect, { reducers });
export { SearchableMultiSelect as SearchableMultiSelectDumb };