I am currently writing a Firefox extension that uses fuzzy search to highligth words on a web page.
The highlighting is done by creating a range that contains the match, then wrapping the content of the range around a custom element. This method from my perspective is equivalent to splitting the text node's text and copying it manually to a newly created node.
The pre-release version of the add-on works beautifully, however there's one type of css styling that I cannot deal with: display: flex; justify-content: space-between
. The issue here is that when I partially wrap the content of a node styled as such, the rendered text loses its integrity.
Below you can find a simple demonstration. You can see that after 1 sec when the formatting starts, the 1st paragraph gets spaced out, while the 2nd one remains intact.
Could someone suggest a solution/workaround to this problem? I'd like to leave the web page's css intact so modifying the element's style is out of the question. I have checked mark.js API and it cannot handle this situation either. I wonder how the browser's built-in ctrl-f Highlight All searchbar deals with this..
function wrapRange(range){
const markedNode = document.createElement('mark');
range.surroundContents(markedNode);
}
setTimeout(() => {
document.querySelectorAll('p').forEach(node => {
const range = new Range();
range.setStart(node.firstChild, 0);
range.setEnd(node.firstChild, 3);
wrapRange(range);
});
}, 1000);
.problematicClass {
display: flex;
justify-content: space-between;
}
mark {
background-color: red;
}
<p class="problematicClass">Lorem ipsum</p>
<p>Lorem ipsum</p>
Flex is always responsible for self- and child-layouts. You have to add a wrapper around the child-nodes (even if they are text-nodes), if you don't want them to be affected by the parents flex-settings.
The specification describes a CSS box model optimized for user interface design. In the flex layout model, the children of a flex container can be laid out in any direction, and can “flex” their sizes, either growing to fill unused space or shrinking to avoid overflowing the parent. Both horizontal and vertical alignment of the children can be easily manipulated. Nesting of these boxes (horizontal inside vertical, or vertical inside horizontal) can be used to build layouts in two dimensions.
Source: https://drafts.csswg.org/css-flexbox-1/
The browser marks the highlight from the search (CTRL+F) on a completely different level and does not inject html code.
That what you want to do, can be solved with the Selection API, but keep in mind, that only Firefox supports multiple selection-ranges at once.
Check out the example here: https://developer.mozilla.org/en-US/docs/Web/API/Selection/addRange#Result