added optional js powered search

This commit is contained in:
Gabriele Musco 2021-04-13 15:21:40 +02:00
parent cfad046bb8
commit f51db60b35
No known key found for this signature in database
GPG key ID: 8539FD3454380B83
8 changed files with 159 additions and 43 deletions

View file

@ -0,0 +1,51 @@
{{ define "main" }}
<noscript>
You need to enable JavaScript to be able to search.
</noscript>
<div class="search">
<input id="searchbar" type="text" placeholder="{{ .Title }}" />
<a class="nerdlink" onclick="newSearch();">&#xf002;</a>
</div>
<div class="postlist {{ if .Site.Params.gridView }}gridView{{ end }}" id="postlist">
</div>
{{- partial "js_paginator.html" . -}}
<script>
function matchTags(page, term) {
for (let tag of page.tags) {
if (tag.includes(term)) return true;
}
return false;
}
function performSearch(term) {
document.getElementById('postlist').innerHTML = '';
term = term.toLowerCase();
fetch('/search/index.json').then(res => res.json())
.then(res => {
let articles = res.pages.filter(page => (
page.title.toLowerCase().includes(term) ||
matchTags(page, term) ||
page.text.includes(term)
));
if (articles.length > 0) renderArticles(articles);
else document.getElementById('postlist').innerHTML = `
<h3>No results found</h3>
`;
});
}
var url = location.href;
var baseUrl = url.split('?')[0];
var searchbar = document.getElementById('searchbar');
if (url.includes('?')) {
var urlParams = new URLSearchParams(url.split('?')[1]);
if (urlParams.has('q')) {
let searchTerm = urlParams.get('q');
searchbar.value = searchTerm;
performSearch(searchTerm);
}
}
function newSearch() {
location.href = baseUrl+`?q=${searchbar.value}`;
}
searchbar.onkeyup = (ev) => {if (ev.keyCode == 13) newSearch()};
</script>
{{ end }}

View file

@ -0,0 +1,26 @@
{{ define "main" }}
{
"pages": [
{{ range $i, $e := .Site.RegularPages }}
{{ if $i }},{{ end }}
{
"title": {{ .Title | jsonify }},
"date": {{ .Date.Format "2006-01-02" | jsonify }},
"tags": {{ if .Params.tags }}
{{ .Params.tags | jsonify }}
{{ else }}
[]
{{ end }},
"summary": {{ .Summary | jsonify }},
"text": {{ lower .Plain | jsonify }},
"link": "{{ .Permalink }}"
{{ if .Site.Params.imageInArticlePreview }}
, "image": {{ if .Params.Image }}
{{ .Params.Image | jsonify }}{{ else }}""
{{ end }}
{{ end }}
}
{{ end }}
]
}
{{ end }}