From 13e44e20c8bf3a0c8d9b9c238cccceb3129f4973 Mon Sep 17 00:00:00 2001 From: yousfi saad Date: Mon, 14 Feb 2022 14:52:34 +0100 Subject: [PATCH] Wrap the splitted text into a span In some cases the creation of two nodes instead of one node (the text) changes the layout of the page, replacing the text node with a span element containing the splitted text (text plus highlight-tag) avoids layout change --- src/js/content.js | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/js/content.js b/src/js/content.js index 9779667..7ff5bcc 100644 --- a/src/js/content.js +++ b/src/js/content.js @@ -5,6 +5,8 @@ var UNEXPANDABLE = /(script|style|svg|audio|canvas|figure|video|select|input|tex var HIGHLIGHT_TAG = 'highlight-tag'; var HIGHLIGHT_CLASS = 'highlighted'; var SELECTED_CLASS = 'selected'; +var WRAPPER_CLASS = 'wrapper-span-highlighting'; +var WRAPPER_TAG = 'span'; var DEFAULT_MAX_RESULTS = 500; var DEFAULT_HIGHLIGHT_COLOR = '#ffff00'; var DEFAULT_SELECTED_COLOR = '#ff9900'; @@ -79,8 +81,11 @@ function highlight(regex, highlightColor, selectedColor, textColor, maxResults) spanNode.style.color = textColor; spanNode.appendChild(matchedTextNode.cloneNode(true)); matchedTextNode.parentNode.replaceChild(spanNode, matchedTextNode); - searchInfo.highlightedNodes.push(spanNode); searchInfo.length += 1; + var parentNode = node.parentNode; + parentNode.innerHTML = + `<${WRAPPER_TAG} class="${WRAPPER_CLASS}">${node.parentNode.innerHTML}`; + searchInfo.highlightedNodes.push(parentNode.querySelector(HIGHLIGHT_TAG + '.' + HIGHLIGHT_CLASS)); return 1; } } else if (isExpandable(node)) { @@ -103,6 +108,9 @@ function removeHighlight() { while (node = document.body.querySelector(HIGHLIGHT_TAG + '.' + SELECTED_CLASS)) { node.outerHTML = node.innerHTML; } + while (node = document.body.querySelector(HIGHLIGHT_TAG + '.' + WRAPPER_CLASS)) { + node.outerHTML = node.innerHTML; + } }; /* Scroll page to given element */