From 7debd0ae6256c89b3c76937d52e802af28562624 Mon Sep 17 00:00:00 2001 From: Michael Schnerring <3743342+schnerring@users.noreply.github.com> Date: Fri, 15 Oct 2021 15:12:42 +0200 Subject: [PATCH] Refactor show_results (flexsearch) to be more descriptive --- assets/js/index.js | 34 +++++++++++++++++++++------------- 1 file changed, 21 insertions(+), 13 deletions(-) diff --git a/assets/js/index.js b/assets/js/index.js index 7bfa6c5..058a107 100644 --- a/assets/js/index.js +++ b/assets/js/index.js @@ -121,31 +121,39 @@ Source: function show_results(){ const maxResult = 5; + var searchQuery = this.value; + var results = index.search(searchQuery, {limit: maxResult, enrich: true}); - var value = this.value; - var results = index.search(value, {limit: maxResult, enrich: true}); - - suggestions.classList.remove('d-none'); - suggestions.innerHTML = ""; - - //flatSearch now returns results for each index field. create a single list - const flatResults = {}; //keyed by href to dedupe results + // flatten results since index.search() returns results for each indexed field + const flatResults = {}; // keyed by href to dedupe results for (const result of results.flatMap(r => r.result)) { flatResults[result.doc.href] = result.doc; } - //construct a list of suggestions list + suggestions.innerHTML = ""; + suggestions.classList.remove('d-none'); + + // construct a list of suggestions for(const href in flatResults) { const doc = flatResults[href]; const entry = document.createElement('div'); - entry.innerHTML = ''; + suggestions.appendChild(entry); - entry.querySelector('a').href = href; - entry.querySelector('span:first-child').textContent = doc.title; - entry.querySelector('span:nth-child(2)').textContent = doc.description; + const a = document.createElement('a'); + a.href = href; + entry.appendChild(a); + + const title = document.createElement('span'); + title.textContent = doc.title; + a.appendChild(title); + + const description = document.createElement('span'); + description.textContent = doc.description; + a.appendChild(description); suggestions.appendChild(entry); + if(suggestions.childElementCount == maxResult) break; } }