website/public/js/search.js
2023-09-05 14:15:29 +02:00

6 lines
No EOL
2.1 KiB
JavaScript

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 hover:bg-gray-200 dark:hover:bg-gray-600 text-black dark:text-gray-200 p-2 rounded-lg border border-black dark:border-gray-200 bg-gray-200 dark:bg-gray-500 rounded-lg hover:shadow-xl mb-2">
<a href="${e.doc.path}">
<span class="text-xl text-bold">${e.doc.title}</span>
<span class="text-lg">${e.doc.description}</span>
</a>
</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 o=0;o<n.length;o++)n[o].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 l=elasticlunr.Index.load(window.searchIndex),a={bool:"AND",fields:{title:{boost:2},body:{boost:1}}},c,d,r=document.getElementById("search-input");document.getElementById("search-results");r.addEventListener("keyup",function(e){if([...document.body.classList].includes("search-active")&&3<r.value.trim().length&&(c=r.value.trim(),d=l.search(c,a),Array.isArray(d)&&0<d.length)){let e=document.getElementById("results-list");e.replaceChildren();for(o=0;o<d.length;o++){var t=formatResultItem(d[o]);e.appendChild(t)}}})});