@elastic/eui
Version:
Elastic UI Component Library
54 lines (52 loc) • 2.64 kB
JavaScript
;
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.HighlightFirst = void 0;
var _react = _interopRequireDefault(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _react2 = require("@emotion/react");
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
/**
* Internal subcomponent with logic for highlighting only the first occurrence
* of a search value within a subject
*
* Uses indexOf for performance (which does matter for, e.g. EuiSelectable searching)
*/
var HighlightFirst = exports.HighlightFirst = function HighlightFirst(_ref) {
var searchSubject = _ref.searchSubject,
searchValue = _ref.searchValue,
isStrict = _ref.isStrict,
_ref$highlightCompone = _ref.highlightComponent,
HighlightComponent = _ref$highlightCompone === void 0 ? 'mark' : _ref$highlightCompone;
if (Array.isArray(searchValue)) {
throw new Error('Cannot parse multiple search strings without `highlightAll` enabled');
}
var normalizedSearchSubject = isStrict ? searchSubject : searchSubject.toLowerCase();
var normalizedSearchValue = isStrict ? searchValue : searchValue.toLowerCase();
var indexOfMatch = normalizedSearchSubject.indexOf(normalizedSearchValue);
if (indexOfMatch === -1) {
return (0, _react2.jsx)(_react.default.Fragment, null, searchSubject);
}
var preMatch = searchSubject.substring(0, indexOfMatch);
var match = searchSubject.substring(indexOfMatch, indexOfMatch + searchValue.length);
var postMatch = searchSubject.substring(indexOfMatch + searchValue.length);
return (
// Note: React 16/17 will render empty strings in the DOM. The
// `|| undefined` prevents this & keeps snapshots the same for all versions
(0, _react2.jsx)(_react.default.Fragment, null, preMatch || undefined, (0, _react2.jsx)(HighlightComponent, null, match), postMatch || undefined)
);
};
HighlightFirst.propTypes = {
searchValue: _propTypes.default.oneOfType([_propTypes.default.string.isRequired, _propTypes.default.arrayOf(_propTypes.default.string.isRequired).isRequired]).isRequired,
searchSubject: _propTypes.default.string.isRequired,
isStrict: _propTypes.default.bool.isRequired,
highlightComponent: _propTypes.default.any
};