From: Ardis Lu Date: Tue, 15 Nov 2022 02:24:33 +0000 (-0800) Subject: Properly record searches in browser history X-Git-Url: https://git.ardis.lu/?a=commitdiff_plain;h=34979c9646e4c0953ce22d48fcc8341b8dfcb4ba;p=ardislu.dev Properly record searches in browser history --- diff --git a/script.js b/script.js index 2f9d837..4cc2e77 100644 --- a/script.js +++ b/script.js @@ -157,12 +157,7 @@ function search(str) { } globalThis.search = search; -/* On search submit, replace
with the search results. */ -document.querySelector('form').addEventListener('submit', async event => { - event.preventDefault(); - - const data = new FormData(event.target); - const query = data.get('query') +function showSearch(query) { if (query === '') { document.querySelector('main').replaceWith(globalThis.components.get('home')); return; @@ -174,6 +169,18 @@ document.querySelector('form').addEventListener('submit', async event => { // TODO: update the query params to support deeplinks // TODO: logic to handle searching while in an article document.querySelector('main').replaceWith(filteredHome); +} + +/* On search submit, replace
with the search results. */ +document.querySelector('form').addEventListener('submit', async event => { + event.preventDefault(); + + const data = new FormData(event.target); + const query = data.get('query'); + + // showPage flow is used for direct link. Manually set history here. + history.pushState({}, '', `/search?q=${query}`); + showSearch(query); }); /* Focus the search input on '/' or Ctrl + k. */ @@ -216,6 +223,13 @@ async function showPage(path) { document.querySelector('main').replaceWith(globalThis.components.get('home')); } + else if (path === '/search') { + const form = document.querySelector('form'); + const params = new URLSearchParams(location.search); + const query = params.get('q'); + form.elements['query'].value = query; + showSearch(query); // Bypass form submission because it will set the history twice on direct link + } else if (globalThis.metadata.has(path)) { const post = globalThis.metadata.get(path);