lucid-ui
Version:
A UI component library from AppNexus.
455 lines (373 loc) • 23.5 kB
JavaScript
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
import _assign from "lodash/assign";
import _keys from "lodash/keys";
import _isNil from "lodash/isNil";
import _first from "lodash/first";
import _get from "lodash/get";
import _isEmpty from "lodash/isEmpty";
import _reject from "lodash/reject";
import _omit from "lodash/omit";
import _isFunction from "lodash/isFunction";
import _isString from "lodash/isString";
import _escapeRegExp from "lodash/escapeRegExp";
import _findIndex from "lodash/findIndex";
import _map from "lodash/map";
import _noop from "lodash/noop";
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
function _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
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 } 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 Selection from '../Selection/Selection';
import { Validation } from '../Validation/Validation';
import * as reducers from './SearchableSingleSelect.reducers';
var any = PropTypes.any,
bool = PropTypes.bool,
func = PropTypes.func,
number = PropTypes.number,
oneOfType = PropTypes.oneOfType,
shape = PropTypes.shape,
string = PropTypes.string,
node = PropTypes.node;
var cx = lucidClassNames.bind('&-SearchableSingleSelect');
/** Option Group Child Component */
var OptionGroup = function OptionGroup(_props) {
return null;
};
OptionGroup.displayName = 'SearchableSingleSelect.OptionGroup';
OptionGroup.peek = {
description: "\n\t\tA special kind of `Option` that is always rendered at the top of\n\t\tthe menu and has an `optionIndex` of `null`. Useful for\n\t\tunselect.\n\t"
};
OptionGroup.propName = 'OptionGroup';
OptionGroup.propTypes = DropMenu.OptionGroup.propTypes;
OptionGroup.defaultProps = DropMenu.OptionGroup.defaultProps;
/** Search Field Child Component */
var SearchFieldComponent = function SearchFieldComponent(_props) {
return null;
};
SearchFieldComponent.displayName = 'SearchableSingleSelect.SearchField';
SearchFieldComponent.peek = {
description: "\n\t\tPasses props through to the `Search Field`.\n\t"
};
SearchFieldComponent.propName = 'SearchField';
SearchFieldComponent.propTypes = SearchField.propTypes;
SearchFieldComponent.defaultProps = SearchField.defaultProps;
/** Option Child Component w/ Selection property */
var Selected = function Selected(_props) {
return null;
};
Selected.displayName = 'SearchableSingleSelect.Option.Selected';
Selected.peek = {
description: "\n\t\tCustomizes the rendering of the Option when it is selected\n\t\tand is displayed instead of the Placeholder.\n\t"
};
Selected.propName = 'Selected';
Selected.propTypes = {};
var Option = function Option(_props) {
return null;
};
Option.displayName = 'SearchableSingleSelect.Option';
Option.peek = {
description: "\n\t\tA selectable option in the list.\n\t"
};
Option.Selected = Selected;
Option.propName = 'Option';
Option.propTypes = _objectSpread({
Selected: any,
value: string,
filterText: string
}, DropMenu.Option.propTypes);
Option.defaultProps = DropMenu.Option.defaultProps;
var defaultProps = {
isDisabled: false,
isLoading: false,
optionFilter: propsSearch,
searchText: '',
selectedIndex: null,
DropMenu: DropMenu.defaultProps,
Error: null,
onSearch: _noop,
onSelect: _noop,
SearchField: SearchField.defaultProps
};
var SearchableSingleSelect = /*#__PURE__*/function (_React$Component) {
_inherits(SearchableSingleSelect, _React$Component);
var _super = _createSuper(SearchableSingleSelect);
function SearchableSingleSelect() {
var _this;
_classCallCheck(this, SearchableSingleSelect);
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _super.call.apply(_super, [this].concat(args));
_defineProperty(_assertThisInitialized(_this), "handleSearch", function (searchText, _ref) {
var event = _ref.event;
var _assertThisInitialize = _assertThisInitialized(_this),
props = _assertThisInitialize.props,
_assertThisInitialize2 = _assertThisInitialize.props,
onSearch = _assertThisInitialize2.onSearch,
optionFilter = _assertThisInitialize2.optionFilter,
onExpand = _assertThisInitialize2.DropMenu.onExpand;
var options = _map(findTypes(props, SearchableSingleSelect.Option), 'props');
var firstVisibleIndex = _findIndex(options, function (option) {
return optionFilter(searchText, option);
});
var firstVisibleProps = options[firstVisibleIndex]; // Just an extra call to make sure the search results show up when a user
// is typing
var dropMenuProps = _this.props.DropMenu;
onExpand && onExpand({
event: event,
props: dropMenuProps
});
return onSearch(searchText, firstVisibleIndex, {
event: event,
props: firstVisibleProps
});
});
_defineProperty(_assertThisInitialized(_this), "renderUnderlinedChildren", function (childText, searchText) {
var _partitionText = partitionText(childText, new RegExp(_escapeRegExp(searchText), 'i'), searchText.length),
_partitionText2 = _slicedToArray(_partitionText, 3),
pre = _partitionText2[0],
match = _partitionText2[1],
post = _partitionText2[2];
return [pre && /*#__PURE__*/React.createElement("span", {
key: "pre",
className: cx('&-Option-underline-pre')
}, pre), match && /*#__PURE__*/React.createElement("span", {
key: "match",
className: cx('&-Option-underline-match')
}, match), post && /*#__PURE__*/React.createElement("span", {
key: "post",
className: cx('&-Option-underline-post')
}, post)];
});
_defineProperty(_assertThisInitialized(_this), "renderOptionContent", function (optionProps, searchText) {
return _isString(optionProps.children) && _isString(searchText) && searchText.length > 0 ? _this.renderUnderlinedChildren(optionProps.children, searchText) : _isFunction(optionProps.children) ? /*#__PURE__*/React.createElement(optionProps.children, {
searchText: searchText
}) : optionProps.children;
});
_defineProperty(_assertThisInitialized(_this), "renderOption", function (_ref2) {
var optionProps = _ref2.optionProps,
optionIndex = _ref2.optionIndex;
var _this$props = _this.props,
searchText = _this$props.searchText,
isLoading = _this$props.isLoading,
optionFilter = _this$props.optionFilter;
return /*#__PURE__*/React.createElement(DropMenu.Option, _extends({
key: 'SearchableSingleSelectOption' + optionIndex
}, _omit(optionProps, ['children', 'Selected', 'filterText']), {
isHidden: !optionFilter(searchText, optionProps),
isDisabled: optionProps.isDisabled || isLoading
}), _this.renderOptionContent(optionProps, searchText));
});
_defineProperty(_assertThisInitialized(_this), "renderOptions", function () {
var _this$props2 = _this.props,
searchText = _this$props2.searchText,
isLoading = _this$props2.isLoading;
var _this$state = _this.state,
optionGroups = _this$state.optionGroups,
optionGroupDataLookup = _this$state.optionGroupDataLookup,
ungroupedOptionData = _this$state.ungroupedOptionData,
flattenedOptionsData = _this$state.flattenedOptionsData;
var visibleOptions = _reject(flattenedOptionsData, 'optionProps.isHidden');
var isAllOptionsHidden = _isEmpty(visibleOptions); // 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
var dropMenuOptions = _map(optionGroups, function (optionGroupProps, optionGroupIndex) {
return /*#__PURE__*/React.createElement(DropMenu.OptionGroup, _extends({
key: 'SearchableSingleSelectOptionGroup' + optionGroupIndex
}, _omit(optionGroupProps, 'children', 'Selected')), optionGroupProps.children, _map(optionGroupDataLookup[optionGroupIndex], _this.renderOption));
}).concat( // then render all the ungrouped options at the end
_map(ungroupedOptionData, function (options) {
return _this.renderOption(options);
}));
if (!isAllOptionsHidden || _isEmpty(searchText)) {
return dropMenuOptions;
}
if (!isLoading) {
return /*#__PURE__*/React.createElement(DropMenu.Option, {
isDisabled: true
}, /*#__PURE__*/React.createElement("span", {
className: cx('&-noresults')
}, "No results match \"", searchText, "\""));
}
return null;
});
_defineProperty(_assertThisInitialized(_this), "removeSelection", function (_ref3) {
var event = _ref3.event,
props = _ref3.props;
var dropMenuProps = _this.props.DropMenu;
_this.props.DropMenu.onCollapse && _this.props.DropMenu.onCollapse({
event: event,
props: dropMenuProps
});
_this.props.onSearch('', null, {
event: event,
props: props
});
_this.props.onSelect(null, {
event: event,
props: props
});
});
_defineProperty(_assertThisInitialized(_this), "render", function () {
var _assertThisInitialize3 = _assertThisInitialized(_this),
props = _assertThisInitialize3.props,
_assertThisInitialize4 = _assertThisInitialize3.props,
className = _assertThisInitialize4.className,
isLoading = _assertThisInitialize4.isLoading,
isDisabled = _assertThisInitialize4.isDisabled,
maxMenuHeight = _assertThisInitialize4.maxMenuHeight,
dropMenuProps = _assertThisInitialize4.DropMenu,
optionContainerStyle = _assertThisInitialize4.DropMenu.optionContainerStyle,
searchText = _assertThisInitialize4.searchText,
selectedIndex = _assertThisInitialize4.selectedIndex,
onSelect = _assertThisInitialize4.onSelect,
passThroughs = _objectWithoutProperties(_assertThisInitialize4, ["className", "isLoading", "isDisabled", "maxMenuHeight", "DropMenu", "DropMenu", "searchText", "selectedIndex", "onSelect"]);
var searchFieldProps = _get(getFirst(props, SearchableSingleSelect.SearchField), 'props', {});
var errorChildProps = _first(_map(findTypes(props, Validation.Error), 'props')); //user made a selection
if (!_isNil(selectedIndex)) {
var selectedOptionProps = _this.state.flattenedOptionsData[selectedIndex].optionProps;
return /*#__PURE__*/React.createElement("div", _extends({}, omitProps(passThroughs, undefined, _keys(SearchableSingleSelect.propTypes)), {
className: cx('&', className)
}), /*#__PURE__*/React.createElement(Selection, {
Label: _isNil(selectedOptionProps.Selected) ? _this.renderOptionContent(selectedOptionProps, '') : selectedOptionProps.Selected,
className: cx('&', {
'&-select-error': errorChildProps && errorChildProps.children && errorChildProps.children !== true
}, className),
onRemove: _this.removeSelection,
kind: "default"
}), errorChildProps && errorChildProps.children && errorChildProps.children !== true ? /*#__PURE__*/React.createElement("div", _extends({}, omitProps(errorChildProps, undefined), {
className: cx('&-error-select-content')
}), errorChildProps.children) : null);
}
return /*#__PURE__*/React.createElement("div", _extends({}, omitProps(passThroughs, undefined, _keys(SearchableSingleSelect.propTypes)), {
className: cx('&', className)
}), /*#__PURE__*/React.createElement(DropMenu, _extends({}, dropMenuProps, {
selectedIndices: null,
className: cx('&-DropMenu', {
'&-DropMenu-is-small': true
}, dropMenuProps.className),
optionContainerStyle: _assign({}, optionContainerStyle, !_isNil(maxMenuHeight) ? {
maxHeight: maxMenuHeight
} : null),
isDisabled: isDisabled,
onSelect: onSelect,
ContextMenu: {
alignmentOffset: -13,
directonOffset: -1,
minWidthOffset: -28
}
}), /*#__PURE__*/React.createElement(DropMenu.Control, null, /*#__PURE__*/React.createElement(SearchField, _extends({}, searchFieldProps, {
autoComplete: searchFieldProps.autoComplete || 'off',
isDisabled: isDisabled,
className: cx('&-search', {
'&-search-is-error': errorChildProps && errorChildProps.children
}, searchFieldProps.className),
value: searchText,
onChange: _this.handleSearch
}))), isLoading ? /*#__PURE__*/React.createElement(DropMenu.Option, {
key: "SearchableSingleSelectLoading",
className: cx('&-loading'),
isDisabled: true
}, /*#__PURE__*/React.createElement(LoadingIcon, null)) : null, _this.renderOptions()), errorChildProps && errorChildProps.children && errorChildProps.children !== true ? /*#__PURE__*/React.createElement("div", _extends({}, omitProps(errorChildProps, undefined), {
className: cx('&-error-content')
}), errorChildProps.children) : null);
});
return _this;
}
_createClass(SearchableSingleSelect, [{
key: "UNSAFE_componentWillMount",
value: function UNSAFE_componentWillMount() {
// preprocess the options data before rendering
var _DropMenu$preprocessO = DropMenu.preprocessOptionData(this.props, SearchableSingleSelect),
optionGroups = _DropMenu$preprocessO.optionGroups,
flattenedOptionsData = _DropMenu$preprocessO.flattenedOptionsData,
ungroupedOptionData = _DropMenu$preprocessO.ungroupedOptionData,
optionGroupDataLookup = _DropMenu$preprocessO.optionGroupDataLookup;
this.setState({
optionGroups: optionGroups,
flattenedOptionsData: flattenedOptionsData,
ungroupedOptionData: ungroupedOptionData,
optionGroupDataLookup: optionGroupDataLookup
});
}
}, {
key: "UNSAFE_componentWillReceiveProps",
value: function UNSAFE_componentWillReceiveProps(nextProps) {
// only preprocess options data when it changes (via new props) - better performance than doing this each render
var _DropMenu$preprocessO2 = DropMenu.preprocessOptionData(nextProps, SearchableSingleSelect),
optionGroups = _DropMenu$preprocessO2.optionGroups,
flattenedOptionsData = _DropMenu$preprocessO2.flattenedOptionsData,
ungroupedOptionData = _DropMenu$preprocessO2.ungroupedOptionData,
optionGroupDataLookup = _DropMenu$preprocessO2.optionGroupDataLookup;
this.setState({
optionGroups: optionGroups,
flattenedOptionsData: flattenedOptionsData,
ungroupedOptionData: ungroupedOptionData,
optionGroupDataLookup: optionGroupDataLookup
});
}
}]);
return SearchableSingleSelect;
}(React.Component);
_defineProperty(SearchableSingleSelect, "displayName", 'SearchableSingleSelect');
_defineProperty(SearchableSingleSelect, "peek", {
description: "\n\t\t\tA control used to select a single option from a dropdown list using a SearchField.\n\t\t",
categories: ['controls', 'selectors'],
madeFrom: ['Checkbox', 'SearchField', 'DropMenu', 'LoadingIcon']
});
_defineProperty(SearchableSingleSelect, "defaultProps", defaultProps);
_defineProperty(SearchableSingleSelect, "reducers", reducers);
_defineProperty(SearchableSingleSelect, "Option", Option);
_defineProperty(SearchableSingleSelect, "OptionGroup", OptionGroup);
_defineProperty(SearchableSingleSelect, "SearchField", SearchFieldComponent);
_defineProperty(SearchableSingleSelect, "NullOption", DropMenu.NullOption);
_defineProperty(SearchableSingleSelect, "FixedOption", DropMenu.FixedOption);
_defineProperty(SearchableSingleSelect, "DropMenu", DropMenu);
_defineProperty(SearchableSingleSelect, "propTypes", {
children: node,
className: string,
isDisabled: bool,
isLoading: bool,
maxMenuHeight: oneOfType([number, string]),
onSearch: func,
onSelect: func,
optionFilter: func,
searchText: string,
selectedIndex: number,
DropMenu: shape(DropMenu.propTypes),
Option: any,
Error: any,
FixedOption: any,
NullOption: any,
OptionGroup: any,
SearchField: any
});
export default buildModernHybridComponent(SearchableSingleSelect, {
reducers: reducers
});
export { SearchableSingleSelect as SearchableSingleSelectDumb };