chipzoller / hugo-clarity

A theme for Hugo based on VMware Clarity
Other
571 stars 263 forks source link

Fix search-term highlighting bugs #329

Closed rootwork closed 2 years ago

rootwork commented 2 years ago

This PR...

Changes / fixes

I created a new function, highlightSearchTerms, because I didn't want to mess up the existing wrapText given it's used for other things. However @onweru this is your creation so if you'd rather integrate it back into that single function you certainly could.

This mostly taken from this blog post and demo. Instead of taking the entire innerHTML of the <main> element and doing a find-and-replace, it recursively searches the contents of each node -- which means it won't run on things like href attributes. Doing it this way also seems to avoid the nested wrapping.

I constrained it to only highlight terms appearing in .post_body (the body text of a post or page) to avoid it highlighting terms in tags.

I don't love the way it wraps the text of a node in which a match is found with a <span>, but I couldn't figure out another way to replace a node with something that's just a string (the RegEx result).

Testing

Running locally, I was testing it on http://localhost:1313/using-hugo-page-bundles/, here are some examples:

The latter two demonstrate that it works when nested in other styles.

Checklist

Ensure you have checked off the following before submitting your PR.