From 68338ecf2f3edcfec06f4d918a0af52d6b898d0c Mon Sep 17 00:00:00 2001 From: Johannes Schindelin Date: Tue, 4 Apr 2023 12:06:59 +0200 Subject: [PATCH] Implement "live search" using Pagefind Now even the live search (i.e. "search as you type") works with the client-side search feature. Signed-off-by: Johannes Schindelin --- static/js/application.js | 69 ++++++++++++++++++++++++---------------- 1 file changed, 42 insertions(+), 27 deletions(-) diff --git a/static/js/application.js b/static/js/application.js index 4dd107b47a..3337aff1de 100644 --- a/static/js/application.js +++ b/static/js/application.js @@ -158,10 +158,42 @@ var Search = { if(term != Search.currentSearch) { Search.currentSearch = term; - $.get("/search", {search: term}, function(results) { - $("#search-results").html(results); + $("#search-results").text(`Searching for ${term}`); + this.initializeSearchIndex(async () => { + const results = await Search.pagefind.debouncedSearch(term); + if (results === null) return; + $("#search-results").html(` +
Search Results
+ + + + + + + + + + + +
  + +
  +
    + ${(await Promise.all(results.results.map(async e => { + const result = await e.data(); + return ` +
  • ${result.meta.title}
  • + ` + }))).join('')} +
+
+ `); Search.searching = false; - }, 'html'); + }); }; } else { @@ -211,32 +243,15 @@ var Search = { }, initializeSearchIndex: function(callback) { - if (Search.searchIndex) { - callback(); + if (Search.pagefind) { + callback().catch(console.log); return; } - $.getJSON('/search/search-data.json', data => { - Search.store = data; - - // Initialize lunr with the fields it will be searching on. Titles get - // a boost of 10 to indicate matches on this field are more important. - Search.searchIndex = lunr(function () { - this.ref('id'); - this.field('title', { boost: 10 }); - this.field('category'); - this.field('content'); - - for (var key in Search.store) { - this.add({ - 'id': key, - 'title': Search.store[key].title, - 'category': Search.store[key].category, - 'content': Search.store[key].content - }); - } - }) - callback(); - }) + (async () => { + Search.pagefind = await import(`${baseURLPrefix}pagefind/pagefind.js`); + await Search.pagefind.init(); + await callback(); + })().catch(console.log); }, displayFullSearchResults: function() {