UNPKG

react-bootstrap-typeahead

Version:
35 lines (34 loc) 1.28 kB
import PropTypes from 'prop-types'; import React from 'react'; import { getMatchBounds } from '../../utils'; const propTypes = { children: PropTypes.string.isRequired, highlightClassName: PropTypes.string, search: PropTypes.string.isRequired, }; const Highlighter = ({ children, highlightClassName = 'rbt-highlight-text', search, }) => { if (!search || !children) { return React.createElement(React.Fragment, null, children); } let matchCount = 0; let remaining = children; const highlighterChildren = []; while (remaining) { const bounds = getMatchBounds(remaining, search); if (!bounds) { highlighterChildren.push(remaining); break; } const nonMatch = remaining.slice(0, bounds.start); if (nonMatch) { highlighterChildren.push(nonMatch); } const match = remaining.slice(bounds.start, bounds.end); highlighterChildren.push(React.createElement("mark", { className: highlightClassName, key: matchCount }, match)); matchCount += 1; remaining = remaining.slice(bounds.end); } return React.createElement(React.Fragment, null, highlighterChildren); }; Highlighter.propTypes = propTypes; export default Highlighter;