Commit 9e25e57d authored by Emmanuele Bassi's avatar Emmanuele Bassi 👣
Browse files

template: Save the latest search in the history

This way, we can get back to it from the results.

Fixes: #102
parent 1ee8f936
Pipeline #312986 passed with stage
in 2 minutes and 17 seconds
......@@ -52,30 +52,36 @@ function onInitSearch() {
function onDidLoadSearchIndex(data) {
searchIndex = new SearchIndex(data)
refs.input = document.querySelector("#search-input")
refs.form = document.querySelector("#search-form")
refs.search = document.querySelector("#search")
refs.main = document.querySelector("#main")
refs.input = document.querySelector("#search-input");
refs.form = document.querySelector("#search-form");
refs.search = document.querySelector("#search");
refs.main = document.querySelector("#main");
attachInputHandlers()
attachInputHandlers();
if (searchParams.q) {
search(searchParams.q);
}
}
function getNakedUrl() {
return window.location.href.split("?")[0].split("#")[0];
}
function onDidSearch() {
const query = refs.input.value
if (query)
search(query)
else
hideSearchResults()
const query = refs.input.value;
if (query) {
search(query);
}
else {
hideSearchResults();
}
}
function onDidSubmit(ev) {
ev.preventDefault();
if (searchResults.length > 0) {
window.location.href = searchResults[0].href
if (searchResults.length == 1) {
window.location.href = searchResults[0].href;
}
}
......@@ -84,7 +90,7 @@ function attachInputHandlers() {
refs.input.value === searchParams.q || "";
}
refs.input.addEventListener('keydown', debounce(200, onDidSearch))
refs.input.addEventListener('keyup', debounce(500, onDidSearch))
refs.form.addEventListener('submit', onDidSubmit)
}
......@@ -153,6 +159,12 @@ function renderResults(query, results) {
}
function showResults(query, results) {
if (window.history && typeof window.history.pushState === "function") {
let baseUrl = getNakedUrl();
let extra = "?q=" + encodeURIComponent(refs.input.value);
window.history.replaceState(refs.input.value, "", baseUrl + extra + window.location.hash);
}
window.title = "Results for: " + query;
window.scroll({ top: 0 })
refs.search.innerHTML = renderResults(query, results);
......@@ -333,18 +345,22 @@ function matchQuery(input) {
}
function debounce(delay, fn) {
let timeout
let savedArgs
return function() {
const self = this
savedArgs = Array.prototype.slice.call(arguments)
if (timeout)
clearTimeout(timeout)
timeout = setTimeout(function() {
fn.apply(self, savedArgs)
timeout = undefined
}, delay)
}
let timeout;
let savedArgs
return function() {
const self = this;
savedArgs = Array.prototype.slice.call(arguments);
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(function() {
fn.apply(self, savedArgs)
timeout = undefined
}, delay)
}
}
})()
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment