Revert "chore: search cleanup"

This reverts commit 52897f58e6.
This commit is contained in:
Cory Dransfeldt 2024-10-19 20:22:47 -07:00
parent 52897f58e6
commit 72676659be
No known key found for this signature in database
3 changed files with 109 additions and 60 deletions

4
package-lock.json generated
View file

@ -1,12 +1,12 @@
{ {
"name": "coryd.dev", "name": "coryd.dev",
"version": "1.5.14", "version": "1.5.13",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "coryd.dev", "name": "coryd.dev",
"version": "1.5.14", "version": "1.5.13",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@cdransf/api-text": "^1.5.0", "@cdransf/api-text": "^1.5.0",

View file

@ -1,6 +1,6 @@
{ {
"name": "coryd.dev", "name": "coryd.dev",
"version": "1.5.14", "version": "1.5.13",
"description": "The source for my personal site. Built using 11ty (and other tools).", "description": "The source for my personal site. Built using 11ty (and other tools).",
"type": "module", "type": "module",
"engines": { "engines": {

View file

@ -106,41 +106,58 @@ window.addEventListener("load", () => {
"tags", "tags",
"total_plays", "total_plays",
], ],
searchOptions: {
fields: ["title", "tags"],
prefix: true,
fuzzy: 0.1,
boost: { title: 3, tags: 1.5 },
},
}); });
const $form = document.querySelector(".search__form");
const $input = document.querySelector(".search__form--input"); const $input = document.querySelector(".search__form--input");
const $fallback = document.querySelector(".search__form--fallback");
const $typeCheckboxes = document.querySelectorAll( const $typeCheckboxes = document.querySelectorAll(
'.search__form--type input[type="checkbox"]' '.search__form--type input[type="checkbox"]'
); );
const $results = document.querySelector(".search__results"); const $results = document.querySelector(".search__results");
const $loadMoreButton = document.querySelector(".search__load-more"); const $loadMoreButton = document.querySelector(".search__load-more");
$form.removeAttribute("action");
$form.removeAttribute("method");
if ($fallback) $fallback.remove();
const PAGE_SIZE = 10; const PAGE_SIZE = 10;
let currentPage = 1; let currentPage = 1;
let currentResults = []; let currentResults = [];
let total = 0; let total = 0;
let resultsById = {};
let debounceTimeout; let debounceTimeout;
const getSearchResults = (query) => { const parseMarkdown = (markdown) => {
return miniSearch.search(query, { if (!markdown) return "";
fields: ["title", "tags"], return markdown
prefix: true, .replace(/\*\*(.*?)\*\*/g, "<strong>$1</strong>")
fuzzy: 0.1, .replace(/\*(.*?)\*/g, "<em>$1</em>")
boost: { title: 4, tags: 2 }, .replace(/\[(.*?)\]\((.*?)\)/g, '<a href="$2">$1</a>')
}); .replace(/\n/g, "<br>")
.replace(/[#*_~`]/g, "");
}; };
const updateSearchResults = (results) => { const truncateDescription = (markdown, maxLength = 150) => {
if (currentPage === 1) { const htmlDescription = parseMarkdown(markdown);
renderSearchResults(results); const tempDiv = document.createElement("div");
} else { tempDiv.innerHTML = htmlDescription;
appendSearchResults(results); const plainText = tempDiv.textContent || tempDiv.innerText || "";
} return plainText.length > maxLength
? `${plainText.substring(0, maxLength)}...`
const moreResultsToShow = currentPage * PAGE_SIZE < total; : plainText;
$loadMoreButton.style.display = moreResultsToShow ? "block" : "none";
}; };
const formatArtistTitle = (title, totalPlays) =>
totalPlays > 0
? `${title} <strong class="highlight-text">${totalPlays} plays</strong>`
: title;
const renderSearchResults = (results) => { const renderSearchResults = (results) => {
if (results.length > 0) { if (results.length > 0) {
const resultHTML = results const resultHTML = results
@ -148,14 +165,17 @@ window.addEventListener("load", () => {
const truncatedDesc = truncateDescription(description); const truncatedDesc = truncateDescription(description);
const formattedTitle = const formattedTitle =
type === "artist" && total_plays !== undefined type === "artist" && total_plays !== undefined
? `${title} <strong class="highlight-text">${total_plays} plays</strong>` ? formatArtistTitle(title, total_plays)
: title; : title;
return ` return `
<li class="search__results--result"> <li class="search__results--result">
<a href="${url}"><h3>${formattedTitle}</h3></a> <a href="${url}">
<p>${truncatedDesc}</p> <h3>${formattedTitle}</h3>
</li>`; </a>
<p>${truncatedDesc}</p>
</li>
`;
}) })
.join(""); .join("");
@ -174,20 +194,63 @@ window.addEventListener("load", () => {
const truncatedDesc = truncateDescription(description); const truncatedDesc = truncateDescription(description);
const formattedTitle = const formattedTitle =
type === "artist" && total_plays !== undefined type === "artist" && total_plays !== undefined
? `${title} <strong class="highlight-text">${total_plays} plays</strong>` ? formatArtistTitle(title, total_plays)
: title; : title;
return ` return `
<li class="search__results--result"> <li class="search__results--result">
<a href="${url}"><h3>${formattedTitle}</h3></a> <a href="${url}"><h3>${formattedTitle}</h3></a>
<p>${truncatedDesc}</p> <p>${truncatedDesc}</p>
</li>`; </li>
`;
}) })
.join(""); .join("");
$results.insertAdjacentHTML("beforeend", newResults); $results.insertAdjacentHTML("beforeend", newResults);
}; };
const loadSearchIndex = async (query = "", types = [], page = 1) => {
const typeQuery = types.join(",");
try {
const response = await fetch(
`https://coryd.dev/api/search?q=${query}&type=${typeQuery}&page=${page}&pageSize=${PAGE_SIZE}`
);
const index = await response.json();
const results = index.results || [];
total = index.total || results.length;
resultsById = results.reduce((acc, item) => {
acc[item.id] = item;
return acc;
}, {});
miniSearch.removeAll();
miniSearch.addAll(results);
return results;
} catch (error) {
console.error("Error fetching search data:", error);
return [];
}
};
const getSelectedTypes = () =>
Array.from($typeCheckboxes)
.filter((checkbox) => checkbox.checked)
.map((checkbox) => checkbox.value);
const updateSearchResults = (results) => {
if (currentPage === 1) {
renderSearchResults(results);
} else {
appendSearchResults(results);
}
const moreResultsToShow = currentPage * PAGE_SIZE < total;
$loadMoreButton.style.display = moreResultsToShow ? "block" : "none";
};
$input.addEventListener("input", () => { $input.addEventListener("input", () => {
const query = $input.value.trim(); const query = $input.value.trim();
clearTimeout(debounceTimeout); clearTimeout(debounceTimeout);
@ -198,8 +261,8 @@ window.addEventListener("load", () => {
return; return;
} }
debounceTimeout = setTimeout(() => { debounceTimeout = setTimeout(async () => {
const results = getSearchResults(query); const results = await loadSearchIndex(query, getSelectedTypes(), 1);
currentResults = results; currentResults = results;
currentPage = 1; currentPage = 1;
@ -208,8 +271,12 @@ window.addEventListener("load", () => {
}); });
$typeCheckboxes.forEach((checkbox) => { $typeCheckboxes.forEach((checkbox) => {
checkbox.addEventListener("change", () => { checkbox.addEventListener("change", async () => {
const results = getSearchResults($input.value.trim()); const results = await loadSearchIndex(
$input.value.trim(),
getSelectedTypes(),
1
);
currentResults = results; currentResults = results;
currentPage = 1; currentPage = 1;
@ -217,34 +284,16 @@ window.addEventListener("load", () => {
}); });
}); });
$loadMoreButton.addEventListener("click", () => { $loadMoreButton.addEventListener("click", async () => {
currentPage++; currentPage++;
const nextResults = getSearchResults($input.value.trim()).slice( const nextResults = await loadSearchIndex(
(currentPage - 1) * PAGE_SIZE, $input.value.trim(),
currentPage * PAGE_SIZE getSelectedTypes(),
currentPage
); );
currentResults = [...currentResults, ...nextResults];
appendSearchResults(nextResults); updateSearchResults(nextResults);
const moreResultsToShow = currentPage * PAGE_SIZE < total;
$loadMoreButton.style.display = moreResultsToShow ? "block" : "none";
}); });
const truncateDescription = (markdown, maxLength = 150) => {
const htmlDescription = markdown
.replace(/\*\*(.*?)\*\*/g, "<strong>$1</strong>")
.replace(/\*(.*?)\*/g, "<em>$1</em>")
.replace(/\[(.*?)\]\((.*?)\)/g, '<a href="$2">$1</a>')
.replace(/\n/g, "<br>")
.replace(/[#*_~`]/g, "");
const tempDiv = document.createElement("div");
tempDiv.innerHTML = htmlDescription;
const plainText = tempDiv.textContent || tempDiv.innerText || "";
return plainText.length > maxLength
? `${plainText.substring(0, maxLength)}...`
: plainText;
};
})(); })();
}); });