From a20149a7e2534561f1f9524523b48dce800b1258 Mon Sep 17 00:00:00 2001 From: Ardis Lu Date: Mon, 19 Feb 2024 22:38:07 -0800 Subject: [PATCH] Highlight search term in search results --- script.js | 17 +++++++++++++++++ style.css | 4 ++++ 2 files changed, 21 insertions(+) diff --git a/script.js b/script.js index a3b439e..5a1f46e 100644 --- a/script.js +++ b/script.js @@ -200,6 +200,23 @@ function showSearch(query) { const filteredMetadata = search(query); const filteredHome = buildHomeComponent(filteredMetadata); + // Highlight instances of query in the text nodes of filteredHome + const walker = document.createTreeWalker(filteredHome, NodeFilter.SHOW_TEXT); + let node; + const ranges = []; + while (node = walker.nextNode()) { + const start = node.nodeValue.toLowerCase().indexOf(query.toLowerCase()); + if (start === -1) { + continue; + } + const range = new Range(); + range.setStart(node, start); + range.setEnd(node, start + query.length); + ranges.push(range); + } + const highlight = new Highlight(...ranges); + CSS.highlights.set('search', highlight); + document.querySelector('main').replaceWith(filteredHome); } diff --git a/style.css b/style.css index 6b4046b..ce13d69 100644 --- a/style.css +++ b/style.css @@ -306,6 +306,10 @@ code:not(.hljs) { transition: background-color 200ms; } +::highlight(search) { + background: hsl(30deg 80% 90%); +} + .post { inline-size: min(100% - 2rem, 1440px); margin-inline: auto; -- 2.47.3