UNPKG

@eccenca/gui-elements

Version:

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

74 lines 2.89 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.markdownUtils = void 0; const Highlighter_1 = require("../../components/Typography/Highlighter"); /** * Creates a react-markdown reHype plugin that marks text based on a multi-word search query. */ const highlightSearchWordsPluginFactory = (searchQuery) => { const searchStringParts = searchQuery ? Highlighter_1.highlighterUtils.extractSearchWords(searchQuery) : []; const multiWordRegex = Highlighter_1.highlighterUtils.createMultiWordRegex(searchStringParts); const createTextNode = (text) => ({ type: "text", value: text }); // Highlight a text node by returning an array of text and mark elements const highlightTextNode = (textNode) => { if (searchStringParts.length === 0) { return [textNode]; } const result = []; const text = textNode.value; let offset = 0; // loop through matches and add unmatched and matched parts to result array let matchArray = multiWordRegex.exec(text); while (matchArray !== null) { result.push(createTextNode(text.slice(offset, matchArray.index))); result.push({ type: "element", tagName: "mark", properties: {}, children: [createTextNode(matchArray[0])], }); offset = multiWordRegex.lastIndex; matchArray = multiWordRegex.exec(text); } // Add remaining unmatched string result.push(createTextNode(text.slice(offset))); return result; }; // Upper level highlight function const highlightRootNode = (node) => highlightParentNode(node); // Highlight function to be called on Parent nodes const highlightParentNode = (parentNode) => { const newChildren = []; parentNode.children.forEach((child) => { const highlightedChild = highlightTextNodes(child); if (Array.isArray(highlightedChild)) { newChildren.push(...highlightedChild); } else { newChildren.push(highlightedChild); } }); return Object.assign(Object.assign({}, parentNode), { children: newChildren }); }; // Highlight function to be called on generic inner nodes const highlightTextNodes = (node) => { if (node.type === "text") { return highlightTextNode(node); } else { if (node.children) { return highlightParentNode(node); } else { return node; } } }; return function highlightSearchWords() { return (input) => highlightRootNode(input); }; }; exports.markdownUtils = { highlightSearchWordsPluginFactory, }; //# sourceMappingURL=highlightSearchWords.js.map