Use HTML5 template to render search results

This commit is contained in:
Serghei Iakovlev 2022-07-31 00:05:43 +02:00
parent 56ee7b58bf
commit 83925df1ef
No known key found for this signature in database
GPG key ID: C6AF1016BBDEA800
5 changed files with 44 additions and 15 deletions

View file

@ -13,7 +13,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Changed
- Set the language target to `es2015` when build JavaScript.
- Set the language target to `es2015` when build JavaScript
- Use HTML5 `<template>` tag to render search results
### Fixed

View file

@ -129,21 +129,32 @@ function clearSearchResults() {
}
function updateSearchResults(query, results) {
document.getElementById('search-results-body').innerHTML = results
.map((hit) => `
<article class="post" data-score="${hit.score.toFixed(2)}">
<header>
<h2 class="post-title">
<a href="${hit.href}?utm_source=search" class="search-result-page-title">${hit.title}</a>
</h2>
</header>
<p class="post-content">${createSearchResultBlurb(query, hit.content)}</p>
</article>
`
)
.join('');
const template = document.querySelector('template').content;
const fragment = document.createDocumentFragment();
document.getElementById('results-count').innerHTML = results.length;
const resultsBody = document.getElementById('search-results-body');
resultsBody.textContent = '';
for (const id in results) {
const item = results[id];
const result = template.cloneNode(true);
const article = result.querySelector('article');
article.dataset.score = item.score.toFixed(2);
const a = result.querySelector('a');
a.innerHTML = item.title;
a.href = `${item.href}?utm_source=search`;
const content = result.querySelector('.post-content');
content.innerHTML = createSearchResultBlurb(query, item.content);
fragment.appendChild(result);
}
resultsBody.appendChild(fragment);
document.getElementById('results-count').textContent = results.length;
}
function createSearchResultBlurb(query, pageContent) {

View file

@ -1,5 +1,10 @@
@import "_mixins";
template {
// IE support for HTML5 <template> tag
display: none;
}
.masthead-title small {
font-size: .78rem;
}

View file

@ -32,6 +32,15 @@
<div id="search-results-body" class="post-list"></div>
</section>
<template>
<article class="post" data-score="">
<header>
<h2 class="post-title"><a href="#" class="search-result-page-title"></a></h2>
</header>
<p class="post-content"></p>
</article>
</template>
{{- $isProduction := (or (eq (getenv "HUGO_ENV") "production") (eq site.Params.env "production")) -}}
{{- /* Add lunr.js. */ -}}

View file

@ -875,6 +875,9 @@ form input:-moz-ui-invalid {
-o-transition: all 0.5s ease-out;
transition: all 0.5s ease-out; }
template {
display: none; }
.masthead-title small {
font-size: .78rem; }