]> git.ardis.lu - ardislu.dev/commitdiff
Highlight search term in search results
authorArdis Lu <ardisglu@gmail.com>
Tue, 20 Feb 2024 06:38:07 +0000 (22:38 -0800)
committerArdis Lu <ardisglu@gmail.com>
Tue, 20 Feb 2024 06:38:07 +0000 (22:38 -0800)
script.js
style.css

index a3b439e747b2aa55ec85fe5d2a2dc380256c77bc..5a1f46e07f13e2e507a7128e09c2dbf0590ab1b7 100644 (file)
--- 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);
 }
 
index 6b4046b9adc168a48109d2a2e42a74a1f2e01e90..ce13d691ca4252293cf58c3440d6b1994912e15d 100644 (file)
--- 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;
This page took 0.041577 seconds and 4 git commands to generate.