UNPKG

terra-search-field

Version:

A search component with a field that automatically performs a search callback after user input.

327 lines (325 loc) 18.5 kB
"use strict"; function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _react = _interopRequireDefault(require("react")); var _propTypes = _interopRequireDefault(require("prop-types")); var _classnames = _interopRequireDefault(require("classnames")); var _bind = _interopRequireDefault(require("classnames/bind")); var _terraThemeContext = _interopRequireDefault(require("terra-theme-context")); var _terraButton = _interopRequireDefault(require("terra-button")); var KeyCode = _interopRequireWildcard(require("keycode-js")); var _IconSearch = _interopRequireDefault(require("terra-icon/lib/icon/IconSearch")); var _reactIntl = require("react-intl"); var _SearchFieldModule = _interopRequireDefault(require("./SearchField.module.scss")); var _excluded = ["defaultValue", "disableAutoSearch", "inputRefCallback", "inputAttributes", "intl", "isBlock", "isDisabled", "minimumSearchTextLength", "onChange", "onInput", "onInvalidSearch", "onSearch", "placeholder", "searchDelay", "value"]; function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && 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 _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _extends() { _extends = Object.assign ? Object.assign.bind() : 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 ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); 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 = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } 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 _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, _toPropertyKey(descriptor.key), descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } 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 } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : 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; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } 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 { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } var cx = _bind.default.bind(_SearchFieldModule.default); var Icon = /*#__PURE__*/_react.default.createElement(_IconSearch.default, null); var propTypes = { /** * The defaultValue of the search field. Use this to create an uncontrolled search field. */ defaultValue: _propTypes.default.string, /** * When true, will disable the auto-search. */ disableAutoSearch: _propTypes.default.bool, /** * Callback ref to pass into the inner input component. */ inputRefCallback: _propTypes.default.func, /** * Custom input attributes to apply to the input field such as aria-label. */ // eslint-disable-next-line react/forbid-prop-types inputAttributes: _propTypes.default.object, /** * @private * The intl object containing translations. This is retrieved from the context automatically by injectIntl. */ intl: _propTypes.default.shape({ formatMessage: _propTypes.default.func }).isRequired, /** * Whether or not the field should display as a block. */ isBlock: _propTypes.default.bool, /** * When true, will disable the field. */ isDisabled: _propTypes.default.bool, /** * The minimum number of characters to perform a search. */ minimumSearchTextLength: _propTypes.default.number, /** * Function to trigger when user changes the input value. Provide a function to create a controlled input. */ onChange: _propTypes.default.func, /** * Function to trigger when user inputs a value. Use when programmatically setting a value. Sends parameter {Event} event. */ onInput: _propTypes.default.func, /** * A callback to indicate an invalid search. Sends parameter {String} searchText. */ onInvalidSearch: _propTypes.default.func, /** * A callback to perform search. Sends parameter {String} searchText. */ onSearch: _propTypes.default.func, /** * Placeholder text to show while the search field is empty. */ placeholder: _propTypes.default.string, /** * How long the component should wait (in milliseconds) after input before performing an automatic search. */ searchDelay: _propTypes.default.number, /** * The value of search field. Use this to create a controlled search field. */ value: _propTypes.default.string }; var defaultProps = { defaultValue: undefined, disableAutoSearch: false, isBlock: false, isDisabled: false, minimumSearchTextLength: 2, placeholder: '', searchDelay: 250, value: undefined, inputAttributes: undefined }; var SearchField = /*#__PURE__*/function (_React$Component) { _inherits(SearchField, _React$Component); var _super = _createSuper(SearchField); function SearchField(props) { var _this; _classCallCheck(this, SearchField); _this = _super.call(this, props); _this.handleClear = _this.handleClear.bind(_assertThisInitialized(_this)); _this.handleTextChange = _this.handleTextChange.bind(_assertThisInitialized(_this)); _this.handleSearch = _this.handleSearch.bind(_assertThisInitialized(_this)); _this.handleKeyDown = _this.handleKeyDown.bind(_assertThisInitialized(_this)); _this.handleInput = _this.handleInput.bind(_assertThisInitialized(_this)); _this.setInputRef = _this.setInputRef.bind(_assertThisInitialized(_this)); _this.updateSearchText = _this.updateSearchText.bind(_assertThisInitialized(_this)); _this.searchTimeout = null; _this.searchText = _this.props.defaultValue || _this.props.value; _this.searchBtnRef = /*#__PURE__*/_react.default.createRef(); return _this; } _createClass(SearchField, [{ key: "componentDidUpdate", value: function componentDidUpdate() { // if consumer updates the value prop with onChange, need to update variable to match this.updateSearchText(this.props.value); } }, { key: "componentWillUnmount", value: function componentWillUnmount() { this.clearSearchTimeout(); } }, { key: "handleClear", value: function handleClear(event) { // Pass along changes to consuming components using associated props if (this.props.onChange) { this.props.onChange(event, ''); } if (this.props.onInvalidSearch) { this.props.onInvalidSearch(''); } this.updateSearchText(''); // Clear input field if (this.inputRef) { this.inputRef.value = ''; this.inputRef.focus(); } } }, { key: "handleTextChange", value: function handleTextChange(event) { var textValue = event.target.value; this.updateSearchText(textValue); if (this.props.onChange) { this.props.onChange(event, textValue); } if (!this.props.disableAutoSearch) { this.clearSearchTimeout(); this.searchTimeout = setTimeout(this.handleSearch, this.props.searchDelay); } } }, { key: "handleInput", value: function handleInput(event) { var textValue = event.target.value; this.updateSearchText(textValue); if (this.props.onInput) { this.props.onInput(event); } } }, { key: "handleKeyDown", value: function handleKeyDown(event) { if (event.nativeEvent.keyCode === KeyCode.KEY_RETURN) { event.preventDefault(); // set focus to search button to hide keyboard on mobile devices this.searchBtnRef.current.focus(); this.handleSearch(); } if (event.nativeEvent.keyCode === KeyCode.KEY_ESCAPE) { this.handleClear(event); } } }, { key: "handleSearch", value: function handleSearch() { this.clearSearchTimeout(); var searchText = this.searchText || ''; if (searchText.length >= this.props.minimumSearchTextLength && this.props.onSearch) { this.props.onSearch(searchText); } else if (this.props.onInvalidSearch) { this.props.onInvalidSearch(searchText); } } }, { key: "setInputRef", value: function setInputRef(node) { this.inputRef = node; if (this.props.inputRefCallback) { this.props.inputRefCallback(node); } } }, { key: "updateSearchText", value: function updateSearchText(searchText) { if (typeof searchText !== 'undefined' && searchText !== this.searchText) { this.searchText = searchText; // Forcing update for clearButton rerender. this.forceUpdate(); } } }, { key: "clearSearchTimeout", value: function clearSearchTimeout() { if (this.searchTimeout) { clearTimeout(this.searchTimeout); this.searchTimeout = null; } } }, { key: "render", value: function render() { var _this2 = this; var _this$props = this.props, defaultValue = _this$props.defaultValue, disableAutoSearch = _this$props.disableAutoSearch, inputRefCallback = _this$props.inputRefCallback, inputAttributes = _this$props.inputAttributes, intl = _this$props.intl, isBlock = _this$props.isBlock, isDisabled = _this$props.isDisabled, minimumSearchTextLength = _this$props.minimumSearchTextLength, onChange = _this$props.onChange, onInput = _this$props.onInput, onInvalidSearch = _this$props.onInvalidSearch, onSearch = _this$props.onSearch, placeholder = _this$props.placeholder, searchDelay = _this$props.searchDelay, value = _this$props.value, customProps = _objectWithoutProperties(_this$props, _excluded); var theme = this.context; var searchFieldClassNames = (0, _classnames.default)(cx('search-field', { block: isBlock }, theme.className), customProps.className); var inputText = inputAttributes && Object.prototype.hasOwnProperty.call(inputAttributes, 'aria-label') ? inputAttributes['aria-label'] : intl.formatMessage({ id: 'Terra.searchField.search' }); var buttonText = intl.formatMessage({ id: 'Terra.searchField.submit-search' }); var clearText = intl.formatMessage({ id: 'Terra.searchField.clear' }); var additionalInputAttributes = _objectSpread({}, inputAttributes); var clearIcon = /*#__PURE__*/_react.default.createElement("span", { className: cx('clear-icon') }); var inputClass = (0, _classnames.default)(cx('input'), additionalInputAttributes.className); if (value !== undefined) { additionalInputAttributes.value = value; } else { additionalInputAttributes.defaultValue = defaultValue; } var clearButton = this.searchText && !isDisabled ? /*#__PURE__*/_react.default.createElement(_terraButton.default, { "data-terra-search-field-button": "Clear", className: cx('clear'), onClick: this.handleClear, text: clearText, variant: "utility", icon: clearIcon, isIconOnly: true }) : undefined; return /*#__PURE__*/_react.default.createElement("div", _extends({}, customProps, { className: searchFieldClassNames }), /*#__PURE__*/_react.default.createElement("div", { className: cx('input-group') }, /*#__PURE__*/_react.default.createElement("input", _extends({}, additionalInputAttributes, { className: inputClass, type: "search", placeholder: placeholder, onChange: this.handleTextChange, disabled: isDisabled, "aria-label": inputText, "aria-disabled": isDisabled, onKeyDown: this.handleKeyDown, onInput: this.handleInput, ref: this.setInputRef })), clearButton), /*#__PURE__*/_react.default.createElement(_terraButton.default, { "data-terra-search-field-button": "Search", className: cx('button'), text: buttonText, onClick: this.handleSearch, isDisabled: isDisabled, icon: Icon, isIconOnly: true, isCompact: true, refCallback: function refCallback(ref) { _this2.searchBtnRef.current = ref; } })); } }]); return SearchField; }(_react.default.Component); SearchField.propTypes = propTypes; SearchField.defaultProps = defaultProps; SearchField.contextType = _terraThemeContext.default; var _default = (0, _reactIntl.injectIntl)(SearchField); exports.default = _default;