avlmap
Version:
Avail Map by Avail Labs
565 lines (469 loc) • 22.4 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var _react = _interopRequireWildcard(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _fuzzy = _interopRequireDefault(require("fuzzy"));
var _classnames = _interopRequireDefault(require("classnames"));
var _styledComponents = _interopRequireDefault(require("styled-components"));
var _accessor = _interopRequireDefault(require("./accessor.js"));
var _keyevent = _interopRequireDefault(require("./keyevent.js"));
var _dropdownList = _interopRequireWildcard(require("./dropdown-list.js"));
var _icons = require("../icons");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
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); }
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 _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 _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; }
function _templateObject4() {
var data = _taggedTemplateLiteral(["\n position: absolute;\n right: 15px;\n top: 14px;\n background-color: transparent !important;\n color: ", ";\n * {\n background-color: transparent !important;\n }\n"]);
_templateObject4 = function _templateObject4() {
return data;
};
return data;
}
function _templateObject3() {
var data = _taggedTemplateLiteral(["\n ", "\n background-color: #ffffff;\n :hover {\n cursor: pointer;\n background-color: ", ";\n }\n"]);
_templateObject3 = function _templateObject3() {
return data;
};
return data;
}
function _templateObject2() {
var data = _taggedTemplateLiteral(["\n padding: 8px;\n"]);
_templateObject2 = function _templateObject2() {
return data;
};
return data;
}
function _templateObject() {
var data = _taggedTemplateLiteral(["\n display: flex;\n flex-direction: column;\n background-color: ", ";\n box-shadow: ", ";\n\n :focus {\n outline: 0;\n }\n"]);
_templateObject = function _templateObject() {
return data;
};
return data;
}
function _taggedTemplateLiteral(strings, raw) { if (!raw) { raw = strings.slice(0); } return Object.freeze(Object.defineProperties(strings, { raw: { value: Object.freeze(raw) } })); }
var DEFAULT_CLASS = 'typeahead';
/**
* Copied mostly from 'react-typeahead', an auto-completing text input
*
* Renders an text input that shows options nearby that you can use the
* keyboard or mouse to select.
*/
var TypeaheadWrapper = _styledComponents["default"].div(_templateObject(), function (props) {
return props.theme.dropdownListBgd;
}, function (props) {
return props.theme.dropdownListShadow;
});
var InputBox = _styledComponents["default"].div(_templateObject2());
var TypeaheadInput = _styledComponents["default"].input(_templateObject3(), function (props) {
return props.theme.secondaryInput;
}, function (props) {
return props.theme.secondaryInputBgd;
});
var InputIcon = _styledComponents["default"].div(_templateObject4(), function (props) {
return props.theme.inputPlaceholderColor;
});
var Typeahead = /*#__PURE__*/function (_Component) {
_inherits(Typeahead, _Component);
var _super = _createSuper(Typeahead);
function Typeahead(props) {
var _this;
_classCallCheck(this, Typeahead);
_this = _super.call(this, props);
_defineProperty(_assertThisInitialized(_this), "_onOptionSelected", function (option, event) {
if (_this.props.searchable) {
// reset entry input
_this.setState({
searchResults: _this.getOptionsForValue('', _this.props.options),
selection: '',
entryValue: ''
});
}
return _this.props.onOptionSelected(option, event);
});
_defineProperty(_assertThisInitialized(_this), "_onTextEntryUpdated", function () {
if (_this.props.searchable) {
var value = _this.entry.value;
_this.setState({
searchResults: _this.getOptionsForValue(value, _this.props.options),
selection: '',
entryValue: value
});
}
});
_defineProperty(_assertThisInitialized(_this), "_onEnter", function (event) {
var selection = _this.getSelection();
if (!selection) {
return _this.props.onKeyDown(event);
}
return _this._onOptionSelected(selection, event);
});
_defineProperty(_assertThisInitialized(_this), "navDown", function () {
_this._nav(1);
});
_defineProperty(_assertThisInitialized(_this), "navUp", function () {
_this._nav(-1);
});
_defineProperty(_assertThisInitialized(_this), "_onChange", function (event) {
if (_this.props.onChange) {
_this.props.onChange(event);
}
_this._onTextEntryUpdated();
});
_defineProperty(_assertThisInitialized(_this), "_onKeyDown", function (event) {
// If there are no visible elements, don't perform selector navigation.
// Just pass this up to the upstream onKeydown handler.
// Also skip if the user is pressing the shift key, since none of our handlers are looking for shift
if (!_this._hasHint() || event.shiftKey) {
return _this.props.onKeyDown(event);
}
var handler = _this.eventMap()[event.keyCode];
if (handler) {
handler(event);
} else {
return _this.props.onKeyDown(event);
} // Don't propagate the keystroke back to the DOM/browser
event.preventDefault();
});
_defineProperty(_assertThisInitialized(_this), "_onFocus", function (event) {
_this.setState({
isFocused: true
});
if (_this.props.onFocus) {
return _this.props.onFocus(event);
}
});
_defineProperty(_assertThisInitialized(_this), "_onBlur", function (event) {
_this.setState({
isFocused: false
});
if (_this.props.onBlur) {
return _this.props.onBlur(event);
}
});
_this.state = {
searchResults: _this.getOptionsForValue(_this.props.initialValue, _this.props.options),
// This should be called something else, 'entryValue'
entryValue: _this.props.value || _this.props.initialValue,
// A valid typeahead value
selection: _this.props.value,
// MapPopover of the selection
selectionIndex: null,
// Keep track of the focus state of the input element, to determine
// whether to show options when empty (if showOptionsWhenEmpty is true)
isFocused: false
};
return _this;
}
_createClass(Typeahead, [{
key: "componentDidMount",
value: function componentDidMount() {
this.setState({
searchResults: this.getOptionsForValue('', this.props.options)
}); // call focus on entry or div to trigger key events listener
if (this.entry) {
this.entry.focus();
} else {
this.root.focus();
}
}
}, {
key: "componentWillReceiveProps",
value: function componentWillReceiveProps(nextProps) {
var searchResults = this.getOptionsForValue(this.state.entryValue, nextProps.options);
this.setState({
searchResults: searchResults
});
}
}, {
key: "_shouldSkipSearch",
value: function _shouldSkipSearch(input) {
var emptyValue = !input || input.trim().length === 0; // this.state must be checked because it may not be defined yet if this function
// is called from within getInitialState
var isFocused = this.state && this.state.isFocused;
return !(this.props.showOptionsWhenEmpty && isFocused) && emptyValue;
}
}, {
key: "getOptionsForValue",
value: function getOptionsForValue(value, options) {
if (!this.props.searchable) {
// directly pass through options if can not be searched
return options;
}
if (this._shouldSkipSearch(value)) {
return options;
} // const searchOptions = this._generateSearchFunction();
// return searchOptions(value, options);
var selector = this.props.displayOption;
return options.reduce(function (a, c) {
return selector(c).toString().toLowerCase().includes(value.toLowerCase()) ? a.concat(c) : a;
}, []);
}
}, {
key: "focus",
value: function focus() {
if (this.entry) {
this.entry.focus();
}
}
}, {
key: "_hasCustomValue",
value: function _hasCustomValue() {
return this.props.allowCustomValues > 0 && this.state.entryValue.length >= this.props.allowCustomValues && this.state.searchResults.indexOf(this.state.entryValue) < 0;
}
}, {
key: "_getCustomValue",
value: function _getCustomValue() {
return this._hasCustomValue() ? this.state.entryValue : null;
}
}, {
key: "_renderIncrementalSearchResults",
value: function _renderIncrementalSearchResults() {
return /*#__PURE__*/_react["default"].createElement(this.props.customListComponent, {
fixedOptions: this.props.fixedOptions,
options: this.props.maxVisible ? this.state.searchResults.slice(0, this.props.maxVisible) : this.state.searchResults,
areResultsTruncated: this.props.maxVisible && this.state.searchResults.length > this.props.maxVisible,
resultsTruncatedMessage: this.props.resultsTruncatedMessage,
onOptionSelected: this._onOptionSelected,
allowCustomValues: this.props.allowCustomValues,
customValue: this._getCustomValue(),
customClasses: this.props.customClasses,
customListItemComponent: this.props.customListItemComponent,
customListHeaderComponent: this.props.customListHeaderComponent,
selectionIndex: this.state.selectionIndex,
defaultClassNames: this.props.defaultClassNames,
displayOption: this.props.displayOption,
selectedItems: this.props.selectedItems
});
}
}, {
key: "getSelection",
value: function getSelection() {
var index = this.state.selectionIndex;
if (this._hasCustomValue()) {
if (index === 0) {
return this.state.entryValue;
}
index--;
}
if (this._hasFixedOptions()) {
return index < this.props.fixedOptions.length ? this.props.fixedOptions[index] : this.state.searchResults[index - this.props.fixedOptions.length];
}
return this.state.searchResults[index];
}
}, {
key: "_onEscape",
value: function _onEscape() {
this.setState({
selectionIndex: null
});
}
}, {
key: "_onTab",
value: function _onTab(event) {
var selection = this.getSelection();
var option = selection ? selection : this.state.searchResults.length > 0 ? this.state.searchResults[0] : null;
if (option === null && this._hasCustomValue()) {
option = this._getCustomValue();
}
if (option !== null) {
return this._onOptionSelected(option, event);
}
}
}, {
key: "eventMap",
value: function eventMap(event) {
var events = {};
events[_keyevent["default"].DOM_VK_UP] = this.navUp;
events[_keyevent["default"].DOM_VK_DOWN] = this.navDown;
events[_keyevent["default"].DOM_VK_RETURN] = events[_keyevent["default"].DOM_VK_ENTER] = this._onEnter;
events[_keyevent["default"].DOM_VK_ESCAPE] = this._onEscape;
events[_keyevent["default"].DOM_VK_TAB] = this._onTab;
return events;
}
}, {
key: "_nav",
value: function _nav(delta) {
if (!this._hasHint()) {
return;
}
var newIndex = this.state.selectionIndex === null ? delta === 1 ? 0 : delta : this.state.selectionIndex + delta;
var length = this.props.maxVisible ? this.state.searchResults.slice(0, this.props.maxVisible).length : this.state.searchResults.length;
if (this._hasCustomValue()) {
length += 1;
}
if (newIndex < 0) {
newIndex += length;
} else if (newIndex >= length) {
newIndex -= length;
}
this.setState({
selectionIndex: newIndex
});
}
}, {
key: "_renderHiddenInput",
value: function _renderHiddenInput() {
if (!this.props.name) {
return null;
}
return /*#__PURE__*/_react["default"].createElement("input", {
type: "hidden",
name: this.props.name,
value: this.state.selection
});
}
}, {
key: "_generateSearchFunction",
value: function _generateSearchFunction() {
var searchOptionsProp = this.props.searchOptions;
var filterOptionProp = this.props.filterOption;
if (typeof searchOptionsProp === 'function') {
if (filterOptionProp !== null) {
console.warn('searchOptions prop is being used, filterOption prop will be ignored');
}
return searchOptionsProp;
} else if (typeof filterOptionProp === 'function') {
// use custom filter option
return function (value, options) {
return options.filter(function (o) {
return filterOptionProp(value, o);
});
};
}
var mapper = typeof filterOptionProp === 'string' ? _accessor["default"].generateAccessor(filterOptionProp) : _accessor["default"].IDENTITY_FN;
return function (value, options) {
return _fuzzy["default"].filter(value, options, {
extract: mapper
}).map(function (res) {
return options[res.HomePage];
});
};
}
}, {
key: "_hasHint",
value: function _hasHint() {
return this.state.searchResults.length > 0 || this._hasCustomValue();
}
}, {
key: "_hasFixedOptions",
value: function _hasFixedOptions() {
return Array.isArray(this.props.fixedOptions) && this.props.fixedOptions.length;
}
}, {
key: "render",
value: function render() {
var _this2 = this;
var inputClasses = {};
inputClasses[this.props.customClasses.input] = Boolean(this.props.customClasses.input);
var inputClassList = (0, _classnames["default"])(inputClasses);
var classes = _defineProperty({}, DEFAULT_CLASS, this.props.defaultClassNames);
classes[this.props.className] = Boolean(this.props.className);
var classList = (0, _classnames["default"])(classes);
return /*#__PURE__*/_react["default"].createElement(TypeaheadWrapper, {
className: classList,
ref: function ref(comp) {
_this2.root = comp;
},
tabIndex: "0",
onKeyDown: this._onKeyDown,
onKeyPress: this.props.onKeyPress,
onKeyUp: this.props.onKeyUp,
onFocus: this._onFocus
}, this._renderHiddenInput(), this.props.searchable ? /*#__PURE__*/_react["default"].createElement(InputBox, null, /*#__PURE__*/_react["default"].createElement(TypeaheadInput, _extends({
ref: function ref(comp) {
_this2.entry = comp;
},
type: "text",
disabled: this.props.disabled
}, this.props.inputProps, {
placeholder: this.props.placeholder,
className: inputClassList,
value: this.state.entryValue,
onChange: this._onChange,
onBlur: this._onBlur
})), /*#__PURE__*/_react["default"].createElement(InputIcon, null, /*#__PURE__*/_react["default"].createElement(_icons.Search, {
height: "18px"
}))) : null, this._renderIncrementalSearchResults());
}
}]);
return Typeahead;
}(_react.Component);
exports["default"] = Typeahead;
;
Typeahead.propTypes = {
name: _propTypes["default"].string,
customClasses: _propTypes["default"].object,
maxVisible: _propTypes["default"].number,
resultsTruncatedMessage: _propTypes["default"].string,
options: _propTypes["default"].arrayOf(_propTypes["default"].any),
fixedOptions: _propTypes["default"].arrayOf(_propTypes["default"].any),
allowCustomValues: _propTypes["default"].number,
initialValue: _propTypes["default"].string,
value: _propTypes["default"].string,
placeholder: _propTypes["default"].string,
disabled: _propTypes["default"].bool,
textarea: _propTypes["default"].bool,
inputProps: _propTypes["default"].object,
onOptionSelected: _propTypes["default"].func,
onChange: _propTypes["default"].func,
onKeyDown: _propTypes["default"].func,
onKeyPress: _propTypes["default"].func,
onKeyUp: _propTypes["default"].func,
onFocus: _propTypes["default"].func,
onBlur: _propTypes["default"].func,
filterOption: _propTypes["default"].oneOfType([_propTypes["default"].string, _propTypes["default"].func]),
searchOptions: _propTypes["default"].func,
displayOption: _propTypes["default"].oneOfType([_propTypes["default"].string, _propTypes["default"].func]),
inputDisplayOption: _propTypes["default"].oneOfType([_propTypes["default"].string, _propTypes["default"].func]),
formInputOption: _propTypes["default"].oneOfType([_propTypes["default"].string, _propTypes["default"].func]),
defaultClassNames: _propTypes["default"].bool,
customListComponent: _propTypes["default"].oneOfType([_propTypes["default"].element, _propTypes["default"].func]),
customListItemComponent: _propTypes["default"].oneOfType([_propTypes["default"].element, _propTypes["default"].func]),
customListHeaderComponent: _propTypes["default"].oneOfType([_propTypes["default"].element, _propTypes["default"].func]),
showOptionsWhenEmpty: _propTypes["default"].bool,
searchable: _propTypes["default"].bool
};
Typeahead.defaultProps = {
options: [],
customClasses: {},
allowCustomValues: 0,
initialValue: '',
value: '',
placeholder: '',
disabled: false,
textarea: false,
inputProps: {},
onOptionSelected: function onOptionSelected(option) {},
onChange: function onChange(event) {},
onKeyDown: function onKeyDown(event) {},
onKeyPress: function onKeyPress(event) {},
onKeyUp: function onKeyUp(event) {},
onFocus: function onFocus(event) {},
onBlur: function onBlur(event) {},
filterOption: null,
searchOptions: null,
inputDisplayOption: null,
defaultClassNames: true,
customListComponent: _dropdownList["default"],
customListItemComponent: _dropdownList.ListItem,
customListHeaderComponent: null,
showOptionsWhenEmpty: true,
searchable: true,
resultsTruncatedMessage: null
};