UNPKG

@eccenca/gui-elements

Version:

GUI elements based on other libraries, usable in React application, written in Typescript.

70 lines 2.72 kB
import React from "react"; /** * Returns a highlighted string according to the words of the search query. * @param label The string to highlight. * @param searchValue The mutli-word search query from which single words should be highlighted in the label. */ export function Highlighter(_a) { var label = _a.label, searchValue = _a.searchValue; return React.createElement(React.Fragment, null, getSearchHighlight(label, searchValue)); } var getSearchHighlight = function (label, searchValue) { if (!searchValue || !label) { return label; } var searchStringParts = extractSearchWords(searchValue); if (searchStringParts.length === 0) { return label; } var multiWordRegex = createMultiWordRegex(searchStringParts); var result = []; var offset = 0; // loop through matches and add unmatched and matched parts to result array var matchArray = multiWordRegex.exec(label); var key = 0; while (matchArray !== null) { key++; result.push(label.slice(offset, matchArray.index)); result.push(React.createElement("mark", { key: key }, matchArray[0])); offset = multiWordRegex.lastIndex; matchArray = multiWordRegex.exec(label); } // Add remaining unmatched string result.push(label.slice(offset)); return result; }; /** Escapes strings to match literally. * taken from https://stackoverflow.com/questions/6318710/javascript-equivalent-of-perls-q-e-or-quotemeta */ var escapeRegexWord = function (str) { return str.toLowerCase().replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); }; /** * Extracts search words separated by white space. */ function extractSearchWords(textQuery, toLowerCase) { if (toLowerCase === void 0) { toLowerCase = false; } var words = textQuery.split(RegExp("\\s+")).filter(function (word) { return word !== ""; }); return toLowerCase ? words.map(function (w) { return w.toLowerCase(); }) : words; } /** * Returns true if all search words are included in the given text */ function matchesAllWords(text, searchWords) { return searchWords.every(function (w) { return text.includes(w); }); } /** * Creates a case-insensitive multi-word regex, that matches any of the given words. */ function createMultiWordRegex(multiWordQuery, global) { if (global === void 0) { global = true; } var regexString = multiWordQuery.map(escapeRegexWord).join("|"); return RegExp(regexString, (global ? "g" : "") + "i"); } export var highlighterUtils = { extractSearchWords: extractSearchWords, matchesAllWords: matchesAllWords, createMultiWordRegex: createMultiWordRegex, }; export default Highlighter; //# sourceMappingURL=Highlighter.js.map