Group search by sections

This commit is contained in:
Lukas Hirt 2020-12-20 20:09:49 +01:00
parent b38255fd90
commit 9f8ac77af6
3 changed files with 99 additions and 23 deletions

View file

@ -6,6 +6,11 @@
(function() {
const input = document.querySelector('#gdoc-search-input');
const results = document.querySelector('#gdoc-search-results');
let showParent = false
{{ if .Site.Params.GeekdocSearchShowParent }}
showParent = true
{{ end }}
input.addEventListener('focus', init);
input.addEventListener('keyup', search);
@ -19,6 +24,7 @@
input.required = false;
search();
});
loadScript('{{ index .Site.Data.assets "js/groupBy.min.js" | relURL }}');
}
function search() {
@ -32,31 +38,68 @@
return;
}
const searchHits = window.geekdocSearchIndex.search(input.value, 10);
let searchHits = window.geekdocSearchIndex.search(input.value, 10);
console.log(searchHits.length);
if (searchHits.length > 0) {
results.classList.add("has-hits");
} else {
results.classList.remove("has-hits");
if (searchHits.length < 1) {
return results.classList.remove("has-hits");
}
searchHits.forEach(function(page) {
const li = document.createElement('li'),
a = li.appendChild(document.createElement('a'));
results.classList.add("has-hits");
if (showParent) {
searchHits = groupBy(searchHits, hit => hit.parent);
}
const items = [];
if (showParent) {
for (const section in searchHits) {
const item = document.createElement('li'),
title = item.appendChild(document.createElement('span')),
subList = item.appendChild(document.createElement('ul'));
title.textContent = section;
title.classList.add('gdoc-search__list__section-title');
createLinks(searchHits[section], subList);
items.push(item);
}
} else {
items.push(...createLinks(searchHits));
}
items.forEach(item => {
results.appendChild(item);
})
results.classList.add('DUMMY');
}
/**
* Creates links to given pages and either returns them in an array or attaches them to a target element
* @param {Object} pages Page to which the link should point to
* @param {HTMLElement} target Element to which the links should be attatched
* @returns {Array} If target is not specified, returns an array of built links
*/
function createLinks(pages, target) {
const items = [];
for (const page of pages) {
const item = document.createElement('li'),
a = item.appendChild(document.createElement('a'));
a.href = page.href;
{{ if .Site.Params.GeekdocSearchShowParent }}
a.textContent = page.parent ? page.parent + ' / ' + page.title : page.title;
{{ else }}
a.textContent = page.title;
{{ end }}
results.appendChild(li);
results.classList.add("DUMMY");
});
if (target) {
target.appendChild(item);
continue
}
items.push(item);
}
return items;
}
function loadScript(src, callback) {