UNPKG

@elastic/eui

Version:

Elastic UI Component Library

76 lines (73 loc) 2.66 kB
import _toConsumableArray from "@babel/runtime/helpers/toConsumableArray"; /* * 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. */ import React, { useMemo } from 'react'; import escapeRegExp from 'lodash/escapeRegExp'; import { jsx as ___EmotionJSX } from "@emotion/react"; /** * Internal subcomponent with logic for highlighting all occurrences * of a search value within a subject * * Uses regex rather than indexOf/while loops for easier dev maintainability */ export var HighlightAll = function HighlightAll(_ref) { var searchSubject = _ref.searchSubject, _searchValue = _ref.searchValue, isStrict = _ref.isStrict, _ref$highlightCompone = _ref.highlightComponent, HighlightComponent = _ref$highlightCompone === void 0 ? 'mark' : _ref$highlightCompone; var searchValue = useMemo(function () { return Array.isArray(_searchValue) ? _searchValue.map(escapeRegExp).join('|') : escapeRegExp(_searchValue); }, [_searchValue]); var chunks = useMemo(function () { var regex = new RegExp(searchValue, isStrict ? 'g' : 'gi'); var matches = _toConsumableArray(searchSubject.matchAll(regex)).map(function (match) { return { start: match.index || 0, end: (match.index || 0) + match[0].length }; }); return fillInChunks(matches, searchSubject.length); }, [searchValue, searchSubject, isStrict]); return ___EmotionJSX(React.Fragment, null, chunks.map(function (chunk) { var end = chunk.end, highlight = chunk.highlight, start = chunk.start; var value = searchSubject.substring(start, end); return highlight ? ___EmotionJSX(HighlightComponent, { key: start }, value) : value; })); }; /** * Chunk utility */ var fillInChunks = function fillInChunks(chunksToHighlight, totalLength) { var allChunks = []; var append = function append(start, end, highlight) { if (end - start > 0) { allChunks.push({ start: start, end: end, highlight: highlight }); } }; if (chunksToHighlight.length === 0) { append(0, totalLength, false); } else { var lastIndex = 0; chunksToHighlight.forEach(function (chunk) { append(lastIndex, chunk.start, false); append(chunk.start, chunk.end, true); lastIndex = chunk.end; }); append(lastIndex, totalLength, false); } return allChunks; };