import * as React from "react";
/**
 *Encode characters of string
 *
 * @param {string} str - String to be encoded
 * @returns {string} String with all characters encoded
 */
const encodeStringChars = (str) => `&#${str.charCodeAt(0)};`;
/**
 *Sanitize string for HTML to prevent XSS attack
 *
 * @param {*} str
 * @return {*}
 */
const sanitizeHTML = (str) => str === null || str === void 0 ? void 0 : str.replace(/[^\w. ]/gi, encodeStringChars);
/**
 * Highlights matching areas of a query against a piece of text, and then renders them
 * on the screen with a highlighted class. The matching is case insensitive.
 * NOTE: This calls dangerouslySetInnerHTML and contains a potential exploit for XSS.  Use with caution
 * when rendering externally-supplied content.
 */
export const Highlight = (props) => {
    const { matchAgainst, text } = props;
    const escapedMatch = matchAgainst.replace(/([.*+?^${}()|[\]\\])/g, encodeStringChars);
    // sanitizeHTML converts special symbols to their codes, so we need to sanitize both the search row and the text before matching
    const sanitizedEscapedMatch = sanitizeHTML(escapedMatch);
    const sanitizedHtml = sanitizeHTML(text);
    let regex;
    // Catch unexpected cases where some combination of characters break the RegExp
    try {
        regex = new RegExp(`(${sanitizedEscapedMatch || sanitizedHtml})`, "gi");
    }
    catch (e) {
        regex = sanitizedEscapedMatch;
        console.error(`Failure in Highlight component in finsemble-ui. Expected a valid regex. Instead received "${matchAgainst}". Please check that your component is passing valid data.`);
    }
    const itemHtml = sanitizedHtml === null || sanitizedHtml === void 0 ? void 0 : sanitizedHtml.replace(regex, `<span class="highlight">$1</span>`);
    return (React.createElement("span", { dangerouslySetInnerHTML: {
            __html: itemHtml,
        } }));
};
//# sourceMappingURL=Highlight.js.map