Focus search bar when open and allow opening it with [/]

This commit is contained in:
daudix
2024-10-02 03:41:21 +03:00
parent 8085b6355c
commit eae48b3762
2 changed files with 188 additions and 175 deletions

View File

@ -7,6 +7,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased](https://codeberg.org/daudix/duckquill/compare/v5.3.2...main) ## [Unreleased](https://codeberg.org/daudix/duckquill/compare/v5.3.2...main)
### Changed
- Allow opening search by pressing the slash key.
- Focus search after opening it.
## [5.3.2](https://codeberg.org/daudix/duckquill/compare/v5.3.1...v5.3.2) ## [5.3.2](https://codeberg.org/daudix/duckquill/compare/v5.3.1...v5.3.2)
### Fixed ### Fixed

View File

@ -1,206 +1,214 @@
{#- Based on https://github.com/getzola/zola/blob/1ac1231de1e342bbaf4d7a51a8a9a40ea152e246/docs/static/search.js -#} {#- Based on https://github.com/getzola/zola/blob/1ac1231de1e342bbaf4d7a51a8a9a40ea152e246/docs/static/search.js -#}
<script type="text/javascript"> <script type="text/javascript">
function debounce(func, wait) { function debounce(func, wait) {
var timeout; var timeout;
return function () { return function () {
var context = this; var context = this;
var args = arguments; var args = arguments;
clearTimeout(timeout); clearTimeout(timeout);
timeout = setTimeout(function () { timeout = setTimeout(function () {
timeout = null; timeout = null;
func.apply(context, args); func.apply(context, args);
}, wait); }, wait);
}; };
} }
// Taken from mdbook // Taken from mdbook
// The strategy is as follows: // The strategy is as follows:
// First, assign a value to each word in the document: // First, assign a value to each word in the document:
// Words that correspond to search terms (stemmer aware): 40 // Words that correspond to search terms (stemmer aware): 40
// Normal words: 2 // Normal words: 2
// First word in a sentence: 8 // First word in a sentence: 8
// Then use a sliding window with a constant number of words and count the // Then use a sliding window with a constant number of words and count the
// sum of the values of the words within the window. Then use the window that got the // sum of the values of the words within the window. Then use the window that got the
// maximum sum. If there are multiple maximas, then get the last one. // maximum sum. If there are multiple maximas, then get the last one.
// Enclose the terms in <b>. // Enclose the terms in <b>.
function makeTeaser(body, terms) { function makeTeaser(body, terms) {
var TERM_WEIGHT = 40; var TERM_WEIGHT = 40;
var NORMAL_WORD_WEIGHT = 2; var NORMAL_WORD_WEIGHT = 2;
var FIRST_WORD_WEIGHT = 8; var FIRST_WORD_WEIGHT = 8;
var TEASER_MAX_WORDS = 30; var TEASER_MAX_WORDS = 30;
var stemmedTerms = terms.map(function (w) { var stemmedTerms = terms.map(function (w) {
return elasticlunr.stemmer(w.toLowerCase()); return elasticlunr.stemmer(w.toLowerCase());
}); });
var termFound = false; var termFound = false;
var index = 0; var index = 0;
var weighted = []; // contains elements of ["word", weight, index_in_document] var weighted = []; // contains elements of ["word", weight, index_in_document]
// split in sentences, then words // split in sentences, then words
var sentences = body.toLowerCase().split(". "); var sentences = body.toLowerCase().split(". ");
for (var i in sentences) { for (var i in sentences) {
var words = sentences[i].split(" "); var words = sentences[i].split(" ");
var value = FIRST_WORD_WEIGHT; var value = FIRST_WORD_WEIGHT;
for (var j in words) { for (var j in words) {
var word = words[j]; var word = words[j];
if (word.length > 0) { if (word.length > 0) {
for (var k in stemmedTerms) { for (var k in stemmedTerms) {
if (elasticlunr.stemmer(word).startsWith(stemmedTerms[k])) { if (elasticlunr.stemmer(word).startsWith(stemmedTerms[k])) {
value = TERM_WEIGHT; value = TERM_WEIGHT;
termFound = true; termFound = true;
} }
} }
weighted.push([word, value, index]); weighted.push([word, value, index]);
value = NORMAL_WORD_WEIGHT; value = NORMAL_WORD_WEIGHT;
} }
index += word.length; index += word.length;
index += 1; // ' ' or '.' if last word in sentence index += 1; // ' ' or '.' if last word in sentence
} }
index += 1; // because we split at a two-char boundary '. ' index += 1; // because we split at a two-char boundary '. '
} }
if (weighted.length === 0) { if (weighted.length === 0) {
return body; return body;
} }
var windowWeights = []; var windowWeights = [];
var windowSize = Math.min(weighted.length, TEASER_MAX_WORDS); var windowSize = Math.min(weighted.length, TEASER_MAX_WORDS);
// We add a window with all the weights first // We add a window with all the weights first
var curSum = 0; var curSum = 0;
for (var i = 0; i < windowSize; i++) { for (var i = 0; i < windowSize; i++) {
curSum += weighted[i][1]; curSum += weighted[i][1];
} }
windowWeights.push(curSum); windowWeights.push(curSum);
for (var i = 0; i < weighted.length - windowSize; i++) { for (var i = 0; i < weighted.length - windowSize; i++) {
curSum -= weighted[i][1]; curSum -= weighted[i][1];
curSum += weighted[i + windowSize][1]; curSum += weighted[i + windowSize][1];
windowWeights.push(curSum); windowWeights.push(curSum);
} }
// If we didn't find the term, just pick the first window // If we didn't find the term, just pick the first window
var maxSumIndex = 0; var maxSumIndex = 0;
if (termFound) { if (termFound) {
var maxFound = 0; var maxFound = 0;
// backwards // backwards
for (var i = windowWeights.length - 1; i >= 0; i--) { for (var i = windowWeights.length - 1; i >= 0; i--) {
if (windowWeights[i] > maxFound) { if (windowWeights[i] > maxFound) {
maxFound = windowWeights[i]; maxFound = windowWeights[i];
maxSumIndex = i; maxSumIndex = i;
} }
} }
} }
var teaser = []; var teaser = [];
var startIndex = weighted[maxSumIndex][2]; var startIndex = weighted[maxSumIndex][2];
for (var i = maxSumIndex; i < maxSumIndex + windowSize; i++) { for (var i = maxSumIndex; i < maxSumIndex + windowSize; i++) {
var word = weighted[i]; var word = weighted[i];
if (startIndex < word[2]) { if (startIndex < word[2]) {
// missing text from index to start of `word` // missing text from index to start of `word`
teaser.push(body.substring(startIndex, word[2])); teaser.push(body.substring(startIndex, word[2]));
startIndex = word[2]; startIndex = word[2];
} }
// add <strong> around search terms // add <strong> around search terms
if (word[1] === TERM_WEIGHT) { if (word[1] === TERM_WEIGHT) {
teaser.push("<strong>"); teaser.push("<strong>");
} }
startIndex = word[2] + word[0].length; startIndex = word[2] + word[0].length;
teaser.push(body.substring(word[2], startIndex)); teaser.push(body.substring(word[2], startIndex));
if (word[1] === TERM_WEIGHT) { if (word[1] === TERM_WEIGHT) {
teaser.push("</strong>"); teaser.push("</strong>");
} }
} }
teaser.push("…"); teaser.push("…");
return teaser.join(""); return teaser.join("");
} }
function formatSearchResultItem(item, terms) { function formatSearchResultItem(item, terms) {
return '<div class="item">' return '<div class="item">'
+ `<a href="${item.ref}">${item.doc.title}</a>` + `<a href="${item.ref}">${item.doc.title}</a>`
+ `<span>${makeTeaser(item.doc.body, terms)}</span>` + `<span>${makeTeaser(item.doc.body, terms)}</span>`
+ '</div>'; + '</div>';
} }
function initSearch() { function initSearch() {
var $searchInput = document.getElementById("search-bar"); var $searchInput = document.getElementById("search-bar");
var $searchResults = document.getElementById("search-results"); var $searchResults = document.getElementById("search-results");
var MAX_ITEMS = 10; var MAX_ITEMS = 10;
var options = { var options = {
bool: "AND", bool: "AND",
fields: { fields: {
title: { boost: 2 }, title: { boost: 2 },
body: { boost: 1 }, body: { boost: 1 },
} }
}; };
var currentTerm = ""; var currentTerm = "";
var index; var index;
var initIndex = async function () { var initIndex = async function () {
if (index === undefined) { if (index === undefined) {
index = fetch("{{ get_url(path='/', lang=lang) }}/search_index.{{ config.default_language }}.json") index = fetch("{{ get_url(path='/', lang=lang) }}/search_index.{{ config.default_language }}.json")
.then( .then(
async function (response) { async function (response) {
return await elasticlunr.Index.load(await response.json()); return await elasticlunr.Index.load(await response.json());
} }
); );
} }
let res = await index; let res = await index;
return res; return res;
} }
$searchInput.addEventListener("keyup", debounce(async function () { $searchInput.addEventListener("keyup", debounce(async function () {
var term = $searchInput.value.trim(); var term = $searchInput.value.trim();
if (term === currentTerm) { if (term === currentTerm) {
return; return;
} }
$searchResults.style.display = term === "" ? "none" : "flex"; $searchResults.style.display = term === "" ? "none" : "flex";
$searchResults.innerHTML = ""; $searchResults.innerHTML = "";
currentTerm = term; currentTerm = term;
if (term === "") { if (term === "") {
return; return;
} }
var results = (await initIndex()).search(term, options); var results = (await initIndex()).search(term, options);
if (results.length === 0) { if (results.length === 0) {
$searchResults.style.display = "none"; $searchResults.style.display = "none";
return; return;
} }
for (var i = 0; i < Math.min(results.length, MAX_ITEMS); i++) { for (var i = 0; i < Math.min(results.length, MAX_ITEMS); i++) {
$searchResults.innerHTML += formatSearchResultItem(results[i], term.split(" ")); $searchResults.innerHTML += formatSearchResultItem(results[i], term.split(" "));
} }
}, 150)); }, 150));
window.addEventListener('click', function (e) { window.addEventListener('click', function (e) {
if ($searchResults.style.display == "flex" && !$searchResults.contains(e.target)) { if ($searchResults.style.display == "flex" && !$searchResults.contains(e.target)) {
$searchResults.style.display = "none"; $searchResults.style.display = "none";
} }
}); });
} }
function toggleSearch() { function toggleSearch() {
var searchContainer = document.getElementById("search-container"); var searchContainer = document.getElementById("search-container");
var searchBar = document.getElementById("search-bar"); var searchBar = document.getElementById("search-bar");
searchContainer.classList.toggle("active"); searchContainer.classList.toggle("active");
searchBar.toggleAttribute("disabled"); searchBar.toggleAttribute("disabled");
} searchBar.focus();
}
if (document.readyState === "complete" || document.addEventListener("keydown", function(event) {
(document.readyState !== "loading" && !document.documentElement.doScroll) if (event.key === "/") {
) { event.preventDefault();
initSearch(); toggleSearch();
} else { }
document.addEventListener("DOMContentLoaded", initSearch); });
}
if (document.readyState === "complete" ||
(document.readyState !== "loading" && !document.documentElement.doScroll)
) {
initSearch();
} else {
document.addEventListener("DOMContentLoaded", initSearch);
}
</script> </script>