|
1 | | -import docsearch from "@docsearch/js"; |
2 | | -import * as params from "@params"; // hugo dict |
3 | | - |
4 | | -const { appid, apikey, indexname } = params; |
5 | | - |
6 | | -docsearch({ |
7 | | - container: "#docsearch", |
8 | | - appId: appid, |
9 | | - apiKey: apikey, |
10 | | - indexName: indexname, |
11 | | - transformItems(items) { |
12 | | - return items.map((item) => ({ |
13 | | - ...item, |
14 | | - url: item.url.replace("https://docs.docker.com", ""), |
15 | | - })); |
16 | | - }, |
17 | | -}); |
| 1 | +import Fuse from "fuse.js"; |
| 2 | + |
| 3 | +let indexed = false; |
| 4 | +let handler = null; |
| 5 | + |
| 6 | +const modalSearchInput = document.querySelector("#modal-search-input"); |
| 7 | +const modalSearchResults = document.querySelector("#modal-search-results"); |
| 8 | + |
| 9 | +async function initializeIndex() { |
| 10 | + const index = await fetch("/metadata.json").then((response) => |
| 11 | + response.json(), |
| 12 | + ); |
| 13 | + |
| 14 | + const options = { |
| 15 | + keys: [ |
| 16 | + { name: "title", weight: 2 }, |
| 17 | + { name: "description", weight: 1 }, |
| 18 | + { name: "keywords", weight: 1 }, |
| 19 | + { name: "tags", weight: 1 }, |
| 20 | + ], |
| 21 | + minMatchCharLength: 2, |
| 22 | + threshold: 0.2, |
| 23 | + }; |
| 24 | + |
| 25 | + handler = new Fuse(index, options); |
| 26 | + indexed = true; |
| 27 | +} |
| 28 | + |
| 29 | +async function executeSearch(query) { |
| 30 | + !indexed && (await initializeIndex()); |
| 31 | + const results = handler.search(query).map(({ item }) => item); |
| 32 | + return results |
| 33 | +} |
| 34 | + |
| 35 | +async function modalSearch(e) { |
| 36 | + const query = e.target.value; |
| 37 | + results = await executeSearch(query) |
| 38 | + |
| 39 | + let resultsHTML = `<div>${results.length} results</div>`; |
| 40 | + resultsHTML += results |
| 41 | + .map((item) => { |
| 42 | + return `<div class="bg-gray-light-100 dark:bg-gray-dark-200 rounded p-4"> |
| 43 | + <div class="flex flex-col"> |
| 44 | + <a class="link" href="${item.url}">${item.title}</a> |
| 45 | + <p>${item.description}</p> |
| 46 | + </div> |
| 47 | + </div>`; |
| 48 | + }) |
| 49 | + .join(""); |
| 50 | + |
| 51 | + modalSearchResults.innerHTML = resultsHTML; |
| 52 | +} |
| 53 | + |
| 54 | +modalSearchInput.addEventListener("input", modalSearch); |
0 commit comments