blow/static/js/search.js

6 lines
2 KiB
JavaScript
Raw Normal View History

2021-11-11 13:24:04 +00:00
function toggleSearchModal(){const e=document.getElementById("search-modal");e.classList.toggle("opacity-0"),e.classList.toggle("pointer-events-none"),document.body.classList.toggle("search-active"),[...document.body.classList].includes("search-active")&&(document.getElementById("search-input").value="",document.getElementById("search-input").focus())}function formatResultItem(e){return console.log(e),htmlToElement(`<li class="flex flex-col gap-y-2 hover:bg-gray-200 dark:hover:bg-gray-600 text-black dark:text-gray-200 p-2 rounded-lg">
<a href="${e.doc.path}">
<span class="text-xl text-bold">${e.doc.title}</span>
<span class="text-lg">${e.doc.description}</span>
2021-11-07 19:33:27 +00:00
</a>
2021-11-11 13:24:04 +00:00
</li>`)}function htmlToElement(e){let t=document.createElement("template");return e=e.trim(),t.innerHTML=e,t.content.firstChild}document.addEventListener("DOMContentLoaded",function(){let e=document.getElementById("search");e.addEventListener("click",function(e){e.preventDefault(),toggleSearchModal()});const t=document.querySelector(".modal-overlay");t.addEventListener("click",toggleSearchModal);let n=document.querySelectorAll(".modal-close");for(var l=0;l<n.length;l++)n[l].addEventListener("click",toggleSearchModal);document.onkeydown=function(e){let t=!1,n=!1;"key"in(e=e||window.event)?(t="Escape"===e.key||"Esc"===e.key,n="k"===e.key&&!0===e.metaKey):(n=75===e.keyCode&&e.metaKey,t=27===e.keyCode),n&&e.preventDefault(),(t&&document.body.classList.contains("search-active")||n)&&toggleSearchModal()};let o=elasticlunr.Index.load(window.searchIndex),c={bool:"AND",fields:{title:{boost:2},body:{boost:1}}},a,d,s=document.getElementById("search-input");document.getElementById("search-results");s.addEventListener("keyup",function(e){if([...document.body.classList].includes("search-active")&&3<s.value.trim().length&&(a=s.value.trim(),d=o.search(a,c),Array.isArray(d)&&0<d.length)){let e=document.getElementById("results-list");e.replaceChildren();for(l=0;l<d.length;l++){var t=formatResultItem(d[l]);e.appendChild(t)}}})});