UNPKG

terra-search-field

Version:

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

349 lines (347 loc) 18.6 kB
"use strict"; function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } 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", "groupName", "inputRefCallback", "inputAttributes", "intl", "isBlock", "isDisabled", "isLabelVisible", "minimumSearchTextLength", "onChange", "onInput", "onInvalidSearch", "onSearch", "placeholder", "searchDelay", "value"]; function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); } function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } 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(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } 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 = {}; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { 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(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } 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() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } 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); } 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, /** * Group name value for search group elements. This value is also used as Label name. Default value Search is being used when no value is provided. */ groupName: _propTypes.default.string, /** * 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, /** * Whether or not the label is visible. Use this prop to include a label above the search field. The label will be same as groupName prop value. */ isLabelVisible: _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, groupName: 'Search', isBlock: false, isDisabled: false, isLabelVisible: false, minimumSearchTextLength: 2, placeholder: '', searchDelay: 2500, value: undefined, inputAttributes: undefined }; var SearchField = /*#__PURE__*/function (_React$Component) { function SearchField(props) { var _this; _classCallCheck(this, SearchField); _this = _callSuper(this, SearchField, [props]); _this.handleClear = _this.handleClear.bind(_this); _this.handleTextChange = _this.handleTextChange.bind(_this); _this.handleSearch = _this.handleSearch.bind(_this); _this.handleKeyDown = _this.handleKeyDown.bind(_this); _this.handleInput = _this.handleInput.bind(_this); _this.setInputRef = _this.setInputRef.bind(_this); _this.updateSearchText = _this.updateSearchText.bind(_this); _this.searchTimeout = null; _this.searchText = _this.props.defaultValue || _this.props.value; _this.searchBtnRef = /*#__PURE__*/_react.default.createRef(); return _this; } _inherits(SearchField, _React$Component); return _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, groupName = _this$props.groupName, inputRefCallback = _this$props.inputRefCallback, inputAttributes = _this$props.inputAttributes, intl = _this$props.intl, isBlock = _this$props.isBlock, isDisabled = _this$props.isDisabled, isLabelVisible = _this$props.isLabelVisible, 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 searchContainerClassNames = cx(['search-container', theme.className]); var searchFieldClassNames = (0, _classnames.default)(cx('search-field', { block: isBlock }), customProps.className); var groupNameValue = groupName === 'Search' ? intl.formatMessage({ id: 'Terra.searchField.search' }) : groupName; var inputAriaLabelText = inputAttributes && Object.prototype.hasOwnProperty.call(inputAttributes, 'aria-label') ? inputAttributes['aria-label'] : groupNameValue; 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", { className: searchContainerClassNames }, isLabelVisible && /*#__PURE__*/_react.default.createElement("label", { className: cx('label') }, groupName), /*#__PURE__*/_react.default.createElement("div", { className: cx('search-role-container') }, /*#__PURE__*/_react.default.createElement("div", _extends({ role: "group", "aria-label": intl.formatMessage({ id: 'Terra.searchField.search' }) }, 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": inputAriaLabelText, "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; } })))); } }]); }(_react.default.Component); SearchField.propTypes = propTypes; SearchField.defaultProps = defaultProps; SearchField.contextType = _terraThemeContext.default; var _default = exports.default = (0, _reactIntl.injectIntl)(SearchField);